blob: 78a29ad35f6b9bf69bdba5b3fc8ae22c50a5c76a [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
14#include "CodeGenFunction.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000015#include "clang/AST/CXXInheritance.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000016#include "clang/AST/RecordLayout.h"
John McCallb81884d2010-02-19 09:25:03 +000017#include "clang/AST/StmtCXX.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000018
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000019using namespace clang;
20using namespace CodeGen;
21
Anders Carlssonc6d171e2009-10-06 22:43:30 +000022static uint64_t
Anders Carlssond829a022010-04-24 21:06:20 +000023ComputeNonVirtualBaseClassOffset(ASTContext &Context,
24 const CXXRecordDecl *DerivedClass,
25 CXXBaseSpecifierArray::iterator Start,
26 CXXBaseSpecifierArray::iterator End) {
27 uint64_t Offset = 0;
28
29 const CXXRecordDecl *RD = DerivedClass;
30
31 for (CXXBaseSpecifierArray::iterator I = Start; I != End; ++I) {
32 const CXXBaseSpecifier *Base = *I;
33 assert(!Base->isVirtual() && "Should not see virtual bases here!");
34
35 // Get the layout.
36 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
37
38 const CXXRecordDecl *BaseDecl =
39 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
40
41 // Add the offset.
42 Offset += Layout.getBaseClassOffset(BaseDecl);
43
44 RD = BaseDecl;
45 }
46
47 // FIXME: We should not use / 8 here.
48 return Offset / 8;
49}
50
51static uint64_t
John McCall6ce74722010-02-16 04:15:37 +000052ComputeNonVirtualBaseClassOffset(ASTContext &Context,
53 const CXXBasePath &Path,
Anders Carlssonc6d171e2009-10-06 22:43:30 +000054 unsigned Start) {
55 uint64_t Offset = 0;
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000056
Anders Carlssonc6d171e2009-10-06 22:43:30 +000057 for (unsigned i = Start, e = Path.size(); i != e; ++i) {
58 const CXXBasePathElement& Element = Path[i];
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000059
Anders Carlssonc6d171e2009-10-06 22:43:30 +000060 // Get the layout.
61 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000062
Anders Carlssonc6d171e2009-10-06 22:43:30 +000063 const CXXBaseSpecifier *BS = Element.Base;
64 assert(!BS->isVirtual() && "Should not see virtual bases here!");
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000065
Anders Carlssonc6d171e2009-10-06 22:43:30 +000066 const CXXRecordDecl *Base =
67 cast<CXXRecordDecl>(BS->getType()->getAs<RecordType>()->getDecl());
68
69 // Add the offset.
70 Offset += Layout.getBaseClassOffset(Base) / 8;
71 }
72
73 return Offset;
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000074}
75
Anders Carlsson9150a2a2009-09-29 03:13:20 +000076llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000077CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
78 const CXXBaseSpecifierArray &BasePath) {
79 assert(!BasePath.empty() && "Base path should not be empty!");
80
81 uint64_t Offset =
82 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
83 BasePath.begin(), BasePath.end());
84 if (!Offset)
85 return 0;
86
87 const llvm::Type *PtrDiffTy =
88 Types.ConvertType(getContext().getPointerDiffType());
89
90 return llvm::ConstantInt::get(PtrDiffTy, Offset);
Anders Carlsson9150a2a2009-09-29 03:13:20 +000091}
92
John McCall6ce74722010-02-16 04:15:37 +000093/// Gets the address of a virtual base class within a complete object.
94/// This should only be used for (1) non-virtual bases or (2) virtual bases
95/// when the type is known to be complete (e.g. in complete destructors).
96///
97/// The object pointed to by 'This' is assumed to be non-null.
98llvm::Value *
99CodeGenFunction::GetAddressOfBaseOfCompleteClass(llvm::Value *This,
100 bool isBaseVirtual,
101 const CXXRecordDecl *Derived,
102 const CXXRecordDecl *Base) {
103 // 'this' must be a pointer (in some address space) to Derived.
104 assert(This->getType()->isPointerTy() &&
105 cast<llvm::PointerType>(This->getType())->getElementType()
106 == ConvertType(Derived));
107
108 // Compute the offset of the virtual base.
109 uint64_t Offset;
110 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
111 if (isBaseVirtual)
112 Offset = Layout.getVBaseClassOffset(Base);
113 else
114 Offset = Layout.getBaseClassOffset(Base);
115
116 // Shift and cast down to the base type.
117 // TODO: for complete types, this should be possible with a GEP.
118 llvm::Value *V = This;
119 if (Offset) {
120 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
121 V = Builder.CreateBitCast(V, Int8PtrTy);
122 V = Builder.CreateConstInBoundsGEP1_64(V, Offset / 8);
123 }
124 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
125
126 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000127}
John McCall6ce74722010-02-16 04:15:37 +0000128
Anders Carlsson53cebd12010-04-20 16:03:35 +0000129static llvm::Value *
130ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
131 uint64_t NonVirtual, llvm::Value *Virtual) {
132 const llvm::Type *PtrDiffTy =
133 CGF.ConvertType(CGF.getContext().getPointerDiffType());
134
135 llvm::Value *NonVirtualOffset = 0;
136 if (NonVirtual)
137 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, NonVirtual);
138
139 llvm::Value *BaseOffset;
140 if (Virtual) {
141 if (NonVirtualOffset)
142 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
143 else
144 BaseOffset = Virtual;
145 } else
146 BaseOffset = NonVirtualOffset;
147
148 // Apply the base offset.
149 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
150 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
151 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
152
153 return ThisPtr;
154}
155
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000156llvm::Value *
Anders Carlssond829a022010-04-24 21:06:20 +0000157CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
158 const CXXRecordDecl *ClassDecl,
159 const CXXBaseSpecifierArray &BasePath,
160 bool NullCheckValue) {
161 assert(!BasePath.empty() && "Base path should not be empty!");
162
163 CXXBaseSpecifierArray::iterator Start = BasePath.begin();
164 const CXXRecordDecl *VBase = 0;
165
166 // Get the virtual base.
167 if ((*Start)->isVirtual()) {
168 VBase =
169 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
170 ++Start;
171 }
172
173 uint64_t NonVirtualOffset =
174 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : ClassDecl,
175 Start, BasePath.end());
176
177 // Get the base pointer type.
178 const llvm::Type *BasePtrTy =
Anders Carlssonc6eaea72010-04-24 21:12:55 +0000179 ConvertType((BasePath.end()[-1])->getType())->getPointerTo();
Anders Carlssond829a022010-04-24 21:06:20 +0000180
181 if (!NonVirtualOffset && !VBase) {
182 // Just cast back.
183 return Builder.CreateBitCast(Value, BasePtrTy);
184 }
185
186 llvm::BasicBlock *CastNull = 0;
187 llvm::BasicBlock *CastNotNull = 0;
188 llvm::BasicBlock *CastEnd = 0;
189
190 if (NullCheckValue) {
191 CastNull = createBasicBlock("cast.null");
192 CastNotNull = createBasicBlock("cast.notnull");
193 CastEnd = createBasicBlock("cast.end");
194
195 llvm::Value *IsNull =
196 Builder.CreateICmpEQ(Value,
197 llvm::Constant::getNullValue(Value->getType()));
198 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
199 EmitBlock(CastNotNull);
200 }
201
202 llvm::Value *VirtualOffset = 0;
203
204 if (VBase)
205 VirtualOffset = GetVirtualBaseClassOffset(Value, ClassDecl, VBase);
206
207 // Apply the offsets.
208 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
209 VirtualOffset);
210
211 // Cast back.
212 Value = Builder.CreateBitCast(Value, BasePtrTy);
213
214 if (NullCheckValue) {
215 Builder.CreateBr(CastEnd);
216 EmitBlock(CastNull);
217 Builder.CreateBr(CastEnd);
218 EmitBlock(CastEnd);
219
220 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
221 PHI->reserveOperandSpace(2);
222 PHI->addIncoming(Value, CastNotNull);
223 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
224 CastNull);
225 Value = PHI;
226 }
227
228 return Value;
229}
230
231llvm::Value *
Anders Carlssonbea9e742010-04-24 21:51:08 +0000232CodeGenFunction::OldGetAddressOfBaseClass(llvm::Value *Value,
233 const CXXRecordDecl *Class,
234 const CXXRecordDecl *BaseClass) {
Anders Carlsson8fef09c2009-09-22 21:58:22 +0000235 QualType BTy =
236 getContext().getCanonicalType(
John McCall6ce74722010-02-16 04:15:37 +0000237 getContext().getTypeDeclType(BaseClass));
Anders Carlsson8fef09c2009-09-22 21:58:22 +0000238 const llvm::Type *BasePtrTy = llvm::PointerType::getUnqual(ConvertType(BTy));
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000239
Anders Carlsson84673e22010-01-31 01:36:53 +0000240 if (Class == BaseClass) {
Anders Carlsson8fef09c2009-09-22 21:58:22 +0000241 // Just cast back.
Anders Carlsson8c793172009-11-23 17:57:54 +0000242 return Builder.CreateBitCast(Value, BasePtrTy);
Anders Carlsson8fef09c2009-09-22 21:58:22 +0000243 }
Anders Carlsson6276b252010-01-31 02:39:02 +0000244
Anders Carlsson3d421852010-04-20 05:07:22 +0000245#ifndef NDEBUG
246 CXXBasePaths Paths(/*FindAmbiguities=*/true,
247 /*RecordPaths=*/true, /*DetectVirtual=*/false);
248#else
Anders Carlsson6276b252010-01-31 02:39:02 +0000249 CXXBasePaths Paths(/*FindAmbiguities=*/false,
250 /*RecordPaths=*/true, /*DetectVirtual=*/false);
Anders Carlsson3d421852010-04-20 05:07:22 +0000251#endif
Anders Carlsson6276b252010-01-31 02:39:02 +0000252 if (!const_cast<CXXRecordDecl *>(Class)->
253 isDerivedFrom(const_cast<CXXRecordDecl *>(BaseClass), Paths)) {
254 assert(false && "Class must be derived from the passed in base class!");
255 return 0;
256 }
257
Anders Carlsson34f54d52010-04-21 18:03:05 +0000258#if 0
259 // FIXME: Re-enable this assert when the underlying bugs have been fixed.
Anders Carlsson3d421852010-04-20 05:07:22 +0000260 assert(!Paths.isAmbiguous(BTy) && "Path is ambiguous");
Anders Carlsson34f54d52010-04-21 18:03:05 +0000261#endif
Anders Carlsson3d421852010-04-20 05:07:22 +0000262
Anders Carlsson6276b252010-01-31 02:39:02 +0000263 unsigned Start = 0;
Anders Carlsson6276b252010-01-31 02:39:02 +0000264
265 const CXXBasePath &Path = Paths.front();
266 const CXXRecordDecl *VBase = 0;
267 for (unsigned i = 0, e = Path.size(); i != e; ++i) {
268 const CXXBasePathElement& Element = Path[i];
269 if (Element.Base->isVirtual()) {
270 Start = i+1;
271 QualType VBaseType = Element.Base->getType();
272 VBase = cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
273 }
274 }
275
276 uint64_t Offset =
John McCall6ce74722010-02-16 04:15:37 +0000277 ComputeNonVirtualBaseClassOffset(getContext(), Paths.front(), Start);
Eli Friedmand76f4382009-11-10 22:48:10 +0000278
Anders Carlsson6276b252010-01-31 02:39:02 +0000279 if (!Offset && !VBase) {
280 // Just cast back.
281 return Builder.CreateBitCast(Value, BasePtrTy);
282 }
283
Anders Carlsson53cebd12010-04-20 16:03:35 +0000284 llvm::Value *VirtualOffset = 0;
285
Anders Carlsson6276b252010-01-31 02:39:02 +0000286 if (VBase)
287 VirtualOffset = GetVirtualBaseClassOffset(Value, Class, VBase);
Eli Friedmand76f4382009-11-10 22:48:10 +0000288
Anders Carlsson53cebd12010-04-20 16:03:35 +0000289 // Apply the offsets.
290 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, Offset, VirtualOffset);
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000291
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000292 // Cast back.
Anders Carlsson8c793172009-11-23 17:57:54 +0000293 Value = Builder.CreateBitCast(Value, BasePtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000294 return Value;
295}
296
297llvm::Value *
298CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson84673e22010-01-31 01:36:53 +0000299 const CXXRecordDecl *DerivedClass,
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000300 const CXXBaseSpecifierArray &BasePath,
Anders Carlsson8c793172009-11-23 17:57:54 +0000301 bool NullCheckValue) {
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000302 assert(!BasePath.empty() && "Base path should not be empty!");
303
Anders Carlsson8c793172009-11-23 17:57:54 +0000304 QualType DerivedTy =
305 getContext().getCanonicalType(
Anders Carlsson84673e22010-01-31 01:36:53 +0000306 getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(DerivedClass)));
Anders Carlsson8c793172009-11-23 17:57:54 +0000307 const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
308
Anders Carlsson600f7372010-01-31 01:43:37 +0000309 llvm::Value *NonVirtualOffset =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000310 CGM.GetNonVirtualBaseClassOffset(DerivedClass, BasePath);
Anders Carlsson600f7372010-01-31 01:43:37 +0000311
312 if (!NonVirtualOffset) {
313 // No offset, we can just cast back.
314 return Builder.CreateBitCast(Value, DerivedPtrTy);
315 }
316
Anders Carlsson8c793172009-11-23 17:57:54 +0000317 llvm::BasicBlock *CastNull = 0;
318 llvm::BasicBlock *CastNotNull = 0;
319 llvm::BasicBlock *CastEnd = 0;
320
321 if (NullCheckValue) {
322 CastNull = createBasicBlock("cast.null");
323 CastNotNull = createBasicBlock("cast.notnull");
324 CastEnd = createBasicBlock("cast.end");
325
326 llvm::Value *IsNull =
327 Builder.CreateICmpEQ(Value,
328 llvm::Constant::getNullValue(Value->getType()));
329 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
330 EmitBlock(CastNotNull);
331 }
332
Anders Carlsson600f7372010-01-31 01:43:37 +0000333 // Apply the offset.
334 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
335 Value = Builder.CreateSub(Value, NonVirtualOffset);
336 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
337
338 // Just cast.
339 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000340
341 if (NullCheckValue) {
342 Builder.CreateBr(CastEnd);
343 EmitBlock(CastNull);
344 Builder.CreateBr(CastEnd);
345 EmitBlock(CastEnd);
346
347 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
348 PHI->reserveOperandSpace(2);
349 PHI->addIncoming(Value, CastNotNull);
350 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
351 CastNull);
352 Value = PHI;
353 }
354
355 return Value;
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000356}
Anders Carlssonfb404882009-12-24 22:46:43 +0000357
Anders Carlsson093bdff2010-03-30 03:27:09 +0000358/// EmitCopyCtorCall - Emit a call to a copy constructor.
359static void
360EmitCopyCtorCall(CodeGenFunction &CGF,
361 const CXXConstructorDecl *CopyCtor, CXXCtorType CopyCtorType,
362 llvm::Value *ThisPtr, llvm::Value *VTT, llvm::Value *Src) {
363 llvm::Value *Callee = CGF.CGM.GetAddrOfCXXConstructor(CopyCtor, CopyCtorType);
364
365 CallArgList CallArgs;
366
367 // Push the this ptr.
368 CallArgs.push_back(std::make_pair(RValue::get(ThisPtr),
369 CopyCtor->getThisType(CGF.getContext())));
370
371 // Push the VTT parameter if necessary.
372 if (VTT) {
373 QualType T = CGF.getContext().getPointerType(CGF.getContext().VoidPtrTy);
374 CallArgs.push_back(std::make_pair(RValue::get(VTT), T));
375 }
376
377 // Push the Src ptr.
378 CallArgs.push_back(std::make_pair(RValue::get(Src),
379 CopyCtor->getParamDecl(0)->getType()));
380
381
382 {
383 CodeGenFunction::CXXTemporariesCleanupScope Scope(CGF);
384
385 // If the copy constructor has default arguments, emit them.
386 for (unsigned I = 1, E = CopyCtor->getNumParams(); I < E; ++I) {
387 const ParmVarDecl *Param = CopyCtor->getParamDecl(I);
388 const Expr *DefaultArgExpr = Param->getDefaultArg();
389
390 assert(DefaultArgExpr && "Ctor parameter must have default arg!");
391
392 QualType ArgType = Param->getType();
393 CallArgs.push_back(std::make_pair(CGF.EmitCallArg(DefaultArgExpr,
394 ArgType),
395 ArgType));
396 }
397
398 const FunctionProtoType *FPT =
399 CopyCtor->getType()->getAs<FunctionProtoType>();
400 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(CallArgs, FPT),
401 Callee, ReturnValueSlot(), CallArgs, CopyCtor);
402 }
403}
404
Anders Carlssonfb404882009-12-24 22:46:43 +0000405/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class
406/// array of objects from SrcValue to DestValue. Copying can be either a bitwise
407/// copy or via a copy constructor call.
408// FIXME. Consolidate this with EmitCXXAggrConstructorCall.
409void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest,
410 llvm::Value *Src,
411 const ArrayType *Array,
412 const CXXRecordDecl *BaseClassDecl,
413 QualType Ty) {
414 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
415 assert(CA && "VLA cannot be copied over");
416 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor();
417
418 // Create a temporary for the loop index and initialize it with 0.
419 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
420 "loop.index");
421 llvm::Value* zeroConstant =
422 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
423 Builder.CreateStore(zeroConstant, IndexPtr);
424 // Start the loop with a block that tests the condition.
425 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
426 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
427
428 EmitBlock(CondBlock);
429
430 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
431 // Generate: if (loop-index < number-of-elements fall to the loop body,
432 // otherwise, go to the block after the for-loop.
433 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
434 llvm::Value * NumElementsPtr =
435 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
436 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
437 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
438 "isless");
439 // If the condition is true, execute the body.
440 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
441
442 EmitBlock(ForBody);
443 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
444 // Inside the loop body, emit the constructor call on the array element.
445 Counter = Builder.CreateLoad(IndexPtr);
446 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
447 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
448 if (BitwiseCopy)
449 EmitAggregateCopy(Dest, Src, Ty);
450 else if (CXXConstructorDecl *BaseCopyCtor =
Anders Carlsson9d08fc12010-03-30 03:30:08 +0000451 BaseClassDecl->getCopyConstructor(getContext(), 0))
452 EmitCopyCtorCall(*this, BaseCopyCtor, Ctor_Complete, Dest, 0, Src);
Anders Carlssonfb404882009-12-24 22:46:43 +0000453
Anders Carlssonfb404882009-12-24 22:46:43 +0000454 EmitBlock(ContinueBlock);
455
456 // Emit the increment of the loop counter.
457 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
458 Counter = Builder.CreateLoad(IndexPtr);
459 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
460 Builder.CreateStore(NextVal, IndexPtr);
461
462 // Finally, branch back up to the condition for the next iteration.
463 EmitBranch(CondBlock);
464
465 // Emit the fall-through block.
466 EmitBlock(AfterFor, true);
467}
468
469/// EmitClassAggrCopyAssignment - This routine generates code to assign a class
470/// array of objects from SrcValue to DestValue. Assignment can be either a
471/// bitwise assignment or via a copy assignment operator function call.
472/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy
473void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest,
474 llvm::Value *Src,
475 const ArrayType *Array,
476 const CXXRecordDecl *BaseClassDecl,
477 QualType Ty) {
478 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
479 assert(CA && "VLA cannot be asssigned");
480 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment();
481
482 // Create a temporary for the loop index and initialize it with 0.
483 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext),
484 "loop.index");
485 llvm::Value* zeroConstant =
486 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext));
487 Builder.CreateStore(zeroConstant, IndexPtr);
488 // Start the loop with a block that tests the condition.
489 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
490 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
491
492 EmitBlock(CondBlock);
493
494 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
495 // Generate: if (loop-index < number-of-elements fall to the loop body,
496 // otherwise, go to the block after the for-loop.
497 uint64_t NumElements = getContext().getConstantArrayElementCount(CA);
498 llvm::Value * NumElementsPtr =
499 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements);
500 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
501 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr,
502 "isless");
503 // If the condition is true, execute the body.
504 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
505
506 EmitBlock(ForBody);
507 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
508 // Inside the loop body, emit the assignment operator call on array element.
509 Counter = Builder.CreateLoad(IndexPtr);
510 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress");
511 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress");
512 const CXXMethodDecl *MD = 0;
513 if (BitwiseAssign)
514 EmitAggregateCopy(Dest, Src, Ty);
515 else {
Eli Friedmancab01472010-01-15 20:06:11 +0000516 BaseClassDecl->hasConstCopyAssignment(getContext(), MD);
517 assert(MD && "EmitClassAggrCopyAssignment - No user assign");
Anders Carlssonfb404882009-12-24 22:46:43 +0000518 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
519 const llvm::Type *LTy =
520 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
521 FPT->isVariadic());
522 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
523
524 CallArgList CallArgs;
525 // Push the this (Dest) ptr.
526 CallArgs.push_back(std::make_pair(RValue::get(Dest),
527 MD->getThisType(getContext())));
528
529 // Push the Src ptr.
Eli Friedmancab01472010-01-15 20:06:11 +0000530 QualType SrcTy = MD->getParamDecl(0)->getType();
531 RValue SrcValue = SrcTy->isReferenceType() ? RValue::get(Src) :
532 RValue::getAggregate(Src);
533 CallArgs.push_back(std::make_pair(SrcValue, SrcTy));
John McCallab26cfa2010-02-05 21:31:56 +0000534 EmitCall(CGM.getTypes().getFunctionInfo(CallArgs, FPT),
Anders Carlssonfb404882009-12-24 22:46:43 +0000535 Callee, ReturnValueSlot(), CallArgs, MD);
536 }
537 EmitBlock(ContinueBlock);
538
539 // Emit the increment of the loop counter.
540 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
541 Counter = Builder.CreateLoad(IndexPtr);
542 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
543 Builder.CreateStore(NextVal, IndexPtr);
544
545 // Finally, branch back up to the condition for the next iteration.
546 EmitBranch(CondBlock);
547
548 // Emit the fall-through block.
549 EmitBlock(AfterFor, true);
550}
551
Anders Carlssone36a6b32010-01-02 01:01:18 +0000552/// GetVTTParameter - Return the VTT parameter that should be passed to a
553/// base constructor/destructor with virtual bases.
554static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD) {
Anders Carlssona864caf2010-03-23 04:11:45 +0000555 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000556 // This constructor/destructor does not need a VTT parameter.
557 return 0;
558 }
559
560 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
561 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000562
Anders Carlssone36a6b32010-01-02 01:01:18 +0000563 llvm::Value *VTT;
564
John McCall5c60a6f2010-02-18 19:59:28 +0000565 uint64_t SubVTTIndex;
566
567 // If the record matches the base, this is the complete ctor/dtor
568 // variant calling the base variant in a class with virtual bases.
569 if (RD == Base) {
Anders Carlssona864caf2010-03-23 04:11:45 +0000570 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000571 "doing no-op VTT offset in base dtor/ctor?");
572 SubVTTIndex = 0;
573 } else {
Anders Carlssona864caf2010-03-23 04:11:45 +0000574 SubVTTIndex = CGF.CGM.getVTables().getSubVTTIndex(RD, Base);
John McCall5c60a6f2010-02-18 19:59:28 +0000575 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
576 }
Anders Carlssone36a6b32010-01-02 01:01:18 +0000577
Anders Carlssona864caf2010-03-23 04:11:45 +0000578 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000579 // A VTT parameter was passed to the constructor, use it.
580 VTT = CGF.LoadCXXVTT();
581 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
582 } else {
583 // We're the complete constructor, so get the VTT by name.
Anders Carlssona864caf2010-03-23 04:11:45 +0000584 VTT = CGF.CGM.getVTables().getVTT(RD);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000585 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
586 }
587
588 return VTT;
589}
590
591
Anders Carlssonfb404882009-12-24 22:46:43 +0000592/// EmitClassMemberwiseCopy - This routine generates code to copy a class
593/// object from SrcValue to DestValue. Copying can be either a bitwise copy
594/// or via a copy constructor call.
595void CodeGenFunction::EmitClassMemberwiseCopy(
596 llvm::Value *Dest, llvm::Value *Src,
597 const CXXRecordDecl *ClassDecl,
598 const CXXRecordDecl *BaseClassDecl, QualType Ty) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000599 CXXCtorType CtorType = Ctor_Complete;
600
Anders Carlssonfb404882009-12-24 22:46:43 +0000601 if (ClassDecl) {
Anders Carlssonbea9e742010-04-24 21:51:08 +0000602 Dest = OldGetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl);
603 Src = OldGetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000604
605 // We want to call the base constructor.
606 CtorType = Ctor_Base;
Anders Carlssonfb404882009-12-24 22:46:43 +0000607 }
608 if (BaseClassDecl->hasTrivialCopyConstructor()) {
609 EmitAggregateCopy(Dest, Src, Ty);
610 return;
611 }
612
Anders Carlsson093bdff2010-03-30 03:27:09 +0000613 CXXConstructorDecl *BaseCopyCtor =
614 BaseClassDecl->getCopyConstructor(getContext(), 0);
615 if (!BaseCopyCtor)
616 return;
Anders Carlssonfb404882009-12-24 22:46:43 +0000617
Anders Carlsson093bdff2010-03-30 03:27:09 +0000618 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(BaseCopyCtor, CtorType));
619 EmitCopyCtorCall(*this, BaseCopyCtor, CtorType, Dest, VTT, Src);
Anders Carlssonfb404882009-12-24 22:46:43 +0000620}
621
622/// EmitClassCopyAssignment - This routine generates code to copy assign a class
623/// object from SrcValue to DestValue. Assignment can be either a bitwise
624/// assignment of via an assignment operator call.
625// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot.
626void CodeGenFunction::EmitClassCopyAssignment(
627 llvm::Value *Dest, llvm::Value *Src,
628 const CXXRecordDecl *ClassDecl,
629 const CXXRecordDecl *BaseClassDecl,
630 QualType Ty) {
631 if (ClassDecl) {
Anders Carlssonbea9e742010-04-24 21:51:08 +0000632 Dest = OldGetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl);
633 Src = OldGetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl);
Anders Carlssonfb404882009-12-24 22:46:43 +0000634 }
635 if (BaseClassDecl->hasTrivialCopyAssignment()) {
636 EmitAggregateCopy(Dest, Src, Ty);
637 return;
638 }
639
640 const CXXMethodDecl *MD = 0;
Eli Friedmancab01472010-01-15 20:06:11 +0000641 BaseClassDecl->hasConstCopyAssignment(getContext(), MD);
642 assert(MD && "EmitClassCopyAssignment - missing copy assign");
Anders Carlssonfb404882009-12-24 22:46:43 +0000643
644 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
645 const llvm::Type *LTy =
646 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
647 FPT->isVariadic());
648 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy);
649
650 CallArgList CallArgs;
651 // Push the this (Dest) ptr.
652 CallArgs.push_back(std::make_pair(RValue::get(Dest),
653 MD->getThisType(getContext())));
654
655 // Push the Src ptr.
Eli Friedmancab01472010-01-15 20:06:11 +0000656 QualType SrcTy = MD->getParamDecl(0)->getType();
657 RValue SrcValue = SrcTy->isReferenceType() ? RValue::get(Src) :
658 RValue::getAggregate(Src);
659 CallArgs.push_back(std::make_pair(SrcValue, SrcTy));
John McCallab26cfa2010-02-05 21:31:56 +0000660 EmitCall(CGM.getTypes().getFunctionInfo(CallArgs, FPT),
Anders Carlssonfb404882009-12-24 22:46:43 +0000661 Callee, ReturnValueSlot(), CallArgs, MD);
662}
663
Anders Carlssonfb404882009-12-24 22:46:43 +0000664/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a
665/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03
666/// The implicitly-defined copy constructor for class X performs a memberwise
667/// copy of its subobjects. The order of copying is the same as the order of
668/// initialization of bases and members in a user-defined constructor
669/// Each subobject is copied in the manner appropriate to its type:
670/// if the subobject is of class type, the copy constructor for the class is
671/// used;
672/// if the subobject is an array, each element is copied, in the manner
673/// appropriate to the element type;
674/// if the subobject is of scalar type, the built-in assignment operator is
675/// used.
676/// Virtual base class subobjects shall be copied only once by the
677/// implicitly-defined copy constructor
678
679void
John McCallb81884d2010-02-19 09:25:03 +0000680CodeGenFunction::SynthesizeCXXCopyConstructor(const FunctionArgList &Args) {
681 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
Anders Carlssonfb404882009-12-24 22:46:43 +0000682 const CXXRecordDecl *ClassDecl = Ctor->getParent();
683 assert(!ClassDecl->hasUserDeclaredCopyConstructor() &&
684 "SynthesizeCXXCopyConstructor - copy constructor has definition already");
685 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor");
Anders Carlssonfb404882009-12-24 22:46:43 +0000686
687 FunctionArgList::const_iterator i = Args.begin();
688 const VarDecl *ThisArg = i->first;
689 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
690 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
691 const VarDecl *SrcArg = (i+1)->first;
692 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
693 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
694
Anders Carlssonfb404882009-12-24 22:46:43 +0000695 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
696 E = ClassDecl->field_end(); I != E; ++I) {
697 const FieldDecl *Field = *I;
698
699 QualType FieldType = getContext().getCanonicalType(Field->getType());
700 const ConstantArrayType *Array =
701 getContext().getAsConstantArrayType(FieldType);
702 if (Array)
703 FieldType = getContext().getBaseElementType(FieldType);
704
705 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
706 CXXRecordDecl *FieldClassDecl
707 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Anders Carlsson5d8645b2010-01-29 05:05:36 +0000708 LValue LHS = EmitLValueForField(LoadOfThis, Field, 0);
709 LValue RHS = EmitLValueForField(LoadOfSrc, Field, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000710 if (Array) {
711 const llvm::Type *BasePtr = ConvertType(FieldType);
712 BasePtr = llvm::PointerType::getUnqual(BasePtr);
713 llvm::Value *DestBaseAddrPtr =
714 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
715 llvm::Value *SrcBaseAddrPtr =
716 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
717 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
718 FieldClassDecl, FieldType);
719 }
720 else
721 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(),
722 0 /*ClassDecl*/, FieldClassDecl, FieldType);
723 continue;
724 }
725
Anders Carlssonfb404882009-12-24 22:46:43 +0000726 // Do a built-in assignment of scalar data members.
Anders Carlsson42c876d2010-01-29 05:41:25 +0000727 LValue LHS = EmitLValueForFieldInitialization(LoadOfThis, Field, 0);
728 LValue RHS = EmitLValueForFieldInitialization(LoadOfSrc, Field, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000729
730 if (!hasAggregateLLVMType(Field->getType())) {
731 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
732 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
733 } else if (Field->getType()->isAnyComplexType()) {
734 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
735 RHS.isVolatileQualified());
736 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
737 } else {
738 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
739 }
740 }
741
Anders Carlssond5895932010-03-28 21:07:49 +0000742 InitializeVTablePointers(ClassDecl);
Anders Carlssonfb404882009-12-24 22:46:43 +0000743}
744
745/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator.
746/// Before the implicitly-declared copy assignment operator for a class is
747/// implicitly defined, all implicitly- declared copy assignment operators for
748/// its direct base classes and its nonstatic data members shall have been
749/// implicitly defined. [12.8-p12]
750/// The implicitly-defined copy assignment operator for class X performs
751/// memberwise assignment of its subob- jects. The direct base classes of X are
752/// assigned first, in the order of their declaration in
753/// the base-specifier-list, and then the immediate nonstatic data members of X
754/// are assigned, in the order in which they were declared in the class
755/// definition.Each subobject is assigned in the manner appropriate to its type:
756/// if the subobject is of class type, the copy assignment operator for the
757/// class is used (as if by explicit qualification; that is, ignoring any
758/// possible virtual overriding functions in more derived classes);
759///
760/// if the subobject is an array, each element is assigned, in the manner
761/// appropriate to the element type;
762///
763/// if the subobject is of scalar type, the built-in assignment operator is
764/// used.
John McCallb81884d2010-02-19 09:25:03 +0000765void CodeGenFunction::SynthesizeCXXCopyAssignment(const FunctionArgList &Args) {
766 const CXXMethodDecl *CD = cast<CXXMethodDecl>(CurGD.getDecl());
Anders Carlssonfb404882009-12-24 22:46:43 +0000767 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext());
768 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
769 "SynthesizeCXXCopyAssignment - copy assignment has user declaration");
Anders Carlssonfb404882009-12-24 22:46:43 +0000770
771 FunctionArgList::const_iterator i = Args.begin();
772 const VarDecl *ThisArg = i->first;
773 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg);
774 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this");
775 const VarDecl *SrcArg = (i+1)->first;
776 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg);
777 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj);
778
779 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
780 Base != ClassDecl->bases_end(); ++Base) {
781 // FIXME. copy assignment of virtual base NYI
782 if (Base->isVirtual())
783 continue;
784
785 CXXRecordDecl *BaseClassDecl
786 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
787 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl,
788 Base->getType());
789 }
790
791 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
792 FieldEnd = ClassDecl->field_end();
793 Field != FieldEnd; ++Field) {
794 QualType FieldType = getContext().getCanonicalType((*Field)->getType());
795 const ConstantArrayType *Array =
796 getContext().getAsConstantArrayType(FieldType);
797 if (Array)
798 FieldType = getContext().getBaseElementType(FieldType);
799
800 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
801 CXXRecordDecl *FieldClassDecl
802 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Anders Carlsson5d8645b2010-01-29 05:05:36 +0000803 LValue LHS = EmitLValueForField(LoadOfThis, *Field, 0);
804 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000805 if (Array) {
806 const llvm::Type *BasePtr = ConvertType(FieldType);
807 BasePtr = llvm::PointerType::getUnqual(BasePtr);
808 llvm::Value *DestBaseAddrPtr =
809 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
810 llvm::Value *SrcBaseAddrPtr =
811 Builder.CreateBitCast(RHS.getAddress(), BasePtr);
812 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array,
813 FieldClassDecl, FieldType);
814 }
815 else
816 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(),
817 0 /*ClassDecl*/, FieldClassDecl, FieldType);
818 continue;
819 }
820 // Do a built-in assignment of scalar data members.
Anders Carlsson5d8645b2010-01-29 05:05:36 +0000821 LValue LHS = EmitLValueForField(LoadOfThis, *Field, 0);
822 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000823 if (!hasAggregateLLVMType(Field->getType())) {
824 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType());
825 EmitStoreThroughLValue(RVRHS, LHS, Field->getType());
826 } else if (Field->getType()->isAnyComplexType()) {
827 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(),
828 RHS.isVolatileQualified());
829 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified());
830 } else {
831 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType());
832 }
833 }
834
835 // return *this;
836 Builder.CreateStore(LoadOfThis, ReturnValue);
Anders Carlssonfb404882009-12-24 22:46:43 +0000837}
838
839static void EmitBaseInitializer(CodeGenFunction &CGF,
840 const CXXRecordDecl *ClassDecl,
841 CXXBaseOrMemberInitializer *BaseInit,
842 CXXCtorType CtorType) {
843 assert(BaseInit->isBaseInitializer() &&
844 "Must have base initializer!");
845
846 llvm::Value *ThisPtr = CGF.LoadCXXThis();
847
848 const Type *BaseType = BaseInit->getBaseClass();
849 CXXRecordDecl *BaseClassDecl =
850 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
851
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000852 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000853
854 // The base constructor doesn't construct virtual bases.
855 if (CtorType == Ctor_Base && isBaseVirtual)
856 return;
857
John McCall6ce74722010-02-16 04:15:37 +0000858 // We can pretend to be a complete class because it only matters for
859 // virtual bases, and we only do virtual bases for complete ctors.
860 llvm::Value *V = ThisPtr;
861 V = CGF.GetAddressOfBaseOfCompleteClass(V, isBaseVirtual,
862 ClassDecl, BaseClassDecl);
863
Douglas Gregor7ae2d772010-01-31 09:12:51 +0000864 CGF.EmitAggExpr(BaseInit->getInit(), V, false, false, true);
Anders Carlsson5ade5d32010-02-06 20:00:21 +0000865
866 if (CGF.Exceptions && !BaseClassDecl->hasTrivialDestructor()) {
867 // FIXME: Is this OK for C++0x delegating constructors?
868 CodeGenFunction::EHCleanupBlock Cleanup(CGF);
869
Anders Carlsson5ade5d32010-02-06 20:00:21 +0000870 CXXDestructorDecl *DD = BaseClassDecl->getDestructor(CGF.getContext());
871 CGF.EmitCXXDestructorCall(DD, Dtor_Base, V);
872 }
Anders Carlssonfb404882009-12-24 22:46:43 +0000873}
874
875static void EmitMemberInitializer(CodeGenFunction &CGF,
876 const CXXRecordDecl *ClassDecl,
877 CXXBaseOrMemberInitializer *MemberInit) {
878 assert(MemberInit->isMemberInitializer() &&
879 "Must have member initializer!");
880
881 // non-static data member initializers.
882 FieldDecl *Field = MemberInit->getMember();
883 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
884
885 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Anders Carlssondb78f0a2010-01-29 05:24:29 +0000886 LValue LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
887
Anders Carlssonfb404882009-12-24 22:46:43 +0000888 // If we are initializing an anonymous union field, drill down to the field.
889 if (MemberInit->getAnonUnionMember()) {
890 Field = MemberInit->getAnonUnionMember();
Anders Carlsson5d8645b2010-01-29 05:05:36 +0000891 LHS = CGF.EmitLValueForField(LHS.getAddress(), Field, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000892 FieldType = Field->getType();
893 }
894
Douglas Gregor7ae2d772010-01-31 09:12:51 +0000895 // FIXME: If there's no initializer and the CXXBaseOrMemberInitializer
896 // was implicitly generated, we shouldn't be zeroing memory.
Anders Carlssonfb404882009-12-24 22:46:43 +0000897 RValue RHS;
898 if (FieldType->isReferenceType()) {
Anders Carlsson3b227bd2010-02-03 16:38:03 +0000899 RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +0000900 /*IsInitializer=*/true);
Anders Carlssonfb404882009-12-24 22:46:43 +0000901 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedman60417972010-01-31 19:07:50 +0000902 } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlssonfb404882009-12-24 22:46:43 +0000903 CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +0000904 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
905 RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit(), true));
Anders Carlssonfb404882009-12-24 22:46:43 +0000906 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Douglas Gregor7ae2d772010-01-31 09:12:51 +0000907 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
908 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlssonfb404882009-12-24 22:46:43 +0000909 LHS.isVolatileQualified());
910 } else {
Douglas Gregor7ae2d772010-01-31 09:12:51 +0000911 CGF.EmitAggExpr(MemberInit->getInit(), LHS.getAddress(),
912 LHS.isVolatileQualified(), false, true);
Anders Carlssonba631672010-02-06 19:50:17 +0000913
914 if (!CGF.Exceptions)
915 return;
916
917 const RecordType *RT = FieldType->getAs<RecordType>();
918 if (!RT)
919 return;
920
921 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
922 if (!RD->hasTrivialDestructor()) {
923 // FIXME: Is this OK for C++0x delegating constructors?
924 CodeGenFunction::EHCleanupBlock Cleanup(CGF);
925
926 llvm::Value *ThisPtr = CGF.LoadCXXThis();
927 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
928
929 CXXDestructorDecl *DD = RD->getDestructor(CGF.getContext());
930 CGF.EmitCXXDestructorCall(DD, Dtor_Complete, LHS.getAddress());
931 }
Anders Carlssonfb404882009-12-24 22:46:43 +0000932 }
933}
934
John McCallf8ff7b92010-02-23 00:48:20 +0000935/// Checks whether the given constructor is a valid subject for the
936/// complete-to-base constructor delegation optimization, i.e.
937/// emitting the complete constructor as a simple call to the base
938/// constructor.
939static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
940
941 // Currently we disable the optimization for classes with virtual
942 // bases because (1) the addresses of parameter variables need to be
943 // consistent across all initializers but (2) the delegate function
944 // call necessarily creates a second copy of the parameter variable.
945 //
946 // The limiting example (purely theoretical AFAIK):
947 // struct A { A(int &c) { c++; } };
948 // struct B : virtual A {
949 // B(int count) : A(count) { printf("%d\n", count); }
950 // };
951 // ...although even this example could in principle be emitted as a
952 // delegation since the address of the parameter doesn't escape.
953 if (Ctor->getParent()->getNumVBases()) {
954 // TODO: white-list trivial vbase initializers. This case wouldn't
955 // be subject to the restrictions below.
956
957 // TODO: white-list cases where:
958 // - there are no non-reference parameters to the constructor
959 // - the initializers don't access any non-reference parameters
960 // - the initializers don't take the address of non-reference
961 // parameters
962 // - etc.
963 // If we ever add any of the above cases, remember that:
964 // - function-try-blocks will always blacklist this optimization
965 // - we need to perform the constructor prologue and cleanup in
966 // EmitConstructorBody.
967
968 return false;
969 }
970
971 // We also disable the optimization for variadic functions because
972 // it's impossible to "re-pass" varargs.
973 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
974 return false;
975
976 return true;
977}
978
John McCallb81884d2010-02-19 09:25:03 +0000979/// EmitConstructorBody - Emits the body of the current constructor.
980void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
981 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
982 CXXCtorType CtorType = CurGD.getCtorType();
983
John McCallf8ff7b92010-02-23 00:48:20 +0000984 // Before we go any further, try the complete->base constructor
985 // delegation optimization.
986 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
987 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
988 return;
989 }
990
John McCallb81884d2010-02-19 09:25:03 +0000991 Stmt *Body = Ctor->getBody();
992
John McCallf8ff7b92010-02-23 00:48:20 +0000993 // Enter the function-try-block before the constructor prologue if
994 // applicable.
John McCallb81884d2010-02-19 09:25:03 +0000995 CXXTryStmtInfo TryInfo;
John McCallf8ff7b92010-02-23 00:48:20 +0000996 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
997
998 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000999 TryInfo = EnterCXXTryStmt(*cast<CXXTryStmt>(Body));
1000
1001 unsigned CleanupStackSize = CleanupEntries.size();
1002
John McCallf8ff7b92010-02-23 00:48:20 +00001003 // Emit the constructor prologue, i.e. the base and member
1004 // initializers.
John McCallb81884d2010-02-19 09:25:03 +00001005 EmitCtorPrologue(Ctor, CtorType);
1006
1007 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +00001008 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +00001009 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1010 else if (Body)
1011 EmitStmt(Body);
1012 else {
1013 assert(Ctor->isImplicit() && "bodyless ctor not implicit");
1014 if (!Ctor->isDefaultConstructor()) {
1015 assert(Ctor->isCopyConstructor());
1016 SynthesizeCXXCopyConstructor(Args);
1017 }
1018 }
1019
1020 // Emit any cleanup blocks associated with the member or base
1021 // initializers, which includes (along the exceptional path) the
1022 // destructors for those members and bases that were fully
1023 // constructed.
1024 EmitCleanupBlocks(CleanupStackSize);
1025
John McCallf8ff7b92010-02-23 00:48:20 +00001026 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +00001027 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), TryInfo);
1028}
1029
Anders Carlssonfb404882009-12-24 22:46:43 +00001030/// EmitCtorPrologue - This routine generates necessary code to initialize
1031/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001032void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1033 CXXCtorType CtorType) {
1034 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001035
1036 llvm::SmallVector<CXXBaseOrMemberInitializer *, 8> MemberInitializers;
Anders Carlssonfb404882009-12-24 22:46:43 +00001037
Anders Carlssonfb404882009-12-24 22:46:43 +00001038 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1039 E = CD->init_end();
1040 B != E; ++B) {
1041 CXXBaseOrMemberInitializer *Member = (*B);
1042
1043 assert(LiveTemporaries.empty() &&
1044 "Should not have any live temporaries at initializer start!");
1045
1046 if (Member->isBaseInitializer())
1047 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
1048 else
Anders Carlsson5dc86332010-02-02 19:58:43 +00001049 MemberInitializers.push_back(Member);
Anders Carlssonfb404882009-12-24 22:46:43 +00001050 }
1051
Anders Carlssond5895932010-03-28 21:07:49 +00001052 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001053
1054 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I) {
1055 assert(LiveTemporaries.empty() &&
1056 "Should not have any live temporaries at initializer start!");
1057
1058 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I]);
1059 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001060}
1061
John McCallb81884d2010-02-19 09:25:03 +00001062/// EmitDestructorBody - Emits the body of the current destructor.
1063void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1064 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1065 CXXDtorType DtorType = CurGD.getDtorType();
1066
1067 Stmt *Body = Dtor->getBody();
1068
1069 // If the body is a function-try-block, enter the try before
1070 // anything else --- unless we're in a deleting destructor, in which
1071 // case we're just going to call the complete destructor and then
1072 // call operator delete() on the way out.
1073 CXXTryStmtInfo TryInfo;
1074 bool isTryBody = (DtorType != Dtor_Deleting &&
1075 Body && isa<CXXTryStmt>(Body));
1076 if (isTryBody)
1077 TryInfo = EnterCXXTryStmt(*cast<CXXTryStmt>(Body));
1078
1079 llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue");
1080 PushCleanupBlock(DtorEpilogue);
1081
1082 bool SkipBody = false; // should get jump-threaded
1083
1084 // If this is the deleting variant, just invoke the complete
1085 // variant, then call the appropriate operator delete() on the way
1086 // out.
1087 if (DtorType == Dtor_Deleting) {
1088 EmitCXXDestructorCall(Dtor, Dtor_Complete, LoadCXXThis());
1089 SkipBody = true;
1090
1091 // If this is the complete variant, just invoke the base variant;
1092 // the epilogue will destruct the virtual bases. But we can't do
1093 // this optimization if the body is a function-try-block, because
1094 // we'd introduce *two* handler blocks.
1095 } else if (!isTryBody && DtorType == Dtor_Complete) {
1096 EmitCXXDestructorCall(Dtor, Dtor_Base, LoadCXXThis());
1097 SkipBody = true;
1098
1099 // Otherwise, we're in the base variant, so we need to ensure the
1100 // vtable ptrs are right before emitting the body.
1101 } else {
Anders Carlssond5895932010-03-28 21:07:49 +00001102 InitializeVTablePointers(Dtor->getParent());
John McCallb81884d2010-02-19 09:25:03 +00001103 }
1104
1105 // Emit the body of the statement.
1106 if (SkipBody)
1107 (void) 0;
1108 else if (isTryBody)
1109 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1110 else if (Body)
1111 EmitStmt(Body);
1112 else {
1113 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1114 // nothing to do besides what's in the epilogue
1115 }
1116
1117 // Jump to the cleanup block.
1118 CleanupBlockInfo Info = PopCleanupBlock();
1119 assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
1120 EmitBlock(DtorEpilogue);
1121
1122 // Emit the destructor epilogue now. If this is a complete
1123 // destructor with a function-try-block, perform the base epilogue
1124 // as well.
1125 if (isTryBody && DtorType == Dtor_Complete)
1126 EmitDtorEpilogue(Dtor, Dtor_Base);
1127 EmitDtorEpilogue(Dtor, DtorType);
1128
1129 // Link up the cleanup information.
1130 if (Info.SwitchBlock)
1131 EmitBlock(Info.SwitchBlock);
1132 if (Info.EndBlock)
1133 EmitBlock(Info.EndBlock);
1134
1135 // Exit the try if applicable.
1136 if (isTryBody)
1137 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), TryInfo);
1138}
1139
Anders Carlssonfb404882009-12-24 22:46:43 +00001140/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1141/// destructor. This is to call destructors on members and base classes
1142/// in reverse order of their construction.
Anders Carlssonfb404882009-12-24 22:46:43 +00001143void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD,
1144 CXXDtorType DtorType) {
1145 assert(!DD->isTrivial() &&
1146 "Should not emit dtor epilogue for trivial dtor!");
1147
1148 const CXXRecordDecl *ClassDecl = DD->getParent();
1149
John McCall5c60a6f2010-02-18 19:59:28 +00001150 // In a deleting destructor, we've already called the complete
1151 // destructor as a subroutine, so we just have to delete the
1152 // appropriate value.
1153 if (DtorType == Dtor_Deleting) {
1154 assert(DD->getOperatorDelete() &&
1155 "operator delete missing - EmitDtorEpilogue");
1156 EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(),
1157 getContext().getTagDeclType(ClassDecl));
1158 return;
1159 }
1160
1161 // For complete destructors, we've already called the base
1162 // destructor (in GenerateBody), so we just need to destruct all the
1163 // virtual bases.
1164 if (DtorType == Dtor_Complete) {
1165 // Handle virtual bases.
1166 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1167 ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend();
1168 I != E; ++I) {
1169 const CXXBaseSpecifier &Base = *I;
1170 CXXRecordDecl *BaseClassDecl
1171 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1172
1173 // Ignore trivial destructors.
1174 if (BaseClassDecl->hasTrivialDestructor())
1175 continue;
1176 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1177 llvm::Value *V = GetAddressOfBaseOfCompleteClass(LoadCXXThis(),
1178 true,
1179 ClassDecl,
1180 BaseClassDecl);
1181 EmitCXXDestructorCall(D, Dtor_Base, V);
1182 }
1183 return;
1184 }
1185
1186 assert(DtorType == Dtor_Base);
1187
Anders Carlssonfb404882009-12-24 22:46:43 +00001188 // Collect the fields.
1189 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
1190 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1191 E = ClassDecl->field_end(); I != E; ++I) {
1192 const FieldDecl *Field = *I;
1193
1194 QualType FieldType = getContext().getCanonicalType(Field->getType());
1195 FieldType = getContext().getBaseElementType(FieldType);
1196
1197 const RecordType *RT = FieldType->getAs<RecordType>();
1198 if (!RT)
1199 continue;
1200
1201 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1202 if (FieldClassDecl->hasTrivialDestructor())
1203 continue;
1204
1205 FieldDecls.push_back(Field);
1206 }
1207
1208 // Now destroy the fields.
1209 for (size_t i = FieldDecls.size(); i > 0; --i) {
1210 const FieldDecl *Field = FieldDecls[i - 1];
1211
1212 QualType FieldType = Field->getType();
1213 const ConstantArrayType *Array =
1214 getContext().getAsConstantArrayType(FieldType);
1215 if (Array)
1216 FieldType = getContext().getBaseElementType(FieldType);
1217
1218 const RecordType *RT = FieldType->getAs<RecordType>();
1219 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1220
1221 llvm::Value *ThisPtr = LoadCXXThis();
1222
1223 LValue LHS = EmitLValueForField(ThisPtr, Field,
Anders Carlssonfb404882009-12-24 22:46:43 +00001224 // FIXME: Qualifiers?
1225 /*CVRQualifiers=*/0);
1226 if (Array) {
1227 const llvm::Type *BasePtr = ConvertType(FieldType);
1228 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1229 llvm::Value *BaseAddrPtr =
1230 Builder.CreateBitCast(LHS.getAddress(), BasePtr);
1231 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()),
1232 Array, BaseAddrPtr);
1233 } else
1234 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()),
1235 Dtor_Complete, LHS.getAddress());
1236 }
1237
1238 // Destroy non-virtual bases.
1239 for (CXXRecordDecl::reverse_base_class_const_iterator I =
1240 ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) {
1241 const CXXBaseSpecifier &Base = *I;
1242
1243 // Ignore virtual bases.
1244 if (Base.isVirtual())
1245 continue;
1246
1247 CXXRecordDecl *BaseClassDecl
1248 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1249
1250 // Ignore trivial destructors.
1251 if (BaseClassDecl->hasTrivialDestructor())
1252 continue;
1253 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext());
1254
Anders Carlssonbea9e742010-04-24 21:51:08 +00001255 llvm::Value *V = OldGetAddressOfBaseClass(LoadCXXThis(),
1256 ClassDecl, BaseClassDecl);
Anders Carlssonfb404882009-12-24 22:46:43 +00001257 EmitCXXDestructorCall(D, Dtor_Base, V);
1258 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001259}
1260
Anders Carlsson27da15b2010-01-01 20:29:01 +00001261/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
1262/// for-loop to call the default constructor on individual members of the
1263/// array.
1264/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
1265/// array type and 'ArrayPtr' points to the beginning fo the array.
1266/// It is assumed that all relevant checks have been made by the caller.
1267void
1268CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1269 const ConstantArrayType *ArrayTy,
1270 llvm::Value *ArrayPtr,
1271 CallExpr::const_arg_iterator ArgBeg,
1272 CallExpr::const_arg_iterator ArgEnd) {
1273
1274 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1275 llvm::Value * NumElements =
1276 llvm::ConstantInt::get(SizeTy,
1277 getContext().getConstantArrayElementCount(ArrayTy));
1278
1279 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd);
1280}
1281
1282void
1283CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1284 llvm::Value *NumElements,
1285 llvm::Value *ArrayPtr,
1286 CallExpr::const_arg_iterator ArgBeg,
1287 CallExpr::const_arg_iterator ArgEnd) {
1288 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1289
1290 // Create a temporary for the loop index and initialize it with 0.
1291 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1292 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1293 Builder.CreateStore(Zero, IndexPtr);
1294
1295 // Start the loop with a block that tests the condition.
1296 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1297 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1298
1299 EmitBlock(CondBlock);
1300
1301 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1302
1303 // Generate: if (loop-index < number-of-elements fall to the loop body,
1304 // otherwise, go to the block after the for-loop.
1305 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1306 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1307 // If the condition is true, execute the body.
1308 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1309
1310 EmitBlock(ForBody);
1311
1312 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1313 // Inside the loop body, emit the constructor call on the array element.
1314 Counter = Builder.CreateLoad(IndexPtr);
1315 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1316 "arrayidx");
1317
1318 // C++ [class.temporary]p4:
1319 // There are two contexts in which temporaries are destroyed at a different
1320 // point than the end of the full-expression. The first context is when a
1321 // default constructor is called to initialize an element of an array.
1322 // If the constructor has one or more default arguments, the destruction of
1323 // every temporary created in a default argument expression is sequenced
1324 // before the construction of the next array element, if any.
1325
1326 // Keep track of the current number of live temporaries.
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001327 {
1328 CXXTemporariesCleanupScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001329
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001330 EmitCXXConstructorCall(D, Ctor_Complete, Address, ArgBeg, ArgEnd);
1331 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001332
Anders Carlsson27da15b2010-01-01 20:29:01 +00001333 EmitBlock(ContinueBlock);
1334
1335 // Emit the increment of the loop counter.
1336 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1337 Counter = Builder.CreateLoad(IndexPtr);
1338 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1339 Builder.CreateStore(NextVal, IndexPtr);
1340
1341 // Finally, branch back up to the condition for the next iteration.
1342 EmitBranch(CondBlock);
1343
1344 // Emit the fall-through block.
1345 EmitBlock(AfterFor, true);
1346}
1347
1348/// EmitCXXAggrDestructorCall - calls the default destructor on array
1349/// elements in reverse order of construction.
1350void
1351CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1352 const ArrayType *Array,
1353 llvm::Value *This) {
1354 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1355 assert(CA && "Do we support VLA for destruction ?");
1356 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1357
1358 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1359 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1360 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1361}
1362
1363/// EmitCXXAggrDestructorCall - calls the default destructor on array
1364/// elements in reverse order of construction.
1365void
1366CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1367 llvm::Value *UpperCount,
1368 llvm::Value *This) {
1369 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1370 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1371
1372 // Create a temporary for the loop index and initialize it with count of
1373 // array elements.
1374 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1375
1376 // Store the number of elements in the index pointer.
1377 Builder.CreateStore(UpperCount, IndexPtr);
1378
1379 // Start the loop with a block that tests the condition.
1380 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1381 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1382
1383 EmitBlock(CondBlock);
1384
1385 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1386
1387 // Generate: if (loop-index != 0 fall to the loop body,
1388 // otherwise, go to the block after the for-loop.
1389 llvm::Value* zeroConstant =
1390 llvm::Constant::getNullValue(SizeLTy);
1391 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1392 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1393 "isne");
1394 // If the condition is true, execute the body.
1395 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1396
1397 EmitBlock(ForBody);
1398
1399 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1400 // Inside the loop body, emit the constructor call on the array element.
1401 Counter = Builder.CreateLoad(IndexPtr);
1402 Counter = Builder.CreateSub(Counter, One);
1403 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
1404 EmitCXXDestructorCall(D, Dtor_Complete, Address);
1405
1406 EmitBlock(ContinueBlock);
1407
1408 // Emit the decrement of the loop counter.
1409 Counter = Builder.CreateLoad(IndexPtr);
1410 Counter = Builder.CreateSub(Counter, One, "dec");
1411 Builder.CreateStore(Counter, IndexPtr);
1412
1413 // Finally, branch back up to the condition for the next iteration.
1414 EmitBranch(CondBlock);
1415
1416 // Emit the fall-through block.
1417 EmitBlock(AfterFor, true);
1418}
1419
1420/// GenerateCXXAggrDestructorHelper - Generates a helper function which when
1421/// invoked, calls the default destructor on array elements in reverse order of
1422/// construction.
1423llvm::Constant *
1424CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
1425 const ArrayType *Array,
1426 llvm::Value *This) {
1427 FunctionArgList Args;
1428 ImplicitParamDecl *Dst =
1429 ImplicitParamDecl::Create(getContext(), 0,
1430 SourceLocation(), 0,
1431 getContext().getPointerType(getContext().VoidTy));
1432 Args.push_back(std::make_pair(Dst, Dst->getType()));
1433
1434 llvm::SmallString<16> Name;
1435 llvm::raw_svector_ostream(Name) << "__tcf_" << (++UniqueAggrDestructorCount);
1436 QualType R = getContext().VoidTy;
John McCallab26cfa2010-02-05 21:31:56 +00001437 const CGFunctionInfo &FI
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001438 = CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001439 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false);
1440 llvm::Function *Fn =
1441 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
1442 Name.str(),
1443 &CGM.getModule());
1444 IdentifierInfo *II = &CGM.getContext().Idents.get(Name.str());
1445 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1446 getContext().getTranslationUnitDecl(),
1447 SourceLocation(), II, R, 0,
1448 FunctionDecl::Static,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001449 FunctionDecl::None,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001450 false, true);
1451 StartFunction(FD, R, Fn, Args, SourceLocation());
1452 QualType BaseElementTy = getContext().getBaseElementType(Array);
1453 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
1454 BasePtr = llvm::PointerType::getUnqual(BasePtr);
1455 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr);
1456 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
1457 FinishFunction();
1458 llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),
1459 0);
1460 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty);
1461 return m;
1462}
1463
Anders Carlssone36a6b32010-01-02 01:01:18 +00001464
Anders Carlsson27da15b2010-01-01 20:29:01 +00001465void
1466CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1467 CXXCtorType Type,
1468 llvm::Value *This,
1469 CallExpr::const_arg_iterator ArgBeg,
1470 CallExpr::const_arg_iterator ArgEnd) {
John McCallca972cd2010-02-06 00:25:16 +00001471 if (D->isTrivial()) {
1472 if (ArgBeg == ArgEnd) {
1473 // Trivial default constructor, no codegen required.
1474 assert(D->isDefaultConstructor() &&
1475 "trivial 0-arg ctor not a default ctor");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001476 return;
1477 }
John McCallca972cd2010-02-06 00:25:16 +00001478
1479 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1480 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1481
John McCallca972cd2010-02-06 00:25:16 +00001482 const Expr *E = (*ArgBeg);
1483 QualType Ty = E->getType();
1484 llvm::Value *Src = EmitLValue(E).getAddress();
1485 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001486 return;
1487 }
1488
Anders Carlssone36a6b32010-01-02 01:01:18 +00001489 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type));
Anders Carlsson27da15b2010-01-01 20:29:01 +00001490 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1491
Anders Carlssone36a6b32010-01-02 01:01:18 +00001492 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001493}
1494
John McCallf8ff7b92010-02-23 00:48:20 +00001495void
1496CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1497 CXXCtorType CtorType,
1498 const FunctionArgList &Args) {
1499 CallArgList DelegateArgs;
1500
1501 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1502 assert(I != E && "no parameters to constructor");
1503
1504 // this
1505 DelegateArgs.push_back(std::make_pair(RValue::get(LoadCXXThis()),
1506 I->second));
1507 ++I;
1508
1509 // vtt
1510 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType))) {
1511 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1512 DelegateArgs.push_back(std::make_pair(RValue::get(VTT), VoidPP));
1513
Anders Carlssona864caf2010-03-23 04:11:45 +00001514 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001515 assert(I != E && "cannot skip vtt parameter, already done with args");
1516 assert(I->second == VoidPP && "skipping parameter not of vtt type");
1517 ++I;
1518 }
1519 }
1520
1521 // Explicit arguments.
1522 for (; I != E; ++I) {
1523
1524 const VarDecl *Param = I->first;
1525 QualType ArgType = Param->getType(); // because we're passing it to itself
1526
1527 // StartFunction converted the ABI-lowered parameter(s) into a
1528 // local alloca. We need to turn that into an r-value suitable
1529 // for EmitCall.
1530 llvm::Value *Local = GetAddrOfLocalVar(Param);
1531 RValue Arg;
1532
1533 // For the most part, we just need to load the alloca, except:
1534 // 1) aggregate r-values are actually pointers to temporaries, and
1535 // 2) references to aggregates are pointers directly to the aggregate.
1536 // I don't know why references to non-aggregates are different here.
1537 if (ArgType->isReferenceType()) {
1538 const ReferenceType *RefType = ArgType->getAs<ReferenceType>();
1539 if (hasAggregateLLVMType(RefType->getPointeeType()))
1540 Arg = RValue::getAggregate(Local);
1541 else
1542 // Locals which are references to scalars are represented
1543 // with allocas holding the pointer.
1544 Arg = RValue::get(Builder.CreateLoad(Local));
1545 } else {
1546 if (hasAggregateLLVMType(ArgType))
1547 Arg = RValue::getAggregate(Local);
1548 else
1549 Arg = RValue::get(EmitLoadOfScalar(Local, false, ArgType));
1550 }
1551
1552 DelegateArgs.push_back(std::make_pair(Arg, ArgType));
1553 }
1554
1555 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1556 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1557 ReturnValueSlot(), DelegateArgs, Ctor);
1558}
1559
Anders Carlsson27da15b2010-01-01 20:29:01 +00001560void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1561 CXXDtorType Type,
1562 llvm::Value *This) {
Anders Carlssone36a6b32010-01-02 01:01:18 +00001563 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type));
Anders Carlsson27da15b2010-01-01 20:29:01 +00001564 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1565
Anders Carlssone36a6b32010-01-02 01:01:18 +00001566 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001567}
1568
1569llvm::Value *
Anders Carlsson84673e22010-01-31 01:36:53 +00001570CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1571 const CXXRecordDecl *ClassDecl,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001572 const CXXRecordDecl *BaseClassDecl) {
1573 const llvm::Type *Int8PtrTy =
1574 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1575
1576 llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1577 Int8PtrTy->getPointerTo());
1578 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1579
Anders Carlsson4cbe83c2010-03-11 07:15:17 +00001580 int64_t VBaseOffsetOffset =
Anders Carlssona864caf2010-03-23 04:11:45 +00001581 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001582
1583 llvm::Value *VBaseOffsetPtr =
Anders Carlsson4cbe83c2010-03-11 07:15:17 +00001584 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset, "vbase.offset.ptr");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001585 const llvm::Type *PtrDiffTy =
1586 ConvertType(getContext().getPointerDiffType());
1587
1588 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1589 PtrDiffTy->getPointerTo());
1590
1591 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1592
1593 return VBaseOffset;
1594}
1595
Anders Carlssone87fae92010-03-28 19:40:00 +00001596void
1597CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001598 const CXXRecordDecl *NearestVBase,
Anders Carlssone87fae92010-03-28 19:40:00 +00001599 llvm::Constant *VTable,
1600 const CXXRecordDecl *VTableClass) {
Anders Carlsson58890272010-03-29 01:08:49 +00001601 const CXXRecordDecl *RD = Base.getBase();
1602
Anders Carlssone87fae92010-03-28 19:40:00 +00001603 // Compute the address point.
Anders Carlsson58890272010-03-29 01:08:49 +00001604 llvm::Value *VTableAddressPoint;
Anders Carlsson383f4cc2010-03-29 02:38:51 +00001605
Anders Carlsson58890272010-03-29 01:08:49 +00001606 // Check if we need to use a vtable from the VTT.
Anders Carlsson383f4cc2010-03-29 02:38:51 +00001607 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlsson652758c2010-04-20 05:22:15 +00001608 (RD->getNumVBases() || NearestVBase)) {
Anders Carlsson58890272010-03-29 01:08:49 +00001609 // Get the secondary vpointer index.
1610 uint64_t VirtualPointerIndex =
1611 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1612
1613 /// Load the VTT.
1614 llvm::Value *VTT = LoadCXXVTT();
1615 if (VirtualPointerIndex)
1616 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1617
1618 // And load the address point from the VTT.
1619 VTableAddressPoint = Builder.CreateLoad(VTT);
1620 } else {
Anders Carlssonf6f24c62010-03-29 02:08:26 +00001621 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlsson58890272010-03-29 01:08:49 +00001622 VTableAddressPoint =
Anders Carlssone87fae92010-03-28 19:40:00 +00001623 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlsson58890272010-03-29 01:08:49 +00001624 }
Anders Carlssone87fae92010-03-28 19:40:00 +00001625
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001626 // Compute where to store the address point.
Anders Carlsson91baecf2010-04-20 18:05:10 +00001627 llvm::Value *VTableField;
1628
1629 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1630 // We need to use the virtual base offset offset because the virtual base
1631 // might have a different offset in the most derived class.
Anders Carlssonbea9e742010-04-24 21:51:08 +00001632 VTableField = OldGetAddressOfBaseClass(LoadCXXThis(), VTableClass, RD);
Anders Carlsson91baecf2010-04-20 18:05:10 +00001633 } else {
1634 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001635
Anders Carlsson91baecf2010-04-20 18:05:10 +00001636 VTableField = Builder.CreateBitCast(LoadCXXThis(), Int8PtrTy);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001637 VTableField =
Anders Carlsson91baecf2010-04-20 18:05:10 +00001638 Builder.CreateConstInBoundsGEP1_64(VTableField, Base.getBaseOffset() / 8);
1639 }
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001640
Anders Carlssone87fae92010-03-28 19:40:00 +00001641 // Finally, store the address point.
1642 const llvm::Type *AddressPointPtrTy =
1643 VTableAddressPoint->getType()->getPointerTo();
1644 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1645 Builder.CreateStore(VTableAddressPoint, VTableField);
1646}
1647
Anders Carlssond5895932010-03-28 21:07:49 +00001648void
1649CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001650 const CXXRecordDecl *NearestVBase,
Anders Carlssond5895932010-03-28 21:07:49 +00001651 bool BaseIsNonVirtualPrimaryBase,
1652 llvm::Constant *VTable,
1653 const CXXRecordDecl *VTableClass,
1654 VisitedVirtualBasesSetTy& VBases) {
1655 // If this base is a non-virtual primary base the address point has already
1656 // been set.
1657 if (!BaseIsNonVirtualPrimaryBase) {
1658 // Initialize the vtable pointer for this base.
Anders Carlsson91baecf2010-04-20 18:05:10 +00001659 InitializeVTablePointer(Base, NearestVBase, VTable, VTableClass);
Anders Carlssond5895932010-03-28 21:07:49 +00001660 }
1661
1662 const CXXRecordDecl *RD = Base.getBase();
1663
1664 // Traverse bases.
1665 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1666 E = RD->bases_end(); I != E; ++I) {
1667 CXXRecordDecl *BaseDecl
1668 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1669
1670 // Ignore classes without a vtable.
1671 if (!BaseDecl->isDynamicClass())
1672 continue;
1673
1674 uint64_t BaseOffset;
Anders Carlsson948d3f42010-03-29 01:16:41 +00001675 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00001676
1677 if (I->isVirtual()) {
1678 // Check if we've visited this virtual base before.
1679 if (!VBases.insert(BaseDecl))
1680 continue;
1681
1682 const ASTRecordLayout &Layout =
1683 getContext().getASTRecordLayout(VTableClass);
1684
Anders Carlssond5895932010-03-28 21:07:49 +00001685 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00001686 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00001687 } else {
1688 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1689
1690 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00001691 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00001692 }
1693
1694 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlsson652758c2010-04-20 05:22:15 +00001695 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson948d3f42010-03-29 01:16:41 +00001696 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlssond5895932010-03-28 21:07:49 +00001697 VTable, VTableClass, VBases);
1698 }
1699}
1700
1701void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1702 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00001703 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00001704 return;
1705
Anders Carlsson1f9348c2010-03-26 04:39:42 +00001706 // Get the VTable.
1707 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlssonb35ea552010-03-24 03:57:14 +00001708
Anders Carlssond5895932010-03-28 21:07:49 +00001709 // Initialize the vtable pointers for this class and all of its bases.
1710 VisitedVirtualBasesSetTy VBases;
Anders Carlsson652758c2010-04-20 05:22:15 +00001711 InitializeVTablePointers(BaseSubobject(RD, 0), /*NearestVBase=*/0,
Anders Carlssond5895932010-03-28 21:07:49 +00001712 /*BaseIsNonVirtualPrimaryBase=*/false,
1713 VTable, RD, VBases);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001714}