clang API Documentation
00001 //===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This contains code dealing with C++ code generation of classes 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "CGBlocks.h" 00015 #include "CGDebugInfo.h" 00016 #include "CodeGenFunction.h" 00017 #include "clang/AST/CXXInheritance.h" 00018 #include "clang/AST/EvaluatedExprVisitor.h" 00019 #include "clang/AST/RecordLayout.h" 00020 #include "clang/AST/StmtCXX.h" 00021 #include "clang/Frontend/CodeGenOptions.h" 00022 00023 using namespace clang; 00024 using namespace CodeGen; 00025 00026 static CharUnits 00027 ComputeNonVirtualBaseClassOffset(ASTContext &Context, 00028 const CXXRecordDecl *DerivedClass, 00029 CastExpr::path_const_iterator Start, 00030 CastExpr::path_const_iterator End) { 00031 CharUnits Offset = CharUnits::Zero(); 00032 00033 const CXXRecordDecl *RD = DerivedClass; 00034 00035 for (CastExpr::path_const_iterator I = Start; I != End; ++I) { 00036 const CXXBaseSpecifier *Base = *I; 00037 assert(!Base->isVirtual() && "Should not see virtual bases here!"); 00038 00039 // Get the layout. 00040 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 00041 00042 const CXXRecordDecl *BaseDecl = 00043 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 00044 00045 // Add the offset. 00046 Offset += Layout.getBaseClassOffset(BaseDecl); 00047 00048 RD = BaseDecl; 00049 } 00050 00051 return Offset; 00052 } 00053 00054 llvm::Constant * 00055 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 00056 CastExpr::path_const_iterator PathBegin, 00057 CastExpr::path_const_iterator PathEnd) { 00058 assert(PathBegin != PathEnd && "Base path should not be empty!"); 00059 00060 CharUnits Offset = 00061 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl, 00062 PathBegin, PathEnd); 00063 if (Offset.isZero()) 00064 return 0; 00065 00066 llvm::Type *PtrDiffTy = 00067 Types.ConvertType(getContext().getPointerDiffType()); 00068 00069 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity()); 00070 } 00071 00072 /// Gets the address of a direct base class within a complete object. 00073 /// This should only be used for (1) non-virtual bases or (2) virtual bases 00074 /// when the type is known to be complete (e.g. in complete destructors). 00075 /// 00076 /// The object pointed to by 'This' is assumed to be non-null. 00077 llvm::Value * 00078 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This, 00079 const CXXRecordDecl *Derived, 00080 const CXXRecordDecl *Base, 00081 bool BaseIsVirtual) { 00082 // 'this' must be a pointer (in some address space) to Derived. 00083 assert(This->getType()->isPointerTy() && 00084 cast<llvm::PointerType>(This->getType())->getElementType() 00085 == ConvertType(Derived)); 00086 00087 // Compute the offset of the virtual base. 00088 CharUnits Offset; 00089 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived); 00090 if (BaseIsVirtual) 00091 Offset = Layout.getVBaseClassOffset(Base); 00092 else 00093 Offset = Layout.getBaseClassOffset(Base); 00094 00095 // Shift and cast down to the base type. 00096 // TODO: for complete types, this should be possible with a GEP. 00097 llvm::Value *V = This; 00098 if (Offset.isPositive()) { 00099 V = Builder.CreateBitCast(V, Int8PtrTy); 00100 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity()); 00101 } 00102 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo()); 00103 00104 return V; 00105 } 00106 00107 static llvm::Value * 00108 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr, 00109 CharUnits NonVirtual, llvm::Value *Virtual) { 00110 llvm::Type *PtrDiffTy = 00111 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 00112 00113 llvm::Value *NonVirtualOffset = 0; 00114 if (!NonVirtual.isZero()) 00115 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, 00116 NonVirtual.getQuantity()); 00117 00118 llvm::Value *BaseOffset; 00119 if (Virtual) { 00120 if (NonVirtualOffset) 00121 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset); 00122 else 00123 BaseOffset = Virtual; 00124 } else 00125 BaseOffset = NonVirtualOffset; 00126 00127 // Apply the base offset. 00128 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, CGF.Int8PtrTy); 00129 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr"); 00130 00131 return ThisPtr; 00132 } 00133 00134 llvm::Value * 00135 CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value, 00136 const CXXRecordDecl *Derived, 00137 CastExpr::path_const_iterator PathBegin, 00138 CastExpr::path_const_iterator PathEnd, 00139 bool NullCheckValue) { 00140 assert(PathBegin != PathEnd && "Base path should not be empty!"); 00141 00142 CastExpr::path_const_iterator Start = PathBegin; 00143 const CXXRecordDecl *VBase = 0; 00144 00145 // Get the virtual base. 00146 if ((*Start)->isVirtual()) { 00147 VBase = 00148 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl()); 00149 ++Start; 00150 } 00151 00152 CharUnits NonVirtualOffset = 00153 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived, 00154 Start, PathEnd); 00155 00156 // Get the base pointer type. 00157 llvm::Type *BasePtrTy = 00158 ConvertType((PathEnd[-1])->getType())->getPointerTo(); 00159 00160 if (NonVirtualOffset.isZero() && !VBase) { 00161 // Just cast back. 00162 return Builder.CreateBitCast(Value, BasePtrTy); 00163 } 00164 00165 llvm::BasicBlock *CastNull = 0; 00166 llvm::BasicBlock *CastNotNull = 0; 00167 llvm::BasicBlock *CastEnd = 0; 00168 00169 if (NullCheckValue) { 00170 CastNull = createBasicBlock("cast.null"); 00171 CastNotNull = createBasicBlock("cast.notnull"); 00172 CastEnd = createBasicBlock("cast.end"); 00173 00174 llvm::Value *IsNull = Builder.CreateIsNull(Value); 00175 Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 00176 EmitBlock(CastNotNull); 00177 } 00178 00179 llvm::Value *VirtualOffset = 0; 00180 00181 if (VBase) { 00182 if (Derived->hasAttr<FinalAttr>()) { 00183 VirtualOffset = 0; 00184 00185 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived); 00186 00187 CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase); 00188 NonVirtualOffset += VBaseOffset; 00189 } else 00190 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase); 00191 } 00192 00193 // Apply the offsets. 00194 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, 00195 NonVirtualOffset, 00196 VirtualOffset); 00197 00198 // Cast back. 00199 Value = Builder.CreateBitCast(Value, BasePtrTy); 00200 00201 if (NullCheckValue) { 00202 Builder.CreateBr(CastEnd); 00203 EmitBlock(CastNull); 00204 Builder.CreateBr(CastEnd); 00205 EmitBlock(CastEnd); 00206 00207 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 00208 PHI->addIncoming(Value, CastNotNull); 00209 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), 00210 CastNull); 00211 Value = PHI; 00212 } 00213 00214 return Value; 00215 } 00216 00217 llvm::Value * 00218 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value, 00219 const CXXRecordDecl *Derived, 00220 CastExpr::path_const_iterator PathBegin, 00221 CastExpr::path_const_iterator PathEnd, 00222 bool NullCheckValue) { 00223 assert(PathBegin != PathEnd && "Base path should not be empty!"); 00224 00225 QualType DerivedTy = 00226 getContext().getCanonicalType(getContext().getTagDeclType(Derived)); 00227 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo(); 00228 00229 llvm::Value *NonVirtualOffset = 00230 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd); 00231 00232 if (!NonVirtualOffset) { 00233 // No offset, we can just cast back. 00234 return Builder.CreateBitCast(Value, DerivedPtrTy); 00235 } 00236 00237 llvm::BasicBlock *CastNull = 0; 00238 llvm::BasicBlock *CastNotNull = 0; 00239 llvm::BasicBlock *CastEnd = 0; 00240 00241 if (NullCheckValue) { 00242 CastNull = createBasicBlock("cast.null"); 00243 CastNotNull = createBasicBlock("cast.notnull"); 00244 CastEnd = createBasicBlock("cast.end"); 00245 00246 llvm::Value *IsNull = Builder.CreateIsNull(Value); 00247 Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 00248 EmitBlock(CastNotNull); 00249 } 00250 00251 // Apply the offset. 00252 Value = Builder.CreateBitCast(Value, Int8PtrTy); 00253 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset), 00254 "sub.ptr"); 00255 00256 // Just cast. 00257 Value = Builder.CreateBitCast(Value, DerivedPtrTy); 00258 00259 if (NullCheckValue) { 00260 Builder.CreateBr(CastEnd); 00261 EmitBlock(CastNull); 00262 Builder.CreateBr(CastEnd); 00263 EmitBlock(CastEnd); 00264 00265 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 00266 PHI->addIncoming(Value, CastNotNull); 00267 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), 00268 CastNull); 00269 Value = PHI; 00270 } 00271 00272 return Value; 00273 } 00274 00275 /// GetVTTParameter - Return the VTT parameter that should be passed to a 00276 /// base constructor/destructor with virtual bases. 00277 static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD, 00278 bool ForVirtualBase) { 00279 if (!CodeGenVTables::needsVTTParameter(GD)) { 00280 // This constructor/destructor does not need a VTT parameter. 00281 return 0; 00282 } 00283 00284 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent(); 00285 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent(); 00286 00287 llvm::Value *VTT; 00288 00289 uint64_t SubVTTIndex; 00290 00291 // If the record matches the base, this is the complete ctor/dtor 00292 // variant calling the base variant in a class with virtual bases. 00293 if (RD == Base) { 00294 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) && 00295 "doing no-op VTT offset in base dtor/ctor?"); 00296 assert(!ForVirtualBase && "Can't have same class as virtual base!"); 00297 SubVTTIndex = 0; 00298 } else { 00299 const ASTRecordLayout &Layout = 00300 CGF.getContext().getASTRecordLayout(RD); 00301 CharUnits BaseOffset = ForVirtualBase ? 00302 Layout.getVBaseClassOffset(Base) : 00303 Layout.getBaseClassOffset(Base); 00304 00305 SubVTTIndex = 00306 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset)); 00307 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!"); 00308 } 00309 00310 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) { 00311 // A VTT parameter was passed to the constructor, use it. 00312 VTT = CGF.LoadCXXVTT(); 00313 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex); 00314 } else { 00315 // We're the complete constructor, so get the VTT by name. 00316 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD); 00317 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex); 00318 } 00319 00320 return VTT; 00321 } 00322 00323 namespace { 00324 /// Call the destructor for a direct base class. 00325 struct CallBaseDtor : EHScopeStack::Cleanup { 00326 const CXXRecordDecl *BaseClass; 00327 bool BaseIsVirtual; 00328 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual) 00329 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {} 00330 00331 void Emit(CodeGenFunction &CGF, Flags flags) { 00332 const CXXRecordDecl *DerivedClass = 00333 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent(); 00334 00335 const CXXDestructorDecl *D = BaseClass->getDestructor(); 00336 llvm::Value *Addr = 00337 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(), 00338 DerivedClass, BaseClass, 00339 BaseIsVirtual); 00340 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr); 00341 } 00342 }; 00343 00344 /// A visitor which checks whether an initializer uses 'this' in a 00345 /// way which requires the vtable to be properly set. 00346 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> { 00347 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super; 00348 00349 bool UsesThis; 00350 00351 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {} 00352 00353 // Black-list all explicit and implicit references to 'this'. 00354 // 00355 // Do we need to worry about external references to 'this' derived 00356 // from arbitrary code? If so, then anything which runs arbitrary 00357 // external code might potentially access the vtable. 00358 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; } 00359 }; 00360 } 00361 00362 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) { 00363 DynamicThisUseChecker Checker(C); 00364 Checker.Visit(const_cast<Expr*>(Init)); 00365 return Checker.UsesThis; 00366 } 00367 00368 static void EmitBaseInitializer(CodeGenFunction &CGF, 00369 const CXXRecordDecl *ClassDecl, 00370 CXXCtorInitializer *BaseInit, 00371 CXXCtorType CtorType) { 00372 assert(BaseInit->isBaseInitializer() && 00373 "Must have base initializer!"); 00374 00375 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 00376 00377 const Type *BaseType = BaseInit->getBaseClass(); 00378 CXXRecordDecl *BaseClassDecl = 00379 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()); 00380 00381 bool isBaseVirtual = BaseInit->isBaseVirtual(); 00382 00383 // The base constructor doesn't construct virtual bases. 00384 if (CtorType == Ctor_Base && isBaseVirtual) 00385 return; 00386 00387 // If the initializer for the base (other than the constructor 00388 // itself) accesses 'this' in any way, we need to initialize the 00389 // vtables. 00390 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit())) 00391 CGF.InitializeVTablePointers(ClassDecl); 00392 00393 // We can pretend to be a complete class because it only matters for 00394 // virtual bases, and we only do virtual bases for complete ctors. 00395 llvm::Value *V = 00396 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl, 00397 BaseClassDecl, 00398 isBaseVirtual); 00399 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType); 00400 AggValueSlot AggSlot = 00401 AggValueSlot::forAddr(V, Alignment, Qualifiers(), 00402 AggValueSlot::IsDestructed, 00403 AggValueSlot::DoesNotNeedGCBarriers, 00404 AggValueSlot::IsNotAliased); 00405 00406 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot); 00407 00408 if (CGF.CGM.getLangOpts().Exceptions && 00409 !BaseClassDecl->hasTrivialDestructor()) 00410 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl, 00411 isBaseVirtual); 00412 } 00413 00414 static void EmitAggMemberInitializer(CodeGenFunction &CGF, 00415 LValue LHS, 00416 Expr *Init, 00417 llvm::Value *ArrayIndexVar, 00418 QualType T, 00419 ArrayRef<VarDecl *> ArrayIndexes, 00420 unsigned Index) { 00421 if (Index == ArrayIndexes.size()) { 00422 LValue LV = LHS; 00423 { // Scope for Cleanups. 00424 CodeGenFunction::RunCleanupsScope Cleanups(CGF); 00425 00426 if (ArrayIndexVar) { 00427 // If we have an array index variable, load it and use it as an offset. 00428 // Then, increment the value. 00429 llvm::Value *Dest = LHS.getAddress(); 00430 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar); 00431 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress"); 00432 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1); 00433 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc"); 00434 CGF.Builder.CreateStore(Next, ArrayIndexVar); 00435 00436 // Update the LValue. 00437 LV.setAddress(Dest); 00438 CharUnits Align = CGF.getContext().getTypeAlignInChars(T); 00439 LV.setAlignment(std::min(Align, LV.getAlignment())); 00440 } 00441 00442 if (!CGF.hasAggregateLLVMType(T)) { 00443 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false); 00444 } else if (T->isAnyComplexType()) { 00445 CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(), 00446 LV.isVolatileQualified()); 00447 } else { 00448 AggValueSlot Slot = 00449 AggValueSlot::forLValue(LV, 00450 AggValueSlot::IsDestructed, 00451 AggValueSlot::DoesNotNeedGCBarriers, 00452 AggValueSlot::IsNotAliased); 00453 00454 CGF.EmitAggExpr(Init, Slot); 00455 } 00456 } 00457 00458 // Now, outside of the initializer cleanup scope, destroy the backing array 00459 // for a std::initializer_list member. 00460 CGF.MaybeEmitStdInitializerListCleanup(LV.getAddress(), Init); 00461 00462 return; 00463 } 00464 00465 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T); 00466 assert(Array && "Array initialization without the array type?"); 00467 llvm::Value *IndexVar 00468 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]); 00469 assert(IndexVar && "Array index variable not loaded"); 00470 00471 // Initialize this index variable to zero. 00472 llvm::Value* Zero 00473 = llvm::Constant::getNullValue( 00474 CGF.ConvertType(CGF.getContext().getSizeType())); 00475 CGF.Builder.CreateStore(Zero, IndexVar); 00476 00477 // Start the loop with a block that tests the condition. 00478 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond"); 00479 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end"); 00480 00481 CGF.EmitBlock(CondBlock); 00482 00483 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body"); 00484 // Generate: if (loop-index < number-of-elements) fall to the loop body, 00485 // otherwise, go to the block after the for-loop. 00486 uint64_t NumElements = Array->getSize().getZExtValue(); 00487 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar); 00488 llvm::Value *NumElementsPtr = 00489 llvm::ConstantInt::get(Counter->getType(), NumElements); 00490 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr, 00491 "isless"); 00492 00493 // If the condition is true, execute the body. 00494 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor); 00495 00496 CGF.EmitBlock(ForBody); 00497 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc"); 00498 00499 { 00500 CodeGenFunction::RunCleanupsScope Cleanups(CGF); 00501 00502 // Inside the loop body recurse to emit the inner loop or, eventually, the 00503 // constructor call. 00504 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar, 00505 Array->getElementType(), ArrayIndexes, Index + 1); 00506 } 00507 00508 CGF.EmitBlock(ContinueBlock); 00509 00510 // Emit the increment of the loop counter. 00511 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1); 00512 Counter = CGF.Builder.CreateLoad(IndexVar); 00513 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc"); 00514 CGF.Builder.CreateStore(NextVal, IndexVar); 00515 00516 // Finally, branch back up to the condition for the next iteration. 00517 CGF.EmitBranch(CondBlock); 00518 00519 // Emit the fall-through block. 00520 CGF.EmitBlock(AfterFor, true); 00521 } 00522 00523 namespace { 00524 struct CallMemberDtor : EHScopeStack::Cleanup { 00525 llvm::Value *V; 00526 CXXDestructorDecl *Dtor; 00527 00528 CallMemberDtor(llvm::Value *V, CXXDestructorDecl *Dtor) 00529 : V(V), Dtor(Dtor) {} 00530 00531 void Emit(CodeGenFunction &CGF, Flags flags) { 00532 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false, 00533 V); 00534 } 00535 }; 00536 } 00537 00538 static bool hasTrivialCopyOrMoveConstructor(const CXXRecordDecl *Record, 00539 bool Moving) { 00540 return Moving ? Record->hasTrivialMoveConstructor() : 00541 Record->hasTrivialCopyConstructor(); 00542 } 00543 00544 static void EmitMemberInitializer(CodeGenFunction &CGF, 00545 const CXXRecordDecl *ClassDecl, 00546 CXXCtorInitializer *MemberInit, 00547 const CXXConstructorDecl *Constructor, 00548 FunctionArgList &Args) { 00549 assert(MemberInit->isAnyMemberInitializer() && 00550 "Must have member initializer!"); 00551 assert(MemberInit->getInit() && "Must have initializer!"); 00552 00553 // non-static data member initializers. 00554 FieldDecl *Field = MemberInit->getAnyMember(); 00555 QualType FieldType = Field->getType(); 00556 00557 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 00558 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl); 00559 LValue LHS; 00560 00561 // If we are initializing an anonymous union field, drill down to the field. 00562 if (MemberInit->isIndirectMemberInitializer()) { 00563 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr, 00564 MemberInit->getIndirectMember(), 0); 00565 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType(); 00566 } else { 00567 LValue ThisLHSLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy); 00568 LHS = CGF.EmitLValueForFieldInitialization(ThisLHSLV, Field); 00569 } 00570 00571 // Special case: if we are in a copy or move constructor, and we are copying 00572 // an array of PODs or classes with trivial copy constructors, ignore the 00573 // AST and perform the copy we know is equivalent. 00574 // FIXME: This is hacky at best... if we had a bit more explicit information 00575 // in the AST, we could generalize it more easily. 00576 const ConstantArrayType *Array 00577 = CGF.getContext().getAsConstantArrayType(FieldType); 00578 if (Array && Constructor->isImplicitlyDefined() && 00579 Constructor->isCopyOrMoveConstructor()) { 00580 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array); 00581 const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl(); 00582 if (BaseElementTy.isPODType(CGF.getContext()) || 00583 (Record && hasTrivialCopyOrMoveConstructor(Record, 00584 Constructor->isMoveConstructor()))) { 00585 // Find the source pointer. We knows it's the last argument because 00586 // we know we're in a copy constructor. 00587 unsigned SrcArgIndex = Args.size() - 1; 00588 llvm::Value *SrcPtr 00589 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex])); 00590 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy); 00591 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field); 00592 00593 // Copy the aggregate. 00594 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType, 00595 LHS.isVolatileQualified()); 00596 return; 00597 } 00598 } 00599 00600 ArrayRef<VarDecl *> ArrayIndexes; 00601 if (MemberInit->getNumArrayIndices()) 00602 ArrayIndexes = MemberInit->getArrayIndexes(); 00603 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes); 00604 } 00605 00606 void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, 00607 LValue LHS, Expr *Init, 00608 ArrayRef<VarDecl *> ArrayIndexes) { 00609 QualType FieldType = Field->getType(); 00610 if (!hasAggregateLLVMType(FieldType)) { 00611 if (LHS.isSimple()) { 00612 EmitExprAsInit(Init, Field, LHS, false); 00613 } else { 00614 RValue RHS = RValue::get(EmitScalarExpr(Init)); 00615 EmitStoreThroughLValue(RHS, LHS); 00616 } 00617 } else if (FieldType->isAnyComplexType()) { 00618 EmitComplexExprIntoAddr(Init, LHS.getAddress(), LHS.isVolatileQualified()); 00619 } else { 00620 llvm::Value *ArrayIndexVar = 0; 00621 if (ArrayIndexes.size()) { 00622 llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 00623 00624 // The LHS is a pointer to the first object we'll be constructing, as 00625 // a flat array. 00626 QualType BaseElementTy = getContext().getBaseElementType(FieldType); 00627 llvm::Type *BasePtr = ConvertType(BaseElementTy); 00628 BasePtr = llvm::PointerType::getUnqual(BasePtr); 00629 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(), 00630 BasePtr); 00631 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy); 00632 00633 // Create an array index that will be used to walk over all of the 00634 // objects we're constructing. 00635 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index"); 00636 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy); 00637 Builder.CreateStore(Zero, ArrayIndexVar); 00638 00639 00640 // Emit the block variables for the array indices, if any. 00641 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I) 00642 EmitAutoVarDecl(*ArrayIndexes[I]); 00643 } 00644 00645 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType, 00646 ArrayIndexes, 0); 00647 00648 if (!CGM.getLangOpts().Exceptions) 00649 return; 00650 00651 // FIXME: If we have an array of classes w/ non-trivial destructors, 00652 // we need to destroy in reverse order of construction along the exception 00653 // path. 00654 const RecordType *RT = FieldType->getAs<RecordType>(); 00655 if (!RT) 00656 return; 00657 00658 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 00659 if (!RD->hasTrivialDestructor()) 00660 EHStack.pushCleanup<CallMemberDtor>(EHCleanup, LHS.getAddress(), 00661 RD->getDestructor()); 00662 } 00663 } 00664 00665 /// Checks whether the given constructor is a valid subject for the 00666 /// complete-to-base constructor delegation optimization, i.e. 00667 /// emitting the complete constructor as a simple call to the base 00668 /// constructor. 00669 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) { 00670 00671 // Currently we disable the optimization for classes with virtual 00672 // bases because (1) the addresses of parameter variables need to be 00673 // consistent across all initializers but (2) the delegate function 00674 // call necessarily creates a second copy of the parameter variable. 00675 // 00676 // The limiting example (purely theoretical AFAIK): 00677 // struct A { A(int &c) { c++; } }; 00678 // struct B : virtual A { 00679 // B(int count) : A(count) { printf("%d\n", count); } 00680 // }; 00681 // ...although even this example could in principle be emitted as a 00682 // delegation since the address of the parameter doesn't escape. 00683 if (Ctor->getParent()->getNumVBases()) { 00684 // TODO: white-list trivial vbase initializers. This case wouldn't 00685 // be subject to the restrictions below. 00686 00687 // TODO: white-list cases where: 00688 // - there are no non-reference parameters to the constructor 00689 // - the initializers don't access any non-reference parameters 00690 // - the initializers don't take the address of non-reference 00691 // parameters 00692 // - etc. 00693 // If we ever add any of the above cases, remember that: 00694 // - function-try-blocks will always blacklist this optimization 00695 // - we need to perform the constructor prologue and cleanup in 00696 // EmitConstructorBody. 00697 00698 return false; 00699 } 00700 00701 // We also disable the optimization for variadic functions because 00702 // it's impossible to "re-pass" varargs. 00703 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic()) 00704 return false; 00705 00706 // FIXME: Decide if we can do a delegation of a delegating constructor. 00707 if (Ctor->isDelegatingConstructor()) 00708 return false; 00709 00710 return true; 00711 } 00712 00713 /// EmitConstructorBody - Emits the body of the current constructor. 00714 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) { 00715 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl()); 00716 CXXCtorType CtorType = CurGD.getCtorType(); 00717 00718 // Before we go any further, try the complete->base constructor 00719 // delegation optimization. 00720 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) && 00721 CGM.getContext().getTargetInfo().getCXXABI() != CXXABI_Microsoft) { 00722 if (CGDebugInfo *DI = getDebugInfo()) 00723 DI->EmitLocation(Builder, Ctor->getLocEnd()); 00724 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args); 00725 return; 00726 } 00727 00728 Stmt *Body = Ctor->getBody(); 00729 00730 // Enter the function-try-block before the constructor prologue if 00731 // applicable. 00732 bool IsTryBody = (Body && isa<CXXTryStmt>(Body)); 00733 if (IsTryBody) 00734 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 00735 00736 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin(); 00737 00738 // TODO: in restricted cases, we can emit the vbase initializers of 00739 // a complete ctor and then delegate to the base ctor. 00740 00741 // Emit the constructor prologue, i.e. the base and member 00742 // initializers. 00743 EmitCtorPrologue(Ctor, CtorType, Args); 00744 00745 // Emit the body of the statement. 00746 if (IsTryBody) 00747 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 00748 else if (Body) 00749 EmitStmt(Body); 00750 00751 // Emit any cleanup blocks associated with the member or base 00752 // initializers, which includes (along the exceptional path) the 00753 // destructors for those members and bases that were fully 00754 // constructed. 00755 PopCleanupBlocks(CleanupDepth); 00756 00757 if (IsTryBody) 00758 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 00759 } 00760 00761 /// EmitCtorPrologue - This routine generates necessary code to initialize 00762 /// base classes and non-static data members belonging to this constructor. 00763 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD, 00764 CXXCtorType CtorType, 00765 FunctionArgList &Args) { 00766 if (CD->isDelegatingConstructor()) 00767 return EmitDelegatingCXXConstructorCall(CD, Args); 00768 00769 const CXXRecordDecl *ClassDecl = CD->getParent(); 00770 00771 SmallVector<CXXCtorInitializer *, 8> MemberInitializers; 00772 00773 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(), 00774 E = CD->init_end(); 00775 B != E; ++B) { 00776 CXXCtorInitializer *Member = (*B); 00777 00778 if (Member->isBaseInitializer()) { 00779 EmitBaseInitializer(*this, ClassDecl, Member, CtorType); 00780 } else { 00781 assert(Member->isAnyMemberInitializer() && 00782 "Delegating initializer on non-delegating constructor"); 00783 MemberInitializers.push_back(Member); 00784 } 00785 } 00786 00787 InitializeVTablePointers(ClassDecl); 00788 00789 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I) 00790 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args); 00791 } 00792 00793 static bool 00794 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field); 00795 00796 static bool 00797 HasTrivialDestructorBody(ASTContext &Context, 00798 const CXXRecordDecl *BaseClassDecl, 00799 const CXXRecordDecl *MostDerivedClassDecl) 00800 { 00801 // If the destructor is trivial we don't have to check anything else. 00802 if (BaseClassDecl->hasTrivialDestructor()) 00803 return true; 00804 00805 if (!BaseClassDecl->getDestructor()->hasTrivialBody()) 00806 return false; 00807 00808 // Check fields. 00809 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(), 00810 E = BaseClassDecl->field_end(); I != E; ++I) { 00811 const FieldDecl *Field = &*I; 00812 00813 if (!FieldHasTrivialDestructorBody(Context, Field)) 00814 return false; 00815 } 00816 00817 // Check non-virtual bases. 00818 for (CXXRecordDecl::base_class_const_iterator I = 00819 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end(); 00820 I != E; ++I) { 00821 if (I->isVirtual()) 00822 continue; 00823 00824 const CXXRecordDecl *NonVirtualBase = 00825 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl()); 00826 if (!HasTrivialDestructorBody(Context, NonVirtualBase, 00827 MostDerivedClassDecl)) 00828 return false; 00829 } 00830 00831 if (BaseClassDecl == MostDerivedClassDecl) { 00832 // Check virtual bases. 00833 for (CXXRecordDecl::base_class_const_iterator I = 00834 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end(); 00835 I != E; ++I) { 00836 const CXXRecordDecl *VirtualBase = 00837 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl()); 00838 if (!HasTrivialDestructorBody(Context, VirtualBase, 00839 MostDerivedClassDecl)) 00840 return false; 00841 } 00842 } 00843 00844 return true; 00845 } 00846 00847 static bool 00848 FieldHasTrivialDestructorBody(ASTContext &Context, 00849 const FieldDecl *Field) 00850 { 00851 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType()); 00852 00853 const RecordType *RT = FieldBaseElementType->getAs<RecordType>(); 00854 if (!RT) 00855 return true; 00856 00857 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 00858 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl); 00859 } 00860 00861 /// CanSkipVTablePointerInitialization - Check whether we need to initialize 00862 /// any vtable pointers before calling this destructor. 00863 static bool CanSkipVTablePointerInitialization(ASTContext &Context, 00864 const CXXDestructorDecl *Dtor) { 00865 if (!Dtor->hasTrivialBody()) 00866 return false; 00867 00868 // Check the fields. 00869 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 00870 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 00871 E = ClassDecl->field_end(); I != E; ++I) { 00872 const FieldDecl *Field = &*I; 00873 00874 if (!FieldHasTrivialDestructorBody(Context, Field)) 00875 return false; 00876 } 00877 00878 return true; 00879 } 00880 00881 /// EmitDestructorBody - Emits the body of the current destructor. 00882 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) { 00883 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl()); 00884 CXXDtorType DtorType = CurGD.getDtorType(); 00885 00886 // The call to operator delete in a deleting destructor happens 00887 // outside of the function-try-block, which means it's always 00888 // possible to delegate the destructor body to the complete 00889 // destructor. Do so. 00890 if (DtorType == Dtor_Deleting) { 00891 EnterDtorCleanups(Dtor, Dtor_Deleting); 00892 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false, 00893 LoadCXXThis()); 00894 PopCleanupBlock(); 00895 return; 00896 } 00897 00898 Stmt *Body = Dtor->getBody(); 00899 00900 // If the body is a function-try-block, enter the try before 00901 // anything else. 00902 bool isTryBody = (Body && isa<CXXTryStmt>(Body)); 00903 if (isTryBody) 00904 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 00905 00906 // Enter the epilogue cleanups. 00907 RunCleanupsScope DtorEpilogue(*this); 00908 00909 // If this is the complete variant, just invoke the base variant; 00910 // the epilogue will destruct the virtual bases. But we can't do 00911 // this optimization if the body is a function-try-block, because 00912 // we'd introduce *two* handler blocks. 00913 switch (DtorType) { 00914 case Dtor_Deleting: llvm_unreachable("already handled deleting case"); 00915 00916 case Dtor_Complete: 00917 // Enter the cleanup scopes for virtual bases. 00918 EnterDtorCleanups(Dtor, Dtor_Complete); 00919 00920 if (!isTryBody && CGM.getContext().getTargetInfo().getCXXABI() != CXXABI_Microsoft) { 00921 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false, 00922 LoadCXXThis()); 00923 break; 00924 } 00925 // Fallthrough: act like we're in the base variant. 00926 00927 case Dtor_Base: 00928 // Enter the cleanup scopes for fields and non-virtual bases. 00929 EnterDtorCleanups(Dtor, Dtor_Base); 00930 00931 // Initialize the vtable pointers before entering the body. 00932 if (!CanSkipVTablePointerInitialization(getContext(), Dtor)) 00933 InitializeVTablePointers(Dtor->getParent()); 00934 00935 if (isTryBody) 00936 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 00937 else if (Body) 00938 EmitStmt(Body); 00939 else { 00940 assert(Dtor->isImplicit() && "bodyless dtor not implicit"); 00941 // nothing to do besides what's in the epilogue 00942 } 00943 // -fapple-kext must inline any call to this dtor into 00944 // the caller's body. 00945 if (getContext().getLangOpts().AppleKext) 00946 CurFn->addFnAttr(llvm::Attribute::AlwaysInline); 00947 break; 00948 } 00949 00950 // Jump out through the epilogue cleanups. 00951 DtorEpilogue.ForceCleanup(); 00952 00953 // Exit the try if applicable. 00954 if (isTryBody) 00955 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 00956 } 00957 00958 namespace { 00959 /// Call the operator delete associated with the current destructor. 00960 struct CallDtorDelete : EHScopeStack::Cleanup { 00961 CallDtorDelete() {} 00962 00963 void Emit(CodeGenFunction &CGF, Flags flags) { 00964 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl); 00965 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 00966 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(), 00967 CGF.getContext().getTagDeclType(ClassDecl)); 00968 } 00969 }; 00970 00971 class DestroyField : public EHScopeStack::Cleanup { 00972 const FieldDecl *field; 00973 CodeGenFunction::Destroyer *destroyer; 00974 bool useEHCleanupForArray; 00975 00976 public: 00977 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer, 00978 bool useEHCleanupForArray) 00979 : field(field), destroyer(destroyer), 00980 useEHCleanupForArray(useEHCleanupForArray) {} 00981 00982 void Emit(CodeGenFunction &CGF, Flags flags) { 00983 // Find the address of the field. 00984 llvm::Value *thisValue = CGF.LoadCXXThis(); 00985 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent()); 00986 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy); 00987 LValue LV = CGF.EmitLValueForField(ThisLV, field); 00988 assert(LV.isSimple()); 00989 00990 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer, 00991 flags.isForNormalCleanup() && useEHCleanupForArray); 00992 } 00993 }; 00994 } 00995 00996 /// EmitDtorEpilogue - Emit all code that comes at the end of class's 00997 /// destructor. This is to call destructors on members and base classes 00998 /// in reverse order of their construction. 00999 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD, 01000 CXXDtorType DtorType) { 01001 assert(!DD->isTrivial() && 01002 "Should not emit dtor epilogue for trivial dtor!"); 01003 01004 // The deleting-destructor phase just needs to call the appropriate 01005 // operator delete that Sema picked up. 01006 if (DtorType == Dtor_Deleting) { 01007 assert(DD->getOperatorDelete() && 01008 "operator delete missing - EmitDtorEpilogue"); 01009 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup); 01010 return; 01011 } 01012 01013 const CXXRecordDecl *ClassDecl = DD->getParent(); 01014 01015 // Unions have no bases and do not call field destructors. 01016 if (ClassDecl->isUnion()) 01017 return; 01018 01019 // The complete-destructor phase just destructs all the virtual bases. 01020 if (DtorType == Dtor_Complete) { 01021 01022 // We push them in the forward order so that they'll be popped in 01023 // the reverse order. 01024 for (CXXRecordDecl::base_class_const_iterator I = 01025 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end(); 01026 I != E; ++I) { 01027 const CXXBaseSpecifier &Base = *I; 01028 CXXRecordDecl *BaseClassDecl 01029 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 01030 01031 // Ignore trivial destructors. 01032 if (BaseClassDecl->hasTrivialDestructor()) 01033 continue; 01034 01035 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 01036 BaseClassDecl, 01037 /*BaseIsVirtual*/ true); 01038 } 01039 01040 return; 01041 } 01042 01043 assert(DtorType == Dtor_Base); 01044 01045 // Destroy non-virtual bases. 01046 for (CXXRecordDecl::base_class_const_iterator I = 01047 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) { 01048 const CXXBaseSpecifier &Base = *I; 01049 01050 // Ignore virtual bases. 01051 if (Base.isVirtual()) 01052 continue; 01053 01054 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl(); 01055 01056 // Ignore trivial destructors. 01057 if (BaseClassDecl->hasTrivialDestructor()) 01058 continue; 01059 01060 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 01061 BaseClassDecl, 01062 /*BaseIsVirtual*/ false); 01063 } 01064 01065 // Destroy direct fields. 01066 SmallVector<const FieldDecl *, 16> FieldDecls; 01067 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 01068 E = ClassDecl->field_end(); I != E; ++I) { 01069 const FieldDecl *field = &*I; 01070 QualType type = field->getType(); 01071 QualType::DestructionKind dtorKind = type.isDestructedType(); 01072 if (!dtorKind) continue; 01073 01074 // Anonymous union members do not have their destructors called. 01075 const RecordType *RT = type->getAsUnionType(); 01076 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue; 01077 01078 CleanupKind cleanupKind = getCleanupKind(dtorKind); 01079 EHStack.pushCleanup<DestroyField>(cleanupKind, field, 01080 getDestroyer(dtorKind), 01081 cleanupKind & EHCleanup); 01082 } 01083 } 01084 01085 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 01086 /// constructor for each of several members of an array. 01087 /// 01088 /// \param ctor the constructor to call for each element 01089 /// \param argBegin,argEnd the arguments to evaluate and pass to the 01090 /// constructor 01091 /// \param arrayType the type of the array to initialize 01092 /// \param arrayBegin an arrayType* 01093 /// \param zeroInitialize true if each element should be 01094 /// zero-initialized before it is constructed 01095 void 01096 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, 01097 const ConstantArrayType *arrayType, 01098 llvm::Value *arrayBegin, 01099 CallExpr::const_arg_iterator argBegin, 01100 CallExpr::const_arg_iterator argEnd, 01101 bool zeroInitialize) { 01102 QualType elementType; 01103 llvm::Value *numElements = 01104 emitArrayLength(arrayType, elementType, arrayBegin); 01105 01106 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, 01107 argBegin, argEnd, zeroInitialize); 01108 } 01109 01110 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 01111 /// constructor for each of several members of an array. 01112 /// 01113 /// \param ctor the constructor to call for each element 01114 /// \param numElements the number of elements in the array; 01115 /// may be zero 01116 /// \param argBegin,argEnd the arguments to evaluate and pass to the 01117 /// constructor 01118 /// \param arrayBegin a T*, where T is the type constructed by ctor 01119 /// \param zeroInitialize true if each element should be 01120 /// zero-initialized before it is constructed 01121 void 01122 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, 01123 llvm::Value *numElements, 01124 llvm::Value *arrayBegin, 01125 CallExpr::const_arg_iterator argBegin, 01126 CallExpr::const_arg_iterator argEnd, 01127 bool zeroInitialize) { 01128 01129 // It's legal for numElements to be zero. This can happen both 01130 // dynamically, because x can be zero in 'new A[x]', and statically, 01131 // because of GCC extensions that permit zero-length arrays. There 01132 // are probably legitimate places where we could assume that this 01133 // doesn't happen, but it's not clear that it's worth it. 01134 llvm::BranchInst *zeroCheckBranch = 0; 01135 01136 // Optimize for a constant count. 01137 llvm::ConstantInt *constantCount 01138 = dyn_cast<llvm::ConstantInt>(numElements); 01139 if (constantCount) { 01140 // Just skip out if the constant count is zero. 01141 if (constantCount->isZero()) return; 01142 01143 // Otherwise, emit the check. 01144 } else { 01145 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop"); 01146 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty"); 01147 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB); 01148 EmitBlock(loopBB); 01149 } 01150 01151 // Find the end of the array. 01152 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements, 01153 "arrayctor.end"); 01154 01155 // Enter the loop, setting up a phi for the current location to initialize. 01156 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 01157 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop"); 01158 EmitBlock(loopBB); 01159 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2, 01160 "arrayctor.cur"); 01161 cur->addIncoming(arrayBegin, entryBB); 01162 01163 // Inside the loop body, emit the constructor call on the array element. 01164 01165 QualType type = getContext().getTypeDeclType(ctor->getParent()); 01166 01167 // Zero initialize the storage, if requested. 01168 if (zeroInitialize) 01169 EmitNullInitialization(cur, type); 01170 01171 // C++ [class.temporary]p4: 01172 // There are two contexts in which temporaries are destroyed at a different 01173 // point than the end of the full-expression. The first context is when a 01174 // default constructor is called to initialize an element of an array. 01175 // If the constructor has one or more default arguments, the destruction of 01176 // every temporary created in a default argument expression is sequenced 01177 // before the construction of the next array element, if any. 01178 01179 { 01180 RunCleanupsScope Scope(*this); 01181 01182 // Evaluate the constructor and its arguments in a regular 01183 // partial-destroy cleanup. 01184 if (getLangOpts().Exceptions && 01185 !ctor->getParent()->hasTrivialDestructor()) { 01186 Destroyer *destroyer = destroyCXXObject; 01187 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer); 01188 } 01189 01190 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false, 01191 cur, argBegin, argEnd); 01192 } 01193 01194 // Go to the next element. 01195 llvm::Value *next = 01196 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1), 01197 "arrayctor.next"); 01198 cur->addIncoming(next, Builder.GetInsertBlock()); 01199 01200 // Check whether that's the end of the loop. 01201 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done"); 01202 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont"); 01203 Builder.CreateCondBr(done, contBB, loopBB); 01204 01205 // Patch the earlier check to skip over the loop. 01206 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB); 01207 01208 EmitBlock(contBB); 01209 } 01210 01211 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF, 01212 llvm::Value *addr, 01213 QualType type) { 01214 const RecordType *rtype = type->castAs<RecordType>(); 01215 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl()); 01216 const CXXDestructorDecl *dtor = record->getDestructor(); 01217 assert(!dtor->isTrivial()); 01218 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false, 01219 addr); 01220 } 01221 01222 void 01223 CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 01224 CXXCtorType Type, bool ForVirtualBase, 01225 llvm::Value *This, 01226 CallExpr::const_arg_iterator ArgBeg, 01227 CallExpr::const_arg_iterator ArgEnd) { 01228 01229 CGDebugInfo *DI = getDebugInfo(); 01230 if (DI && 01231 CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo) { 01232 // If debug info for this class has not been emitted then this is the 01233 // right time to do so. 01234 const CXXRecordDecl *Parent = D->getParent(); 01235 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent), 01236 Parent->getLocation()); 01237 } 01238 01239 if (D->isTrivial()) { 01240 if (ArgBeg == ArgEnd) { 01241 // Trivial default constructor, no codegen required. 01242 assert(D->isDefaultConstructor() && 01243 "trivial 0-arg ctor not a default ctor"); 01244 return; 01245 } 01246 01247 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor"); 01248 assert(D->isCopyOrMoveConstructor() && 01249 "trivial 1-arg ctor not a copy/move ctor"); 01250 01251 const Expr *E = (*ArgBeg); 01252 QualType Ty = E->getType(); 01253 llvm::Value *Src = EmitLValue(E).getAddress(); 01254 EmitAggregateCopy(This, Src, Ty); 01255 return; 01256 } 01257 01258 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase); 01259 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type); 01260 01261 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd); 01262 } 01263 01264 void 01265 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 01266 llvm::Value *This, llvm::Value *Src, 01267 CallExpr::const_arg_iterator ArgBeg, 01268 CallExpr::const_arg_iterator ArgEnd) { 01269 if (D->isTrivial()) { 01270 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor"); 01271 assert(D->isCopyOrMoveConstructor() && 01272 "trivial 1-arg ctor not a copy/move ctor"); 01273 EmitAggregateCopy(This, Src, (*ArgBeg)->getType()); 01274 return; 01275 } 01276 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, 01277 clang::Ctor_Complete); 01278 assert(D->isInstance() && 01279 "Trying to emit a member call expr on a static method!"); 01280 01281 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>(); 01282 01283 CallArgList Args; 01284 01285 // Push the this ptr. 01286 Args.add(RValue::get(This), D->getThisType(getContext())); 01287 01288 01289 // Push the src ptr. 01290 QualType QT = *(FPT->arg_type_begin()); 01291 llvm::Type *t = CGM.getTypes().ConvertType(QT); 01292 Src = Builder.CreateBitCast(Src, t); 01293 Args.add(RValue::get(Src), QT); 01294 01295 // Skip over first argument (Src). 01296 ++ArgBeg; 01297 CallExpr::const_arg_iterator Arg = ArgBeg; 01298 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1, 01299 E = FPT->arg_type_end(); I != E; ++I, ++Arg) { 01300 assert(Arg != ArgEnd && "Running over edge of argument list!"); 01301 EmitCallArg(Args, *Arg, *I); 01302 } 01303 // Either we've emitted all the call args, or we have a call to a 01304 // variadic function. 01305 assert((Arg == ArgEnd || FPT->isVariadic()) && 01306 "Extra arguments in non-variadic function!"); 01307 // If we still have any arguments, emit them using the type of the argument. 01308 for (; Arg != ArgEnd; ++Arg) { 01309 QualType ArgType = Arg->getType(); 01310 EmitCallArg(Args, *Arg, ArgType); 01311 } 01312 01313 EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee, 01314 ReturnValueSlot(), Args, D); 01315 } 01316 01317 void 01318 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 01319 CXXCtorType CtorType, 01320 const FunctionArgList &Args) { 01321 CallArgList DelegateArgs; 01322 01323 FunctionArgList::const_iterator I = Args.begin(), E = Args.end(); 01324 assert(I != E && "no parameters to constructor"); 01325 01326 // this 01327 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType()); 01328 ++I; 01329 01330 // vtt 01331 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType), 01332 /*ForVirtualBase=*/false)) { 01333 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy); 01334 DelegateArgs.add(RValue::get(VTT), VoidPP); 01335 01336 if (CodeGenVTables::needsVTTParameter(CurGD)) { 01337 assert(I != E && "cannot skip vtt parameter, already done with args"); 01338 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type"); 01339 ++I; 01340 } 01341 } 01342 01343 // Explicit arguments. 01344 for (; I != E; ++I) { 01345 const VarDecl *param = *I; 01346 EmitDelegateCallArg(DelegateArgs, param); 01347 } 01348 01349 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType), 01350 CGM.GetAddrOfCXXConstructor(Ctor, CtorType), 01351 ReturnValueSlot(), DelegateArgs, Ctor); 01352 } 01353 01354 namespace { 01355 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup { 01356 const CXXDestructorDecl *Dtor; 01357 llvm::Value *Addr; 01358 CXXDtorType Type; 01359 01360 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr, 01361 CXXDtorType Type) 01362 : Dtor(D), Addr(Addr), Type(Type) {} 01363 01364 void Emit(CodeGenFunction &CGF, Flags flags) { 01365 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false, 01366 Addr); 01367 } 01368 }; 01369 } 01370 01371 void 01372 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 01373 const FunctionArgList &Args) { 01374 assert(Ctor->isDelegatingConstructor()); 01375 01376 llvm::Value *ThisPtr = LoadCXXThis(); 01377 01378 QualType Ty = getContext().getTagDeclType(Ctor->getParent()); 01379 CharUnits Alignment = getContext().getTypeAlignInChars(Ty); 01380 AggValueSlot AggSlot = 01381 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(), 01382 AggValueSlot::IsDestructed, 01383 AggValueSlot::DoesNotNeedGCBarriers, 01384 AggValueSlot::IsNotAliased); 01385 01386 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot); 01387 01388 const CXXRecordDecl *ClassDecl = Ctor->getParent(); 01389 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) { 01390 CXXDtorType Type = 01391 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base; 01392 01393 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup, 01394 ClassDecl->getDestructor(), 01395 ThisPtr, Type); 01396 } 01397 } 01398 01399 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD, 01400 CXXDtorType Type, 01401 bool ForVirtualBase, 01402 llvm::Value *This) { 01403 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type), 01404 ForVirtualBase); 01405 llvm::Value *Callee = 0; 01406 if (getContext().getLangOpts().AppleKext) 01407 Callee = BuildAppleKextVirtualDestructorCall(DD, Type, 01408 DD->getParent()); 01409 01410 if (!Callee) 01411 Callee = CGM.GetAddrOfCXXDestructor(DD, Type); 01412 01413 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0); 01414 } 01415 01416 namespace { 01417 struct CallLocalDtor : EHScopeStack::Cleanup { 01418 const CXXDestructorDecl *Dtor; 01419 llvm::Value *Addr; 01420 01421 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr) 01422 : Dtor(D), Addr(Addr) {} 01423 01424 void Emit(CodeGenFunction &CGF, Flags flags) { 01425 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 01426 /*ForVirtualBase=*/false, Addr); 01427 } 01428 }; 01429 } 01430 01431 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D, 01432 llvm::Value *Addr) { 01433 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr); 01434 } 01435 01436 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) { 01437 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl(); 01438 if (!ClassDecl) return; 01439 if (ClassDecl->hasTrivialDestructor()) return; 01440 01441 const CXXDestructorDecl *D = ClassDecl->getDestructor(); 01442 assert(D && D->isUsed() && "destructor not marked as used!"); 01443 PushDestructorCleanup(D, Addr); 01444 } 01445 01446 llvm::Value * 01447 CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This, 01448 const CXXRecordDecl *ClassDecl, 01449 const CXXRecordDecl *BaseClassDecl) { 01450 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy); 01451 CharUnits VBaseOffsetOffset = 01452 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl); 01453 01454 llvm::Value *VBaseOffsetPtr = 01455 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(), 01456 "vbase.offset.ptr"); 01457 llvm::Type *PtrDiffTy = 01458 ConvertType(getContext().getPointerDiffType()); 01459 01460 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr, 01461 PtrDiffTy->getPointerTo()); 01462 01463 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset"); 01464 01465 return VBaseOffset; 01466 } 01467 01468 void 01469 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base, 01470 const CXXRecordDecl *NearestVBase, 01471 CharUnits OffsetFromNearestVBase, 01472 llvm::Constant *VTable, 01473 const CXXRecordDecl *VTableClass) { 01474 const CXXRecordDecl *RD = Base.getBase(); 01475 01476 // Compute the address point. 01477 llvm::Value *VTableAddressPoint; 01478 01479 // Check if we need to use a vtable from the VTT. 01480 if (CodeGenVTables::needsVTTParameter(CurGD) && 01481 (RD->getNumVBases() || NearestVBase)) { 01482 // Get the secondary vpointer index. 01483 uint64_t VirtualPointerIndex = 01484 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base); 01485 01486 /// Load the VTT. 01487 llvm::Value *VTT = LoadCXXVTT(); 01488 if (VirtualPointerIndex) 01489 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex); 01490 01491 // And load the address point from the VTT. 01492 VTableAddressPoint = Builder.CreateLoad(VTT); 01493 } else { 01494 uint64_t AddressPoint = 01495 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base); 01496 VTableAddressPoint = 01497 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint); 01498 } 01499 01500 // Compute where to store the address point. 01501 llvm::Value *VirtualOffset = 0; 01502 CharUnits NonVirtualOffset = CharUnits::Zero(); 01503 01504 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) { 01505 // We need to use the virtual base offset offset because the virtual base 01506 // might have a different offset in the most derived class. 01507 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass, 01508 NearestVBase); 01509 NonVirtualOffset = OffsetFromNearestVBase; 01510 } else { 01511 // We can just use the base offset in the complete class. 01512 NonVirtualOffset = Base.getBaseOffset(); 01513 } 01514 01515 // Apply the offsets. 01516 llvm::Value *VTableField = LoadCXXThis(); 01517 01518 if (!NonVirtualOffset.isZero() || VirtualOffset) 01519 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField, 01520 NonVirtualOffset, 01521 VirtualOffset); 01522 01523 // Finally, store the address point. 01524 llvm::Type *AddressPointPtrTy = 01525 VTableAddressPoint->getType()->getPointerTo(); 01526 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy); 01527 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField); 01528 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr()); 01529 } 01530 01531 void 01532 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base, 01533 const CXXRecordDecl *NearestVBase, 01534 CharUnits OffsetFromNearestVBase, 01535 bool BaseIsNonVirtualPrimaryBase, 01536 llvm::Constant *VTable, 01537 const CXXRecordDecl *VTableClass, 01538 VisitedVirtualBasesSetTy& VBases) { 01539 // If this base is a non-virtual primary base the address point has already 01540 // been set. 01541 if (!BaseIsNonVirtualPrimaryBase) { 01542 // Initialize the vtable pointer for this base. 01543 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase, 01544 VTable, VTableClass); 01545 } 01546 01547 const CXXRecordDecl *RD = Base.getBase(); 01548 01549 // Traverse bases. 01550 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 01551 E = RD->bases_end(); I != E; ++I) { 01552 CXXRecordDecl *BaseDecl 01553 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 01554 01555 // Ignore classes without a vtable. 01556 if (!BaseDecl->isDynamicClass()) 01557 continue; 01558 01559 CharUnits BaseOffset; 01560 CharUnits BaseOffsetFromNearestVBase; 01561 bool BaseDeclIsNonVirtualPrimaryBase; 01562 01563 if (I->isVirtual()) { 01564 // Check if we've visited this virtual base before. 01565 if (!VBases.insert(BaseDecl)) 01566 continue; 01567 01568 const ASTRecordLayout &Layout = 01569 getContext().getASTRecordLayout(VTableClass); 01570 01571 BaseOffset = Layout.getVBaseClassOffset(BaseDecl); 01572 BaseOffsetFromNearestVBase = CharUnits::Zero(); 01573 BaseDeclIsNonVirtualPrimaryBase = false; 01574 } else { 01575 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 01576 01577 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); 01578 BaseOffsetFromNearestVBase = 01579 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl); 01580 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl; 01581 } 01582 01583 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset), 01584 I->isVirtual() ? BaseDecl : NearestVBase, 01585 BaseOffsetFromNearestVBase, 01586 BaseDeclIsNonVirtualPrimaryBase, 01587 VTable, VTableClass, VBases); 01588 } 01589 } 01590 01591 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) { 01592 // Ignore classes without a vtable. 01593 if (!RD->isDynamicClass()) 01594 return; 01595 01596 // Get the VTable. 01597 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD); 01598 01599 // Initialize the vtable pointers for this class and all of its bases. 01600 VisitedVirtualBasesSetTy VBases; 01601 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()), 01602 /*NearestVBase=*/0, 01603 /*OffsetFromNearestVBase=*/CharUnits::Zero(), 01604 /*BaseIsNonVirtualPrimaryBase=*/false, 01605 VTable, RD, VBases); 01606 } 01607 01608 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This, 01609 llvm::Type *Ty) { 01610 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo()); 01611 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable"); 01612 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr()); 01613 return VTable; 01614 } 01615 01616 static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) { 01617 const Expr *E = Base; 01618 01619 while (true) { 01620 E = E->IgnoreParens(); 01621 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 01622 if (CE->getCastKind() == CK_DerivedToBase || 01623 CE->getCastKind() == CK_UncheckedDerivedToBase || 01624 CE->getCastKind() == CK_NoOp) { 01625 E = CE->getSubExpr(); 01626 continue; 01627 } 01628 } 01629 01630 break; 01631 } 01632 01633 QualType DerivedType = E->getType(); 01634 if (const PointerType *PTy = DerivedType->getAs<PointerType>()) 01635 DerivedType = PTy->getPointeeType(); 01636 01637 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl()); 01638 } 01639 01640 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do 01641 // quite what we want. 01642 static const Expr *skipNoOpCastsAndParens(const Expr *E) { 01643 while (true) { 01644 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 01645 E = PE->getSubExpr(); 01646 continue; 01647 } 01648 01649 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 01650 if (CE->getCastKind() == CK_NoOp) { 01651 E = CE->getSubExpr(); 01652 continue; 01653 } 01654 } 01655 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 01656 if (UO->getOpcode() == UO_Extension) { 01657 E = UO->getSubExpr(); 01658 continue; 01659 } 01660 } 01661 return E; 01662 } 01663 } 01664 01665 /// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member 01666 /// function call on the given expr can be devirtualized. 01667 static bool canDevirtualizeMemberFunctionCall(const Expr *Base, 01668 const CXXMethodDecl *MD) { 01669 // If the most derived class is marked final, we know that no subclass can 01670 // override this member function and so we can devirtualize it. For example: 01671 // 01672 // struct A { virtual void f(); } 01673 // struct B final : A { }; 01674 // 01675 // void f(B *b) { 01676 // b->f(); 01677 // } 01678 // 01679 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base); 01680 if (MostDerivedClassDecl->hasAttr<FinalAttr>()) 01681 return true; 01682 01683 // If the member function is marked 'final', we know that it can't be 01684 // overridden and can therefore devirtualize it. 01685 if (MD->hasAttr<FinalAttr>()) 01686 return true; 01687 01688 // Similarly, if the class itself is marked 'final' it can't be overridden 01689 // and we can therefore devirtualize the member function call. 01690 if (MD->getParent()->hasAttr<FinalAttr>()) 01691 return true; 01692 01693 Base = skipNoOpCastsAndParens(Base); 01694 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 01695 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 01696 // This is a record decl. We know the type and can devirtualize it. 01697 return VD->getType()->isRecordType(); 01698 } 01699 01700 return false; 01701 } 01702 01703 // We can always devirtualize calls on temporary object expressions. 01704 if (isa<CXXConstructExpr>(Base)) 01705 return true; 01706 01707 // And calls on bound temporaries. 01708 if (isa<CXXBindTemporaryExpr>(Base)) 01709 return true; 01710 01711 // Check if this is a call expr that returns a record type. 01712 if (const CallExpr *CE = dyn_cast<CallExpr>(Base)) 01713 return CE->getCallReturnType()->isRecordType(); 01714 01715 // We can't devirtualize the call. 01716 return false; 01717 } 01718 01719 static bool UseVirtualCall(ASTContext &Context, 01720 const CXXOperatorCallExpr *CE, 01721 const CXXMethodDecl *MD) { 01722 if (!MD->isVirtual()) 01723 return false; 01724 01725 // When building with -fapple-kext, all calls must go through the vtable since 01726 // the kernel linker can do runtime patching of vtables. 01727 if (Context.getLangOpts().AppleKext) 01728 return true; 01729 01730 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD); 01731 } 01732 01733 llvm::Value * 01734 CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E, 01735 const CXXMethodDecl *MD, 01736 llvm::Value *This) { 01737 llvm::FunctionType *fnType = 01738 CGM.getTypes().GetFunctionType( 01739 CGM.getTypes().arrangeCXXMethodDeclaration(MD)); 01740 01741 if (UseVirtualCall(getContext(), E, MD)) 01742 return BuildVirtualCall(MD, This, fnType); 01743 01744 return CGM.GetAddrOfFunction(MD, fnType); 01745 } 01746 01747 void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *Lambda, 01748 CallArgList &CallArgs) { 01749 // Lookup the call operator 01750 DeclarationName Name 01751 = getContext().DeclarationNames.getCXXOperatorName(OO_Call); 01752 DeclContext::lookup_const_result Calls = Lambda->lookup(Name); 01753 CXXMethodDecl *CallOperator = cast<CXXMethodDecl>(*Calls.first++); 01754 const FunctionProtoType *FPT = 01755 CallOperator->getType()->getAs<FunctionProtoType>(); 01756 QualType ResultType = FPT->getResultType(); 01757 01758 // Get the address of the call operator. 01759 GlobalDecl GD(CallOperator); 01760 const CGFunctionInfo &CalleeFnInfo = 01761 CGM.getTypes().arrangeFunctionCall(ResultType, CallArgs, FPT->getExtInfo(), 01762 RequiredArgs::forPrototypePlus(FPT, 1)); 01763 llvm::Type *Ty = CGM.getTypes().GetFunctionType(CalleeFnInfo); 01764 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty); 01765 01766 // Determine whether we have a return value slot to use. 01767 ReturnValueSlot Slot; 01768 if (!ResultType->isVoidType() && 01769 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 01770 hasAggregateLLVMType(CurFnInfo->getReturnType())) 01771 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified()); 01772 01773 // Now emit our call. 01774 RValue RV = EmitCall(CalleeFnInfo, Callee, Slot, CallArgs, CallOperator); 01775 01776 // Forward the returned value 01777 if (!ResultType->isVoidType() && Slot.isNull()) 01778 EmitReturnOfRValue(RV, ResultType); 01779 } 01780 01781 void CodeGenFunction::EmitLambdaBlockInvokeBody() { 01782 const BlockDecl *BD = BlockInfo->getBlockDecl(); 01783 const VarDecl *variable = BD->capture_begin()->getVariable(); 01784 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl(); 01785 01786 // Start building arguments for forwarding call 01787 CallArgList CallArgs; 01788 01789 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda)); 01790 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false); 01791 CallArgs.add(RValue::get(ThisPtr), ThisType); 01792 01793 // Add the rest of the parameters. 01794 for (BlockDecl::param_const_iterator I = BD->param_begin(), 01795 E = BD->param_end(); I != E; ++I) { 01796 ParmVarDecl *param = *I; 01797 EmitDelegateCallArg(CallArgs, param); 01798 } 01799 01800 EmitForwardingCallToLambda(Lambda, CallArgs); 01801 } 01802 01803 void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) { 01804 if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) { 01805 // FIXME: Making this work correctly is nasty because it requires either 01806 // cloning the body of the call operator or making the call operator forward. 01807 CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic function"); 01808 return; 01809 } 01810 01811 EmitFunctionBody(Args); 01812 } 01813 01814 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) { 01815 const CXXRecordDecl *Lambda = MD->getParent(); 01816 01817 // Start building arguments for forwarding call 01818 CallArgList CallArgs; 01819 01820 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda)); 01821 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType)); 01822 CallArgs.add(RValue::get(ThisPtr), ThisType); 01823 01824 // Add the rest of the parameters. 01825 for (FunctionDecl::param_const_iterator I = MD->param_begin(), 01826 E = MD->param_end(); I != E; ++I) { 01827 ParmVarDecl *param = *I; 01828 EmitDelegateCallArg(CallArgs, param); 01829 } 01830 01831 EmitForwardingCallToLambda(Lambda, CallArgs); 01832 } 01833 01834 void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) { 01835 if (MD->isVariadic()) { 01836 // FIXME: Making this work correctly is nasty because it requires either 01837 // cloning the body of the call operator or making the call operator forward. 01838 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function"); 01839 return; 01840 } 01841 01842 EmitLambdaDelegatingInvokeBody(MD); 01843 }