1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===// 2 // 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 "CGDebugInfo.h" 15 #include "CodeGenFunction.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/EvaluatedExprVisitor.h" 18 #include "clang/AST/RecordLayout.h" 19 #include "clang/AST/StmtCXX.h" 20 #include "clang/Frontend/CodeGenOptions.h" 21 22 using namespace clang; 23 using namespace CodeGen; 24 25 static CharUnits 26 ComputeNonVirtualBaseClassOffset(ASTContext &Context, 27 const CXXRecordDecl *DerivedClass, 28 CastExpr::path_const_iterator Start, 29 CastExpr::path_const_iterator End) { 30 CharUnits Offset = CharUnits::Zero(); 31 32 const CXXRecordDecl *RD = DerivedClass; 33 34 for (CastExpr::path_const_iterator I = Start; I != End; ++I) { 35 const CXXBaseSpecifier *Base = *I; 36 assert(!Base->isVirtual() && "Should not see virtual bases here!"); 37 38 // Get the layout. 39 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 40 41 const CXXRecordDecl *BaseDecl = 42 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 43 44 // Add the offset. 45 Offset += Layout.getBaseClassOffset(BaseDecl); 46 47 RD = BaseDecl; 48 } 49 50 return Offset; 51 } 52 53 llvm::Constant * 54 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 55 CastExpr::path_const_iterator PathBegin, 56 CastExpr::path_const_iterator PathEnd) { 57 assert(PathBegin != PathEnd && "Base path should not be empty!"); 58 59 CharUnits Offset = 60 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl, 61 PathBegin, PathEnd); 62 if (Offset.isZero()) 63 return 0; 64 65 llvm::Type *PtrDiffTy = 66 Types.ConvertType(getContext().getPointerDiffType()); 67 68 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity()); 69 } 70 71 /// Gets the address of a direct base class within a complete object. 72 /// This should only be used for (1) non-virtual bases or (2) virtual bases 73 /// when the type is known to be complete (e.g. in complete destructors). 74 /// 75 /// The object pointed to by 'This' is assumed to be non-null. 76 llvm::Value * 77 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This, 78 const CXXRecordDecl *Derived, 79 const CXXRecordDecl *Base, 80 bool BaseIsVirtual) { 81 // 'this' must be a pointer (in some address space) to Derived. 82 assert(This->getType()->isPointerTy() && 83 cast<llvm::PointerType>(This->getType())->getElementType() 84 == ConvertType(Derived)); 85 86 // Compute the offset of the virtual base. 87 CharUnits Offset; 88 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived); 89 if (BaseIsVirtual) 90 Offset = Layout.getVBaseClassOffset(Base); 91 else 92 Offset = Layout.getBaseClassOffset(Base); 93 94 // Shift and cast down to the base type. 95 // TODO: for complete types, this should be possible with a GEP. 96 llvm::Value *V = This; 97 if (Offset.isPositive()) { 98 V = Builder.CreateBitCast(V, Int8PtrTy); 99 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity()); 100 } 101 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo()); 102 103 return V; 104 } 105 106 static llvm::Value * 107 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr, 108 CharUnits NonVirtual, llvm::Value *Virtual) { 109 llvm::Type *PtrDiffTy = 110 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 111 112 llvm::Value *NonVirtualOffset = 0; 113 if (!NonVirtual.isZero()) 114 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, 115 NonVirtual.getQuantity()); 116 117 llvm::Value *BaseOffset; 118 if (Virtual) { 119 if (NonVirtualOffset) 120 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset); 121 else 122 BaseOffset = Virtual; 123 } else 124 BaseOffset = NonVirtualOffset; 125 126 // Apply the base offset. 127 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, CGF.Int8PtrTy); 128 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr"); 129 130 return ThisPtr; 131 } 132 133 llvm::Value * 134 CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value, 135 const CXXRecordDecl *Derived, 136 CastExpr::path_const_iterator PathBegin, 137 CastExpr::path_const_iterator PathEnd, 138 bool NullCheckValue) { 139 assert(PathBegin != PathEnd && "Base path should not be empty!"); 140 141 CastExpr::path_const_iterator Start = PathBegin; 142 const CXXRecordDecl *VBase = 0; 143 144 // Get the virtual base. 145 if ((*Start)->isVirtual()) { 146 VBase = 147 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl()); 148 ++Start; 149 } 150 151 CharUnits NonVirtualOffset = 152 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived, 153 Start, PathEnd); 154 155 // Get the base pointer type. 156 llvm::Type *BasePtrTy = 157 ConvertType((PathEnd[-1])->getType())->getPointerTo(); 158 159 if (NonVirtualOffset.isZero() && !VBase) { 160 // Just cast back. 161 return Builder.CreateBitCast(Value, BasePtrTy); 162 } 163 164 llvm::BasicBlock *CastNull = 0; 165 llvm::BasicBlock *CastNotNull = 0; 166 llvm::BasicBlock *CastEnd = 0; 167 168 if (NullCheckValue) { 169 CastNull = createBasicBlock("cast.null"); 170 CastNotNull = createBasicBlock("cast.notnull"); 171 CastEnd = createBasicBlock("cast.end"); 172 173 llvm::Value *IsNull = Builder.CreateIsNull(Value); 174 Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 175 EmitBlock(CastNotNull); 176 } 177 178 llvm::Value *VirtualOffset = 0; 179 180 if (VBase) { 181 if (Derived->hasAttr<FinalAttr>()) { 182 VirtualOffset = 0; 183 184 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived); 185 186 CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase); 187 NonVirtualOffset += VBaseOffset; 188 } else 189 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase); 190 } 191 192 // Apply the offsets. 193 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, 194 NonVirtualOffset, 195 VirtualOffset); 196 197 // Cast back. 198 Value = Builder.CreateBitCast(Value, BasePtrTy); 199 200 if (NullCheckValue) { 201 Builder.CreateBr(CastEnd); 202 EmitBlock(CastNull); 203 Builder.CreateBr(CastEnd); 204 EmitBlock(CastEnd); 205 206 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 207 PHI->addIncoming(Value, CastNotNull); 208 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), 209 CastNull); 210 Value = PHI; 211 } 212 213 return Value; 214 } 215 216 llvm::Value * 217 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value, 218 const CXXRecordDecl *Derived, 219 CastExpr::path_const_iterator PathBegin, 220 CastExpr::path_const_iterator PathEnd, 221 bool NullCheckValue) { 222 assert(PathBegin != PathEnd && "Base path should not be empty!"); 223 224 QualType DerivedTy = 225 getContext().getCanonicalType(getContext().getTagDeclType(Derived)); 226 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo(); 227 228 llvm::Value *NonVirtualOffset = 229 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd); 230 231 if (!NonVirtualOffset) { 232 // No offset, we can just cast back. 233 return Builder.CreateBitCast(Value, DerivedPtrTy); 234 } 235 236 llvm::BasicBlock *CastNull = 0; 237 llvm::BasicBlock *CastNotNull = 0; 238 llvm::BasicBlock *CastEnd = 0; 239 240 if (NullCheckValue) { 241 CastNull = createBasicBlock("cast.null"); 242 CastNotNull = createBasicBlock("cast.notnull"); 243 CastEnd = createBasicBlock("cast.end"); 244 245 llvm::Value *IsNull = Builder.CreateIsNull(Value); 246 Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 247 EmitBlock(CastNotNull); 248 } 249 250 // Apply the offset. 251 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType()); 252 Value = Builder.CreateSub(Value, NonVirtualOffset); 253 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy); 254 255 // Just cast. 256 Value = Builder.CreateBitCast(Value, DerivedPtrTy); 257 258 if (NullCheckValue) { 259 Builder.CreateBr(CastEnd); 260 EmitBlock(CastNull); 261 Builder.CreateBr(CastEnd); 262 EmitBlock(CastEnd); 263 264 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 265 PHI->addIncoming(Value, CastNotNull); 266 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), 267 CastNull); 268 Value = PHI; 269 } 270 271 return Value; 272 } 273 274 /// GetVTTParameter - Return the VTT parameter that should be passed to a 275 /// base constructor/destructor with virtual bases. 276 static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD, 277 bool ForVirtualBase) { 278 if (!CodeGenVTables::needsVTTParameter(GD)) { 279 // This constructor/destructor does not need a VTT parameter. 280 return 0; 281 } 282 283 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent(); 284 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent(); 285 286 llvm::Value *VTT; 287 288 uint64_t SubVTTIndex; 289 290 // If the record matches the base, this is the complete ctor/dtor 291 // variant calling the base variant in a class with virtual bases. 292 if (RD == Base) { 293 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) && 294 "doing no-op VTT offset in base dtor/ctor?"); 295 assert(!ForVirtualBase && "Can't have same class as virtual base!"); 296 SubVTTIndex = 0; 297 } else { 298 const ASTRecordLayout &Layout = 299 CGF.getContext().getASTRecordLayout(RD); 300 CharUnits BaseOffset = ForVirtualBase ? 301 Layout.getVBaseClassOffset(Base) : 302 Layout.getBaseClassOffset(Base); 303 304 SubVTTIndex = 305 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset)); 306 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!"); 307 } 308 309 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) { 310 // A VTT parameter was passed to the constructor, use it. 311 VTT = CGF.LoadCXXVTT(); 312 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex); 313 } else { 314 // We're the complete constructor, so get the VTT by name. 315 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD); 316 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex); 317 } 318 319 return VTT; 320 } 321 322 namespace { 323 /// Call the destructor for a direct base class. 324 struct CallBaseDtor : EHScopeStack::Cleanup { 325 const CXXRecordDecl *BaseClass; 326 bool BaseIsVirtual; 327 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual) 328 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {} 329 330 void Emit(CodeGenFunction &CGF, Flags flags) { 331 const CXXRecordDecl *DerivedClass = 332 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent(); 333 334 const CXXDestructorDecl *D = BaseClass->getDestructor(); 335 llvm::Value *Addr = 336 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(), 337 DerivedClass, BaseClass, 338 BaseIsVirtual); 339 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr); 340 } 341 }; 342 343 /// A visitor which checks whether an initializer uses 'this' in a 344 /// way which requires the vtable to be properly set. 345 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> { 346 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super; 347 348 bool UsesThis; 349 350 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {} 351 352 // Black-list all explicit and implicit references to 'this'. 353 // 354 // Do we need to worry about external references to 'this' derived 355 // from arbitrary code? If so, then anything which runs arbitrary 356 // external code might potentially access the vtable. 357 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; } 358 }; 359 } 360 361 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) { 362 DynamicThisUseChecker Checker(C); 363 Checker.Visit(const_cast<Expr*>(Init)); 364 return Checker.UsesThis; 365 } 366 367 static void EmitBaseInitializer(CodeGenFunction &CGF, 368 const CXXRecordDecl *ClassDecl, 369 CXXCtorInitializer *BaseInit, 370 CXXCtorType CtorType) { 371 assert(BaseInit->isBaseInitializer() && 372 "Must have base initializer!"); 373 374 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 375 376 const Type *BaseType = BaseInit->getBaseClass(); 377 CXXRecordDecl *BaseClassDecl = 378 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()); 379 380 bool isBaseVirtual = BaseInit->isBaseVirtual(); 381 382 // The base constructor doesn't construct virtual bases. 383 if (CtorType == Ctor_Base && isBaseVirtual) 384 return; 385 386 // If the initializer for the base (other than the constructor 387 // itself) accesses 'this' in any way, we need to initialize the 388 // vtables. 389 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit())) 390 CGF.InitializeVTablePointers(ClassDecl); 391 392 // We can pretend to be a complete class because it only matters for 393 // virtual bases, and we only do virtual bases for complete ctors. 394 llvm::Value *V = 395 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl, 396 BaseClassDecl, 397 isBaseVirtual); 398 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType); 399 AggValueSlot AggSlot = 400 AggValueSlot::forAddr(V, Alignment, Qualifiers(), 401 AggValueSlot::IsDestructed, 402 AggValueSlot::DoesNotNeedGCBarriers, 403 AggValueSlot::IsNotAliased); 404 405 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot); 406 407 if (CGF.CGM.getLangOptions().Exceptions && 408 !BaseClassDecl->hasTrivialDestructor()) 409 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl, 410 isBaseVirtual); 411 } 412 413 static void EmitAggMemberInitializer(CodeGenFunction &CGF, 414 LValue LHS, 415 Expr *Init, 416 llvm::Value *ArrayIndexVar, 417 QualType T, 418 ArrayRef<VarDecl *> ArrayIndexes, 419 unsigned Index) { 420 if (Index == ArrayIndexes.size()) { 421 CodeGenFunction::RunCleanupsScope Cleanups(CGF); 422 423 LValue LV = LHS; 424 if (ArrayIndexVar) { 425 // If we have an array index variable, load it and use it as an offset. 426 // Then, increment the value. 427 llvm::Value *Dest = LHS.getAddress(); 428 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar); 429 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress"); 430 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1); 431 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc"); 432 CGF.Builder.CreateStore(Next, ArrayIndexVar); 433 434 // Update the LValue. 435 LV.setAddress(Dest); 436 CharUnits Align = CGF.getContext().getTypeAlignInChars(T); 437 LV.setAlignment(std::min(Align, LV.getAlignment())); 438 } 439 440 if (!CGF.hasAggregateLLVMType(T)) { 441 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false); 442 } else if (T->isAnyComplexType()) { 443 CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(), 444 LV.isVolatileQualified()); 445 } else { 446 AggValueSlot Slot = 447 AggValueSlot::forLValue(LV, 448 AggValueSlot::IsDestructed, 449 AggValueSlot::DoesNotNeedGCBarriers, 450 AggValueSlot::IsNotAliased); 451 452 CGF.EmitAggExpr(Init, Slot); 453 } 454 455 return; 456 } 457 458 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T); 459 assert(Array && "Array initialization without the array type?"); 460 llvm::Value *IndexVar 461 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]); 462 assert(IndexVar && "Array index variable not loaded"); 463 464 // Initialize this index variable to zero. 465 llvm::Value* Zero 466 = llvm::Constant::getNullValue( 467 CGF.ConvertType(CGF.getContext().getSizeType())); 468 CGF.Builder.CreateStore(Zero, IndexVar); 469 470 // Start the loop with a block that tests the condition. 471 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond"); 472 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end"); 473 474 CGF.EmitBlock(CondBlock); 475 476 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body"); 477 // Generate: if (loop-index < number-of-elements) fall to the loop body, 478 // otherwise, go to the block after the for-loop. 479 uint64_t NumElements = Array->getSize().getZExtValue(); 480 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar); 481 llvm::Value *NumElementsPtr = 482 llvm::ConstantInt::get(Counter->getType(), NumElements); 483 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr, 484 "isless"); 485 486 // If the condition is true, execute the body. 487 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor); 488 489 CGF.EmitBlock(ForBody); 490 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc"); 491 492 { 493 CodeGenFunction::RunCleanupsScope Cleanups(CGF); 494 495 // Inside the loop body recurse to emit the inner loop or, eventually, the 496 // constructor call. 497 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar, 498 Array->getElementType(), ArrayIndexes, Index + 1); 499 } 500 501 CGF.EmitBlock(ContinueBlock); 502 503 // Emit the increment of the loop counter. 504 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1); 505 Counter = CGF.Builder.CreateLoad(IndexVar); 506 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc"); 507 CGF.Builder.CreateStore(NextVal, IndexVar); 508 509 // Finally, branch back up to the condition for the next iteration. 510 CGF.EmitBranch(CondBlock); 511 512 // Emit the fall-through block. 513 CGF.EmitBlock(AfterFor, true); 514 } 515 516 namespace { 517 struct CallMemberDtor : EHScopeStack::Cleanup { 518 llvm::Value *V; 519 CXXDestructorDecl *Dtor; 520 521 CallMemberDtor(llvm::Value *V, CXXDestructorDecl *Dtor) 522 : V(V), Dtor(Dtor) {} 523 524 void Emit(CodeGenFunction &CGF, Flags flags) { 525 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false, 526 V); 527 } 528 }; 529 } 530 531 static bool hasTrivialCopyOrMoveConstructor(const CXXRecordDecl *Record, 532 bool Moving) { 533 return Moving ? Record->hasTrivialMoveConstructor() : 534 Record->hasTrivialCopyConstructor(); 535 } 536 537 static void EmitMemberInitializer(CodeGenFunction &CGF, 538 const CXXRecordDecl *ClassDecl, 539 CXXCtorInitializer *MemberInit, 540 const CXXConstructorDecl *Constructor, 541 FunctionArgList &Args) { 542 assert(MemberInit->isAnyMemberInitializer() && 543 "Must have member initializer!"); 544 assert(MemberInit->getInit() && "Must have initializer!"); 545 546 // non-static data member initializers. 547 FieldDecl *Field = MemberInit->getAnyMember(); 548 QualType FieldType = Field->getType(); 549 550 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 551 LValue LHS; 552 553 // If we are initializing an anonymous union field, drill down to the field. 554 if (MemberInit->isIndirectMemberInitializer()) { 555 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr, 556 MemberInit->getIndirectMember(), 0); 557 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType(); 558 } else { 559 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0); 560 } 561 562 // Special case: if we are in a copy or move constructor, and we are copying 563 // an array of PODs or classes with trivial copy constructors, ignore the 564 // AST and perform the copy we know is equivalent. 565 // FIXME: This is hacky at best... if we had a bit more explicit information 566 // in the AST, we could generalize it more easily. 567 const ConstantArrayType *Array 568 = CGF.getContext().getAsConstantArrayType(FieldType); 569 if (Array && Constructor->isImplicitlyDefined() && 570 Constructor->isCopyOrMoveConstructor()) { 571 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array); 572 const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl(); 573 if (BaseElementTy.isPODType(CGF.getContext()) || 574 (Record && hasTrivialCopyOrMoveConstructor(Record, 575 Constructor->isMoveConstructor()))) { 576 // Find the source pointer. We knows it's the last argument because 577 // we know we're in a copy constructor. 578 unsigned SrcArgIndex = Args.size() - 1; 579 llvm::Value *SrcPtr 580 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex])); 581 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0); 582 583 // Copy the aggregate. 584 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType, 585 LHS.isVolatileQualified()); 586 return; 587 } 588 } 589 590 ArrayRef<VarDecl *> ArrayIndexes; 591 if (MemberInit->getNumArrayIndices()) 592 ArrayIndexes = MemberInit->getArrayIndexes(); 593 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes); 594 } 595 596 void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, 597 LValue LHS, Expr *Init, 598 ArrayRef<VarDecl *> ArrayIndexes) { 599 QualType FieldType = Field->getType(); 600 if (!hasAggregateLLVMType(FieldType)) { 601 if (LHS.isSimple()) { 602 EmitExprAsInit(Init, Field, LHS, false); 603 } else { 604 RValue RHS = RValue::get(EmitScalarExpr(Init)); 605 EmitStoreThroughLValue(RHS, LHS); 606 } 607 } else if (FieldType->isAnyComplexType()) { 608 EmitComplexExprIntoAddr(Init, LHS.getAddress(), LHS.isVolatileQualified()); 609 } else { 610 llvm::Value *ArrayIndexVar = 0; 611 if (ArrayIndexes.size()) { 612 llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 613 614 // The LHS is a pointer to the first object we'll be constructing, as 615 // a flat array. 616 QualType BaseElementTy = getContext().getBaseElementType(FieldType); 617 llvm::Type *BasePtr = ConvertType(BaseElementTy); 618 BasePtr = llvm::PointerType::getUnqual(BasePtr); 619 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(), 620 BasePtr); 621 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy); 622 623 // Create an array index that will be used to walk over all of the 624 // objects we're constructing. 625 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index"); 626 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy); 627 Builder.CreateStore(Zero, ArrayIndexVar); 628 629 630 // Emit the block variables for the array indices, if any. 631 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I) 632 EmitAutoVarDecl(*ArrayIndexes[I]); 633 } 634 635 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType, 636 ArrayIndexes, 0); 637 638 if (!CGM.getLangOptions().Exceptions) 639 return; 640 641 // FIXME: If we have an array of classes w/ non-trivial destructors, 642 // we need to destroy in reverse order of construction along the exception 643 // path. 644 const RecordType *RT = FieldType->getAs<RecordType>(); 645 if (!RT) 646 return; 647 648 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 649 if (!RD->hasTrivialDestructor()) 650 EHStack.pushCleanup<CallMemberDtor>(EHCleanup, LHS.getAddress(), 651 RD->getDestructor()); 652 } 653 } 654 655 /// Checks whether the given constructor is a valid subject for the 656 /// complete-to-base constructor delegation optimization, i.e. 657 /// emitting the complete constructor as a simple call to the base 658 /// constructor. 659 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) { 660 661 // Currently we disable the optimization for classes with virtual 662 // bases because (1) the addresses of parameter variables need to be 663 // consistent across all initializers but (2) the delegate function 664 // call necessarily creates a second copy of the parameter variable. 665 // 666 // The limiting example (purely theoretical AFAIK): 667 // struct A { A(int &c) { c++; } }; 668 // struct B : virtual A { 669 // B(int count) : A(count) { printf("%d\n", count); } 670 // }; 671 // ...although even this example could in principle be emitted as a 672 // delegation since the address of the parameter doesn't escape. 673 if (Ctor->getParent()->getNumVBases()) { 674 // TODO: white-list trivial vbase initializers. This case wouldn't 675 // be subject to the restrictions below. 676 677 // TODO: white-list cases where: 678 // - there are no non-reference parameters to the constructor 679 // - the initializers don't access any non-reference parameters 680 // - the initializers don't take the address of non-reference 681 // parameters 682 // - etc. 683 // If we ever add any of the above cases, remember that: 684 // - function-try-blocks will always blacklist this optimization 685 // - we need to perform the constructor prologue and cleanup in 686 // EmitConstructorBody. 687 688 return false; 689 } 690 691 // We also disable the optimization for variadic functions because 692 // it's impossible to "re-pass" varargs. 693 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic()) 694 return false; 695 696 // FIXME: Decide if we can do a delegation of a delegating constructor. 697 if (Ctor->isDelegatingConstructor()) 698 return false; 699 700 return true; 701 } 702 703 /// EmitConstructorBody - Emits the body of the current constructor. 704 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) { 705 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl()); 706 CXXCtorType CtorType = CurGD.getCtorType(); 707 708 // Before we go any further, try the complete->base constructor 709 // delegation optimization. 710 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) { 711 if (CGDebugInfo *DI = getDebugInfo()) 712 DI->EmitLocation(Builder, Ctor->getLocEnd()); 713 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args); 714 return; 715 } 716 717 Stmt *Body = Ctor->getBody(); 718 719 // Enter the function-try-block before the constructor prologue if 720 // applicable. 721 bool IsTryBody = (Body && isa<CXXTryStmt>(Body)); 722 if (IsTryBody) 723 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 724 725 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin(); 726 727 // Emit the constructor prologue, i.e. the base and member 728 // initializers. 729 EmitCtorPrologue(Ctor, CtorType, Args); 730 731 // Emit the body of the statement. 732 if (IsTryBody) 733 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 734 else if (Body) 735 EmitStmt(Body); 736 737 // Emit any cleanup blocks associated with the member or base 738 // initializers, which includes (along the exceptional path) the 739 // destructors for those members and bases that were fully 740 // constructed. 741 PopCleanupBlocks(CleanupDepth); 742 743 if (IsTryBody) 744 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 745 } 746 747 /// EmitCtorPrologue - This routine generates necessary code to initialize 748 /// base classes and non-static data members belonging to this constructor. 749 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD, 750 CXXCtorType CtorType, 751 FunctionArgList &Args) { 752 if (CD->isDelegatingConstructor()) 753 return EmitDelegatingCXXConstructorCall(CD, Args); 754 755 const CXXRecordDecl *ClassDecl = CD->getParent(); 756 757 SmallVector<CXXCtorInitializer *, 8> MemberInitializers; 758 759 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(), 760 E = CD->init_end(); 761 B != E; ++B) { 762 CXXCtorInitializer *Member = (*B); 763 764 if (Member->isBaseInitializer()) { 765 EmitBaseInitializer(*this, ClassDecl, Member, CtorType); 766 } else { 767 assert(Member->isAnyMemberInitializer() && 768 "Delegating initializer on non-delegating constructor"); 769 MemberInitializers.push_back(Member); 770 } 771 } 772 773 InitializeVTablePointers(ClassDecl); 774 775 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I) 776 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args); 777 } 778 779 static bool 780 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field); 781 782 static bool 783 HasTrivialDestructorBody(ASTContext &Context, 784 const CXXRecordDecl *BaseClassDecl, 785 const CXXRecordDecl *MostDerivedClassDecl) 786 { 787 // If the destructor is trivial we don't have to check anything else. 788 if (BaseClassDecl->hasTrivialDestructor()) 789 return true; 790 791 if (!BaseClassDecl->getDestructor()->hasTrivialBody()) 792 return false; 793 794 // Check fields. 795 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(), 796 E = BaseClassDecl->field_end(); I != E; ++I) { 797 const FieldDecl *Field = *I; 798 799 if (!FieldHasTrivialDestructorBody(Context, Field)) 800 return false; 801 } 802 803 // Check non-virtual bases. 804 for (CXXRecordDecl::base_class_const_iterator I = 805 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end(); 806 I != E; ++I) { 807 if (I->isVirtual()) 808 continue; 809 810 const CXXRecordDecl *NonVirtualBase = 811 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl()); 812 if (!HasTrivialDestructorBody(Context, NonVirtualBase, 813 MostDerivedClassDecl)) 814 return false; 815 } 816 817 if (BaseClassDecl == MostDerivedClassDecl) { 818 // Check virtual bases. 819 for (CXXRecordDecl::base_class_const_iterator I = 820 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end(); 821 I != E; ++I) { 822 const CXXRecordDecl *VirtualBase = 823 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl()); 824 if (!HasTrivialDestructorBody(Context, VirtualBase, 825 MostDerivedClassDecl)) 826 return false; 827 } 828 } 829 830 return true; 831 } 832 833 static bool 834 FieldHasTrivialDestructorBody(ASTContext &Context, 835 const FieldDecl *Field) 836 { 837 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType()); 838 839 const RecordType *RT = FieldBaseElementType->getAs<RecordType>(); 840 if (!RT) 841 return true; 842 843 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 844 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl); 845 } 846 847 /// CanSkipVTablePointerInitialization - Check whether we need to initialize 848 /// any vtable pointers before calling this destructor. 849 static bool CanSkipVTablePointerInitialization(ASTContext &Context, 850 const CXXDestructorDecl *Dtor) { 851 if (!Dtor->hasTrivialBody()) 852 return false; 853 854 // Check the fields. 855 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 856 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 857 E = ClassDecl->field_end(); I != E; ++I) { 858 const FieldDecl *Field = *I; 859 860 if (!FieldHasTrivialDestructorBody(Context, Field)) 861 return false; 862 } 863 864 return true; 865 } 866 867 /// EmitDestructorBody - Emits the body of the current destructor. 868 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) { 869 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl()); 870 CXXDtorType DtorType = CurGD.getDtorType(); 871 872 // The call to operator delete in a deleting destructor happens 873 // outside of the function-try-block, which means it's always 874 // possible to delegate the destructor body to the complete 875 // destructor. Do so. 876 if (DtorType == Dtor_Deleting) { 877 EnterDtorCleanups(Dtor, Dtor_Deleting); 878 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false, 879 LoadCXXThis()); 880 PopCleanupBlock(); 881 return; 882 } 883 884 Stmt *Body = Dtor->getBody(); 885 886 // If the body is a function-try-block, enter the try before 887 // anything else. 888 bool isTryBody = (Body && isa<CXXTryStmt>(Body)); 889 if (isTryBody) 890 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 891 892 // Enter the epilogue cleanups. 893 RunCleanupsScope DtorEpilogue(*this); 894 895 // If this is the complete variant, just invoke the base variant; 896 // the epilogue will destruct the virtual bases. But we can't do 897 // this optimization if the body is a function-try-block, because 898 // we'd introduce *two* handler blocks. 899 switch (DtorType) { 900 case Dtor_Deleting: llvm_unreachable("already handled deleting case"); 901 902 case Dtor_Complete: 903 // Enter the cleanup scopes for virtual bases. 904 EnterDtorCleanups(Dtor, Dtor_Complete); 905 906 if (!isTryBody) { 907 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false, 908 LoadCXXThis()); 909 break; 910 } 911 // Fallthrough: act like we're in the base variant. 912 913 case Dtor_Base: 914 // Enter the cleanup scopes for fields and non-virtual bases. 915 EnterDtorCleanups(Dtor, Dtor_Base); 916 917 // Initialize the vtable pointers before entering the body. 918 if (!CanSkipVTablePointerInitialization(getContext(), Dtor)) 919 InitializeVTablePointers(Dtor->getParent()); 920 921 if (isTryBody) 922 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 923 else if (Body) 924 EmitStmt(Body); 925 else { 926 assert(Dtor->isImplicit() && "bodyless dtor not implicit"); 927 // nothing to do besides what's in the epilogue 928 } 929 // -fapple-kext must inline any call to this dtor into 930 // the caller's body. 931 if (getContext().getLangOptions().AppleKext) 932 CurFn->addFnAttr(llvm::Attribute::AlwaysInline); 933 break; 934 } 935 936 // Jump out through the epilogue cleanups. 937 DtorEpilogue.ForceCleanup(); 938 939 // Exit the try if applicable. 940 if (isTryBody) 941 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 942 } 943 944 namespace { 945 /// Call the operator delete associated with the current destructor. 946 struct CallDtorDelete : EHScopeStack::Cleanup { 947 CallDtorDelete() {} 948 949 void Emit(CodeGenFunction &CGF, Flags flags) { 950 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl); 951 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 952 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(), 953 CGF.getContext().getTagDeclType(ClassDecl)); 954 } 955 }; 956 957 class DestroyField : public EHScopeStack::Cleanup { 958 const FieldDecl *field; 959 CodeGenFunction::Destroyer *destroyer; 960 bool useEHCleanupForArray; 961 962 public: 963 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer, 964 bool useEHCleanupForArray) 965 : field(field), destroyer(destroyer), 966 useEHCleanupForArray(useEHCleanupForArray) {} 967 968 void Emit(CodeGenFunction &CGF, Flags flags) { 969 // Find the address of the field. 970 llvm::Value *thisValue = CGF.LoadCXXThis(); 971 LValue LV = CGF.EmitLValueForField(thisValue, field, /*CVRQualifiers=*/0); 972 assert(LV.isSimple()); 973 974 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer, 975 flags.isForNormalCleanup() && useEHCleanupForArray); 976 } 977 }; 978 } 979 980 /// EmitDtorEpilogue - Emit all code that comes at the end of class's 981 /// destructor. This is to call destructors on members and base classes 982 /// in reverse order of their construction. 983 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD, 984 CXXDtorType DtorType) { 985 assert(!DD->isTrivial() && 986 "Should not emit dtor epilogue for trivial dtor!"); 987 988 // The deleting-destructor phase just needs to call the appropriate 989 // operator delete that Sema picked up. 990 if (DtorType == Dtor_Deleting) { 991 assert(DD->getOperatorDelete() && 992 "operator delete missing - EmitDtorEpilogue"); 993 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup); 994 return; 995 } 996 997 const CXXRecordDecl *ClassDecl = DD->getParent(); 998 999 // Unions have no bases and do not call field destructors. 1000 if (ClassDecl->isUnion()) 1001 return; 1002 1003 // The complete-destructor phase just destructs all the virtual bases. 1004 if (DtorType == Dtor_Complete) { 1005 1006 // We push them in the forward order so that they'll be popped in 1007 // the reverse order. 1008 for (CXXRecordDecl::base_class_const_iterator I = 1009 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end(); 1010 I != E; ++I) { 1011 const CXXBaseSpecifier &Base = *I; 1012 CXXRecordDecl *BaseClassDecl 1013 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 1014 1015 // Ignore trivial destructors. 1016 if (BaseClassDecl->hasTrivialDestructor()) 1017 continue; 1018 1019 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1020 BaseClassDecl, 1021 /*BaseIsVirtual*/ true); 1022 } 1023 1024 return; 1025 } 1026 1027 assert(DtorType == Dtor_Base); 1028 1029 // Destroy non-virtual bases. 1030 for (CXXRecordDecl::base_class_const_iterator I = 1031 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) { 1032 const CXXBaseSpecifier &Base = *I; 1033 1034 // Ignore virtual bases. 1035 if (Base.isVirtual()) 1036 continue; 1037 1038 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl(); 1039 1040 // Ignore trivial destructors. 1041 if (BaseClassDecl->hasTrivialDestructor()) 1042 continue; 1043 1044 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1045 BaseClassDecl, 1046 /*BaseIsVirtual*/ false); 1047 } 1048 1049 // Destroy direct fields. 1050 SmallVector<const FieldDecl *, 16> FieldDecls; 1051 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 1052 E = ClassDecl->field_end(); I != E; ++I) { 1053 const FieldDecl *field = *I; 1054 QualType type = field->getType(); 1055 QualType::DestructionKind dtorKind = type.isDestructedType(); 1056 if (!dtorKind) continue; 1057 1058 CleanupKind cleanupKind = getCleanupKind(dtorKind); 1059 EHStack.pushCleanup<DestroyField>(cleanupKind, field, 1060 getDestroyer(dtorKind), 1061 cleanupKind & EHCleanup); 1062 } 1063 } 1064 1065 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 1066 /// constructor for each of several members of an array. 1067 /// 1068 /// \param ctor the constructor to call for each element 1069 /// \param argBegin,argEnd the arguments to evaluate and pass to the 1070 /// constructor 1071 /// \param arrayType the type of the array to initialize 1072 /// \param arrayBegin an arrayType* 1073 /// \param zeroInitialize true if each element should be 1074 /// zero-initialized before it is constructed 1075 void 1076 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, 1077 const ConstantArrayType *arrayType, 1078 llvm::Value *arrayBegin, 1079 CallExpr::const_arg_iterator argBegin, 1080 CallExpr::const_arg_iterator argEnd, 1081 bool zeroInitialize) { 1082 QualType elementType; 1083 llvm::Value *numElements = 1084 emitArrayLength(arrayType, elementType, arrayBegin); 1085 1086 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, 1087 argBegin, argEnd, zeroInitialize); 1088 } 1089 1090 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 1091 /// constructor for each of several members of an array. 1092 /// 1093 /// \param ctor the constructor to call for each element 1094 /// \param numElements the number of elements in the array; 1095 /// may be zero 1096 /// \param argBegin,argEnd the arguments to evaluate and pass to the 1097 /// constructor 1098 /// \param arrayBegin a T*, where T is the type constructed by ctor 1099 /// \param zeroInitialize true if each element should be 1100 /// zero-initialized before it is constructed 1101 void 1102 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, 1103 llvm::Value *numElements, 1104 llvm::Value *arrayBegin, 1105 CallExpr::const_arg_iterator argBegin, 1106 CallExpr::const_arg_iterator argEnd, 1107 bool zeroInitialize) { 1108 1109 // It's legal for numElements to be zero. This can happen both 1110 // dynamically, because x can be zero in 'new A[x]', and statically, 1111 // because of GCC extensions that permit zero-length arrays. There 1112 // are probably legitimate places where we could assume that this 1113 // doesn't happen, but it's not clear that it's worth it. 1114 llvm::BranchInst *zeroCheckBranch = 0; 1115 1116 // Optimize for a constant count. 1117 llvm::ConstantInt *constantCount 1118 = dyn_cast<llvm::ConstantInt>(numElements); 1119 if (constantCount) { 1120 // Just skip out if the constant count is zero. 1121 if (constantCount->isZero()) return; 1122 1123 // Otherwise, emit the check. 1124 } else { 1125 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop"); 1126 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty"); 1127 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB); 1128 EmitBlock(loopBB); 1129 } 1130 1131 // Find the end of the array. 1132 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements, 1133 "arrayctor.end"); 1134 1135 // Enter the loop, setting up a phi for the current location to initialize. 1136 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1137 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop"); 1138 EmitBlock(loopBB); 1139 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2, 1140 "arrayctor.cur"); 1141 cur->addIncoming(arrayBegin, entryBB); 1142 1143 // Inside the loop body, emit the constructor call on the array element. 1144 1145 QualType type = getContext().getTypeDeclType(ctor->getParent()); 1146 1147 // Zero initialize the storage, if requested. 1148 if (zeroInitialize) 1149 EmitNullInitialization(cur, type); 1150 1151 // C++ [class.temporary]p4: 1152 // There are two contexts in which temporaries are destroyed at a different 1153 // point than the end of the full-expression. The first context is when a 1154 // default constructor is called to initialize an element of an array. 1155 // If the constructor has one or more default arguments, the destruction of 1156 // every temporary created in a default argument expression is sequenced 1157 // before the construction of the next array element, if any. 1158 1159 { 1160 RunCleanupsScope Scope(*this); 1161 1162 // Evaluate the constructor and its arguments in a regular 1163 // partial-destroy cleanup. 1164 if (getLangOptions().Exceptions && 1165 !ctor->getParent()->hasTrivialDestructor()) { 1166 Destroyer *destroyer = destroyCXXObject; 1167 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer); 1168 } 1169 1170 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false, 1171 cur, argBegin, argEnd); 1172 } 1173 1174 // Go to the next element. 1175 llvm::Value *next = 1176 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1), 1177 "arrayctor.next"); 1178 cur->addIncoming(next, Builder.GetInsertBlock()); 1179 1180 // Check whether that's the end of the loop. 1181 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done"); 1182 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont"); 1183 Builder.CreateCondBr(done, contBB, loopBB); 1184 1185 // Patch the earlier check to skip over the loop. 1186 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB); 1187 1188 EmitBlock(contBB); 1189 } 1190 1191 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF, 1192 llvm::Value *addr, 1193 QualType type) { 1194 const RecordType *rtype = type->castAs<RecordType>(); 1195 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl()); 1196 const CXXDestructorDecl *dtor = record->getDestructor(); 1197 assert(!dtor->isTrivial()); 1198 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false, 1199 addr); 1200 } 1201 1202 void 1203 CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 1204 CXXCtorType Type, bool ForVirtualBase, 1205 llvm::Value *This, 1206 CallExpr::const_arg_iterator ArgBeg, 1207 CallExpr::const_arg_iterator ArgEnd) { 1208 1209 CGDebugInfo *DI = getDebugInfo(); 1210 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) { 1211 // If debug info for this class has not been emitted then this is the 1212 // right time to do so. 1213 const CXXRecordDecl *Parent = D->getParent(); 1214 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent), 1215 Parent->getLocation()); 1216 } 1217 1218 if (D->isTrivial()) { 1219 if (ArgBeg == ArgEnd) { 1220 // Trivial default constructor, no codegen required. 1221 assert(D->isDefaultConstructor() && 1222 "trivial 0-arg ctor not a default ctor"); 1223 return; 1224 } 1225 1226 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor"); 1227 assert(D->isCopyOrMoveConstructor() && 1228 "trivial 1-arg ctor not a copy/move ctor"); 1229 1230 const Expr *E = (*ArgBeg); 1231 QualType Ty = E->getType(); 1232 llvm::Value *Src = EmitLValue(E).getAddress(); 1233 EmitAggregateCopy(This, Src, Ty); 1234 return; 1235 } 1236 1237 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase); 1238 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type); 1239 1240 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd); 1241 } 1242 1243 void 1244 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 1245 llvm::Value *This, llvm::Value *Src, 1246 CallExpr::const_arg_iterator ArgBeg, 1247 CallExpr::const_arg_iterator ArgEnd) { 1248 if (D->isTrivial()) { 1249 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor"); 1250 assert(D->isCopyOrMoveConstructor() && 1251 "trivial 1-arg ctor not a copy/move ctor"); 1252 EmitAggregateCopy(This, Src, (*ArgBeg)->getType()); 1253 return; 1254 } 1255 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, 1256 clang::Ctor_Complete); 1257 assert(D->isInstance() && 1258 "Trying to emit a member call expr on a static method!"); 1259 1260 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>(); 1261 1262 CallArgList Args; 1263 1264 // Push the this ptr. 1265 Args.add(RValue::get(This), D->getThisType(getContext())); 1266 1267 1268 // Push the src ptr. 1269 QualType QT = *(FPT->arg_type_begin()); 1270 llvm::Type *t = CGM.getTypes().ConvertType(QT); 1271 Src = Builder.CreateBitCast(Src, t); 1272 Args.add(RValue::get(Src), QT); 1273 1274 // Skip over first argument (Src). 1275 ++ArgBeg; 1276 CallExpr::const_arg_iterator Arg = ArgBeg; 1277 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1, 1278 E = FPT->arg_type_end(); I != E; ++I, ++Arg) { 1279 assert(Arg != ArgEnd && "Running over edge of argument list!"); 1280 EmitCallArg(Args, *Arg, *I); 1281 } 1282 // Either we've emitted all the call args, or we have a call to a 1283 // variadic function. 1284 assert((Arg == ArgEnd || FPT->isVariadic()) && 1285 "Extra arguments in non-variadic function!"); 1286 // If we still have any arguments, emit them using the type of the argument. 1287 for (; Arg != ArgEnd; ++Arg) { 1288 QualType ArgType = Arg->getType(); 1289 EmitCallArg(Args, *Arg, ArgType); 1290 } 1291 1292 EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee, 1293 ReturnValueSlot(), Args, D); 1294 } 1295 1296 void 1297 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 1298 CXXCtorType CtorType, 1299 const FunctionArgList &Args) { 1300 CallArgList DelegateArgs; 1301 1302 FunctionArgList::const_iterator I = Args.begin(), E = Args.end(); 1303 assert(I != E && "no parameters to constructor"); 1304 1305 // this 1306 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType()); 1307 ++I; 1308 1309 // vtt 1310 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType), 1311 /*ForVirtualBase=*/false)) { 1312 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy); 1313 DelegateArgs.add(RValue::get(VTT), VoidPP); 1314 1315 if (CodeGenVTables::needsVTTParameter(CurGD)) { 1316 assert(I != E && "cannot skip vtt parameter, already done with args"); 1317 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type"); 1318 ++I; 1319 } 1320 } 1321 1322 // Explicit arguments. 1323 for (; I != E; ++I) { 1324 const VarDecl *param = *I; 1325 EmitDelegateCallArg(DelegateArgs, param); 1326 } 1327 1328 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType), 1329 CGM.GetAddrOfCXXConstructor(Ctor, CtorType), 1330 ReturnValueSlot(), DelegateArgs, Ctor); 1331 } 1332 1333 namespace { 1334 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup { 1335 const CXXDestructorDecl *Dtor; 1336 llvm::Value *Addr; 1337 CXXDtorType Type; 1338 1339 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr, 1340 CXXDtorType Type) 1341 : Dtor(D), Addr(Addr), Type(Type) {} 1342 1343 void Emit(CodeGenFunction &CGF, Flags flags) { 1344 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false, 1345 Addr); 1346 } 1347 }; 1348 } 1349 1350 void 1351 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 1352 const FunctionArgList &Args) { 1353 assert(Ctor->isDelegatingConstructor()); 1354 1355 llvm::Value *ThisPtr = LoadCXXThis(); 1356 1357 QualType Ty = getContext().getTagDeclType(Ctor->getParent()); 1358 CharUnits Alignment = getContext().getTypeAlignInChars(Ty); 1359 AggValueSlot AggSlot = 1360 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(), 1361 AggValueSlot::IsDestructed, 1362 AggValueSlot::DoesNotNeedGCBarriers, 1363 AggValueSlot::IsNotAliased); 1364 1365 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot); 1366 1367 const CXXRecordDecl *ClassDecl = Ctor->getParent(); 1368 if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) { 1369 CXXDtorType Type = 1370 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base; 1371 1372 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup, 1373 ClassDecl->getDestructor(), 1374 ThisPtr, Type); 1375 } 1376 } 1377 1378 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD, 1379 CXXDtorType Type, 1380 bool ForVirtualBase, 1381 llvm::Value *This) { 1382 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type), 1383 ForVirtualBase); 1384 llvm::Value *Callee = 0; 1385 if (getContext().getLangOptions().AppleKext) 1386 Callee = BuildAppleKextVirtualDestructorCall(DD, Type, 1387 DD->getParent()); 1388 1389 if (!Callee) 1390 Callee = CGM.GetAddrOfCXXDestructor(DD, Type); 1391 1392 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0); 1393 } 1394 1395 namespace { 1396 struct CallLocalDtor : EHScopeStack::Cleanup { 1397 const CXXDestructorDecl *Dtor; 1398 llvm::Value *Addr; 1399 1400 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr) 1401 : Dtor(D), Addr(Addr) {} 1402 1403 void Emit(CodeGenFunction &CGF, Flags flags) { 1404 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 1405 /*ForVirtualBase=*/false, Addr); 1406 } 1407 }; 1408 } 1409 1410 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D, 1411 llvm::Value *Addr) { 1412 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr); 1413 } 1414 1415 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) { 1416 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl(); 1417 if (!ClassDecl) return; 1418 if (ClassDecl->hasTrivialDestructor()) return; 1419 1420 const CXXDestructorDecl *D = ClassDecl->getDestructor(); 1421 assert(D && D->isUsed() && "destructor not marked as used!"); 1422 PushDestructorCleanup(D, Addr); 1423 } 1424 1425 llvm::Value * 1426 CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This, 1427 const CXXRecordDecl *ClassDecl, 1428 const CXXRecordDecl *BaseClassDecl) { 1429 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy); 1430 CharUnits VBaseOffsetOffset = 1431 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl); 1432 1433 llvm::Value *VBaseOffsetPtr = 1434 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(), 1435 "vbase.offset.ptr"); 1436 llvm::Type *PtrDiffTy = 1437 ConvertType(getContext().getPointerDiffType()); 1438 1439 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr, 1440 PtrDiffTy->getPointerTo()); 1441 1442 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset"); 1443 1444 return VBaseOffset; 1445 } 1446 1447 void 1448 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base, 1449 const CXXRecordDecl *NearestVBase, 1450 CharUnits OffsetFromNearestVBase, 1451 llvm::Constant *VTable, 1452 const CXXRecordDecl *VTableClass) { 1453 const CXXRecordDecl *RD = Base.getBase(); 1454 1455 // Compute the address point. 1456 llvm::Value *VTableAddressPoint; 1457 1458 // Check if we need to use a vtable from the VTT. 1459 if (CodeGenVTables::needsVTTParameter(CurGD) && 1460 (RD->getNumVBases() || NearestVBase)) { 1461 // Get the secondary vpointer index. 1462 uint64_t VirtualPointerIndex = 1463 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base); 1464 1465 /// Load the VTT. 1466 llvm::Value *VTT = LoadCXXVTT(); 1467 if (VirtualPointerIndex) 1468 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex); 1469 1470 // And load the address point from the VTT. 1471 VTableAddressPoint = Builder.CreateLoad(VTT); 1472 } else { 1473 uint64_t AddressPoint = 1474 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base); 1475 VTableAddressPoint = 1476 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint); 1477 } 1478 1479 // Compute where to store the address point. 1480 llvm::Value *VirtualOffset = 0; 1481 CharUnits NonVirtualOffset = CharUnits::Zero(); 1482 1483 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) { 1484 // We need to use the virtual base offset offset because the virtual base 1485 // might have a different offset in the most derived class. 1486 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass, 1487 NearestVBase); 1488 NonVirtualOffset = OffsetFromNearestVBase; 1489 } else { 1490 // We can just use the base offset in the complete class. 1491 NonVirtualOffset = Base.getBaseOffset(); 1492 } 1493 1494 // Apply the offsets. 1495 llvm::Value *VTableField = LoadCXXThis(); 1496 1497 if (!NonVirtualOffset.isZero() || VirtualOffset) 1498 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField, 1499 NonVirtualOffset, 1500 VirtualOffset); 1501 1502 // Finally, store the address point. 1503 llvm::Type *AddressPointPtrTy = 1504 VTableAddressPoint->getType()->getPointerTo(); 1505 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy); 1506 Builder.CreateStore(VTableAddressPoint, VTableField); 1507 } 1508 1509 void 1510 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base, 1511 const CXXRecordDecl *NearestVBase, 1512 CharUnits OffsetFromNearestVBase, 1513 bool BaseIsNonVirtualPrimaryBase, 1514 llvm::Constant *VTable, 1515 const CXXRecordDecl *VTableClass, 1516 VisitedVirtualBasesSetTy& VBases) { 1517 // If this base is a non-virtual primary base the address point has already 1518 // been set. 1519 if (!BaseIsNonVirtualPrimaryBase) { 1520 // Initialize the vtable pointer for this base. 1521 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase, 1522 VTable, VTableClass); 1523 } 1524 1525 const CXXRecordDecl *RD = Base.getBase(); 1526 1527 // Traverse bases. 1528 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1529 E = RD->bases_end(); I != E; ++I) { 1530 CXXRecordDecl *BaseDecl 1531 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 1532 1533 // Ignore classes without a vtable. 1534 if (!BaseDecl->isDynamicClass()) 1535 continue; 1536 1537 CharUnits BaseOffset; 1538 CharUnits BaseOffsetFromNearestVBase; 1539 bool BaseDeclIsNonVirtualPrimaryBase; 1540 1541 if (I->isVirtual()) { 1542 // Check if we've visited this virtual base before. 1543 if (!VBases.insert(BaseDecl)) 1544 continue; 1545 1546 const ASTRecordLayout &Layout = 1547 getContext().getASTRecordLayout(VTableClass); 1548 1549 BaseOffset = Layout.getVBaseClassOffset(BaseDecl); 1550 BaseOffsetFromNearestVBase = CharUnits::Zero(); 1551 BaseDeclIsNonVirtualPrimaryBase = false; 1552 } else { 1553 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 1554 1555 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); 1556 BaseOffsetFromNearestVBase = 1557 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl); 1558 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl; 1559 } 1560 1561 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset), 1562 I->isVirtual() ? BaseDecl : NearestVBase, 1563 BaseOffsetFromNearestVBase, 1564 BaseDeclIsNonVirtualPrimaryBase, 1565 VTable, VTableClass, VBases); 1566 } 1567 } 1568 1569 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) { 1570 // Ignore classes without a vtable. 1571 if (!RD->isDynamicClass()) 1572 return; 1573 1574 // Get the VTable. 1575 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD); 1576 1577 // Initialize the vtable pointers for this class and all of its bases. 1578 VisitedVirtualBasesSetTy VBases; 1579 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()), 1580 /*NearestVBase=*/0, 1581 /*OffsetFromNearestVBase=*/CharUnits::Zero(), 1582 /*BaseIsNonVirtualPrimaryBase=*/false, 1583 VTable, RD, VBases); 1584 } 1585 1586 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This, 1587 llvm::Type *Ty) { 1588 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo()); 1589 return Builder.CreateLoad(VTablePtrSrc, "vtable"); 1590 } 1591 1592 static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) { 1593 const Expr *E = Base; 1594 1595 while (true) { 1596 E = E->IgnoreParens(); 1597 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 1598 if (CE->getCastKind() == CK_DerivedToBase || 1599 CE->getCastKind() == CK_UncheckedDerivedToBase || 1600 CE->getCastKind() == CK_NoOp) { 1601 E = CE->getSubExpr(); 1602 continue; 1603 } 1604 } 1605 1606 break; 1607 } 1608 1609 QualType DerivedType = E->getType(); 1610 if (const PointerType *PTy = DerivedType->getAs<PointerType>()) 1611 DerivedType = PTy->getPointeeType(); 1612 1613 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl()); 1614 } 1615 1616 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do 1617 // quite what we want. 1618 static const Expr *skipNoOpCastsAndParens(const Expr *E) { 1619 while (true) { 1620 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 1621 E = PE->getSubExpr(); 1622 continue; 1623 } 1624 1625 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 1626 if (CE->getCastKind() == CK_NoOp) { 1627 E = CE->getSubExpr(); 1628 continue; 1629 } 1630 } 1631 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 1632 if (UO->getOpcode() == UO_Extension) { 1633 E = UO->getSubExpr(); 1634 continue; 1635 } 1636 } 1637 return E; 1638 } 1639 } 1640 1641 /// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member 1642 /// function call on the given expr can be devirtualized. 1643 static bool canDevirtualizeMemberFunctionCall(const Expr *Base, 1644 const CXXMethodDecl *MD) { 1645 // If the most derived class is marked final, we know that no subclass can 1646 // override this member function and so we can devirtualize it. For example: 1647 // 1648 // struct A { virtual void f(); } 1649 // struct B final : A { }; 1650 // 1651 // void f(B *b) { 1652 // b->f(); 1653 // } 1654 // 1655 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base); 1656 if (MostDerivedClassDecl->hasAttr<FinalAttr>()) 1657 return true; 1658 1659 // If the member function is marked 'final', we know that it can't be 1660 // overridden and can therefore devirtualize it. 1661 if (MD->hasAttr<FinalAttr>()) 1662 return true; 1663 1664 // Similarly, if the class itself is marked 'final' it can't be overridden 1665 // and we can therefore devirtualize the member function call. 1666 if (MD->getParent()->hasAttr<FinalAttr>()) 1667 return true; 1668 1669 Base = skipNoOpCastsAndParens(Base); 1670 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 1671 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 1672 // This is a record decl. We know the type and can devirtualize it. 1673 return VD->getType()->isRecordType(); 1674 } 1675 1676 return false; 1677 } 1678 1679 // We can always devirtualize calls on temporary object expressions. 1680 if (isa<CXXConstructExpr>(Base)) 1681 return true; 1682 1683 // And calls on bound temporaries. 1684 if (isa<CXXBindTemporaryExpr>(Base)) 1685 return true; 1686 1687 // Check if this is a call expr that returns a record type. 1688 if (const CallExpr *CE = dyn_cast<CallExpr>(Base)) 1689 return CE->getCallReturnType()->isRecordType(); 1690 1691 // We can't devirtualize the call. 1692 return false; 1693 } 1694 1695 static bool UseVirtualCall(ASTContext &Context, 1696 const CXXOperatorCallExpr *CE, 1697 const CXXMethodDecl *MD) { 1698 if (!MD->isVirtual()) 1699 return false; 1700 1701 // When building with -fapple-kext, all calls must go through the vtable since 1702 // the kernel linker can do runtime patching of vtables. 1703 if (Context.getLangOptions().AppleKext) 1704 return true; 1705 1706 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD); 1707 } 1708 1709 llvm::Value * 1710 CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E, 1711 const CXXMethodDecl *MD, 1712 llvm::Value *This) { 1713 llvm::FunctionType *fnType = 1714 CGM.getTypes().GetFunctionType( 1715 CGM.getTypes().arrangeCXXMethodDeclaration(MD)); 1716 1717 if (UseVirtualCall(getContext(), E, MD)) 1718 return BuildVirtualCall(MD, This, fnType); 1719 1720 return CGM.GetAddrOfFunction(MD, fnType); 1721 } 1722 1723 void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) { 1724 CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to block"); 1725 } 1726 1727 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) { 1728 const CXXRecordDecl *Lambda = MD->getParent(); 1729 DeclarationName Name 1730 = getContext().DeclarationNames.getCXXOperatorName(OO_Call); 1731 DeclContext::lookup_const_result Calls = Lambda->lookup(Name); 1732 CXXMethodDecl *CallOperator = cast<CXXMethodDecl>(*Calls.first++); 1733 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 1734 QualType ResultType = FPT->getResultType(); 1735 1736 // Start building arguments for forwarding call 1737 CallArgList CallArgs; 1738 1739 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda)); 1740 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType)); 1741 CallArgs.add(RValue::get(ThisPtr), ThisType); 1742 1743 // Add the rest of the parameters. 1744 for (FunctionDecl::param_const_iterator I = MD->param_begin(), 1745 E = MD->param_end(); I != E; ++I) { 1746 ParmVarDecl *param = *I; 1747 EmitDelegateCallArg(CallArgs, param); 1748 } 1749 1750 // Get the address of the call operator. 1751 GlobalDecl GD(CallOperator); 1752 const CGFunctionInfo &CalleeFnInfo = 1753 CGM.getTypes().arrangeFunctionCall(ResultType, CallArgs, FPT->getExtInfo(), 1754 RequiredArgs::forPrototypePlus(FPT, 1)); 1755 llvm::Type *Ty = CGM.getTypes().GetFunctionType(CalleeFnInfo); 1756 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty); 1757 1758 // Determine whether we have a return value slot to use. 1759 ReturnValueSlot Slot; 1760 if (!ResultType->isVoidType() && 1761 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 1762 hasAggregateLLVMType(CurFnInfo->getReturnType())) 1763 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified()); 1764 1765 // Now emit our call. 1766 RValue RV = EmitCall(CalleeFnInfo, Callee, Slot, CallArgs, CallOperator); 1767 1768 // Forward the returned value 1769 if (!ResultType->isVoidType() && Slot.isNull()) 1770 EmitReturnOfRValue(RV, ResultType); 1771 } 1772 1773 void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) { 1774 if (MD->isVariadic()) { 1775 // FIXME: Making this work correctly is nasty because it requires either 1776 // cloning the body of the call operator or making the call operator forward. 1777 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function"); 1778 } 1779 1780 EmitLambdaDelegatingInvokeBody(MD); 1781 } 1782