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 "CGBlocks.h" 15 #include "CGCXXABI.h" 16 #include "CGDebugInfo.h" 17 #include "CGRecordLayout.h" 18 #include "CodeGenFunction.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/StmtCXX.h" 24 #include "clang/Basic/TargetBuiltins.h" 25 #include "clang/CodeGen/CGFunctionInfo.h" 26 #include "clang/Frontend/CodeGenOptions.h" 27 28 using namespace clang; 29 using namespace CodeGen; 30 31 static CharUnits 32 ComputeNonVirtualBaseClassOffset(ASTContext &Context, 33 const CXXRecordDecl *DerivedClass, 34 CastExpr::path_const_iterator Start, 35 CastExpr::path_const_iterator End) { 36 CharUnits Offset = CharUnits::Zero(); 37 38 const CXXRecordDecl *RD = DerivedClass; 39 40 for (CastExpr::path_const_iterator I = Start; I != End; ++I) { 41 const CXXBaseSpecifier *Base = *I; 42 assert(!Base->isVirtual() && "Should not see virtual bases here!"); 43 44 // Get the layout. 45 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 46 47 const CXXRecordDecl *BaseDecl = 48 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 49 50 // Add the offset. 51 Offset += Layout.getBaseClassOffset(BaseDecl); 52 53 RD = BaseDecl; 54 } 55 56 return Offset; 57 } 58 59 llvm::Constant * 60 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 61 CastExpr::path_const_iterator PathBegin, 62 CastExpr::path_const_iterator PathEnd) { 63 assert(PathBegin != PathEnd && "Base path should not be empty!"); 64 65 CharUnits Offset = 66 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl, 67 PathBegin, PathEnd); 68 if (Offset.isZero()) 69 return nullptr; 70 71 llvm::Type *PtrDiffTy = 72 Types.ConvertType(getContext().getPointerDiffType()); 73 74 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity()); 75 } 76 77 /// Gets the address of a direct base class within a complete object. 78 /// This should only be used for (1) non-virtual bases or (2) virtual bases 79 /// when the type is known to be complete (e.g. in complete destructors). 80 /// 81 /// The object pointed to by 'This' is assumed to be non-null. 82 llvm::Value * 83 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This, 84 const CXXRecordDecl *Derived, 85 const CXXRecordDecl *Base, 86 bool BaseIsVirtual) { 87 // 'this' must be a pointer (in some address space) to Derived. 88 assert(This->getType()->isPointerTy() && 89 cast<llvm::PointerType>(This->getType())->getElementType() 90 == ConvertType(Derived)); 91 92 // Compute the offset of the virtual base. 93 CharUnits Offset; 94 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived); 95 if (BaseIsVirtual) 96 Offset = Layout.getVBaseClassOffset(Base); 97 else 98 Offset = Layout.getBaseClassOffset(Base); 99 100 // Shift and cast down to the base type. 101 // TODO: for complete types, this should be possible with a GEP. 102 llvm::Value *V = This; 103 if (Offset.isPositive()) { 104 V = Builder.CreateBitCast(V, Int8PtrTy); 105 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity()); 106 } 107 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo()); 108 109 return V; 110 } 111 112 static llvm::Value * 113 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr, 114 CharUnits nonVirtualOffset, 115 llvm::Value *virtualOffset) { 116 // Assert that we have something to do. 117 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr); 118 119 // Compute the offset from the static and dynamic components. 120 llvm::Value *baseOffset; 121 if (!nonVirtualOffset.isZero()) { 122 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy, 123 nonVirtualOffset.getQuantity()); 124 if (virtualOffset) { 125 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset); 126 } 127 } else { 128 baseOffset = virtualOffset; 129 } 130 131 // Apply the base offset. 132 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy); 133 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr"); 134 return ptr; 135 } 136 137 llvm::Value * 138 CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value, 139 const CXXRecordDecl *Derived, 140 CastExpr::path_const_iterator PathBegin, 141 CastExpr::path_const_iterator PathEnd, 142 bool NullCheckValue) { 143 assert(PathBegin != PathEnd && "Base path should not be empty!"); 144 145 CastExpr::path_const_iterator Start = PathBegin; 146 const CXXRecordDecl *VBase = nullptr; 147 148 // Sema has done some convenient canonicalization here: if the 149 // access path involved any virtual steps, the conversion path will 150 // *start* with a step down to the correct virtual base subobject, 151 // and hence will not require any further steps. 152 if ((*Start)->isVirtual()) { 153 VBase = 154 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl()); 155 ++Start; 156 } 157 158 // Compute the static offset of the ultimate destination within its 159 // allocating subobject (the virtual base, if there is one, or else 160 // the "complete" object that we see). 161 CharUnits NonVirtualOffset = 162 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived, 163 Start, PathEnd); 164 165 // If there's a virtual step, we can sometimes "devirtualize" it. 166 // For now, that's limited to when the derived type is final. 167 // TODO: "devirtualize" this for accesses to known-complete objects. 168 if (VBase && Derived->hasAttr<FinalAttr>()) { 169 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived); 170 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase); 171 NonVirtualOffset += vBaseOffset; 172 VBase = nullptr; // we no longer have a virtual step 173 } 174 175 // Get the base pointer type. 176 llvm::Type *BasePtrTy = 177 ConvertType((PathEnd[-1])->getType())->getPointerTo(); 178 179 // If the static offset is zero and we don't have a virtual step, 180 // just do a bitcast; null checks are unnecessary. 181 if (NonVirtualOffset.isZero() && !VBase) { 182 return Builder.CreateBitCast(Value, BasePtrTy); 183 } 184 185 llvm::BasicBlock *origBB = nullptr; 186 llvm::BasicBlock *endBB = nullptr; 187 188 // Skip over the offset (and the vtable load) if we're supposed to 189 // null-check the pointer. 190 if (NullCheckValue) { 191 origBB = Builder.GetInsertBlock(); 192 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull"); 193 endBB = createBasicBlock("cast.end"); 194 195 llvm::Value *isNull = Builder.CreateIsNull(Value); 196 Builder.CreateCondBr(isNull, endBB, notNullBB); 197 EmitBlock(notNullBB); 198 } 199 200 // Compute the virtual offset. 201 llvm::Value *VirtualOffset = nullptr; 202 if (VBase) { 203 VirtualOffset = 204 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase); 205 } 206 207 // Apply both offsets. 208 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, 209 NonVirtualOffset, 210 VirtualOffset); 211 212 // Cast to the destination type. 213 Value = Builder.CreateBitCast(Value, BasePtrTy); 214 215 // Build a phi if we needed a null check. 216 if (NullCheckValue) { 217 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock(); 218 Builder.CreateBr(endBB); 219 EmitBlock(endBB); 220 221 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result"); 222 PHI->addIncoming(Value, notNullBB); 223 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB); 224 Value = PHI; 225 } 226 227 return Value; 228 } 229 230 llvm::Value * 231 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value, 232 const CXXRecordDecl *Derived, 233 CastExpr::path_const_iterator PathBegin, 234 CastExpr::path_const_iterator PathEnd, 235 bool NullCheckValue) { 236 assert(PathBegin != PathEnd && "Base path should not be empty!"); 237 238 QualType DerivedTy = 239 getContext().getCanonicalType(getContext().getTagDeclType(Derived)); 240 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo(); 241 242 llvm::Value *NonVirtualOffset = 243 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd); 244 245 if (!NonVirtualOffset) { 246 // No offset, we can just cast back. 247 return Builder.CreateBitCast(Value, DerivedPtrTy); 248 } 249 250 llvm::BasicBlock *CastNull = nullptr; 251 llvm::BasicBlock *CastNotNull = nullptr; 252 llvm::BasicBlock *CastEnd = nullptr; 253 254 if (NullCheckValue) { 255 CastNull = createBasicBlock("cast.null"); 256 CastNotNull = createBasicBlock("cast.notnull"); 257 CastEnd = createBasicBlock("cast.end"); 258 259 llvm::Value *IsNull = Builder.CreateIsNull(Value); 260 Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 261 EmitBlock(CastNotNull); 262 } 263 264 // Apply the offset. 265 Value = Builder.CreateBitCast(Value, Int8PtrTy); 266 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset), 267 "sub.ptr"); 268 269 // Just cast. 270 Value = Builder.CreateBitCast(Value, DerivedPtrTy); 271 272 if (NullCheckValue) { 273 Builder.CreateBr(CastEnd); 274 EmitBlock(CastNull); 275 Builder.CreateBr(CastEnd); 276 EmitBlock(CastEnd); 277 278 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 279 PHI->addIncoming(Value, CastNotNull); 280 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), 281 CastNull); 282 Value = PHI; 283 } 284 285 return Value; 286 } 287 288 llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD, 289 bool ForVirtualBase, 290 bool Delegating) { 291 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) { 292 // This constructor/destructor does not need a VTT parameter. 293 return nullptr; 294 } 295 296 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent(); 297 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent(); 298 299 llvm::Value *VTT; 300 301 uint64_t SubVTTIndex; 302 303 if (Delegating) { 304 // If this is a delegating constructor call, just load the VTT. 305 return LoadCXXVTT(); 306 } else if (RD == Base) { 307 // If the record matches the base, this is the complete ctor/dtor 308 // variant calling the base variant in a class with virtual bases. 309 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) && 310 "doing no-op VTT offset in base dtor/ctor?"); 311 assert(!ForVirtualBase && "Can't have same class as virtual base!"); 312 SubVTTIndex = 0; 313 } else { 314 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 315 CharUnits BaseOffset = ForVirtualBase ? 316 Layout.getVBaseClassOffset(Base) : 317 Layout.getBaseClassOffset(Base); 318 319 SubVTTIndex = 320 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset)); 321 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!"); 322 } 323 324 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) { 325 // A VTT parameter was passed to the constructor, use it. 326 VTT = LoadCXXVTT(); 327 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex); 328 } else { 329 // We're the complete constructor, so get the VTT by name. 330 VTT = CGM.getVTables().GetAddrOfVTT(RD); 331 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex); 332 } 333 334 return VTT; 335 } 336 337 namespace { 338 /// Call the destructor for a direct base class. 339 struct CallBaseDtor : EHScopeStack::Cleanup { 340 const CXXRecordDecl *BaseClass; 341 bool BaseIsVirtual; 342 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual) 343 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {} 344 345 void Emit(CodeGenFunction &CGF, Flags flags) override { 346 const CXXRecordDecl *DerivedClass = 347 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent(); 348 349 const CXXDestructorDecl *D = BaseClass->getDestructor(); 350 llvm::Value *Addr = 351 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(), 352 DerivedClass, BaseClass, 353 BaseIsVirtual); 354 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, 355 /*Delegating=*/false, Addr); 356 } 357 }; 358 359 /// A visitor which checks whether an initializer uses 'this' in a 360 /// way which requires the vtable to be properly set. 361 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> { 362 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super; 363 364 bool UsesThis; 365 366 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {} 367 368 // Black-list all explicit and implicit references to 'this'. 369 // 370 // Do we need to worry about external references to 'this' derived 371 // from arbitrary code? If so, then anything which runs arbitrary 372 // external code might potentially access the vtable. 373 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; } 374 }; 375 } 376 377 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) { 378 DynamicThisUseChecker Checker(C); 379 Checker.Visit(const_cast<Expr*>(Init)); 380 return Checker.UsesThis; 381 } 382 383 static void EmitBaseInitializer(CodeGenFunction &CGF, 384 const CXXRecordDecl *ClassDecl, 385 CXXCtorInitializer *BaseInit, 386 CXXCtorType CtorType) { 387 assert(BaseInit->isBaseInitializer() && 388 "Must have base initializer!"); 389 390 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 391 392 const Type *BaseType = BaseInit->getBaseClass(); 393 CXXRecordDecl *BaseClassDecl = 394 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()); 395 396 bool isBaseVirtual = BaseInit->isBaseVirtual(); 397 398 // The base constructor doesn't construct virtual bases. 399 if (CtorType == Ctor_Base && isBaseVirtual) 400 return; 401 402 // If the initializer for the base (other than the constructor 403 // itself) accesses 'this' in any way, we need to initialize the 404 // vtables. 405 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit())) 406 CGF.InitializeVTablePointers(ClassDecl); 407 408 // We can pretend to be a complete class because it only matters for 409 // virtual bases, and we only do virtual bases for complete ctors. 410 llvm::Value *V = 411 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl, 412 BaseClassDecl, 413 isBaseVirtual); 414 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType); 415 AggValueSlot AggSlot = 416 AggValueSlot::forAddr(V, Alignment, Qualifiers(), 417 AggValueSlot::IsDestructed, 418 AggValueSlot::DoesNotNeedGCBarriers, 419 AggValueSlot::IsNotAliased); 420 421 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot); 422 423 if (CGF.CGM.getLangOpts().Exceptions && 424 !BaseClassDecl->hasTrivialDestructor()) 425 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl, 426 isBaseVirtual); 427 } 428 429 static void EmitAggMemberInitializer(CodeGenFunction &CGF, 430 LValue LHS, 431 Expr *Init, 432 llvm::Value *ArrayIndexVar, 433 QualType T, 434 ArrayRef<VarDecl *> ArrayIndexes, 435 unsigned Index) { 436 if (Index == ArrayIndexes.size()) { 437 LValue LV = LHS; 438 439 if (ArrayIndexVar) { 440 // If we have an array index variable, load it and use it as an offset. 441 // Then, increment the value. 442 llvm::Value *Dest = LHS.getAddress(); 443 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar); 444 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress"); 445 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1); 446 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc"); 447 CGF.Builder.CreateStore(Next, ArrayIndexVar); 448 449 // Update the LValue. 450 LV.setAddress(Dest); 451 CharUnits Align = CGF.getContext().getTypeAlignInChars(T); 452 LV.setAlignment(std::min(Align, LV.getAlignment())); 453 } 454 455 switch (CGF.getEvaluationKind(T)) { 456 case TEK_Scalar: 457 CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false); 458 break; 459 case TEK_Complex: 460 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true); 461 break; 462 case TEK_Aggregate: { 463 AggValueSlot Slot = 464 AggValueSlot::forLValue(LV, 465 AggValueSlot::IsDestructed, 466 AggValueSlot::DoesNotNeedGCBarriers, 467 AggValueSlot::IsNotAliased); 468 469 CGF.EmitAggExpr(Init, Slot); 470 break; 471 } 472 } 473 474 return; 475 } 476 477 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T); 478 assert(Array && "Array initialization without the array type?"); 479 llvm::Value *IndexVar 480 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]); 481 assert(IndexVar && "Array index variable not loaded"); 482 483 // Initialize this index variable to zero. 484 llvm::Value* Zero 485 = llvm::Constant::getNullValue( 486 CGF.ConvertType(CGF.getContext().getSizeType())); 487 CGF.Builder.CreateStore(Zero, IndexVar); 488 489 // Start the loop with a block that tests the condition. 490 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond"); 491 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end"); 492 493 CGF.EmitBlock(CondBlock); 494 495 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body"); 496 // Generate: if (loop-index < number-of-elements) fall to the loop body, 497 // otherwise, go to the block after the for-loop. 498 uint64_t NumElements = Array->getSize().getZExtValue(); 499 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar); 500 llvm::Value *NumElementsPtr = 501 llvm::ConstantInt::get(Counter->getType(), NumElements); 502 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr, 503 "isless"); 504 505 // If the condition is true, execute the body. 506 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor); 507 508 CGF.EmitBlock(ForBody); 509 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc"); 510 511 // Inside the loop body recurse to emit the inner loop or, eventually, the 512 // constructor call. 513 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar, 514 Array->getElementType(), ArrayIndexes, Index + 1); 515 516 CGF.EmitBlock(ContinueBlock); 517 518 // Emit the increment of the loop counter. 519 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1); 520 Counter = CGF.Builder.CreateLoad(IndexVar); 521 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc"); 522 CGF.Builder.CreateStore(NextVal, IndexVar); 523 524 // Finally, branch back up to the condition for the next iteration. 525 CGF.EmitBranch(CondBlock); 526 527 // Emit the fall-through block. 528 CGF.EmitBlock(AfterFor, true); 529 } 530 531 static void EmitMemberInitializer(CodeGenFunction &CGF, 532 const CXXRecordDecl *ClassDecl, 533 CXXCtorInitializer *MemberInit, 534 const CXXConstructorDecl *Constructor, 535 FunctionArgList &Args) { 536 assert(MemberInit->isAnyMemberInitializer() && 537 "Must have member initializer!"); 538 assert(MemberInit->getInit() && "Must have initializer!"); 539 540 // non-static data member initializers. 541 FieldDecl *Field = MemberInit->getAnyMember(); 542 QualType FieldType = Field->getType(); 543 544 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 545 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl); 546 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy); 547 548 if (MemberInit->isIndirectMemberInitializer()) { 549 // If we are initializing an anonymous union field, drill down to 550 // the field. 551 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember(); 552 for (const auto *I : IndirectField->chain()) 553 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I)); 554 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType(); 555 } else { 556 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field); 557 } 558 559 // Special case: if we are in a copy or move constructor, and we are copying 560 // an array of PODs or classes with trivial copy constructors, ignore the 561 // AST and perform the copy we know is equivalent. 562 // FIXME: This is hacky at best... if we had a bit more explicit information 563 // in the AST, we could generalize it more easily. 564 const ConstantArrayType *Array 565 = CGF.getContext().getAsConstantArrayType(FieldType); 566 if (Array && Constructor->isDefaulted() && 567 Constructor->isCopyOrMoveConstructor()) { 568 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array); 569 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit()); 570 if (BaseElementTy.isPODType(CGF.getContext()) || 571 (CE && CE->getConstructor()->isTrivial())) { 572 // Find the source pointer. We know it's the last argument because 573 // we know we're in an implicit copy constructor. 574 unsigned SrcArgIndex = Args.size() - 1; 575 llvm::Value *SrcPtr 576 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex])); 577 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy); 578 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field); 579 580 // Copy the aggregate. 581 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType, 582 LHS.isVolatileQualified()); 583 return; 584 } 585 } 586 587 ArrayRef<VarDecl *> ArrayIndexes; 588 if (MemberInit->getNumArrayIndices()) 589 ArrayIndexes = MemberInit->getArrayIndexes(); 590 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes); 591 } 592 593 void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, 594 LValue LHS, Expr *Init, 595 ArrayRef<VarDecl *> ArrayIndexes) { 596 QualType FieldType = Field->getType(); 597 switch (getEvaluationKind(FieldType)) { 598 case TEK_Scalar: 599 if (LHS.isSimple()) { 600 EmitExprAsInit(Init, Field, LHS, false); 601 } else { 602 RValue RHS = RValue::get(EmitScalarExpr(Init)); 603 EmitStoreThroughLValue(RHS, LHS); 604 } 605 break; 606 case TEK_Complex: 607 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true); 608 break; 609 case TEK_Aggregate: { 610 llvm::Value *ArrayIndexVar = nullptr; 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 } 639 640 // Ensure that we destroy this object if an exception is thrown 641 // later in the constructor. 642 QualType::DestructionKind dtorKind = FieldType.isDestructedType(); 643 if (needsEHCleanup(dtorKind)) 644 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType); 645 } 646 647 /// Checks whether the given constructor is a valid subject for the 648 /// complete-to-base constructor delegation optimization, i.e. 649 /// emitting the complete constructor as a simple call to the base 650 /// constructor. 651 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) { 652 653 // Currently we disable the optimization for classes with virtual 654 // bases because (1) the addresses of parameter variables need to be 655 // consistent across all initializers but (2) the delegate function 656 // call necessarily creates a second copy of the parameter variable. 657 // 658 // The limiting example (purely theoretical AFAIK): 659 // struct A { A(int &c) { c++; } }; 660 // struct B : virtual A { 661 // B(int count) : A(count) { printf("%d\n", count); } 662 // }; 663 // ...although even this example could in principle be emitted as a 664 // delegation since the address of the parameter doesn't escape. 665 if (Ctor->getParent()->getNumVBases()) { 666 // TODO: white-list trivial vbase initializers. This case wouldn't 667 // be subject to the restrictions below. 668 669 // TODO: white-list cases where: 670 // - there are no non-reference parameters to the constructor 671 // - the initializers don't access any non-reference parameters 672 // - the initializers don't take the address of non-reference 673 // parameters 674 // - etc. 675 // If we ever add any of the above cases, remember that: 676 // - function-try-blocks will always blacklist this optimization 677 // - we need to perform the constructor prologue and cleanup in 678 // EmitConstructorBody. 679 680 return false; 681 } 682 683 // We also disable the optimization for variadic functions because 684 // it's impossible to "re-pass" varargs. 685 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic()) 686 return false; 687 688 // FIXME: Decide if we can do a delegation of a delegating constructor. 689 if (Ctor->isDelegatingConstructor()) 690 return false; 691 692 return true; 693 } 694 695 /// EmitConstructorBody - Emits the body of the current constructor. 696 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) { 697 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl()); 698 CXXCtorType CtorType = CurGD.getCtorType(); 699 700 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() || 701 CtorType == Ctor_Complete) && 702 "can only generate complete ctor for this ABI"); 703 704 // Before we go any further, try the complete->base constructor 705 // delegation optimization. 706 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) && 707 CGM.getTarget().getCXXABI().hasConstructorVariants()) { 708 if (CGDebugInfo *DI = getDebugInfo()) 709 DI->EmitLocation(Builder, Ctor->getLocEnd()); 710 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd()); 711 return; 712 } 713 714 const FunctionDecl *Definition = 0; 715 Stmt *Body = Ctor->getBody(Definition); 716 assert(Definition == Ctor && "emitting wrong constructor body"); 717 718 // Enter the function-try-block before the constructor prologue if 719 // applicable. 720 bool IsTryBody = (Body && isa<CXXTryStmt>(Body)); 721 if (IsTryBody) 722 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 723 724 RegionCounter Cnt = getPGORegionCounter(Body); 725 Cnt.beginRegion(Builder); 726 727 RunCleanupsScope RunCleanups(*this); 728 729 // TODO: in restricted cases, we can emit the vbase initializers of 730 // a complete ctor and then delegate to the base ctor. 731 732 // Emit the constructor prologue, i.e. the base and member 733 // initializers. 734 EmitCtorPrologue(Ctor, CtorType, Args); 735 736 // Emit the body of the statement. 737 if (IsTryBody) 738 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 739 else if (Body) 740 EmitStmt(Body); 741 742 // Emit any cleanup blocks associated with the member or base 743 // initializers, which includes (along the exceptional path) the 744 // destructors for those members and bases that were fully 745 // constructed. 746 RunCleanups.ForceCleanup(); 747 748 if (IsTryBody) 749 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 750 } 751 752 namespace { 753 /// RAII object to indicate that codegen is copying the value representation 754 /// instead of the object representation. Useful when copying a struct or 755 /// class which has uninitialized members and we're only performing 756 /// lvalue-to-rvalue conversion on the object but not its members. 757 class CopyingValueRepresentation { 758 public: 759 explicit CopyingValueRepresentation(CodeGenFunction &CGF) 760 : CGF(CGF), SO(*CGF.SanOpts), OldSanOpts(CGF.SanOpts) { 761 SO.Bool = false; 762 SO.Enum = false; 763 CGF.SanOpts = &SO; 764 } 765 ~CopyingValueRepresentation() { 766 CGF.SanOpts = OldSanOpts; 767 } 768 private: 769 CodeGenFunction &CGF; 770 SanitizerOptions SO; 771 const SanitizerOptions *OldSanOpts; 772 }; 773 } 774 775 namespace { 776 class FieldMemcpyizer { 777 public: 778 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl, 779 const VarDecl *SrcRec) 780 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec), 781 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)), 782 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0), 783 LastFieldOffset(0), LastAddedFieldIndex(0) {} 784 785 static bool isMemcpyableField(FieldDecl *F) { 786 Qualifiers Qual = F->getType().getQualifiers(); 787 if (Qual.hasVolatile() || Qual.hasObjCLifetime()) 788 return false; 789 return true; 790 } 791 792 void addMemcpyableField(FieldDecl *F) { 793 if (!FirstField) 794 addInitialField(F); 795 else 796 addNextField(F); 797 } 798 799 CharUnits getMemcpySize() const { 800 unsigned LastFieldSize = 801 LastField->isBitField() ? 802 LastField->getBitWidthValue(CGF.getContext()) : 803 CGF.getContext().getTypeSize(LastField->getType()); 804 uint64_t MemcpySizeBits = 805 LastFieldOffset + LastFieldSize - FirstFieldOffset + 806 CGF.getContext().getCharWidth() - 1; 807 CharUnits MemcpySize = 808 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits); 809 return MemcpySize; 810 } 811 812 void emitMemcpy() { 813 // Give the subclass a chance to bail out if it feels the memcpy isn't 814 // worth it (e.g. Hasn't aggregated enough data). 815 if (!FirstField) { 816 return; 817 } 818 819 CharUnits Alignment; 820 821 if (FirstField->isBitField()) { 822 const CGRecordLayout &RL = 823 CGF.getTypes().getCGRecordLayout(FirstField->getParent()); 824 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField); 825 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment); 826 } else { 827 Alignment = CGF.getContext().getDeclAlign(FirstField); 828 } 829 830 assert((CGF.getContext().toCharUnitsFromBits(FirstFieldOffset) % 831 Alignment) == 0 && "Bad field alignment."); 832 833 CharUnits MemcpySize = getMemcpySize(); 834 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl); 835 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 836 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy); 837 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField); 838 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec)); 839 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy); 840 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField); 841 842 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(), 843 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(), 844 MemcpySize, Alignment); 845 reset(); 846 } 847 848 void reset() { 849 FirstField = nullptr; 850 } 851 852 protected: 853 CodeGenFunction &CGF; 854 const CXXRecordDecl *ClassDecl; 855 856 private: 857 858 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr, 859 CharUnits Size, CharUnits Alignment) { 860 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType()); 861 llvm::Type *DBP = 862 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace()); 863 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP); 864 865 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType()); 866 llvm::Type *SBP = 867 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace()); 868 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP); 869 870 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(), 871 Alignment.getQuantity()); 872 } 873 874 void addInitialField(FieldDecl *F) { 875 FirstField = F; 876 LastField = F; 877 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex()); 878 LastFieldOffset = FirstFieldOffset; 879 LastAddedFieldIndex = F->getFieldIndex(); 880 return; 881 } 882 883 void addNextField(FieldDecl *F) { 884 // For the most part, the following invariant will hold: 885 // F->getFieldIndex() == LastAddedFieldIndex + 1 886 // The one exception is that Sema won't add a copy-initializer for an 887 // unnamed bitfield, which will show up here as a gap in the sequence. 888 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 && 889 "Cannot aggregate fields out of order."); 890 LastAddedFieldIndex = F->getFieldIndex(); 891 892 // The 'first' and 'last' fields are chosen by offset, rather than field 893 // index. This allows the code to support bitfields, as well as regular 894 // fields. 895 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex()); 896 if (FOffset < FirstFieldOffset) { 897 FirstField = F; 898 FirstFieldOffset = FOffset; 899 } else if (FOffset > LastFieldOffset) { 900 LastField = F; 901 LastFieldOffset = FOffset; 902 } 903 } 904 905 const VarDecl *SrcRec; 906 const ASTRecordLayout &RecLayout; 907 FieldDecl *FirstField; 908 FieldDecl *LastField; 909 uint64_t FirstFieldOffset, LastFieldOffset; 910 unsigned LastAddedFieldIndex; 911 }; 912 913 class ConstructorMemcpyizer : public FieldMemcpyizer { 914 private: 915 916 /// Get source argument for copy constructor. Returns null if not a copy 917 /// constructor. 918 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF, 919 const CXXConstructorDecl *CD, 920 FunctionArgList &Args) { 921 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted()) 922 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)]; 923 return nullptr; 924 } 925 926 // Returns true if a CXXCtorInitializer represents a member initialization 927 // that can be rolled into a memcpy. 928 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const { 929 if (!MemcpyableCtor) 930 return false; 931 FieldDecl *Field = MemberInit->getMember(); 932 assert(Field && "No field for member init."); 933 QualType FieldType = Field->getType(); 934 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit()); 935 936 // Bail out on non-POD, not-trivially-constructable members. 937 if (!(CE && CE->getConstructor()->isTrivial()) && 938 !(FieldType.isTriviallyCopyableType(CGF.getContext()) || 939 FieldType->isReferenceType())) 940 return false; 941 942 // Bail out on volatile fields. 943 if (!isMemcpyableField(Field)) 944 return false; 945 946 // Otherwise we're good. 947 return true; 948 } 949 950 public: 951 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD, 952 FunctionArgList &Args) 953 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)), 954 ConstructorDecl(CD), 955 MemcpyableCtor(CD->isDefaulted() && 956 CD->isCopyOrMoveConstructor() && 957 CGF.getLangOpts().getGC() == LangOptions::NonGC), 958 Args(Args) { } 959 960 void addMemberInitializer(CXXCtorInitializer *MemberInit) { 961 if (isMemberInitMemcpyable(MemberInit)) { 962 AggregatedInits.push_back(MemberInit); 963 addMemcpyableField(MemberInit->getMember()); 964 } else { 965 emitAggregatedInits(); 966 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit, 967 ConstructorDecl, Args); 968 } 969 } 970 971 void emitAggregatedInits() { 972 if (AggregatedInits.size() <= 1) { 973 // This memcpy is too small to be worthwhile. Fall back on default 974 // codegen. 975 if (!AggregatedInits.empty()) { 976 CopyingValueRepresentation CVR(CGF); 977 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), 978 AggregatedInits[0], ConstructorDecl, Args); 979 } 980 reset(); 981 return; 982 } 983 984 pushEHDestructors(); 985 emitMemcpy(); 986 AggregatedInits.clear(); 987 } 988 989 void pushEHDestructors() { 990 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 991 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl); 992 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy); 993 994 for (unsigned i = 0; i < AggregatedInits.size(); ++i) { 995 QualType FieldType = AggregatedInits[i]->getMember()->getType(); 996 QualType::DestructionKind dtorKind = FieldType.isDestructedType(); 997 if (CGF.needsEHCleanup(dtorKind)) 998 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType); 999 } 1000 } 1001 1002 void finish() { 1003 emitAggregatedInits(); 1004 } 1005 1006 private: 1007 const CXXConstructorDecl *ConstructorDecl; 1008 bool MemcpyableCtor; 1009 FunctionArgList &Args; 1010 SmallVector<CXXCtorInitializer*, 16> AggregatedInits; 1011 }; 1012 1013 class AssignmentMemcpyizer : public FieldMemcpyizer { 1014 private: 1015 1016 // Returns the memcpyable field copied by the given statement, if one 1017 // exists. Otherwise returns null. 1018 FieldDecl *getMemcpyableField(Stmt *S) { 1019 if (!AssignmentsMemcpyable) 1020 return nullptr; 1021 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) { 1022 // Recognise trivial assignments. 1023 if (BO->getOpcode() != BO_Assign) 1024 return nullptr; 1025 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS()); 1026 if (!ME) 1027 return nullptr; 1028 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl()); 1029 if (!Field || !isMemcpyableField(Field)) 1030 return nullptr; 1031 Stmt *RHS = BO->getRHS(); 1032 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS)) 1033 RHS = EC->getSubExpr(); 1034 if (!RHS) 1035 return nullptr; 1036 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS); 1037 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field) 1038 return nullptr; 1039 return Field; 1040 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) { 1041 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl()); 1042 if (!(MD && (MD->isCopyAssignmentOperator() || 1043 MD->isMoveAssignmentOperator()) && 1044 MD->isTrivial())) 1045 return nullptr; 1046 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument()); 1047 if (!IOA) 1048 return nullptr; 1049 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl()); 1050 if (!Field || !isMemcpyableField(Field)) 1051 return nullptr; 1052 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0)); 1053 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl())) 1054 return nullptr; 1055 return Field; 1056 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) { 1057 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 1058 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy) 1059 return nullptr; 1060 Expr *DstPtr = CE->getArg(0); 1061 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr)) 1062 DstPtr = DC->getSubExpr(); 1063 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr); 1064 if (!DUO || DUO->getOpcode() != UO_AddrOf) 1065 return nullptr; 1066 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr()); 1067 if (!ME) 1068 return nullptr; 1069 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl()); 1070 if (!Field || !isMemcpyableField(Field)) 1071 return nullptr; 1072 Expr *SrcPtr = CE->getArg(1); 1073 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr)) 1074 SrcPtr = SC->getSubExpr(); 1075 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr); 1076 if (!SUO || SUO->getOpcode() != UO_AddrOf) 1077 return nullptr; 1078 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr()); 1079 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl())) 1080 return nullptr; 1081 return Field; 1082 } 1083 1084 return nullptr; 1085 } 1086 1087 bool AssignmentsMemcpyable; 1088 SmallVector<Stmt*, 16> AggregatedStmts; 1089 1090 public: 1091 1092 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD, 1093 FunctionArgList &Args) 1094 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]), 1095 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) { 1096 assert(Args.size() == 2); 1097 } 1098 1099 void emitAssignment(Stmt *S) { 1100 FieldDecl *F = getMemcpyableField(S); 1101 if (F) { 1102 addMemcpyableField(F); 1103 AggregatedStmts.push_back(S); 1104 } else { 1105 emitAggregatedStmts(); 1106 CGF.EmitStmt(S); 1107 } 1108 } 1109 1110 void emitAggregatedStmts() { 1111 if (AggregatedStmts.size() <= 1) { 1112 if (!AggregatedStmts.empty()) { 1113 CopyingValueRepresentation CVR(CGF); 1114 CGF.EmitStmt(AggregatedStmts[0]); 1115 } 1116 reset(); 1117 } 1118 1119 emitMemcpy(); 1120 AggregatedStmts.clear(); 1121 } 1122 1123 void finish() { 1124 emitAggregatedStmts(); 1125 } 1126 }; 1127 1128 } 1129 1130 /// EmitCtorPrologue - This routine generates necessary code to initialize 1131 /// base classes and non-static data members belonging to this constructor. 1132 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD, 1133 CXXCtorType CtorType, 1134 FunctionArgList &Args) { 1135 if (CD->isDelegatingConstructor()) 1136 return EmitDelegatingCXXConstructorCall(CD, Args); 1137 1138 const CXXRecordDecl *ClassDecl = CD->getParent(); 1139 1140 CXXConstructorDecl::init_const_iterator B = CD->init_begin(), 1141 E = CD->init_end(); 1142 1143 llvm::BasicBlock *BaseCtorContinueBB = nullptr; 1144 if (ClassDecl->getNumVBases() && 1145 !CGM.getTarget().getCXXABI().hasConstructorVariants()) { 1146 // The ABIs that don't have constructor variants need to put a branch 1147 // before the virtual base initialization code. 1148 BaseCtorContinueBB = 1149 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl); 1150 assert(BaseCtorContinueBB); 1151 } 1152 1153 // Virtual base initializers first. 1154 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) { 1155 EmitBaseInitializer(*this, ClassDecl, *B, CtorType); 1156 } 1157 1158 if (BaseCtorContinueBB) { 1159 // Complete object handler should continue to the remaining initializers. 1160 Builder.CreateBr(BaseCtorContinueBB); 1161 EmitBlock(BaseCtorContinueBB); 1162 } 1163 1164 // Then, non-virtual base initializers. 1165 for (; B != E && (*B)->isBaseInitializer(); B++) { 1166 assert(!(*B)->isBaseVirtual()); 1167 EmitBaseInitializer(*this, ClassDecl, *B, CtorType); 1168 } 1169 1170 InitializeVTablePointers(ClassDecl); 1171 1172 // And finally, initialize class members. 1173 FieldConstructionScope FCS(*this, CXXThisValue); 1174 ConstructorMemcpyizer CM(*this, CD, Args); 1175 for (; B != E; B++) { 1176 CXXCtorInitializer *Member = (*B); 1177 assert(!Member->isBaseInitializer()); 1178 assert(Member->isAnyMemberInitializer() && 1179 "Delegating initializer on non-delegating constructor"); 1180 CM.addMemberInitializer(Member); 1181 } 1182 CM.finish(); 1183 } 1184 1185 static bool 1186 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field); 1187 1188 static bool 1189 HasTrivialDestructorBody(ASTContext &Context, 1190 const CXXRecordDecl *BaseClassDecl, 1191 const CXXRecordDecl *MostDerivedClassDecl) 1192 { 1193 // If the destructor is trivial we don't have to check anything else. 1194 if (BaseClassDecl->hasTrivialDestructor()) 1195 return true; 1196 1197 if (!BaseClassDecl->getDestructor()->hasTrivialBody()) 1198 return false; 1199 1200 // Check fields. 1201 for (const auto *Field : BaseClassDecl->fields()) 1202 if (!FieldHasTrivialDestructorBody(Context, Field)) 1203 return false; 1204 1205 // Check non-virtual bases. 1206 for (const auto &I : BaseClassDecl->bases()) { 1207 if (I.isVirtual()) 1208 continue; 1209 1210 const CXXRecordDecl *NonVirtualBase = 1211 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 1212 if (!HasTrivialDestructorBody(Context, NonVirtualBase, 1213 MostDerivedClassDecl)) 1214 return false; 1215 } 1216 1217 if (BaseClassDecl == MostDerivedClassDecl) { 1218 // Check virtual bases. 1219 for (const auto &I : BaseClassDecl->vbases()) { 1220 const CXXRecordDecl *VirtualBase = 1221 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 1222 if (!HasTrivialDestructorBody(Context, VirtualBase, 1223 MostDerivedClassDecl)) 1224 return false; 1225 } 1226 } 1227 1228 return true; 1229 } 1230 1231 static bool 1232 FieldHasTrivialDestructorBody(ASTContext &Context, 1233 const FieldDecl *Field) 1234 { 1235 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType()); 1236 1237 const RecordType *RT = FieldBaseElementType->getAs<RecordType>(); 1238 if (!RT) 1239 return true; 1240 1241 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1242 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl); 1243 } 1244 1245 /// CanSkipVTablePointerInitialization - Check whether we need to initialize 1246 /// any vtable pointers before calling this destructor. 1247 static bool CanSkipVTablePointerInitialization(ASTContext &Context, 1248 const CXXDestructorDecl *Dtor) { 1249 if (!Dtor->hasTrivialBody()) 1250 return false; 1251 1252 // Check the fields. 1253 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1254 for (const auto *Field : ClassDecl->fields()) 1255 if (!FieldHasTrivialDestructorBody(Context, Field)) 1256 return false; 1257 1258 return true; 1259 } 1260 1261 /// EmitDestructorBody - Emits the body of the current destructor. 1262 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) { 1263 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl()); 1264 CXXDtorType DtorType = CurGD.getDtorType(); 1265 1266 // The call to operator delete in a deleting destructor happens 1267 // outside of the function-try-block, which means it's always 1268 // possible to delegate the destructor body to the complete 1269 // destructor. Do so. 1270 if (DtorType == Dtor_Deleting) { 1271 EnterDtorCleanups(Dtor, Dtor_Deleting); 1272 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false, 1273 /*Delegating=*/false, LoadCXXThis()); 1274 PopCleanupBlock(); 1275 return; 1276 } 1277 1278 Stmt *Body = Dtor->getBody(); 1279 1280 // If the body is a function-try-block, enter the try before 1281 // anything else. 1282 bool isTryBody = (Body && isa<CXXTryStmt>(Body)); 1283 if (isTryBody) 1284 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 1285 1286 // Enter the epilogue cleanups. 1287 RunCleanupsScope DtorEpilogue(*this); 1288 1289 // If this is the complete variant, just invoke the base variant; 1290 // the epilogue will destruct the virtual bases. But we can't do 1291 // this optimization if the body is a function-try-block, because 1292 // we'd introduce *two* handler blocks. In the Microsoft ABI, we 1293 // always delegate because we might not have a definition in this TU. 1294 switch (DtorType) { 1295 case Dtor_Comdat: 1296 llvm_unreachable("not expecting a COMDAT"); 1297 1298 case Dtor_Deleting: llvm_unreachable("already handled deleting case"); 1299 1300 case Dtor_Complete: 1301 assert((Body || getTarget().getCXXABI().isMicrosoft()) && 1302 "can't emit a dtor without a body for non-Microsoft ABIs"); 1303 1304 // Enter the cleanup scopes for virtual bases. 1305 EnterDtorCleanups(Dtor, Dtor_Complete); 1306 1307 if (!isTryBody) { 1308 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false, 1309 /*Delegating=*/false, LoadCXXThis()); 1310 break; 1311 } 1312 // Fallthrough: act like we're in the base variant. 1313 1314 case Dtor_Base: 1315 assert(Body); 1316 1317 RegionCounter Cnt = getPGORegionCounter(Body); 1318 Cnt.beginRegion(Builder); 1319 1320 // Enter the cleanup scopes for fields and non-virtual bases. 1321 EnterDtorCleanups(Dtor, Dtor_Base); 1322 1323 // Initialize the vtable pointers before entering the body. 1324 if (!CanSkipVTablePointerInitialization(getContext(), Dtor)) 1325 InitializeVTablePointers(Dtor->getParent()); 1326 1327 if (isTryBody) 1328 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 1329 else if (Body) 1330 EmitStmt(Body); 1331 else { 1332 assert(Dtor->isImplicit() && "bodyless dtor not implicit"); 1333 // nothing to do besides what's in the epilogue 1334 } 1335 // -fapple-kext must inline any call to this dtor into 1336 // the caller's body. 1337 if (getLangOpts().AppleKext) 1338 CurFn->addFnAttr(llvm::Attribute::AlwaysInline); 1339 break; 1340 } 1341 1342 // Jump out through the epilogue cleanups. 1343 DtorEpilogue.ForceCleanup(); 1344 1345 // Exit the try if applicable. 1346 if (isTryBody) 1347 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 1348 } 1349 1350 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) { 1351 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl()); 1352 const Stmt *RootS = AssignOp->getBody(); 1353 assert(isa<CompoundStmt>(RootS) && 1354 "Body of an implicit assignment operator should be compound stmt."); 1355 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS); 1356 1357 LexicalScope Scope(*this, RootCS->getSourceRange()); 1358 1359 AssignmentMemcpyizer AM(*this, AssignOp, Args); 1360 for (auto *I : RootCS->body()) 1361 AM.emitAssignment(I); 1362 AM.finish(); 1363 } 1364 1365 namespace { 1366 /// Call the operator delete associated with the current destructor. 1367 struct CallDtorDelete : EHScopeStack::Cleanup { 1368 CallDtorDelete() {} 1369 1370 void Emit(CodeGenFunction &CGF, Flags flags) override { 1371 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl); 1372 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1373 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(), 1374 CGF.getContext().getTagDeclType(ClassDecl)); 1375 } 1376 }; 1377 1378 struct CallDtorDeleteConditional : EHScopeStack::Cleanup { 1379 llvm::Value *ShouldDeleteCondition; 1380 public: 1381 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition) 1382 : ShouldDeleteCondition(ShouldDeleteCondition) { 1383 assert(ShouldDeleteCondition != nullptr); 1384 } 1385 1386 void Emit(CodeGenFunction &CGF, Flags flags) override { 1387 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete"); 1388 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue"); 1389 llvm::Value *ShouldCallDelete 1390 = CGF.Builder.CreateIsNull(ShouldDeleteCondition); 1391 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB); 1392 1393 CGF.EmitBlock(callDeleteBB); 1394 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl); 1395 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1396 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(), 1397 CGF.getContext().getTagDeclType(ClassDecl)); 1398 CGF.Builder.CreateBr(continueBB); 1399 1400 CGF.EmitBlock(continueBB); 1401 } 1402 }; 1403 1404 class DestroyField : public EHScopeStack::Cleanup { 1405 const FieldDecl *field; 1406 CodeGenFunction::Destroyer *destroyer; 1407 bool useEHCleanupForArray; 1408 1409 public: 1410 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer, 1411 bool useEHCleanupForArray) 1412 : field(field), destroyer(destroyer), 1413 useEHCleanupForArray(useEHCleanupForArray) {} 1414 1415 void Emit(CodeGenFunction &CGF, Flags flags) override { 1416 // Find the address of the field. 1417 llvm::Value *thisValue = CGF.LoadCXXThis(); 1418 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent()); 1419 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy); 1420 LValue LV = CGF.EmitLValueForField(ThisLV, field); 1421 assert(LV.isSimple()); 1422 1423 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer, 1424 flags.isForNormalCleanup() && useEHCleanupForArray); 1425 } 1426 }; 1427 } 1428 1429 /// \brief Emit all code that comes at the end of class's 1430 /// destructor. This is to call destructors on members and base classes 1431 /// in reverse order of their construction. 1432 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD, 1433 CXXDtorType DtorType) { 1434 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) && 1435 "Should not emit dtor epilogue for non-exported trivial dtor!"); 1436 1437 // The deleting-destructor phase just needs to call the appropriate 1438 // operator delete that Sema picked up. 1439 if (DtorType == Dtor_Deleting) { 1440 assert(DD->getOperatorDelete() && 1441 "operator delete missing - EnterDtorCleanups"); 1442 if (CXXStructorImplicitParamValue) { 1443 // If there is an implicit param to the deleting dtor, it's a boolean 1444 // telling whether we should call delete at the end of the dtor. 1445 EHStack.pushCleanup<CallDtorDeleteConditional>( 1446 NormalAndEHCleanup, CXXStructorImplicitParamValue); 1447 } else { 1448 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup); 1449 } 1450 return; 1451 } 1452 1453 const CXXRecordDecl *ClassDecl = DD->getParent(); 1454 1455 // Unions have no bases and do not call field destructors. 1456 if (ClassDecl->isUnion()) 1457 return; 1458 1459 // The complete-destructor phase just destructs all the virtual bases. 1460 if (DtorType == Dtor_Complete) { 1461 1462 // We push them in the forward order so that they'll be popped in 1463 // the reverse order. 1464 for (const auto &Base : ClassDecl->vbases()) { 1465 CXXRecordDecl *BaseClassDecl 1466 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 1467 1468 // Ignore trivial destructors. 1469 if (BaseClassDecl->hasTrivialDestructor()) 1470 continue; 1471 1472 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1473 BaseClassDecl, 1474 /*BaseIsVirtual*/ true); 1475 } 1476 1477 return; 1478 } 1479 1480 assert(DtorType == Dtor_Base); 1481 1482 // Destroy non-virtual bases. 1483 for (const auto &Base : ClassDecl->bases()) { 1484 // Ignore virtual bases. 1485 if (Base.isVirtual()) 1486 continue; 1487 1488 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl(); 1489 1490 // Ignore trivial destructors. 1491 if (BaseClassDecl->hasTrivialDestructor()) 1492 continue; 1493 1494 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1495 BaseClassDecl, 1496 /*BaseIsVirtual*/ false); 1497 } 1498 1499 // Destroy direct fields. 1500 for (const auto *Field : ClassDecl->fields()) { 1501 QualType type = Field->getType(); 1502 QualType::DestructionKind dtorKind = type.isDestructedType(); 1503 if (!dtorKind) continue; 1504 1505 // Anonymous union members do not have their destructors called. 1506 const RecordType *RT = type->getAsUnionType(); 1507 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue; 1508 1509 CleanupKind cleanupKind = getCleanupKind(dtorKind); 1510 EHStack.pushCleanup<DestroyField>(cleanupKind, Field, 1511 getDestroyer(dtorKind), 1512 cleanupKind & EHCleanup); 1513 } 1514 } 1515 1516 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 1517 /// constructor for each of several members of an array. 1518 /// 1519 /// \param ctor the constructor to call for each element 1520 /// \param arrayType the type of the array to initialize 1521 /// \param arrayBegin an arrayType* 1522 /// \param zeroInitialize true if each element should be 1523 /// zero-initialized before it is constructed 1524 void CodeGenFunction::EmitCXXAggrConstructorCall( 1525 const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType, 1526 llvm::Value *arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) { 1527 QualType elementType; 1528 llvm::Value *numElements = 1529 emitArrayLength(arrayType, elementType, arrayBegin); 1530 1531 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize); 1532 } 1533 1534 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 1535 /// constructor for each of several members of an array. 1536 /// 1537 /// \param ctor the constructor to call for each element 1538 /// \param numElements the number of elements in the array; 1539 /// may be zero 1540 /// \param arrayBegin a T*, where T is the type constructed by ctor 1541 /// \param zeroInitialize true if each element should be 1542 /// zero-initialized before it is constructed 1543 void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, 1544 llvm::Value *numElements, 1545 llvm::Value *arrayBegin, 1546 const CXXConstructExpr *E, 1547 bool zeroInitialize) { 1548 1549 // It's legal for numElements to be zero. This can happen both 1550 // dynamically, because x can be zero in 'new A[x]', and statically, 1551 // because of GCC extensions that permit zero-length arrays. There 1552 // are probably legitimate places where we could assume that this 1553 // doesn't happen, but it's not clear that it's worth it. 1554 llvm::BranchInst *zeroCheckBranch = nullptr; 1555 1556 // Optimize for a constant count. 1557 llvm::ConstantInt *constantCount 1558 = dyn_cast<llvm::ConstantInt>(numElements); 1559 if (constantCount) { 1560 // Just skip out if the constant count is zero. 1561 if (constantCount->isZero()) return; 1562 1563 // Otherwise, emit the check. 1564 } else { 1565 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop"); 1566 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty"); 1567 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB); 1568 EmitBlock(loopBB); 1569 } 1570 1571 // Find the end of the array. 1572 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements, 1573 "arrayctor.end"); 1574 1575 // Enter the loop, setting up a phi for the current location to initialize. 1576 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1577 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop"); 1578 EmitBlock(loopBB); 1579 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2, 1580 "arrayctor.cur"); 1581 cur->addIncoming(arrayBegin, entryBB); 1582 1583 // Inside the loop body, emit the constructor call on the array element. 1584 1585 QualType type = getContext().getTypeDeclType(ctor->getParent()); 1586 1587 // Zero initialize the storage, if requested. 1588 if (zeroInitialize) 1589 EmitNullInitialization(cur, type); 1590 1591 // C++ [class.temporary]p4: 1592 // There are two contexts in which temporaries are destroyed at a different 1593 // point than the end of the full-expression. The first context is when a 1594 // default constructor is called to initialize an element of an array. 1595 // If the constructor has one or more default arguments, the destruction of 1596 // every temporary created in a default argument expression is sequenced 1597 // before the construction of the next array element, if any. 1598 1599 { 1600 RunCleanupsScope Scope(*this); 1601 1602 // Evaluate the constructor and its arguments in a regular 1603 // partial-destroy cleanup. 1604 if (getLangOpts().Exceptions && 1605 !ctor->getParent()->hasTrivialDestructor()) { 1606 Destroyer *destroyer = destroyCXXObject; 1607 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer); 1608 } 1609 1610 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false, 1611 /*Delegating=*/false, cur, E); 1612 } 1613 1614 // Go to the next element. 1615 llvm::Value *next = 1616 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1), 1617 "arrayctor.next"); 1618 cur->addIncoming(next, Builder.GetInsertBlock()); 1619 1620 // Check whether that's the end of the loop. 1621 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done"); 1622 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont"); 1623 Builder.CreateCondBr(done, contBB, loopBB); 1624 1625 // Patch the earlier check to skip over the loop. 1626 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB); 1627 1628 EmitBlock(contBB); 1629 } 1630 1631 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF, 1632 llvm::Value *addr, 1633 QualType type) { 1634 const RecordType *rtype = type->castAs<RecordType>(); 1635 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl()); 1636 const CXXDestructorDecl *dtor = record->getDestructor(); 1637 assert(!dtor->isTrivial()); 1638 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false, 1639 /*Delegating=*/false, addr); 1640 } 1641 1642 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 1643 CXXCtorType Type, 1644 bool ForVirtualBase, 1645 bool Delegating, llvm::Value *This, 1646 const CXXConstructExpr *E) { 1647 // If this is a trivial constructor, just emit what's needed. 1648 if (D->isTrivial()) { 1649 if (E->getNumArgs() == 0) { 1650 // Trivial default constructor, no codegen required. 1651 assert(D->isDefaultConstructor() && 1652 "trivial 0-arg ctor not a default ctor"); 1653 return; 1654 } 1655 1656 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor"); 1657 assert(D->isCopyOrMoveConstructor() && 1658 "trivial 1-arg ctor not a copy/move ctor"); 1659 1660 const Expr *Arg = E->getArg(0); 1661 QualType Ty = Arg->getType(); 1662 llvm::Value *Src = EmitLValue(Arg).getAddress(); 1663 EmitAggregateCopy(This, Src, Ty); 1664 return; 1665 } 1666 1667 // C++11 [class.mfct.non-static]p2: 1668 // If a non-static member function of a class X is called for an object that 1669 // is not of type X, or of a type derived from X, the behavior is undefined. 1670 // FIXME: Provide a source location here. 1671 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), This, 1672 getContext().getRecordType(D->getParent())); 1673 1674 CallArgList Args; 1675 1676 // Push the this ptr. 1677 Args.add(RValue::get(This), D->getThisType(getContext())); 1678 1679 // Add the rest of the user-supplied arguments. 1680 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 1681 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getConstructor()); 1682 1683 // Insert any ABI-specific implicit constructor arguments. 1684 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs( 1685 *this, D, Type, ForVirtualBase, Delegating, Args); 1686 1687 // Emit the call. 1688 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type)); 1689 const CGFunctionInfo &Info = 1690 CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs); 1691 EmitCall(Info, Callee, ReturnValueSlot(), Args, D); 1692 } 1693 1694 void 1695 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 1696 llvm::Value *This, llvm::Value *Src, 1697 const CXXConstructExpr *E) { 1698 if (D->isTrivial()) { 1699 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor"); 1700 assert(D->isCopyOrMoveConstructor() && 1701 "trivial 1-arg ctor not a copy/move ctor"); 1702 EmitAggregateCopy(This, Src, E->arg_begin()->getType()); 1703 return; 1704 } 1705 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete); 1706 assert(D->isInstance() && 1707 "Trying to emit a member call expr on a static method!"); 1708 1709 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 1710 1711 CallArgList Args; 1712 1713 // Push the this ptr. 1714 Args.add(RValue::get(This), D->getThisType(getContext())); 1715 1716 // Push the src ptr. 1717 QualType QT = *(FPT->param_type_begin()); 1718 llvm::Type *t = CGM.getTypes().ConvertType(QT); 1719 Src = Builder.CreateBitCast(Src, t); 1720 Args.add(RValue::get(Src), QT); 1721 1722 // Skip over first argument (Src). 1723 EmitCallArgs(Args, FPT, E->arg_begin() + 1, E->arg_end(), E->getConstructor(), 1724 /*ParamsToSkip*/ 1); 1725 1726 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All), 1727 Callee, ReturnValueSlot(), Args, D); 1728 } 1729 1730 void 1731 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 1732 CXXCtorType CtorType, 1733 const FunctionArgList &Args, 1734 SourceLocation Loc) { 1735 CallArgList DelegateArgs; 1736 1737 FunctionArgList::const_iterator I = Args.begin(), E = Args.end(); 1738 assert(I != E && "no parameters to constructor"); 1739 1740 // this 1741 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType()); 1742 ++I; 1743 1744 // vtt 1745 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType), 1746 /*ForVirtualBase=*/false, 1747 /*Delegating=*/true)) { 1748 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy); 1749 DelegateArgs.add(RValue::get(VTT), VoidPP); 1750 1751 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) { 1752 assert(I != E && "cannot skip vtt parameter, already done with args"); 1753 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type"); 1754 ++I; 1755 } 1756 } 1757 1758 // Explicit arguments. 1759 for (; I != E; ++I) { 1760 const VarDecl *param = *I; 1761 // FIXME: per-argument source location 1762 EmitDelegateCallArg(DelegateArgs, param, Loc); 1763 } 1764 1765 llvm::Value *Callee = 1766 CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType)); 1767 EmitCall(CGM.getTypes() 1768 .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)), 1769 Callee, ReturnValueSlot(), DelegateArgs, Ctor); 1770 } 1771 1772 namespace { 1773 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup { 1774 const CXXDestructorDecl *Dtor; 1775 llvm::Value *Addr; 1776 CXXDtorType Type; 1777 1778 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr, 1779 CXXDtorType Type) 1780 : Dtor(D), Addr(Addr), Type(Type) {} 1781 1782 void Emit(CodeGenFunction &CGF, Flags flags) override { 1783 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false, 1784 /*Delegating=*/true, Addr); 1785 } 1786 }; 1787 } 1788 1789 void 1790 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 1791 const FunctionArgList &Args) { 1792 assert(Ctor->isDelegatingConstructor()); 1793 1794 llvm::Value *ThisPtr = LoadCXXThis(); 1795 1796 QualType Ty = getContext().getTagDeclType(Ctor->getParent()); 1797 CharUnits Alignment = getContext().getTypeAlignInChars(Ty); 1798 AggValueSlot AggSlot = 1799 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(), 1800 AggValueSlot::IsDestructed, 1801 AggValueSlot::DoesNotNeedGCBarriers, 1802 AggValueSlot::IsNotAliased); 1803 1804 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot); 1805 1806 const CXXRecordDecl *ClassDecl = Ctor->getParent(); 1807 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) { 1808 CXXDtorType Type = 1809 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base; 1810 1811 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup, 1812 ClassDecl->getDestructor(), 1813 ThisPtr, Type); 1814 } 1815 } 1816 1817 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD, 1818 CXXDtorType Type, 1819 bool ForVirtualBase, 1820 bool Delegating, 1821 llvm::Value *This) { 1822 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase, 1823 Delegating, This); 1824 } 1825 1826 namespace { 1827 struct CallLocalDtor : EHScopeStack::Cleanup { 1828 const CXXDestructorDecl *Dtor; 1829 llvm::Value *Addr; 1830 1831 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr) 1832 : Dtor(D), Addr(Addr) {} 1833 1834 void Emit(CodeGenFunction &CGF, Flags flags) override { 1835 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 1836 /*ForVirtualBase=*/false, 1837 /*Delegating=*/false, Addr); 1838 } 1839 }; 1840 } 1841 1842 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D, 1843 llvm::Value *Addr) { 1844 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr); 1845 } 1846 1847 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) { 1848 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl(); 1849 if (!ClassDecl) return; 1850 if (ClassDecl->hasTrivialDestructor()) return; 1851 1852 const CXXDestructorDecl *D = ClassDecl->getDestructor(); 1853 assert(D && D->isUsed() && "destructor not marked as used!"); 1854 PushDestructorCleanup(D, Addr); 1855 } 1856 1857 void 1858 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base, 1859 const CXXRecordDecl *NearestVBase, 1860 CharUnits OffsetFromNearestVBase, 1861 const CXXRecordDecl *VTableClass) { 1862 // Compute the address point. 1863 bool NeedsVirtualOffset; 1864 llvm::Value *VTableAddressPoint = 1865 CGM.getCXXABI().getVTableAddressPointInStructor( 1866 *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset); 1867 if (!VTableAddressPoint) 1868 return; 1869 1870 // Compute where to store the address point. 1871 llvm::Value *VirtualOffset = nullptr; 1872 CharUnits NonVirtualOffset = CharUnits::Zero(); 1873 1874 if (NeedsVirtualOffset) { 1875 // We need to use the virtual base offset offset because the virtual base 1876 // might have a different offset in the most derived class. 1877 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this, 1878 LoadCXXThis(), 1879 VTableClass, 1880 NearestVBase); 1881 NonVirtualOffset = OffsetFromNearestVBase; 1882 } else { 1883 // We can just use the base offset in the complete class. 1884 NonVirtualOffset = Base.getBaseOffset(); 1885 } 1886 1887 // Apply the offsets. 1888 llvm::Value *VTableField = LoadCXXThis(); 1889 1890 if (!NonVirtualOffset.isZero() || VirtualOffset) 1891 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField, 1892 NonVirtualOffset, 1893 VirtualOffset); 1894 1895 // Finally, store the address point. 1896 llvm::Type *AddressPointPtrTy = 1897 VTableAddressPoint->getType()->getPointerTo(); 1898 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy); 1899 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField); 1900 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr()); 1901 } 1902 1903 void 1904 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base, 1905 const CXXRecordDecl *NearestVBase, 1906 CharUnits OffsetFromNearestVBase, 1907 bool BaseIsNonVirtualPrimaryBase, 1908 const CXXRecordDecl *VTableClass, 1909 VisitedVirtualBasesSetTy& VBases) { 1910 // If this base is a non-virtual primary base the address point has already 1911 // been set. 1912 if (!BaseIsNonVirtualPrimaryBase) { 1913 // Initialize the vtable pointer for this base. 1914 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase, 1915 VTableClass); 1916 } 1917 1918 const CXXRecordDecl *RD = Base.getBase(); 1919 1920 // Traverse bases. 1921 for (const auto &I : RD->bases()) { 1922 CXXRecordDecl *BaseDecl 1923 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 1924 1925 // Ignore classes without a vtable. 1926 if (!BaseDecl->isDynamicClass()) 1927 continue; 1928 1929 CharUnits BaseOffset; 1930 CharUnits BaseOffsetFromNearestVBase; 1931 bool BaseDeclIsNonVirtualPrimaryBase; 1932 1933 if (I.isVirtual()) { 1934 // Check if we've visited this virtual base before. 1935 if (!VBases.insert(BaseDecl)) 1936 continue; 1937 1938 const ASTRecordLayout &Layout = 1939 getContext().getASTRecordLayout(VTableClass); 1940 1941 BaseOffset = Layout.getVBaseClassOffset(BaseDecl); 1942 BaseOffsetFromNearestVBase = CharUnits::Zero(); 1943 BaseDeclIsNonVirtualPrimaryBase = false; 1944 } else { 1945 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 1946 1947 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); 1948 BaseOffsetFromNearestVBase = 1949 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl); 1950 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl; 1951 } 1952 1953 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset), 1954 I.isVirtual() ? BaseDecl : NearestVBase, 1955 BaseOffsetFromNearestVBase, 1956 BaseDeclIsNonVirtualPrimaryBase, 1957 VTableClass, VBases); 1958 } 1959 } 1960 1961 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) { 1962 // Ignore classes without a vtable. 1963 if (!RD->isDynamicClass()) 1964 return; 1965 1966 // Initialize the vtable pointers for this class and all of its bases. 1967 VisitedVirtualBasesSetTy VBases; 1968 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()), 1969 /*NearestVBase=*/nullptr, 1970 /*OffsetFromNearestVBase=*/CharUnits::Zero(), 1971 /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases); 1972 1973 if (RD->getNumVBases()) 1974 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD); 1975 } 1976 1977 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This, 1978 llvm::Type *Ty) { 1979 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo()); 1980 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable"); 1981 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr()); 1982 return VTable; 1983 } 1984 1985 1986 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do 1987 // quite what we want. 1988 static const Expr *skipNoOpCastsAndParens(const Expr *E) { 1989 while (true) { 1990 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 1991 E = PE->getSubExpr(); 1992 continue; 1993 } 1994 1995 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 1996 if (CE->getCastKind() == CK_NoOp) { 1997 E = CE->getSubExpr(); 1998 continue; 1999 } 2000 } 2001 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 2002 if (UO->getOpcode() == UO_Extension) { 2003 E = UO->getSubExpr(); 2004 continue; 2005 } 2006 } 2007 return E; 2008 } 2009 } 2010 2011 bool 2012 CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base, 2013 const CXXMethodDecl *MD) { 2014 // When building with -fapple-kext, all calls must go through the vtable since 2015 // the kernel linker can do runtime patching of vtables. 2016 if (getLangOpts().AppleKext) 2017 return false; 2018 2019 // If the most derived class is marked final, we know that no subclass can 2020 // override this member function and so we can devirtualize it. For example: 2021 // 2022 // struct A { virtual void f(); } 2023 // struct B final : A { }; 2024 // 2025 // void f(B *b) { 2026 // b->f(); 2027 // } 2028 // 2029 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 2030 if (MostDerivedClassDecl->hasAttr<FinalAttr>()) 2031 return true; 2032 2033 // If the member function is marked 'final', we know that it can't be 2034 // overridden and can therefore devirtualize it. 2035 if (MD->hasAttr<FinalAttr>()) 2036 return true; 2037 2038 // Similarly, if the class itself is marked 'final' it can't be overridden 2039 // and we can therefore devirtualize the member function call. 2040 if (MD->getParent()->hasAttr<FinalAttr>()) 2041 return true; 2042 2043 Base = skipNoOpCastsAndParens(Base); 2044 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 2045 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 2046 // This is a record decl. We know the type and can devirtualize it. 2047 return VD->getType()->isRecordType(); 2048 } 2049 2050 return false; 2051 } 2052 2053 // We can devirtualize calls on an object accessed by a class member access 2054 // expression, since by C++11 [basic.life]p6 we know that it can't refer to 2055 // a derived class object constructed in the same location. 2056 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base)) 2057 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl())) 2058 return VD->getType()->isRecordType(); 2059 2060 // We can always devirtualize calls on temporary object expressions. 2061 if (isa<CXXConstructExpr>(Base)) 2062 return true; 2063 2064 // And calls on bound temporaries. 2065 if (isa<CXXBindTemporaryExpr>(Base)) 2066 return true; 2067 2068 // Check if this is a call expr that returns a record type. 2069 if (const CallExpr *CE = dyn_cast<CallExpr>(Base)) 2070 return CE->getCallReturnType()->isRecordType(); 2071 2072 // We can't devirtualize the call. 2073 return false; 2074 } 2075 2076 llvm::Value * 2077 CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E, 2078 const CXXMethodDecl *MD, 2079 llvm::Value *This) { 2080 llvm::FunctionType *fnType = 2081 CGM.getTypes().GetFunctionType( 2082 CGM.getTypes().arrangeCXXMethodDeclaration(MD)); 2083 2084 if (MD->isVirtual() && !CanDevirtualizeMemberFunctionCall(E->getArg(0), MD)) 2085 return CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, fnType); 2086 2087 return CGM.GetAddrOfFunction(MD, fnType); 2088 } 2089 2090 void CodeGenFunction::EmitForwardingCallToLambda( 2091 const CXXMethodDecl *callOperator, 2092 CallArgList &callArgs) { 2093 // Get the address of the call operator. 2094 const CGFunctionInfo &calleeFnInfo = 2095 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator); 2096 llvm::Value *callee = 2097 CGM.GetAddrOfFunction(GlobalDecl(callOperator), 2098 CGM.getTypes().GetFunctionType(calleeFnInfo)); 2099 2100 // Prepare the return slot. 2101 const FunctionProtoType *FPT = 2102 callOperator->getType()->castAs<FunctionProtoType>(); 2103 QualType resultType = FPT->getReturnType(); 2104 ReturnValueSlot returnSlot; 2105 if (!resultType->isVoidType() && 2106 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect && 2107 !hasScalarEvaluationKind(calleeFnInfo.getReturnType())) 2108 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified()); 2109 2110 // We don't need to separately arrange the call arguments because 2111 // the call can't be variadic anyway --- it's impossible to forward 2112 // variadic arguments. 2113 2114 // Now emit our call. 2115 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, 2116 callArgs, callOperator); 2117 2118 // If necessary, copy the returned value into the slot. 2119 if (!resultType->isVoidType() && returnSlot.isNull()) 2120 EmitReturnOfRValue(RV, resultType); 2121 else 2122 EmitBranchThroughCleanup(ReturnBlock); 2123 } 2124 2125 void CodeGenFunction::EmitLambdaBlockInvokeBody() { 2126 const BlockDecl *BD = BlockInfo->getBlockDecl(); 2127 const VarDecl *variable = BD->capture_begin()->getVariable(); 2128 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl(); 2129 2130 // Start building arguments for forwarding call 2131 CallArgList CallArgs; 2132 2133 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda)); 2134 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false); 2135 CallArgs.add(RValue::get(ThisPtr), ThisType); 2136 2137 // Add the rest of the parameters. 2138 for (auto param : BD->params()) 2139 EmitDelegateCallArg(CallArgs, param, param->getLocStart()); 2140 2141 assert(!Lambda->isGenericLambda() && 2142 "generic lambda interconversion to block not implemented"); 2143 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs); 2144 } 2145 2146 void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) { 2147 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) { 2148 // FIXME: Making this work correctly is nasty because it requires either 2149 // cloning the body of the call operator or making the call operator forward. 2150 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function"); 2151 return; 2152 } 2153 2154 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody()); 2155 } 2156 2157 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) { 2158 const CXXRecordDecl *Lambda = MD->getParent(); 2159 2160 // Start building arguments for forwarding call 2161 CallArgList CallArgs; 2162 2163 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda)); 2164 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType)); 2165 CallArgs.add(RValue::get(ThisPtr), ThisType); 2166 2167 // Add the rest of the parameters. 2168 for (auto Param : MD->params()) 2169 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart()); 2170 2171 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 2172 // For a generic lambda, find the corresponding call operator specialization 2173 // to which the call to the static-invoker shall be forwarded. 2174 if (Lambda->isGenericLambda()) { 2175 assert(MD->isFunctionTemplateSpecialization()); 2176 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 2177 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate(); 2178 void *InsertPos = nullptr; 2179 FunctionDecl *CorrespondingCallOpSpecialization = 2180 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 2181 assert(CorrespondingCallOpSpecialization); 2182 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 2183 } 2184 EmitForwardingCallToLambda(CallOp, CallArgs); 2185 } 2186 2187 void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) { 2188 if (MD->isVariadic()) { 2189 // FIXME: Making this work correctly is nasty because it requires either 2190 // cloning the body of the call operator or making the call operator forward. 2191 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function"); 2192 return; 2193 } 2194 2195 EmitLambdaDelegatingInvokeBody(MD); 2196 } 2197