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 llvm::Value *ArrayIndexVar, 416 CXXCtorInitializer *MemberInit, 417 QualType T, 418 unsigned Index) { 419 if (Index == MemberInit->getNumArrayIndices()) { 420 CodeGenFunction::RunCleanupsScope Cleanups(CGF); 421 422 LValue LV = LHS; 423 if (ArrayIndexVar) { 424 // If we have an array index variable, load it and use it as an offset. 425 // Then, increment the value. 426 llvm::Value *Dest = LHS.getAddress(); 427 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar); 428 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress"); 429 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1); 430 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc"); 431 CGF.Builder.CreateStore(Next, ArrayIndexVar); 432 433 // Update the LValue. 434 LV.setAddress(Dest); 435 CharUnits Align = CGF.getContext().getTypeAlignInChars(T); 436 LV.setAlignment(std::min(Align, LV.getAlignment())); 437 } 438 439 if (!CGF.hasAggregateLLVMType(T)) { 440 CGF.EmitScalarInit(MemberInit->getInit(), /*decl*/ 0, LV, false); 441 } else if (T->isAnyComplexType()) { 442 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LV.getAddress(), 443 LV.isVolatileQualified()); 444 } else { 445 AggValueSlot Slot = 446 AggValueSlot::forLValue(LV, 447 AggValueSlot::IsDestructed, 448 AggValueSlot::DoesNotNeedGCBarriers, 449 AggValueSlot::IsNotAliased); 450 451 CGF.EmitAggExpr(MemberInit->getInit(), Slot); 452 } 453 454 return; 455 } 456 457 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T); 458 assert(Array && "Array initialization without the array type?"); 459 llvm::Value *IndexVar 460 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index)); 461 assert(IndexVar && "Array index variable not loaded"); 462 463 // Initialize this index variable to zero. 464 llvm::Value* Zero 465 = llvm::Constant::getNullValue( 466 CGF.ConvertType(CGF.getContext().getSizeType())); 467 CGF.Builder.CreateStore(Zero, IndexVar); 468 469 // Start the loop with a block that tests the condition. 470 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond"); 471 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end"); 472 473 CGF.EmitBlock(CondBlock); 474 475 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body"); 476 // Generate: if (loop-index < number-of-elements) fall to the loop body, 477 // otherwise, go to the block after the for-loop. 478 uint64_t NumElements = Array->getSize().getZExtValue(); 479 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar); 480 llvm::Value *NumElementsPtr = 481 llvm::ConstantInt::get(Counter->getType(), NumElements); 482 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr, 483 "isless"); 484 485 // If the condition is true, execute the body. 486 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor); 487 488 CGF.EmitBlock(ForBody); 489 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc"); 490 491 { 492 CodeGenFunction::RunCleanupsScope Cleanups(CGF); 493 494 // Inside the loop body recurse to emit the inner loop or, eventually, the 495 // constructor call. 496 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, 497 Array->getElementType(), Index + 1); 498 } 499 500 CGF.EmitBlock(ContinueBlock); 501 502 // Emit the increment of the loop counter. 503 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1); 504 Counter = CGF.Builder.CreateLoad(IndexVar); 505 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc"); 506 CGF.Builder.CreateStore(NextVal, IndexVar); 507 508 // Finally, branch back up to the condition for the next iteration. 509 CGF.EmitBranch(CondBlock); 510 511 // Emit the fall-through block. 512 CGF.EmitBlock(AfterFor, true); 513 } 514 515 namespace { 516 struct CallMemberDtor : EHScopeStack::Cleanup { 517 FieldDecl *Field; 518 CXXDestructorDecl *Dtor; 519 520 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor) 521 : Field(Field), Dtor(Dtor) {} 522 523 void Emit(CodeGenFunction &CGF, Flags flags) { 524 // FIXME: Is this OK for C++0x delegating constructors? 525 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 526 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0); 527 528 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false, 529 LHS.getAddress()); 530 } 531 }; 532 } 533 534 static bool hasTrivialCopyOrMoveConstructor(const CXXRecordDecl *Record, 535 bool Moving) { 536 return Moving ? Record->hasTrivialMoveConstructor() : 537 Record->hasTrivialCopyConstructor(); 538 } 539 540 static void EmitMemberInitializer(CodeGenFunction &CGF, 541 const CXXRecordDecl *ClassDecl, 542 CXXCtorInitializer *MemberInit, 543 const CXXConstructorDecl *Constructor, 544 FunctionArgList &Args) { 545 assert(MemberInit->isAnyMemberInitializer() && 546 "Must have member initializer!"); 547 assert(MemberInit->getInit() && "Must have initializer!"); 548 549 // non-static data member initializers. 550 FieldDecl *Field = MemberInit->getAnyMember(); 551 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType()); 552 553 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 554 LValue LHS; 555 556 // If we are initializing an anonymous union field, drill down to the field. 557 if (MemberInit->isIndirectMemberInitializer()) { 558 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr, 559 MemberInit->getIndirectMember(), 0); 560 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType(); 561 } else { 562 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0); 563 } 564 565 if (!CGF.hasAggregateLLVMType(Field->getType())) { 566 if (LHS.isSimple()) { 567 CGF.EmitExprAsInit(MemberInit->getInit(), Field, LHS, false); 568 } else { 569 RValue RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit())); 570 CGF.EmitStoreThroughLValue(RHS, LHS); 571 } 572 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) { 573 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(), 574 LHS.isVolatileQualified()); 575 } else { 576 llvm::Value *ArrayIndexVar = 0; 577 const ConstantArrayType *Array 578 = CGF.getContext().getAsConstantArrayType(FieldType); 579 if (Array && Constructor->isImplicitlyDefined() && 580 Constructor->isCopyOrMoveConstructor()) { 581 llvm::Type *SizeTy 582 = CGF.ConvertType(CGF.getContext().getSizeType()); 583 584 // The LHS is a pointer to the first object we'll be constructing, as 585 // a flat array. 586 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array); 587 llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy); 588 BasePtr = llvm::PointerType::getUnqual(BasePtr); 589 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(), 590 BasePtr); 591 LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy); 592 593 // Create an array index that will be used to walk over all of the 594 // objects we're constructing. 595 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index"); 596 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy); 597 CGF.Builder.CreateStore(Zero, ArrayIndexVar); 598 599 // If we are copying an array of PODs or classes with trivial copy 600 // constructors, perform a single aggregate copy. 601 const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl(); 602 if (BaseElementTy.isPODType(CGF.getContext()) || 603 (Record && hasTrivialCopyOrMoveConstructor(Record, 604 Constructor->isMoveConstructor()))) { 605 // Find the source pointer. We knows it's the last argument because 606 // we know we're in a copy constructor. 607 unsigned SrcArgIndex = Args.size() - 1; 608 llvm::Value *SrcPtr 609 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex])); 610 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0); 611 612 // Copy the aggregate. 613 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType, 614 LHS.isVolatileQualified()); 615 return; 616 } 617 618 // Emit the block variables for the array indices, if any. 619 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I) 620 CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I)); 621 } 622 623 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0); 624 625 if (!CGF.CGM.getLangOptions().Exceptions) 626 return; 627 628 // FIXME: If we have an array of classes w/ non-trivial destructors, 629 // we need to destroy in reverse order of construction along the exception 630 // path. 631 const RecordType *RT = FieldType->getAs<RecordType>(); 632 if (!RT) 633 return; 634 635 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 636 if (!RD->hasTrivialDestructor()) 637 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field, 638 RD->getDestructor()); 639 } 640 } 641 642 /// Checks whether the given constructor is a valid subject for the 643 /// complete-to-base constructor delegation optimization, i.e. 644 /// emitting the complete constructor as a simple call to the base 645 /// constructor. 646 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) { 647 648 // Currently we disable the optimization for classes with virtual 649 // bases because (1) the addresses of parameter variables need to be 650 // consistent across all initializers but (2) the delegate function 651 // call necessarily creates a second copy of the parameter variable. 652 // 653 // The limiting example (purely theoretical AFAIK): 654 // struct A { A(int &c) { c++; } }; 655 // struct B : virtual A { 656 // B(int count) : A(count) { printf("%d\n", count); } 657 // }; 658 // ...although even this example could in principle be emitted as a 659 // delegation since the address of the parameter doesn't escape. 660 if (Ctor->getParent()->getNumVBases()) { 661 // TODO: white-list trivial vbase initializers. This case wouldn't 662 // be subject to the restrictions below. 663 664 // TODO: white-list cases where: 665 // - there are no non-reference parameters to the constructor 666 // - the initializers don't access any non-reference parameters 667 // - the initializers don't take the address of non-reference 668 // parameters 669 // - etc. 670 // If we ever add any of the above cases, remember that: 671 // - function-try-blocks will always blacklist this optimization 672 // - we need to perform the constructor prologue and cleanup in 673 // EmitConstructorBody. 674 675 return false; 676 } 677 678 // We also disable the optimization for variadic functions because 679 // it's impossible to "re-pass" varargs. 680 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic()) 681 return false; 682 683 // FIXME: Decide if we can do a delegation of a delegating constructor. 684 if (Ctor->isDelegatingConstructor()) 685 return false; 686 687 return true; 688 } 689 690 /// EmitConstructorBody - Emits the body of the current constructor. 691 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) { 692 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl()); 693 CXXCtorType CtorType = CurGD.getCtorType(); 694 695 // Before we go any further, try the complete->base constructor 696 // delegation optimization. 697 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) { 698 if (CGDebugInfo *DI = getDebugInfo()) 699 DI->EmitLocation(Builder, Ctor->getLocEnd()); 700 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args); 701 return; 702 } 703 704 Stmt *Body = Ctor->getBody(); 705 706 // Enter the function-try-block before the constructor prologue if 707 // applicable. 708 bool IsTryBody = (Body && isa<CXXTryStmt>(Body)); 709 if (IsTryBody) 710 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 711 712 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin(); 713 714 // Emit the constructor prologue, i.e. the base and member 715 // initializers. 716 EmitCtorPrologue(Ctor, CtorType, Args); 717 718 // Emit the body of the statement. 719 if (IsTryBody) 720 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 721 else if (Body) 722 EmitStmt(Body); 723 724 // Emit any cleanup blocks associated with the member or base 725 // initializers, which includes (along the exceptional path) the 726 // destructors for those members and bases that were fully 727 // constructed. 728 PopCleanupBlocks(CleanupDepth); 729 730 if (IsTryBody) 731 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 732 } 733 734 /// EmitCtorPrologue - This routine generates necessary code to initialize 735 /// base classes and non-static data members belonging to this constructor. 736 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD, 737 CXXCtorType CtorType, 738 FunctionArgList &Args) { 739 if (CD->isDelegatingConstructor()) 740 return EmitDelegatingCXXConstructorCall(CD, Args); 741 742 const CXXRecordDecl *ClassDecl = CD->getParent(); 743 744 SmallVector<CXXCtorInitializer *, 8> MemberInitializers; 745 746 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(), 747 E = CD->init_end(); 748 B != E; ++B) { 749 CXXCtorInitializer *Member = (*B); 750 751 if (Member->isBaseInitializer()) { 752 EmitBaseInitializer(*this, ClassDecl, Member, CtorType); 753 } else { 754 assert(Member->isAnyMemberInitializer() && 755 "Delegating initializer on non-delegating constructor"); 756 MemberInitializers.push_back(Member); 757 } 758 } 759 760 InitializeVTablePointers(ClassDecl); 761 762 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I) 763 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args); 764 } 765 766 static bool 767 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field); 768 769 static bool 770 HasTrivialDestructorBody(ASTContext &Context, 771 const CXXRecordDecl *BaseClassDecl, 772 const CXXRecordDecl *MostDerivedClassDecl) 773 { 774 // If the destructor is trivial we don't have to check anything else. 775 if (BaseClassDecl->hasTrivialDestructor()) 776 return true; 777 778 if (!BaseClassDecl->getDestructor()->hasTrivialBody()) 779 return false; 780 781 // Check fields. 782 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(), 783 E = BaseClassDecl->field_end(); I != E; ++I) { 784 const FieldDecl *Field = *I; 785 786 if (!FieldHasTrivialDestructorBody(Context, Field)) 787 return false; 788 } 789 790 // Check non-virtual bases. 791 for (CXXRecordDecl::base_class_const_iterator I = 792 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end(); 793 I != E; ++I) { 794 if (I->isVirtual()) 795 continue; 796 797 const CXXRecordDecl *NonVirtualBase = 798 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl()); 799 if (!HasTrivialDestructorBody(Context, NonVirtualBase, 800 MostDerivedClassDecl)) 801 return false; 802 } 803 804 if (BaseClassDecl == MostDerivedClassDecl) { 805 // Check virtual bases. 806 for (CXXRecordDecl::base_class_const_iterator I = 807 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end(); 808 I != E; ++I) { 809 const CXXRecordDecl *VirtualBase = 810 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl()); 811 if (!HasTrivialDestructorBody(Context, VirtualBase, 812 MostDerivedClassDecl)) 813 return false; 814 } 815 } 816 817 return true; 818 } 819 820 static bool 821 FieldHasTrivialDestructorBody(ASTContext &Context, 822 const FieldDecl *Field) 823 { 824 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType()); 825 826 const RecordType *RT = FieldBaseElementType->getAs<RecordType>(); 827 if (!RT) 828 return true; 829 830 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 831 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl); 832 } 833 834 /// CanSkipVTablePointerInitialization - Check whether we need to initialize 835 /// any vtable pointers before calling this destructor. 836 static bool CanSkipVTablePointerInitialization(ASTContext &Context, 837 const CXXDestructorDecl *Dtor) { 838 if (!Dtor->hasTrivialBody()) 839 return false; 840 841 // Check the fields. 842 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 843 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 844 E = ClassDecl->field_end(); I != E; ++I) { 845 const FieldDecl *Field = *I; 846 847 if (!FieldHasTrivialDestructorBody(Context, Field)) 848 return false; 849 } 850 851 return true; 852 } 853 854 /// EmitDestructorBody - Emits the body of the current destructor. 855 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) { 856 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl()); 857 CXXDtorType DtorType = CurGD.getDtorType(); 858 859 // The call to operator delete in a deleting destructor happens 860 // outside of the function-try-block, which means it's always 861 // possible to delegate the destructor body to the complete 862 // destructor. Do so. 863 if (DtorType == Dtor_Deleting) { 864 EnterDtorCleanups(Dtor, Dtor_Deleting); 865 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false, 866 LoadCXXThis()); 867 PopCleanupBlock(); 868 return; 869 } 870 871 Stmt *Body = Dtor->getBody(); 872 873 // If the body is a function-try-block, enter the try before 874 // anything else. 875 bool isTryBody = (Body && isa<CXXTryStmt>(Body)); 876 if (isTryBody) 877 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 878 879 // Enter the epilogue cleanups. 880 RunCleanupsScope DtorEpilogue(*this); 881 882 // If this is the complete variant, just invoke the base variant; 883 // the epilogue will destruct the virtual bases. But we can't do 884 // this optimization if the body is a function-try-block, because 885 // we'd introduce *two* handler blocks. 886 switch (DtorType) { 887 case Dtor_Deleting: llvm_unreachable("already handled deleting case"); 888 889 case Dtor_Complete: 890 // Enter the cleanup scopes for virtual bases. 891 EnterDtorCleanups(Dtor, Dtor_Complete); 892 893 if (!isTryBody) { 894 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false, 895 LoadCXXThis()); 896 break; 897 } 898 // Fallthrough: act like we're in the base variant. 899 900 case Dtor_Base: 901 // Enter the cleanup scopes for fields and non-virtual bases. 902 EnterDtorCleanups(Dtor, Dtor_Base); 903 904 // Initialize the vtable pointers before entering the body. 905 if (!CanSkipVTablePointerInitialization(getContext(), Dtor)) 906 InitializeVTablePointers(Dtor->getParent()); 907 908 if (isTryBody) 909 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 910 else if (Body) 911 EmitStmt(Body); 912 else { 913 assert(Dtor->isImplicit() && "bodyless dtor not implicit"); 914 // nothing to do besides what's in the epilogue 915 } 916 // -fapple-kext must inline any call to this dtor into 917 // the caller's body. 918 if (getContext().getLangOptions().AppleKext) 919 CurFn->addFnAttr(llvm::Attribute::AlwaysInline); 920 break; 921 } 922 923 // Jump out through the epilogue cleanups. 924 DtorEpilogue.ForceCleanup(); 925 926 // Exit the try if applicable. 927 if (isTryBody) 928 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 929 } 930 931 namespace { 932 /// Call the operator delete associated with the current destructor. 933 struct CallDtorDelete : EHScopeStack::Cleanup { 934 CallDtorDelete() {} 935 936 void Emit(CodeGenFunction &CGF, Flags flags) { 937 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl); 938 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 939 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(), 940 CGF.getContext().getTagDeclType(ClassDecl)); 941 } 942 }; 943 944 class DestroyField : public EHScopeStack::Cleanup { 945 const FieldDecl *field; 946 CodeGenFunction::Destroyer *destroyer; 947 bool useEHCleanupForArray; 948 949 public: 950 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer, 951 bool useEHCleanupForArray) 952 : field(field), destroyer(destroyer), 953 useEHCleanupForArray(useEHCleanupForArray) {} 954 955 void Emit(CodeGenFunction &CGF, Flags flags) { 956 // Find the address of the field. 957 llvm::Value *thisValue = CGF.LoadCXXThis(); 958 LValue LV = CGF.EmitLValueForField(thisValue, field, /*CVRQualifiers=*/0); 959 assert(LV.isSimple()); 960 961 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer, 962 flags.isForNormalCleanup() && useEHCleanupForArray); 963 } 964 }; 965 } 966 967 /// EmitDtorEpilogue - Emit all code that comes at the end of class's 968 /// destructor. This is to call destructors on members and base classes 969 /// in reverse order of their construction. 970 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD, 971 CXXDtorType DtorType) { 972 assert(!DD->isTrivial() && 973 "Should not emit dtor epilogue for trivial dtor!"); 974 975 // The deleting-destructor phase just needs to call the appropriate 976 // operator delete that Sema picked up. 977 if (DtorType == Dtor_Deleting) { 978 assert(DD->getOperatorDelete() && 979 "operator delete missing - EmitDtorEpilogue"); 980 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup); 981 return; 982 } 983 984 const CXXRecordDecl *ClassDecl = DD->getParent(); 985 986 // Unions have no bases and do not call field destructors. 987 if (ClassDecl->isUnion()) 988 return; 989 990 // The complete-destructor phase just destructs all the virtual bases. 991 if (DtorType == Dtor_Complete) { 992 993 // We push them in the forward order so that they'll be popped in 994 // the reverse order. 995 for (CXXRecordDecl::base_class_const_iterator I = 996 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end(); 997 I != E; ++I) { 998 const CXXBaseSpecifier &Base = *I; 999 CXXRecordDecl *BaseClassDecl 1000 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 1001 1002 // Ignore trivial destructors. 1003 if (BaseClassDecl->hasTrivialDestructor()) 1004 continue; 1005 1006 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1007 BaseClassDecl, 1008 /*BaseIsVirtual*/ true); 1009 } 1010 1011 return; 1012 } 1013 1014 assert(DtorType == Dtor_Base); 1015 1016 // Destroy non-virtual bases. 1017 for (CXXRecordDecl::base_class_const_iterator I = 1018 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) { 1019 const CXXBaseSpecifier &Base = *I; 1020 1021 // Ignore virtual bases. 1022 if (Base.isVirtual()) 1023 continue; 1024 1025 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl(); 1026 1027 // Ignore trivial destructors. 1028 if (BaseClassDecl->hasTrivialDestructor()) 1029 continue; 1030 1031 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1032 BaseClassDecl, 1033 /*BaseIsVirtual*/ false); 1034 } 1035 1036 // Destroy direct fields. 1037 SmallVector<const FieldDecl *, 16> FieldDecls; 1038 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 1039 E = ClassDecl->field_end(); I != E; ++I) { 1040 const FieldDecl *field = *I; 1041 QualType type = field->getType(); 1042 QualType::DestructionKind dtorKind = type.isDestructedType(); 1043 if (!dtorKind) continue; 1044 1045 CleanupKind cleanupKind = getCleanupKind(dtorKind); 1046 EHStack.pushCleanup<DestroyField>(cleanupKind, field, 1047 getDestroyer(dtorKind), 1048 cleanupKind & EHCleanup); 1049 } 1050 } 1051 1052 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 1053 /// constructor for each of several members of an array. 1054 /// 1055 /// \param ctor the constructor to call for each element 1056 /// \param argBegin,argEnd the arguments to evaluate and pass to the 1057 /// constructor 1058 /// \param arrayType the type of the array to initialize 1059 /// \param arrayBegin an arrayType* 1060 /// \param zeroInitialize true if each element should be 1061 /// zero-initialized before it is constructed 1062 void 1063 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, 1064 const ConstantArrayType *arrayType, 1065 llvm::Value *arrayBegin, 1066 CallExpr::const_arg_iterator argBegin, 1067 CallExpr::const_arg_iterator argEnd, 1068 bool zeroInitialize) { 1069 QualType elementType; 1070 llvm::Value *numElements = 1071 emitArrayLength(arrayType, elementType, arrayBegin); 1072 1073 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, 1074 argBegin, argEnd, zeroInitialize); 1075 } 1076 1077 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 1078 /// constructor for each of several members of an array. 1079 /// 1080 /// \param ctor the constructor to call for each element 1081 /// \param numElements the number of elements in the array; 1082 /// may be zero 1083 /// \param argBegin,argEnd the arguments to evaluate and pass to the 1084 /// constructor 1085 /// \param arrayBegin a T*, where T is the type constructed by ctor 1086 /// \param zeroInitialize true if each element should be 1087 /// zero-initialized before it is constructed 1088 void 1089 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, 1090 llvm::Value *numElements, 1091 llvm::Value *arrayBegin, 1092 CallExpr::const_arg_iterator argBegin, 1093 CallExpr::const_arg_iterator argEnd, 1094 bool zeroInitialize) { 1095 1096 // It's legal for numElements to be zero. This can happen both 1097 // dynamically, because x can be zero in 'new A[x]', and statically, 1098 // because of GCC extensions that permit zero-length arrays. There 1099 // are probably legitimate places where we could assume that this 1100 // doesn't happen, but it's not clear that it's worth it. 1101 llvm::BranchInst *zeroCheckBranch = 0; 1102 1103 // Optimize for a constant count. 1104 llvm::ConstantInt *constantCount 1105 = dyn_cast<llvm::ConstantInt>(numElements); 1106 if (constantCount) { 1107 // Just skip out if the constant count is zero. 1108 if (constantCount->isZero()) return; 1109 1110 // Otherwise, emit the check. 1111 } else { 1112 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop"); 1113 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty"); 1114 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB); 1115 EmitBlock(loopBB); 1116 } 1117 1118 // Find the end of the array. 1119 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements, 1120 "arrayctor.end"); 1121 1122 // Enter the loop, setting up a phi for the current location to initialize. 1123 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1124 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop"); 1125 EmitBlock(loopBB); 1126 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2, 1127 "arrayctor.cur"); 1128 cur->addIncoming(arrayBegin, entryBB); 1129 1130 // Inside the loop body, emit the constructor call on the array element. 1131 1132 QualType type = getContext().getTypeDeclType(ctor->getParent()); 1133 1134 // Zero initialize the storage, if requested. 1135 if (zeroInitialize) 1136 EmitNullInitialization(cur, type); 1137 1138 // C++ [class.temporary]p4: 1139 // There are two contexts in which temporaries are destroyed at a different 1140 // point than the end of the full-expression. The first context is when a 1141 // default constructor is called to initialize an element of an array. 1142 // If the constructor has one or more default arguments, the destruction of 1143 // every temporary created in a default argument expression is sequenced 1144 // before the construction of the next array element, if any. 1145 1146 { 1147 RunCleanupsScope Scope(*this); 1148 1149 // Evaluate the constructor and its arguments in a regular 1150 // partial-destroy cleanup. 1151 if (getLangOptions().Exceptions && 1152 !ctor->getParent()->hasTrivialDestructor()) { 1153 Destroyer *destroyer = destroyCXXObject; 1154 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer); 1155 } 1156 1157 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false, 1158 cur, argBegin, argEnd); 1159 } 1160 1161 // Go to the next element. 1162 llvm::Value *next = 1163 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1), 1164 "arrayctor.next"); 1165 cur->addIncoming(next, Builder.GetInsertBlock()); 1166 1167 // Check whether that's the end of the loop. 1168 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done"); 1169 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont"); 1170 Builder.CreateCondBr(done, contBB, loopBB); 1171 1172 // Patch the earlier check to skip over the loop. 1173 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB); 1174 1175 EmitBlock(contBB); 1176 } 1177 1178 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF, 1179 llvm::Value *addr, 1180 QualType type) { 1181 const RecordType *rtype = type->castAs<RecordType>(); 1182 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl()); 1183 const CXXDestructorDecl *dtor = record->getDestructor(); 1184 assert(!dtor->isTrivial()); 1185 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false, 1186 addr); 1187 } 1188 1189 void 1190 CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 1191 CXXCtorType Type, bool ForVirtualBase, 1192 llvm::Value *This, 1193 CallExpr::const_arg_iterator ArgBeg, 1194 CallExpr::const_arg_iterator ArgEnd) { 1195 1196 CGDebugInfo *DI = getDebugInfo(); 1197 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) { 1198 // If debug info for this class has not been emitted then this is the 1199 // right time to do so. 1200 const CXXRecordDecl *Parent = D->getParent(); 1201 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent), 1202 Parent->getLocation()); 1203 } 1204 1205 if (D->isTrivial()) { 1206 if (ArgBeg == ArgEnd) { 1207 // Trivial default constructor, no codegen required. 1208 assert(D->isDefaultConstructor() && 1209 "trivial 0-arg ctor not a default ctor"); 1210 return; 1211 } 1212 1213 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor"); 1214 assert(D->isCopyOrMoveConstructor() && 1215 "trivial 1-arg ctor not a copy/move ctor"); 1216 1217 const Expr *E = (*ArgBeg); 1218 QualType Ty = E->getType(); 1219 llvm::Value *Src = EmitLValue(E).getAddress(); 1220 EmitAggregateCopy(This, Src, Ty); 1221 return; 1222 } 1223 1224 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase); 1225 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type); 1226 1227 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd); 1228 } 1229 1230 void 1231 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 1232 llvm::Value *This, llvm::Value *Src, 1233 CallExpr::const_arg_iterator ArgBeg, 1234 CallExpr::const_arg_iterator ArgEnd) { 1235 if (D->isTrivial()) { 1236 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor"); 1237 assert(D->isCopyOrMoveConstructor() && 1238 "trivial 1-arg ctor not a copy/move ctor"); 1239 EmitAggregateCopy(This, Src, (*ArgBeg)->getType()); 1240 return; 1241 } 1242 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, 1243 clang::Ctor_Complete); 1244 assert(D->isInstance() && 1245 "Trying to emit a member call expr on a static method!"); 1246 1247 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>(); 1248 1249 CallArgList Args; 1250 1251 // Push the this ptr. 1252 Args.add(RValue::get(This), D->getThisType(getContext())); 1253 1254 1255 // Push the src ptr. 1256 QualType QT = *(FPT->arg_type_begin()); 1257 llvm::Type *t = CGM.getTypes().ConvertType(QT); 1258 Src = Builder.CreateBitCast(Src, t); 1259 Args.add(RValue::get(Src), QT); 1260 1261 // Skip over first argument (Src). 1262 ++ArgBeg; 1263 CallExpr::const_arg_iterator Arg = ArgBeg; 1264 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1, 1265 E = FPT->arg_type_end(); I != E; ++I, ++Arg) { 1266 assert(Arg != ArgEnd && "Running over edge of argument list!"); 1267 EmitCallArg(Args, *Arg, *I); 1268 } 1269 // Either we've emitted all the call args, or we have a call to a 1270 // variadic function. 1271 assert((Arg == ArgEnd || FPT->isVariadic()) && 1272 "Extra arguments in non-variadic function!"); 1273 // If we still have any arguments, emit them using the type of the argument. 1274 for (; Arg != ArgEnd; ++Arg) { 1275 QualType ArgType = Arg->getType(); 1276 EmitCallArg(Args, *Arg, ArgType); 1277 } 1278 1279 EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee, 1280 ReturnValueSlot(), Args, D); 1281 } 1282 1283 void 1284 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 1285 CXXCtorType CtorType, 1286 const FunctionArgList &Args) { 1287 CallArgList DelegateArgs; 1288 1289 FunctionArgList::const_iterator I = Args.begin(), E = Args.end(); 1290 assert(I != E && "no parameters to constructor"); 1291 1292 // this 1293 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType()); 1294 ++I; 1295 1296 // vtt 1297 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType), 1298 /*ForVirtualBase=*/false)) { 1299 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy); 1300 DelegateArgs.add(RValue::get(VTT), VoidPP); 1301 1302 if (CodeGenVTables::needsVTTParameter(CurGD)) { 1303 assert(I != E && "cannot skip vtt parameter, already done with args"); 1304 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type"); 1305 ++I; 1306 } 1307 } 1308 1309 // Explicit arguments. 1310 for (; I != E; ++I) { 1311 const VarDecl *param = *I; 1312 EmitDelegateCallArg(DelegateArgs, param); 1313 } 1314 1315 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType), 1316 CGM.GetAddrOfCXXConstructor(Ctor, CtorType), 1317 ReturnValueSlot(), DelegateArgs, Ctor); 1318 } 1319 1320 namespace { 1321 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup { 1322 const CXXDestructorDecl *Dtor; 1323 llvm::Value *Addr; 1324 CXXDtorType Type; 1325 1326 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr, 1327 CXXDtorType Type) 1328 : Dtor(D), Addr(Addr), Type(Type) {} 1329 1330 void Emit(CodeGenFunction &CGF, Flags flags) { 1331 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false, 1332 Addr); 1333 } 1334 }; 1335 } 1336 1337 void 1338 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 1339 const FunctionArgList &Args) { 1340 assert(Ctor->isDelegatingConstructor()); 1341 1342 llvm::Value *ThisPtr = LoadCXXThis(); 1343 1344 QualType Ty = getContext().getTagDeclType(Ctor->getParent()); 1345 CharUnits Alignment = getContext().getTypeAlignInChars(Ty); 1346 AggValueSlot AggSlot = 1347 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(), 1348 AggValueSlot::IsDestructed, 1349 AggValueSlot::DoesNotNeedGCBarriers, 1350 AggValueSlot::IsNotAliased); 1351 1352 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot); 1353 1354 const CXXRecordDecl *ClassDecl = Ctor->getParent(); 1355 if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) { 1356 CXXDtorType Type = 1357 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base; 1358 1359 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup, 1360 ClassDecl->getDestructor(), 1361 ThisPtr, Type); 1362 } 1363 } 1364 1365 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD, 1366 CXXDtorType Type, 1367 bool ForVirtualBase, 1368 llvm::Value *This) { 1369 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type), 1370 ForVirtualBase); 1371 llvm::Value *Callee = 0; 1372 if (getContext().getLangOptions().AppleKext) 1373 Callee = BuildAppleKextVirtualDestructorCall(DD, Type, 1374 DD->getParent()); 1375 1376 if (!Callee) 1377 Callee = CGM.GetAddrOfCXXDestructor(DD, Type); 1378 1379 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0); 1380 } 1381 1382 namespace { 1383 struct CallLocalDtor : EHScopeStack::Cleanup { 1384 const CXXDestructorDecl *Dtor; 1385 llvm::Value *Addr; 1386 1387 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr) 1388 : Dtor(D), Addr(Addr) {} 1389 1390 void Emit(CodeGenFunction &CGF, Flags flags) { 1391 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 1392 /*ForVirtualBase=*/false, Addr); 1393 } 1394 }; 1395 } 1396 1397 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D, 1398 llvm::Value *Addr) { 1399 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr); 1400 } 1401 1402 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) { 1403 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl(); 1404 if (!ClassDecl) return; 1405 if (ClassDecl->hasTrivialDestructor()) return; 1406 1407 const CXXDestructorDecl *D = ClassDecl->getDestructor(); 1408 assert(D && D->isUsed() && "destructor not marked as used!"); 1409 PushDestructorCleanup(D, Addr); 1410 } 1411 1412 llvm::Value * 1413 CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This, 1414 const CXXRecordDecl *ClassDecl, 1415 const CXXRecordDecl *BaseClassDecl) { 1416 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy); 1417 CharUnits VBaseOffsetOffset = 1418 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl); 1419 1420 llvm::Value *VBaseOffsetPtr = 1421 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(), 1422 "vbase.offset.ptr"); 1423 llvm::Type *PtrDiffTy = 1424 ConvertType(getContext().getPointerDiffType()); 1425 1426 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr, 1427 PtrDiffTy->getPointerTo()); 1428 1429 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset"); 1430 1431 return VBaseOffset; 1432 } 1433 1434 void 1435 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base, 1436 const CXXRecordDecl *NearestVBase, 1437 CharUnits OffsetFromNearestVBase, 1438 llvm::Constant *VTable, 1439 const CXXRecordDecl *VTableClass) { 1440 const CXXRecordDecl *RD = Base.getBase(); 1441 1442 // Compute the address point. 1443 llvm::Value *VTableAddressPoint; 1444 1445 // Check if we need to use a vtable from the VTT. 1446 if (CodeGenVTables::needsVTTParameter(CurGD) && 1447 (RD->getNumVBases() || NearestVBase)) { 1448 // Get the secondary vpointer index. 1449 uint64_t VirtualPointerIndex = 1450 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base); 1451 1452 /// Load the VTT. 1453 llvm::Value *VTT = LoadCXXVTT(); 1454 if (VirtualPointerIndex) 1455 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex); 1456 1457 // And load the address point from the VTT. 1458 VTableAddressPoint = Builder.CreateLoad(VTT); 1459 } else { 1460 uint64_t AddressPoint = 1461 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base); 1462 VTableAddressPoint = 1463 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint); 1464 } 1465 1466 // Compute where to store the address point. 1467 llvm::Value *VirtualOffset = 0; 1468 CharUnits NonVirtualOffset = CharUnits::Zero(); 1469 1470 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) { 1471 // We need to use the virtual base offset offset because the virtual base 1472 // might have a different offset in the most derived class. 1473 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass, 1474 NearestVBase); 1475 NonVirtualOffset = OffsetFromNearestVBase; 1476 } else { 1477 // We can just use the base offset in the complete class. 1478 NonVirtualOffset = Base.getBaseOffset(); 1479 } 1480 1481 // Apply the offsets. 1482 llvm::Value *VTableField = LoadCXXThis(); 1483 1484 if (!NonVirtualOffset.isZero() || VirtualOffset) 1485 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField, 1486 NonVirtualOffset, 1487 VirtualOffset); 1488 1489 // Finally, store the address point. 1490 llvm::Type *AddressPointPtrTy = 1491 VTableAddressPoint->getType()->getPointerTo(); 1492 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy); 1493 Builder.CreateStore(VTableAddressPoint, VTableField); 1494 } 1495 1496 void 1497 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base, 1498 const CXXRecordDecl *NearestVBase, 1499 CharUnits OffsetFromNearestVBase, 1500 bool BaseIsNonVirtualPrimaryBase, 1501 llvm::Constant *VTable, 1502 const CXXRecordDecl *VTableClass, 1503 VisitedVirtualBasesSetTy& VBases) { 1504 // If this base is a non-virtual primary base the address point has already 1505 // been set. 1506 if (!BaseIsNonVirtualPrimaryBase) { 1507 // Initialize the vtable pointer for this base. 1508 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase, 1509 VTable, VTableClass); 1510 } 1511 1512 const CXXRecordDecl *RD = Base.getBase(); 1513 1514 // Traverse bases. 1515 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1516 E = RD->bases_end(); I != E; ++I) { 1517 CXXRecordDecl *BaseDecl 1518 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 1519 1520 // Ignore classes without a vtable. 1521 if (!BaseDecl->isDynamicClass()) 1522 continue; 1523 1524 CharUnits BaseOffset; 1525 CharUnits BaseOffsetFromNearestVBase; 1526 bool BaseDeclIsNonVirtualPrimaryBase; 1527 1528 if (I->isVirtual()) { 1529 // Check if we've visited this virtual base before. 1530 if (!VBases.insert(BaseDecl)) 1531 continue; 1532 1533 const ASTRecordLayout &Layout = 1534 getContext().getASTRecordLayout(VTableClass); 1535 1536 BaseOffset = Layout.getVBaseClassOffset(BaseDecl); 1537 BaseOffsetFromNearestVBase = CharUnits::Zero(); 1538 BaseDeclIsNonVirtualPrimaryBase = false; 1539 } else { 1540 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 1541 1542 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); 1543 BaseOffsetFromNearestVBase = 1544 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl); 1545 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl; 1546 } 1547 1548 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset), 1549 I->isVirtual() ? BaseDecl : NearestVBase, 1550 BaseOffsetFromNearestVBase, 1551 BaseDeclIsNonVirtualPrimaryBase, 1552 VTable, VTableClass, VBases); 1553 } 1554 } 1555 1556 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) { 1557 // Ignore classes without a vtable. 1558 if (!RD->isDynamicClass()) 1559 return; 1560 1561 // Get the VTable. 1562 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD); 1563 1564 // Initialize the vtable pointers for this class and all of its bases. 1565 VisitedVirtualBasesSetTy VBases; 1566 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()), 1567 /*NearestVBase=*/0, 1568 /*OffsetFromNearestVBase=*/CharUnits::Zero(), 1569 /*BaseIsNonVirtualPrimaryBase=*/false, 1570 VTable, RD, VBases); 1571 } 1572 1573 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This, 1574 llvm::Type *Ty) { 1575 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo()); 1576 return Builder.CreateLoad(VTablePtrSrc, "vtable"); 1577 } 1578 1579 static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) { 1580 const Expr *E = Base; 1581 1582 while (true) { 1583 E = E->IgnoreParens(); 1584 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 1585 if (CE->getCastKind() == CK_DerivedToBase || 1586 CE->getCastKind() == CK_UncheckedDerivedToBase || 1587 CE->getCastKind() == CK_NoOp) { 1588 E = CE->getSubExpr(); 1589 continue; 1590 } 1591 } 1592 1593 break; 1594 } 1595 1596 QualType DerivedType = E->getType(); 1597 if (const PointerType *PTy = DerivedType->getAs<PointerType>()) 1598 DerivedType = PTy->getPointeeType(); 1599 1600 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl()); 1601 } 1602 1603 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do 1604 // quite what we want. 1605 static const Expr *skipNoOpCastsAndParens(const Expr *E) { 1606 while (true) { 1607 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 1608 E = PE->getSubExpr(); 1609 continue; 1610 } 1611 1612 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 1613 if (CE->getCastKind() == CK_NoOp) { 1614 E = CE->getSubExpr(); 1615 continue; 1616 } 1617 } 1618 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 1619 if (UO->getOpcode() == UO_Extension) { 1620 E = UO->getSubExpr(); 1621 continue; 1622 } 1623 } 1624 return E; 1625 } 1626 } 1627 1628 /// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member 1629 /// function call on the given expr can be devirtualized. 1630 static bool canDevirtualizeMemberFunctionCall(const Expr *Base, 1631 const CXXMethodDecl *MD) { 1632 // If the most derived class is marked final, we know that no subclass can 1633 // override this member function and so we can devirtualize it. For example: 1634 // 1635 // struct A { virtual void f(); } 1636 // struct B final : A { }; 1637 // 1638 // void f(B *b) { 1639 // b->f(); 1640 // } 1641 // 1642 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base); 1643 if (MostDerivedClassDecl->hasAttr<FinalAttr>()) 1644 return true; 1645 1646 // If the member function is marked 'final', we know that it can't be 1647 // overridden and can therefore devirtualize it. 1648 if (MD->hasAttr<FinalAttr>()) 1649 return true; 1650 1651 // Similarly, if the class itself is marked 'final' it can't be overridden 1652 // and we can therefore devirtualize the member function call. 1653 if (MD->getParent()->hasAttr<FinalAttr>()) 1654 return true; 1655 1656 Base = skipNoOpCastsAndParens(Base); 1657 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 1658 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 1659 // This is a record decl. We know the type and can devirtualize it. 1660 return VD->getType()->isRecordType(); 1661 } 1662 1663 return false; 1664 } 1665 1666 // We can always devirtualize calls on temporary object expressions. 1667 if (isa<CXXConstructExpr>(Base)) 1668 return true; 1669 1670 // And calls on bound temporaries. 1671 if (isa<CXXBindTemporaryExpr>(Base)) 1672 return true; 1673 1674 // Check if this is a call expr that returns a record type. 1675 if (const CallExpr *CE = dyn_cast<CallExpr>(Base)) 1676 return CE->getCallReturnType()->isRecordType(); 1677 1678 // We can't devirtualize the call. 1679 return false; 1680 } 1681 1682 static bool UseVirtualCall(ASTContext &Context, 1683 const CXXOperatorCallExpr *CE, 1684 const CXXMethodDecl *MD) { 1685 if (!MD->isVirtual()) 1686 return false; 1687 1688 // When building with -fapple-kext, all calls must go through the vtable since 1689 // the kernel linker can do runtime patching of vtables. 1690 if (Context.getLangOptions().AppleKext) 1691 return true; 1692 1693 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD); 1694 } 1695 1696 llvm::Value * 1697 CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E, 1698 const CXXMethodDecl *MD, 1699 llvm::Value *This) { 1700 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 1701 llvm::Type *Ty = 1702 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 1703 FPT->isVariadic()); 1704 1705 if (UseVirtualCall(getContext(), E, MD)) 1706 return BuildVirtualCall(MD, This, Ty); 1707 1708 return CGM.GetAddrOfFunction(MD, Ty); 1709 } 1710