1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This contains code dealing with C++ code generation of classes 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGBlocks.h" 14 #include "CGCXXABI.h" 15 #include "CGDebugInfo.h" 16 #include "CGRecordLayout.h" 17 #include "CodeGenFunction.h" 18 #include "TargetInfo.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/CXXInheritance.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/Basic/CodeGenOptions.h" 26 #include "clang/Basic/TargetBuiltins.h" 27 #include "clang/CodeGen/CGFunctionInfo.h" 28 #include "llvm/IR/Intrinsics.h" 29 #include "llvm/IR/Metadata.h" 30 #include "llvm/Transforms/Utils/SanitizerStats.h" 31 32 using namespace clang; 33 using namespace CodeGen; 34 35 /// Return the best known alignment for an unknown pointer to a 36 /// particular class. 37 CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) { 38 if (!RD->hasDefinition()) 39 return CharUnits::One(); // Hopefully won't be used anywhere. 40 41 auto &layout = getContext().getASTRecordLayout(RD); 42 43 // If the class is final, then we know that the pointer points to an 44 // object of that type and can use the full alignment. 45 if (RD->isEffectivelyFinal()) 46 return layout.getAlignment(); 47 48 // Otherwise, we have to assume it could be a subclass. 49 return layout.getNonVirtualAlignment(); 50 } 51 52 /// Return the smallest possible amount of storage that might be allocated 53 /// starting from the beginning of an object of a particular class. 54 /// 55 /// This may be smaller than sizeof(RD) if RD has virtual base classes. 56 CharUnits CodeGenModule::getMinimumClassObjectSize(const CXXRecordDecl *RD) { 57 if (!RD->hasDefinition()) 58 return CharUnits::One(); 59 60 auto &layout = getContext().getASTRecordLayout(RD); 61 62 // If the class is final, then we know that the pointer points to an 63 // object of that type and can use the full alignment. 64 if (RD->isEffectivelyFinal()) 65 return layout.getSize(); 66 67 // Otherwise, we have to assume it could be a subclass. 68 return std::max(layout.getNonVirtualSize(), CharUnits::One()); 69 } 70 71 /// Return the best known alignment for a pointer to a virtual base, 72 /// given the alignment of a pointer to the derived class. 73 CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign, 74 const CXXRecordDecl *derivedClass, 75 const CXXRecordDecl *vbaseClass) { 76 // The basic idea here is that an underaligned derived pointer might 77 // indicate an underaligned base pointer. 78 79 assert(vbaseClass->isCompleteDefinition()); 80 auto &baseLayout = getContext().getASTRecordLayout(vbaseClass); 81 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment(); 82 83 return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass, 84 expectedVBaseAlign); 85 } 86 87 CharUnits 88 CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign, 89 const CXXRecordDecl *baseDecl, 90 CharUnits expectedTargetAlign) { 91 // If the base is an incomplete type (which is, alas, possible with 92 // member pointers), be pessimistic. 93 if (!baseDecl->isCompleteDefinition()) 94 return std::min(actualBaseAlign, expectedTargetAlign); 95 96 auto &baseLayout = getContext().getASTRecordLayout(baseDecl); 97 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment(); 98 99 // If the class is properly aligned, assume the target offset is, too. 100 // 101 // This actually isn't necessarily the right thing to do --- if the 102 // class is a complete object, but it's only properly aligned for a 103 // base subobject, then the alignments of things relative to it are 104 // probably off as well. (Note that this requires the alignment of 105 // the target to be greater than the NV alignment of the derived 106 // class.) 107 // 108 // However, our approach to this kind of under-alignment can only 109 // ever be best effort; after all, we're never going to propagate 110 // alignments through variables or parameters. Note, in particular, 111 // that constructing a polymorphic type in an address that's less 112 // than pointer-aligned will generally trap in the constructor, 113 // unless we someday add some sort of attribute to change the 114 // assumed alignment of 'this'. So our goal here is pretty much 115 // just to allow the user to explicitly say that a pointer is 116 // under-aligned and then safely access its fields and vtables. 117 if (actualBaseAlign >= expectedBaseAlign) { 118 return expectedTargetAlign; 119 } 120 121 // Otherwise, we might be offset by an arbitrary multiple of the 122 // actual alignment. The correct adjustment is to take the min of 123 // the two alignments. 124 return std::min(actualBaseAlign, expectedTargetAlign); 125 } 126 127 Address CodeGenFunction::LoadCXXThisAddress() { 128 assert(CurFuncDecl && "loading 'this' without a func declaration?"); 129 assert(isa<CXXMethodDecl>(CurFuncDecl)); 130 131 // Lazily compute CXXThisAlignment. 132 if (CXXThisAlignment.isZero()) { 133 // Just use the best known alignment for the parent. 134 // TODO: if we're currently emitting a complete-object ctor/dtor, 135 // we can always use the complete-object alignment. 136 auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent(); 137 CXXThisAlignment = CGM.getClassPointerAlignment(RD); 138 } 139 140 return Address(LoadCXXThis(), CXXThisAlignment); 141 } 142 143 /// Emit the address of a field using a member data pointer. 144 /// 145 /// \param E Only used for emergency diagnostics 146 Address 147 CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base, 148 llvm::Value *memberPtr, 149 const MemberPointerType *memberPtrType, 150 LValueBaseInfo *BaseInfo, 151 TBAAAccessInfo *TBAAInfo) { 152 // Ask the ABI to compute the actual address. 153 llvm::Value *ptr = 154 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base, 155 memberPtr, memberPtrType); 156 157 QualType memberType = memberPtrType->getPointeeType(); 158 CharUnits memberAlign = 159 CGM.getNaturalTypeAlignment(memberType, BaseInfo, TBAAInfo); 160 memberAlign = 161 CGM.getDynamicOffsetAlignment(base.getAlignment(), 162 memberPtrType->getClass()->getAsCXXRecordDecl(), 163 memberAlign); 164 return Address(ptr, memberAlign); 165 } 166 167 CharUnits CodeGenModule::computeNonVirtualBaseClassOffset( 168 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start, 169 CastExpr::path_const_iterator End) { 170 CharUnits Offset = CharUnits::Zero(); 171 172 const ASTContext &Context = getContext(); 173 const CXXRecordDecl *RD = DerivedClass; 174 175 for (CastExpr::path_const_iterator I = Start; I != End; ++I) { 176 const CXXBaseSpecifier *Base = *I; 177 assert(!Base->isVirtual() && "Should not see virtual bases here!"); 178 179 // Get the layout. 180 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 181 182 const auto *BaseDecl = 183 cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl()); 184 185 // Add the offset. 186 Offset += Layout.getBaseClassOffset(BaseDecl); 187 188 RD = BaseDecl; 189 } 190 191 return Offset; 192 } 193 194 llvm::Constant * 195 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 196 CastExpr::path_const_iterator PathBegin, 197 CastExpr::path_const_iterator PathEnd) { 198 assert(PathBegin != PathEnd && "Base path should not be empty!"); 199 200 CharUnits Offset = 201 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd); 202 if (Offset.isZero()) 203 return nullptr; 204 205 llvm::Type *PtrDiffTy = 206 Types.ConvertType(getContext().getPointerDiffType()); 207 208 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity()); 209 } 210 211 /// Gets the address of a direct base class within a complete object. 212 /// This should only be used for (1) non-virtual bases or (2) virtual bases 213 /// when the type is known to be complete (e.g. in complete destructors). 214 /// 215 /// The object pointed to by 'This' is assumed to be non-null. 216 Address 217 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This, 218 const CXXRecordDecl *Derived, 219 const CXXRecordDecl *Base, 220 bool BaseIsVirtual) { 221 // 'this' must be a pointer (in some address space) to Derived. 222 assert(This.getElementType() == ConvertType(Derived)); 223 224 // Compute the offset of the virtual base. 225 CharUnits Offset; 226 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived); 227 if (BaseIsVirtual) 228 Offset = Layout.getVBaseClassOffset(Base); 229 else 230 Offset = Layout.getBaseClassOffset(Base); 231 232 // Shift and cast down to the base type. 233 // TODO: for complete types, this should be possible with a GEP. 234 Address V = This; 235 if (!Offset.isZero()) { 236 V = Builder.CreateElementBitCast(V, Int8Ty); 237 V = Builder.CreateConstInBoundsByteGEP(V, Offset); 238 } 239 V = Builder.CreateElementBitCast(V, ConvertType(Base)); 240 241 return V; 242 } 243 244 static Address 245 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr, 246 CharUnits nonVirtualOffset, 247 llvm::Value *virtualOffset, 248 const CXXRecordDecl *derivedClass, 249 const CXXRecordDecl *nearestVBase) { 250 // Assert that we have something to do. 251 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr); 252 253 // Compute the offset from the static and dynamic components. 254 llvm::Value *baseOffset; 255 if (!nonVirtualOffset.isZero()) { 256 llvm::Type *OffsetType = 257 (CGF.CGM.getTarget().getCXXABI().isItaniumFamily() && 258 CGF.CGM.getItaniumVTableContext().isRelativeLayout()) 259 ? CGF.Int32Ty 260 : CGF.PtrDiffTy; 261 baseOffset = 262 llvm::ConstantInt::get(OffsetType, nonVirtualOffset.getQuantity()); 263 if (virtualOffset) { 264 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset); 265 } 266 } else { 267 baseOffset = virtualOffset; 268 } 269 270 // Apply the base offset. 271 llvm::Value *ptr = addr.getPointer(); 272 unsigned AddrSpace = ptr->getType()->getPointerAddressSpace(); 273 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8Ty->getPointerTo(AddrSpace)); 274 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr"); 275 276 // If we have a virtual component, the alignment of the result will 277 // be relative only to the known alignment of that vbase. 278 CharUnits alignment; 279 if (virtualOffset) { 280 assert(nearestVBase && "virtual offset without vbase?"); 281 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(), 282 derivedClass, nearestVBase); 283 } else { 284 alignment = addr.getAlignment(); 285 } 286 alignment = alignment.alignmentAtOffset(nonVirtualOffset); 287 288 return Address(ptr, alignment); 289 } 290 291 Address CodeGenFunction::GetAddressOfBaseClass( 292 Address Value, const CXXRecordDecl *Derived, 293 CastExpr::path_const_iterator PathBegin, 294 CastExpr::path_const_iterator PathEnd, bool NullCheckValue, 295 SourceLocation Loc) { 296 assert(PathBegin != PathEnd && "Base path should not be empty!"); 297 298 CastExpr::path_const_iterator Start = PathBegin; 299 const CXXRecordDecl *VBase = nullptr; 300 301 // Sema has done some convenient canonicalization here: if the 302 // access path involved any virtual steps, the conversion path will 303 // *start* with a step down to the correct virtual base subobject, 304 // and hence will not require any further steps. 305 if ((*Start)->isVirtual()) { 306 VBase = cast<CXXRecordDecl>( 307 (*Start)->getType()->castAs<RecordType>()->getDecl()); 308 ++Start; 309 } 310 311 // Compute the static offset of the ultimate destination within its 312 // allocating subobject (the virtual base, if there is one, or else 313 // the "complete" object that we see). 314 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset( 315 VBase ? VBase : Derived, Start, PathEnd); 316 317 // If there's a virtual step, we can sometimes "devirtualize" it. 318 // For now, that's limited to when the derived type is final. 319 // TODO: "devirtualize" this for accesses to known-complete objects. 320 if (VBase && Derived->hasAttr<FinalAttr>()) { 321 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived); 322 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase); 323 NonVirtualOffset += vBaseOffset; 324 VBase = nullptr; // we no longer have a virtual step 325 } 326 327 // Get the base pointer type. 328 llvm::Type *BasePtrTy = 329 ConvertType((PathEnd[-1])->getType()) 330 ->getPointerTo(Value.getType()->getPointerAddressSpace()); 331 332 QualType DerivedTy = getContext().getRecordType(Derived); 333 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived); 334 335 // If the static offset is zero and we don't have a virtual step, 336 // just do a bitcast; null checks are unnecessary. 337 if (NonVirtualOffset.isZero() && !VBase) { 338 if (sanitizePerformTypeCheck()) { 339 SanitizerSet SkippedChecks; 340 SkippedChecks.set(SanitizerKind::Null, !NullCheckValue); 341 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(), 342 DerivedTy, DerivedAlign, SkippedChecks); 343 } 344 return Builder.CreateBitCast(Value, BasePtrTy); 345 } 346 347 llvm::BasicBlock *origBB = nullptr; 348 llvm::BasicBlock *endBB = nullptr; 349 350 // Skip over the offset (and the vtable load) if we're supposed to 351 // null-check the pointer. 352 if (NullCheckValue) { 353 origBB = Builder.GetInsertBlock(); 354 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull"); 355 endBB = createBasicBlock("cast.end"); 356 357 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer()); 358 Builder.CreateCondBr(isNull, endBB, notNullBB); 359 EmitBlock(notNullBB); 360 } 361 362 if (sanitizePerformTypeCheck()) { 363 SanitizerSet SkippedChecks; 364 SkippedChecks.set(SanitizerKind::Null, true); 365 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc, 366 Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks); 367 } 368 369 // Compute the virtual offset. 370 llvm::Value *VirtualOffset = nullptr; 371 if (VBase) { 372 VirtualOffset = 373 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase); 374 } 375 376 // Apply both offsets. 377 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset, 378 VirtualOffset, Derived, VBase); 379 380 // Cast to the destination type. 381 Value = Builder.CreateBitCast(Value, BasePtrTy); 382 383 // Build a phi if we needed a null check. 384 if (NullCheckValue) { 385 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock(); 386 Builder.CreateBr(endBB); 387 EmitBlock(endBB); 388 389 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result"); 390 PHI->addIncoming(Value.getPointer(), notNullBB); 391 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB); 392 Value = Address(PHI, Value.getAlignment()); 393 } 394 395 return Value; 396 } 397 398 Address 399 CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr, 400 const CXXRecordDecl *Derived, 401 CastExpr::path_const_iterator PathBegin, 402 CastExpr::path_const_iterator PathEnd, 403 bool NullCheckValue) { 404 assert(PathBegin != PathEnd && "Base path should not be empty!"); 405 406 QualType DerivedTy = 407 getContext().getCanonicalType(getContext().getTagDeclType(Derived)); 408 unsigned AddrSpace = 409 BaseAddr.getPointer()->getType()->getPointerAddressSpace(); 410 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo(AddrSpace); 411 412 llvm::Value *NonVirtualOffset = 413 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd); 414 415 if (!NonVirtualOffset) { 416 // No offset, we can just cast back. 417 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy); 418 } 419 420 llvm::BasicBlock *CastNull = nullptr; 421 llvm::BasicBlock *CastNotNull = nullptr; 422 llvm::BasicBlock *CastEnd = nullptr; 423 424 if (NullCheckValue) { 425 CastNull = createBasicBlock("cast.null"); 426 CastNotNull = createBasicBlock("cast.notnull"); 427 CastEnd = createBasicBlock("cast.end"); 428 429 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer()); 430 Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 431 EmitBlock(CastNotNull); 432 } 433 434 // Apply the offset. 435 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy); 436 Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset), 437 "sub.ptr"); 438 439 // Just cast. 440 Value = Builder.CreateBitCast(Value, DerivedPtrTy); 441 442 // Produce a PHI if we had a null-check. 443 if (NullCheckValue) { 444 Builder.CreateBr(CastEnd); 445 EmitBlock(CastNull); 446 Builder.CreateBr(CastEnd); 447 EmitBlock(CastEnd); 448 449 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 450 PHI->addIncoming(Value, CastNotNull); 451 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull); 452 Value = PHI; 453 } 454 455 return Address(Value, CGM.getClassPointerAlignment(Derived)); 456 } 457 458 llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD, 459 bool ForVirtualBase, 460 bool Delegating) { 461 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) { 462 // This constructor/destructor does not need a VTT parameter. 463 return nullptr; 464 } 465 466 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent(); 467 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent(); 468 469 llvm::Value *VTT; 470 471 uint64_t SubVTTIndex; 472 473 if (Delegating) { 474 // If this is a delegating constructor call, just load the VTT. 475 return LoadCXXVTT(); 476 } else if (RD == Base) { 477 // If the record matches the base, this is the complete ctor/dtor 478 // variant calling the base variant in a class with virtual bases. 479 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) && 480 "doing no-op VTT offset in base dtor/ctor?"); 481 assert(!ForVirtualBase && "Can't have same class as virtual base!"); 482 SubVTTIndex = 0; 483 } else { 484 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 485 CharUnits BaseOffset = ForVirtualBase ? 486 Layout.getVBaseClassOffset(Base) : 487 Layout.getBaseClassOffset(Base); 488 489 SubVTTIndex = 490 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset)); 491 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!"); 492 } 493 494 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) { 495 // A VTT parameter was passed to the constructor, use it. 496 VTT = LoadCXXVTT(); 497 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex); 498 } else { 499 // We're the complete constructor, so get the VTT by name. 500 VTT = CGM.getVTables().GetAddrOfVTT(RD); 501 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex); 502 } 503 504 return VTT; 505 } 506 507 namespace { 508 /// Call the destructor for a direct base class. 509 struct CallBaseDtor final : EHScopeStack::Cleanup { 510 const CXXRecordDecl *BaseClass; 511 bool BaseIsVirtual; 512 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual) 513 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {} 514 515 void Emit(CodeGenFunction &CGF, Flags flags) override { 516 const CXXRecordDecl *DerivedClass = 517 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent(); 518 519 const CXXDestructorDecl *D = BaseClass->getDestructor(); 520 // We are already inside a destructor, so presumably the object being 521 // destroyed should have the expected type. 522 QualType ThisTy = D->getThisObjectType(); 523 Address Addr = 524 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(), 525 DerivedClass, BaseClass, 526 BaseIsVirtual); 527 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, 528 /*Delegating=*/false, Addr, ThisTy); 529 } 530 }; 531 532 /// A visitor which checks whether an initializer uses 'this' in a 533 /// way which requires the vtable to be properly set. 534 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> { 535 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super; 536 537 bool UsesThis; 538 539 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {} 540 541 // Black-list all explicit and implicit references to 'this'. 542 // 543 // Do we need to worry about external references to 'this' derived 544 // from arbitrary code? If so, then anything which runs arbitrary 545 // external code might potentially access the vtable. 546 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; } 547 }; 548 } // end anonymous namespace 549 550 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) { 551 DynamicThisUseChecker Checker(C); 552 Checker.Visit(Init); 553 return Checker.UsesThis; 554 } 555 556 static void EmitBaseInitializer(CodeGenFunction &CGF, 557 const CXXRecordDecl *ClassDecl, 558 CXXCtorInitializer *BaseInit) { 559 assert(BaseInit->isBaseInitializer() && 560 "Must have base initializer!"); 561 562 Address ThisPtr = CGF.LoadCXXThisAddress(); 563 564 const Type *BaseType = BaseInit->getBaseClass(); 565 const auto *BaseClassDecl = 566 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl()); 567 568 bool isBaseVirtual = BaseInit->isBaseVirtual(); 569 570 // If the initializer for the base (other than the constructor 571 // itself) accesses 'this' in any way, we need to initialize the 572 // vtables. 573 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit())) 574 CGF.InitializeVTablePointers(ClassDecl); 575 576 // We can pretend to be a complete class because it only matters for 577 // virtual bases, and we only do virtual bases for complete ctors. 578 Address V = 579 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl, 580 BaseClassDecl, 581 isBaseVirtual); 582 AggValueSlot AggSlot = 583 AggValueSlot::forAddr( 584 V, Qualifiers(), 585 AggValueSlot::IsDestructed, 586 AggValueSlot::DoesNotNeedGCBarriers, 587 AggValueSlot::IsNotAliased, 588 CGF.getOverlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual)); 589 590 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot); 591 592 if (CGF.CGM.getLangOpts().Exceptions && 593 !BaseClassDecl->hasTrivialDestructor()) 594 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl, 595 isBaseVirtual); 596 } 597 598 static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) { 599 auto *CD = dyn_cast<CXXConstructorDecl>(D); 600 if (!(CD && CD->isCopyOrMoveConstructor()) && 601 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator()) 602 return false; 603 604 // We can emit a memcpy for a trivial copy or move constructor/assignment. 605 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding()) 606 return true; 607 608 // We *must* emit a memcpy for a defaulted union copy or move op. 609 if (D->getParent()->isUnion() && D->isDefaulted()) 610 return true; 611 612 return false; 613 } 614 615 static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF, 616 CXXCtorInitializer *MemberInit, 617 LValue &LHS) { 618 FieldDecl *Field = MemberInit->getAnyMember(); 619 if (MemberInit->isIndirectMemberInitializer()) { 620 // If we are initializing an anonymous union field, drill down to the field. 621 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember(); 622 for (const auto *I : IndirectField->chain()) 623 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I)); 624 } else { 625 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field); 626 } 627 } 628 629 static void EmitMemberInitializer(CodeGenFunction &CGF, 630 const CXXRecordDecl *ClassDecl, 631 CXXCtorInitializer *MemberInit, 632 const CXXConstructorDecl *Constructor, 633 FunctionArgList &Args) { 634 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation()); 635 assert(MemberInit->isAnyMemberInitializer() && 636 "Must have member initializer!"); 637 assert(MemberInit->getInit() && "Must have initializer!"); 638 639 // non-static data member initializers. 640 FieldDecl *Field = MemberInit->getAnyMember(); 641 QualType FieldType = Field->getType(); 642 643 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 644 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl); 645 LValue LHS; 646 647 // If a base constructor is being emitted, create an LValue that has the 648 // non-virtual alignment. 649 if (CGF.CurGD.getCtorType() == Ctor_Base) 650 LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy); 651 else 652 LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy); 653 654 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS); 655 656 // Special case: if we are in a copy or move constructor, and we are copying 657 // an array of PODs or classes with trivial copy constructors, ignore the 658 // AST and perform the copy we know is equivalent. 659 // FIXME: This is hacky at best... if we had a bit more explicit information 660 // in the AST, we could generalize it more easily. 661 const ConstantArrayType *Array 662 = CGF.getContext().getAsConstantArrayType(FieldType); 663 if (Array && Constructor->isDefaulted() && 664 Constructor->isCopyOrMoveConstructor()) { 665 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array); 666 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit()); 667 if (BaseElementTy.isPODType(CGF.getContext()) || 668 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) { 669 unsigned SrcArgIndex = 670 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args); 671 llvm::Value *SrcPtr 672 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex])); 673 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy); 674 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field); 675 676 // Copy the aggregate. 677 CGF.EmitAggregateCopy(LHS, Src, FieldType, CGF.getOverlapForFieldInit(Field), 678 LHS.isVolatileQualified()); 679 // Ensure that we destroy the objects if an exception is thrown later in 680 // the constructor. 681 QualType::DestructionKind dtorKind = FieldType.isDestructedType(); 682 if (CGF.needsEHCleanup(dtorKind)) 683 CGF.pushEHDestroy(dtorKind, LHS.getAddress(CGF), FieldType); 684 return; 685 } 686 } 687 688 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit()); 689 } 690 691 void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS, 692 Expr *Init) { 693 QualType FieldType = Field->getType(); 694 switch (getEvaluationKind(FieldType)) { 695 case TEK_Scalar: 696 if (LHS.isSimple()) { 697 EmitExprAsInit(Init, Field, LHS, false); 698 } else { 699 RValue RHS = RValue::get(EmitScalarExpr(Init)); 700 EmitStoreThroughLValue(RHS, LHS); 701 } 702 break; 703 case TEK_Complex: 704 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true); 705 break; 706 case TEK_Aggregate: { 707 AggValueSlot Slot = AggValueSlot::forLValue( 708 LHS, *this, AggValueSlot::IsDestructed, 709 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, 710 getOverlapForFieldInit(Field), AggValueSlot::IsNotZeroed, 711 // Checks are made by the code that calls constructor. 712 AggValueSlot::IsSanitizerChecked); 713 EmitAggExpr(Init, Slot); 714 break; 715 } 716 } 717 718 // Ensure that we destroy this object if an exception is thrown 719 // later in the constructor. 720 QualType::DestructionKind dtorKind = FieldType.isDestructedType(); 721 if (needsEHCleanup(dtorKind)) 722 pushEHDestroy(dtorKind, LHS.getAddress(*this), FieldType); 723 } 724 725 /// Checks whether the given constructor is a valid subject for the 726 /// complete-to-base constructor delegation optimization, i.e. 727 /// emitting the complete constructor as a simple call to the base 728 /// constructor. 729 bool CodeGenFunction::IsConstructorDelegationValid( 730 const CXXConstructorDecl *Ctor) { 731 732 // Currently we disable the optimization for classes with virtual 733 // bases because (1) the addresses of parameter variables need to be 734 // consistent across all initializers but (2) the delegate function 735 // call necessarily creates a second copy of the parameter variable. 736 // 737 // The limiting example (purely theoretical AFAIK): 738 // struct A { A(int &c) { c++; } }; 739 // struct B : virtual A { 740 // B(int count) : A(count) { printf("%d\n", count); } 741 // }; 742 // ...although even this example could in principle be emitted as a 743 // delegation since the address of the parameter doesn't escape. 744 if (Ctor->getParent()->getNumVBases()) { 745 // TODO: white-list trivial vbase initializers. This case wouldn't 746 // be subject to the restrictions below. 747 748 // TODO: white-list cases where: 749 // - there are no non-reference parameters to the constructor 750 // - the initializers don't access any non-reference parameters 751 // - the initializers don't take the address of non-reference 752 // parameters 753 // - etc. 754 // If we ever add any of the above cases, remember that: 755 // - function-try-blocks will always exclude this optimization 756 // - we need to perform the constructor prologue and cleanup in 757 // EmitConstructorBody. 758 759 return false; 760 } 761 762 // We also disable the optimization for variadic functions because 763 // it's impossible to "re-pass" varargs. 764 if (Ctor->getType()->castAs<FunctionProtoType>()->isVariadic()) 765 return false; 766 767 // FIXME: Decide if we can do a delegation of a delegating constructor. 768 if (Ctor->isDelegatingConstructor()) 769 return false; 770 771 return true; 772 } 773 774 // Emit code in ctor (Prologue==true) or dtor (Prologue==false) 775 // to poison the extra field paddings inserted under 776 // -fsanitize-address-field-padding=1|2. 777 void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) { 778 ASTContext &Context = getContext(); 779 const CXXRecordDecl *ClassDecl = 780 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent() 781 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent(); 782 if (!ClassDecl->mayInsertExtraPadding()) return; 783 784 struct SizeAndOffset { 785 uint64_t Size; 786 uint64_t Offset; 787 }; 788 789 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits(); 790 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl); 791 792 // Populate sizes and offsets of fields. 793 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount()); 794 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) 795 SSV[i].Offset = 796 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity(); 797 798 size_t NumFields = 0; 799 for (const auto *Field : ClassDecl->fields()) { 800 const FieldDecl *D = Field; 801 auto FieldInfo = Context.getTypeInfoInChars(D->getType()); 802 CharUnits FieldSize = FieldInfo.Width; 803 assert(NumFields < SSV.size()); 804 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity(); 805 NumFields++; 806 } 807 assert(NumFields == SSV.size()); 808 if (SSV.size() <= 1) return; 809 810 // We will insert calls to __asan_* run-time functions. 811 // LLVM AddressSanitizer pass may decide to inline them later. 812 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy}; 813 llvm::FunctionType *FTy = 814 llvm::FunctionType::get(CGM.VoidTy, Args, false); 815 llvm::FunctionCallee F = CGM.CreateRuntimeFunction( 816 FTy, Prologue ? "__asan_poison_intra_object_redzone" 817 : "__asan_unpoison_intra_object_redzone"); 818 819 llvm::Value *ThisPtr = LoadCXXThis(); 820 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy); 821 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity(); 822 // For each field check if it has sufficient padding, 823 // if so (un)poison it with a call. 824 for (size_t i = 0; i < SSV.size(); i++) { 825 uint64_t AsanAlignment = 8; 826 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset; 827 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size; 828 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size; 829 if (PoisonSize < AsanAlignment || !SSV[i].Size || 830 (NextField % AsanAlignment) != 0) 831 continue; 832 Builder.CreateCall( 833 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)), 834 Builder.getIntN(PtrSize, PoisonSize)}); 835 } 836 } 837 838 /// EmitConstructorBody - Emits the body of the current constructor. 839 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) { 840 EmitAsanPrologueOrEpilogue(true); 841 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl()); 842 CXXCtorType CtorType = CurGD.getCtorType(); 843 844 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() || 845 CtorType == Ctor_Complete) && 846 "can only generate complete ctor for this ABI"); 847 848 // Before we go any further, try the complete->base constructor 849 // delegation optimization. 850 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) && 851 CGM.getTarget().getCXXABI().hasConstructorVariants()) { 852 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getEndLoc()); 853 return; 854 } 855 856 const FunctionDecl *Definition = nullptr; 857 Stmt *Body = Ctor->getBody(Definition); 858 assert(Definition == Ctor && "emitting wrong constructor body"); 859 860 // Enter the function-try-block before the constructor prologue if 861 // applicable. 862 bool IsTryBody = (Body && isa<CXXTryStmt>(Body)); 863 if (IsTryBody) 864 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 865 866 incrementProfileCounter(Body); 867 868 RunCleanupsScope RunCleanups(*this); 869 870 // TODO: in restricted cases, we can emit the vbase initializers of 871 // a complete ctor and then delegate to the base ctor. 872 873 // Emit the constructor prologue, i.e. the base and member 874 // initializers. 875 EmitCtorPrologue(Ctor, CtorType, Args); 876 877 // Emit the body of the statement. 878 if (IsTryBody) 879 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 880 else if (Body) 881 EmitStmt(Body); 882 883 // Emit any cleanup blocks associated with the member or base 884 // initializers, which includes (along the exceptional path) the 885 // destructors for those members and bases that were fully 886 // constructed. 887 RunCleanups.ForceCleanup(); 888 889 if (IsTryBody) 890 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 891 } 892 893 namespace { 894 /// RAII object to indicate that codegen is copying the value representation 895 /// instead of the object representation. Useful when copying a struct or 896 /// class which has uninitialized members and we're only performing 897 /// lvalue-to-rvalue conversion on the object but not its members. 898 class CopyingValueRepresentation { 899 public: 900 explicit CopyingValueRepresentation(CodeGenFunction &CGF) 901 : CGF(CGF), OldSanOpts(CGF.SanOpts) { 902 CGF.SanOpts.set(SanitizerKind::Bool, false); 903 CGF.SanOpts.set(SanitizerKind::Enum, false); 904 } 905 ~CopyingValueRepresentation() { 906 CGF.SanOpts = OldSanOpts; 907 } 908 private: 909 CodeGenFunction &CGF; 910 SanitizerSet OldSanOpts; 911 }; 912 } // end anonymous namespace 913 914 namespace { 915 class FieldMemcpyizer { 916 public: 917 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl, 918 const VarDecl *SrcRec) 919 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec), 920 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)), 921 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0), 922 LastFieldOffset(0), LastAddedFieldIndex(0) {} 923 924 bool isMemcpyableField(FieldDecl *F) const { 925 // Never memcpy fields when we are adding poisoned paddings. 926 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding) 927 return false; 928 Qualifiers Qual = F->getType().getQualifiers(); 929 if (Qual.hasVolatile() || Qual.hasObjCLifetime()) 930 return false; 931 return true; 932 } 933 934 void addMemcpyableField(FieldDecl *F) { 935 if (F->isZeroSize(CGF.getContext())) 936 return; 937 if (!FirstField) 938 addInitialField(F); 939 else 940 addNextField(F); 941 } 942 943 CharUnits getMemcpySize(uint64_t FirstByteOffset) const { 944 ASTContext &Ctx = CGF.getContext(); 945 unsigned LastFieldSize = 946 LastField->isBitField() 947 ? LastField->getBitWidthValue(Ctx) 948 : Ctx.toBits( 949 Ctx.getTypeInfoDataSizeInChars(LastField->getType()).Width); 950 uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize - 951 FirstByteOffset + Ctx.getCharWidth() - 1; 952 CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits); 953 return MemcpySize; 954 } 955 956 void emitMemcpy() { 957 // Give the subclass a chance to bail out if it feels the memcpy isn't 958 // worth it (e.g. Hasn't aggregated enough data). 959 if (!FirstField) { 960 return; 961 } 962 963 uint64_t FirstByteOffset; 964 if (FirstField->isBitField()) { 965 const CGRecordLayout &RL = 966 CGF.getTypes().getCGRecordLayout(FirstField->getParent()); 967 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField); 968 // FirstFieldOffset is not appropriate for bitfields, 969 // we need to use the storage offset instead. 970 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset); 971 } else { 972 FirstByteOffset = FirstFieldOffset; 973 } 974 975 CharUnits MemcpySize = getMemcpySize(FirstByteOffset); 976 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl); 977 Address ThisPtr = CGF.LoadCXXThisAddress(); 978 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy); 979 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField); 980 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec)); 981 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy); 982 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField); 983 984 emitMemcpyIR( 985 Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(CGF), 986 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(CGF), 987 MemcpySize); 988 reset(); 989 } 990 991 void reset() { 992 FirstField = nullptr; 993 } 994 995 protected: 996 CodeGenFunction &CGF; 997 const CXXRecordDecl *ClassDecl; 998 999 private: 1000 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) { 1001 llvm::PointerType *DPT = DestPtr.getType(); 1002 llvm::Type *DBP = 1003 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace()); 1004 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP); 1005 1006 llvm::PointerType *SPT = SrcPtr.getType(); 1007 llvm::Type *SBP = 1008 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace()); 1009 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP); 1010 1011 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity()); 1012 } 1013 1014 void addInitialField(FieldDecl *F) { 1015 FirstField = F; 1016 LastField = F; 1017 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex()); 1018 LastFieldOffset = FirstFieldOffset; 1019 LastAddedFieldIndex = F->getFieldIndex(); 1020 } 1021 1022 void addNextField(FieldDecl *F) { 1023 // For the most part, the following invariant will hold: 1024 // F->getFieldIndex() == LastAddedFieldIndex + 1 1025 // The one exception is that Sema won't add a copy-initializer for an 1026 // unnamed bitfield, which will show up here as a gap in the sequence. 1027 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 && 1028 "Cannot aggregate fields out of order."); 1029 LastAddedFieldIndex = F->getFieldIndex(); 1030 1031 // The 'first' and 'last' fields are chosen by offset, rather than field 1032 // index. This allows the code to support bitfields, as well as regular 1033 // fields. 1034 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex()); 1035 if (FOffset < FirstFieldOffset) { 1036 FirstField = F; 1037 FirstFieldOffset = FOffset; 1038 } else if (FOffset >= LastFieldOffset) { 1039 LastField = F; 1040 LastFieldOffset = FOffset; 1041 } 1042 } 1043 1044 const VarDecl *SrcRec; 1045 const ASTRecordLayout &RecLayout; 1046 FieldDecl *FirstField; 1047 FieldDecl *LastField; 1048 uint64_t FirstFieldOffset, LastFieldOffset; 1049 unsigned LastAddedFieldIndex; 1050 }; 1051 1052 class ConstructorMemcpyizer : public FieldMemcpyizer { 1053 private: 1054 /// Get source argument for copy constructor. Returns null if not a copy 1055 /// constructor. 1056 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF, 1057 const CXXConstructorDecl *CD, 1058 FunctionArgList &Args) { 1059 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted()) 1060 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)]; 1061 return nullptr; 1062 } 1063 1064 // Returns true if a CXXCtorInitializer represents a member initialization 1065 // that can be rolled into a memcpy. 1066 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const { 1067 if (!MemcpyableCtor) 1068 return false; 1069 FieldDecl *Field = MemberInit->getMember(); 1070 assert(Field && "No field for member init."); 1071 QualType FieldType = Field->getType(); 1072 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit()); 1073 1074 // Bail out on non-memcpyable, not-trivially-copyable members. 1075 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) && 1076 !(FieldType.isTriviallyCopyableType(CGF.getContext()) || 1077 FieldType->isReferenceType())) 1078 return false; 1079 1080 // Bail out on volatile fields. 1081 if (!isMemcpyableField(Field)) 1082 return false; 1083 1084 // Otherwise we're good. 1085 return true; 1086 } 1087 1088 public: 1089 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD, 1090 FunctionArgList &Args) 1091 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)), 1092 ConstructorDecl(CD), 1093 MemcpyableCtor(CD->isDefaulted() && 1094 CD->isCopyOrMoveConstructor() && 1095 CGF.getLangOpts().getGC() == LangOptions::NonGC), 1096 Args(Args) { } 1097 1098 void addMemberInitializer(CXXCtorInitializer *MemberInit) { 1099 if (isMemberInitMemcpyable(MemberInit)) { 1100 AggregatedInits.push_back(MemberInit); 1101 addMemcpyableField(MemberInit->getMember()); 1102 } else { 1103 emitAggregatedInits(); 1104 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit, 1105 ConstructorDecl, Args); 1106 } 1107 } 1108 1109 void emitAggregatedInits() { 1110 if (AggregatedInits.size() <= 1) { 1111 // This memcpy is too small to be worthwhile. Fall back on default 1112 // codegen. 1113 if (!AggregatedInits.empty()) { 1114 CopyingValueRepresentation CVR(CGF); 1115 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), 1116 AggregatedInits[0], ConstructorDecl, Args); 1117 AggregatedInits.clear(); 1118 } 1119 reset(); 1120 return; 1121 } 1122 1123 pushEHDestructors(); 1124 emitMemcpy(); 1125 AggregatedInits.clear(); 1126 } 1127 1128 void pushEHDestructors() { 1129 Address ThisPtr = CGF.LoadCXXThisAddress(); 1130 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl); 1131 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy); 1132 1133 for (unsigned i = 0; i < AggregatedInits.size(); ++i) { 1134 CXXCtorInitializer *MemberInit = AggregatedInits[i]; 1135 QualType FieldType = MemberInit->getAnyMember()->getType(); 1136 QualType::DestructionKind dtorKind = FieldType.isDestructedType(); 1137 if (!CGF.needsEHCleanup(dtorKind)) 1138 continue; 1139 LValue FieldLHS = LHS; 1140 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS); 1141 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(CGF), FieldType); 1142 } 1143 } 1144 1145 void finish() { 1146 emitAggregatedInits(); 1147 } 1148 1149 private: 1150 const CXXConstructorDecl *ConstructorDecl; 1151 bool MemcpyableCtor; 1152 FunctionArgList &Args; 1153 SmallVector<CXXCtorInitializer*, 16> AggregatedInits; 1154 }; 1155 1156 class AssignmentMemcpyizer : public FieldMemcpyizer { 1157 private: 1158 // Returns the memcpyable field copied by the given statement, if one 1159 // exists. Otherwise returns null. 1160 FieldDecl *getMemcpyableField(Stmt *S) { 1161 if (!AssignmentsMemcpyable) 1162 return nullptr; 1163 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) { 1164 // Recognise trivial assignments. 1165 if (BO->getOpcode() != BO_Assign) 1166 return nullptr; 1167 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS()); 1168 if (!ME) 1169 return nullptr; 1170 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl()); 1171 if (!Field || !isMemcpyableField(Field)) 1172 return nullptr; 1173 Stmt *RHS = BO->getRHS(); 1174 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS)) 1175 RHS = EC->getSubExpr(); 1176 if (!RHS) 1177 return nullptr; 1178 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) { 1179 if (ME2->getMemberDecl() == Field) 1180 return Field; 1181 } 1182 return nullptr; 1183 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) { 1184 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl()); 1185 if (!(MD && isMemcpyEquivalentSpecialMember(MD))) 1186 return nullptr; 1187 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument()); 1188 if (!IOA) 1189 return nullptr; 1190 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl()); 1191 if (!Field || !isMemcpyableField(Field)) 1192 return nullptr; 1193 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0)); 1194 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl())) 1195 return nullptr; 1196 return Field; 1197 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) { 1198 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 1199 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy) 1200 return nullptr; 1201 Expr *DstPtr = CE->getArg(0); 1202 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr)) 1203 DstPtr = DC->getSubExpr(); 1204 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr); 1205 if (!DUO || DUO->getOpcode() != UO_AddrOf) 1206 return nullptr; 1207 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr()); 1208 if (!ME) 1209 return nullptr; 1210 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl()); 1211 if (!Field || !isMemcpyableField(Field)) 1212 return nullptr; 1213 Expr *SrcPtr = CE->getArg(1); 1214 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr)) 1215 SrcPtr = SC->getSubExpr(); 1216 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr); 1217 if (!SUO || SUO->getOpcode() != UO_AddrOf) 1218 return nullptr; 1219 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr()); 1220 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl())) 1221 return nullptr; 1222 return Field; 1223 } 1224 1225 return nullptr; 1226 } 1227 1228 bool AssignmentsMemcpyable; 1229 SmallVector<Stmt*, 16> AggregatedStmts; 1230 1231 public: 1232 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD, 1233 FunctionArgList &Args) 1234 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]), 1235 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) { 1236 assert(Args.size() == 2); 1237 } 1238 1239 void emitAssignment(Stmt *S) { 1240 FieldDecl *F = getMemcpyableField(S); 1241 if (F) { 1242 addMemcpyableField(F); 1243 AggregatedStmts.push_back(S); 1244 } else { 1245 emitAggregatedStmts(); 1246 CGF.EmitStmt(S); 1247 } 1248 } 1249 1250 void emitAggregatedStmts() { 1251 if (AggregatedStmts.size() <= 1) { 1252 if (!AggregatedStmts.empty()) { 1253 CopyingValueRepresentation CVR(CGF); 1254 CGF.EmitStmt(AggregatedStmts[0]); 1255 } 1256 reset(); 1257 } 1258 1259 emitMemcpy(); 1260 AggregatedStmts.clear(); 1261 } 1262 1263 void finish() { 1264 emitAggregatedStmts(); 1265 } 1266 }; 1267 } // end anonymous namespace 1268 1269 static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) { 1270 const Type *BaseType = BaseInit->getBaseClass(); 1271 const auto *BaseClassDecl = 1272 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl()); 1273 return BaseClassDecl->isDynamicClass(); 1274 } 1275 1276 /// EmitCtorPrologue - This routine generates necessary code to initialize 1277 /// base classes and non-static data members belonging to this constructor. 1278 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD, 1279 CXXCtorType CtorType, 1280 FunctionArgList &Args) { 1281 if (CD->isDelegatingConstructor()) 1282 return EmitDelegatingCXXConstructorCall(CD, Args); 1283 1284 const CXXRecordDecl *ClassDecl = CD->getParent(); 1285 1286 CXXConstructorDecl::init_const_iterator B = CD->init_begin(), 1287 E = CD->init_end(); 1288 1289 // Virtual base initializers first, if any. They aren't needed if: 1290 // - This is a base ctor variant 1291 // - There are no vbases 1292 // - The class is abstract, so a complete object of it cannot be constructed 1293 // 1294 // The check for an abstract class is necessary because sema may not have 1295 // marked virtual base destructors referenced. 1296 bool ConstructVBases = CtorType != Ctor_Base && 1297 ClassDecl->getNumVBases() != 0 && 1298 !ClassDecl->isAbstract(); 1299 1300 // In the Microsoft C++ ABI, there are no constructor variants. Instead, the 1301 // constructor of a class with virtual bases takes an additional parameter to 1302 // conditionally construct the virtual bases. Emit that check here. 1303 llvm::BasicBlock *BaseCtorContinueBB = nullptr; 1304 if (ConstructVBases && 1305 !CGM.getTarget().getCXXABI().hasConstructorVariants()) { 1306 BaseCtorContinueBB = 1307 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl); 1308 assert(BaseCtorContinueBB); 1309 } 1310 1311 llvm::Value *const OldThis = CXXThisValue; 1312 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) { 1313 if (!ConstructVBases) 1314 continue; 1315 if (CGM.getCodeGenOpts().StrictVTablePointers && 1316 CGM.getCodeGenOpts().OptimizationLevel > 0 && 1317 isInitializerOfDynamicClass(*B)) 1318 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis()); 1319 EmitBaseInitializer(*this, ClassDecl, *B); 1320 } 1321 1322 if (BaseCtorContinueBB) { 1323 // Complete object handler should continue to the remaining initializers. 1324 Builder.CreateBr(BaseCtorContinueBB); 1325 EmitBlock(BaseCtorContinueBB); 1326 } 1327 1328 // Then, non-virtual base initializers. 1329 for (; B != E && (*B)->isBaseInitializer(); B++) { 1330 assert(!(*B)->isBaseVirtual()); 1331 1332 if (CGM.getCodeGenOpts().StrictVTablePointers && 1333 CGM.getCodeGenOpts().OptimizationLevel > 0 && 1334 isInitializerOfDynamicClass(*B)) 1335 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis()); 1336 EmitBaseInitializer(*this, ClassDecl, *B); 1337 } 1338 1339 CXXThisValue = OldThis; 1340 1341 InitializeVTablePointers(ClassDecl); 1342 1343 // And finally, initialize class members. 1344 FieldConstructionScope FCS(*this, LoadCXXThisAddress()); 1345 ConstructorMemcpyizer CM(*this, CD, Args); 1346 for (; B != E; B++) { 1347 CXXCtorInitializer *Member = (*B); 1348 assert(!Member->isBaseInitializer()); 1349 assert(Member->isAnyMemberInitializer() && 1350 "Delegating initializer on non-delegating constructor"); 1351 CM.addMemberInitializer(Member); 1352 } 1353 CM.finish(); 1354 } 1355 1356 static bool 1357 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field); 1358 1359 static bool 1360 HasTrivialDestructorBody(ASTContext &Context, 1361 const CXXRecordDecl *BaseClassDecl, 1362 const CXXRecordDecl *MostDerivedClassDecl) 1363 { 1364 // If the destructor is trivial we don't have to check anything else. 1365 if (BaseClassDecl->hasTrivialDestructor()) 1366 return true; 1367 1368 if (!BaseClassDecl->getDestructor()->hasTrivialBody()) 1369 return false; 1370 1371 // Check fields. 1372 for (const auto *Field : BaseClassDecl->fields()) 1373 if (!FieldHasTrivialDestructorBody(Context, Field)) 1374 return false; 1375 1376 // Check non-virtual bases. 1377 for (const auto &I : BaseClassDecl->bases()) { 1378 if (I.isVirtual()) 1379 continue; 1380 1381 const CXXRecordDecl *NonVirtualBase = 1382 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 1383 if (!HasTrivialDestructorBody(Context, NonVirtualBase, 1384 MostDerivedClassDecl)) 1385 return false; 1386 } 1387 1388 if (BaseClassDecl == MostDerivedClassDecl) { 1389 // Check virtual bases. 1390 for (const auto &I : BaseClassDecl->vbases()) { 1391 const CXXRecordDecl *VirtualBase = 1392 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 1393 if (!HasTrivialDestructorBody(Context, VirtualBase, 1394 MostDerivedClassDecl)) 1395 return false; 1396 } 1397 } 1398 1399 return true; 1400 } 1401 1402 static bool 1403 FieldHasTrivialDestructorBody(ASTContext &Context, 1404 const FieldDecl *Field) 1405 { 1406 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType()); 1407 1408 const RecordType *RT = FieldBaseElementType->getAs<RecordType>(); 1409 if (!RT) 1410 return true; 1411 1412 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1413 1414 // The destructor for an implicit anonymous union member is never invoked. 1415 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 1416 return false; 1417 1418 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl); 1419 } 1420 1421 /// CanSkipVTablePointerInitialization - Check whether we need to initialize 1422 /// any vtable pointers before calling this destructor. 1423 static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF, 1424 const CXXDestructorDecl *Dtor) { 1425 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1426 if (!ClassDecl->isDynamicClass()) 1427 return true; 1428 1429 if (!Dtor->hasTrivialBody()) 1430 return false; 1431 1432 // Check the fields. 1433 for (const auto *Field : ClassDecl->fields()) 1434 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field)) 1435 return false; 1436 1437 return true; 1438 } 1439 1440 /// EmitDestructorBody - Emits the body of the current destructor. 1441 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) { 1442 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl()); 1443 CXXDtorType DtorType = CurGD.getDtorType(); 1444 1445 // For an abstract class, non-base destructors are never used (and can't 1446 // be emitted in general, because vbase dtors may not have been validated 1447 // by Sema), but the Itanium ABI doesn't make them optional and Clang may 1448 // in fact emit references to them from other compilations, so emit them 1449 // as functions containing a trap instruction. 1450 if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) { 1451 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 1452 TrapCall->setDoesNotReturn(); 1453 TrapCall->setDoesNotThrow(); 1454 Builder.CreateUnreachable(); 1455 Builder.ClearInsertionPoint(); 1456 return; 1457 } 1458 1459 Stmt *Body = Dtor->getBody(); 1460 if (Body) 1461 incrementProfileCounter(Body); 1462 1463 // The call to operator delete in a deleting destructor happens 1464 // outside of the function-try-block, which means it's always 1465 // possible to delegate the destructor body to the complete 1466 // destructor. Do so. 1467 if (DtorType == Dtor_Deleting) { 1468 RunCleanupsScope DtorEpilogue(*this); 1469 EnterDtorCleanups(Dtor, Dtor_Deleting); 1470 if (HaveInsertPoint()) { 1471 QualType ThisTy = Dtor->getThisObjectType(); 1472 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false, 1473 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy); 1474 } 1475 return; 1476 } 1477 1478 // If the body is a function-try-block, enter the try before 1479 // anything else. 1480 bool isTryBody = (Body && isa<CXXTryStmt>(Body)); 1481 if (isTryBody) 1482 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 1483 EmitAsanPrologueOrEpilogue(false); 1484 1485 // Enter the epilogue cleanups. 1486 RunCleanupsScope DtorEpilogue(*this); 1487 1488 // If this is the complete variant, just invoke the base variant; 1489 // the epilogue will destruct the virtual bases. But we can't do 1490 // this optimization if the body is a function-try-block, because 1491 // we'd introduce *two* handler blocks. In the Microsoft ABI, we 1492 // always delegate because we might not have a definition in this TU. 1493 switch (DtorType) { 1494 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT"); 1495 case Dtor_Deleting: llvm_unreachable("already handled deleting case"); 1496 1497 case Dtor_Complete: 1498 assert((Body || getTarget().getCXXABI().isMicrosoft()) && 1499 "can't emit a dtor without a body for non-Microsoft ABIs"); 1500 1501 // Enter the cleanup scopes for virtual bases. 1502 EnterDtorCleanups(Dtor, Dtor_Complete); 1503 1504 if (!isTryBody) { 1505 QualType ThisTy = Dtor->getThisObjectType(); 1506 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false, 1507 /*Delegating=*/false, LoadCXXThisAddress(), ThisTy); 1508 break; 1509 } 1510 1511 // Fallthrough: act like we're in the base variant. 1512 LLVM_FALLTHROUGH; 1513 1514 case Dtor_Base: 1515 assert(Body); 1516 1517 // Enter the cleanup scopes for fields and non-virtual bases. 1518 EnterDtorCleanups(Dtor, Dtor_Base); 1519 1520 // Initialize the vtable pointers before entering the body. 1521 if (!CanSkipVTablePointerInitialization(*this, Dtor)) { 1522 // Insert the llvm.launder.invariant.group intrinsic before initializing 1523 // the vptrs to cancel any previous assumptions we might have made. 1524 if (CGM.getCodeGenOpts().StrictVTablePointers && 1525 CGM.getCodeGenOpts().OptimizationLevel > 0) 1526 CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis()); 1527 InitializeVTablePointers(Dtor->getParent()); 1528 } 1529 1530 if (isTryBody) 1531 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 1532 else if (Body) 1533 EmitStmt(Body); 1534 else { 1535 assert(Dtor->isImplicit() && "bodyless dtor not implicit"); 1536 // nothing to do besides what's in the epilogue 1537 } 1538 // -fapple-kext must inline any call to this dtor into 1539 // the caller's body. 1540 if (getLangOpts().AppleKext) 1541 CurFn->addFnAttr(llvm::Attribute::AlwaysInline); 1542 1543 break; 1544 } 1545 1546 // Jump out through the epilogue cleanups. 1547 DtorEpilogue.ForceCleanup(); 1548 1549 // Exit the try if applicable. 1550 if (isTryBody) 1551 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 1552 } 1553 1554 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) { 1555 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl()); 1556 const Stmt *RootS = AssignOp->getBody(); 1557 assert(isa<CompoundStmt>(RootS) && 1558 "Body of an implicit assignment operator should be compound stmt."); 1559 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS); 1560 1561 LexicalScope Scope(*this, RootCS->getSourceRange()); 1562 1563 incrementProfileCounter(RootCS); 1564 AssignmentMemcpyizer AM(*this, AssignOp, Args); 1565 for (auto *I : RootCS->body()) 1566 AM.emitAssignment(I); 1567 AM.finish(); 1568 } 1569 1570 namespace { 1571 llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF, 1572 const CXXDestructorDecl *DD) { 1573 if (Expr *ThisArg = DD->getOperatorDeleteThisArg()) 1574 return CGF.EmitScalarExpr(ThisArg); 1575 return CGF.LoadCXXThis(); 1576 } 1577 1578 /// Call the operator delete associated with the current destructor. 1579 struct CallDtorDelete final : EHScopeStack::Cleanup { 1580 CallDtorDelete() {} 1581 1582 void Emit(CodeGenFunction &CGF, Flags flags) override { 1583 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl); 1584 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1585 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), 1586 LoadThisForDtorDelete(CGF, Dtor), 1587 CGF.getContext().getTagDeclType(ClassDecl)); 1588 } 1589 }; 1590 1591 void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF, 1592 llvm::Value *ShouldDeleteCondition, 1593 bool ReturnAfterDelete) { 1594 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete"); 1595 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue"); 1596 llvm::Value *ShouldCallDelete 1597 = CGF.Builder.CreateIsNull(ShouldDeleteCondition); 1598 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB); 1599 1600 CGF.EmitBlock(callDeleteBB); 1601 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl); 1602 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1603 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), 1604 LoadThisForDtorDelete(CGF, Dtor), 1605 CGF.getContext().getTagDeclType(ClassDecl)); 1606 assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() == 1607 ReturnAfterDelete && 1608 "unexpected value for ReturnAfterDelete"); 1609 if (ReturnAfterDelete) 1610 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock); 1611 else 1612 CGF.Builder.CreateBr(continueBB); 1613 1614 CGF.EmitBlock(continueBB); 1615 } 1616 1617 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup { 1618 llvm::Value *ShouldDeleteCondition; 1619 1620 public: 1621 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition) 1622 : ShouldDeleteCondition(ShouldDeleteCondition) { 1623 assert(ShouldDeleteCondition != nullptr); 1624 } 1625 1626 void Emit(CodeGenFunction &CGF, Flags flags) override { 1627 EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition, 1628 /*ReturnAfterDelete*/false); 1629 } 1630 }; 1631 1632 class DestroyField final : public EHScopeStack::Cleanup { 1633 const FieldDecl *field; 1634 CodeGenFunction::Destroyer *destroyer; 1635 bool useEHCleanupForArray; 1636 1637 public: 1638 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer, 1639 bool useEHCleanupForArray) 1640 : field(field), destroyer(destroyer), 1641 useEHCleanupForArray(useEHCleanupForArray) {} 1642 1643 void Emit(CodeGenFunction &CGF, Flags flags) override { 1644 // Find the address of the field. 1645 Address thisValue = CGF.LoadCXXThisAddress(); 1646 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent()); 1647 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy); 1648 LValue LV = CGF.EmitLValueForField(ThisLV, field); 1649 assert(LV.isSimple()); 1650 1651 CGF.emitDestroy(LV.getAddress(CGF), field->getType(), destroyer, 1652 flags.isForNormalCleanup() && useEHCleanupForArray); 1653 } 1654 }; 1655 1656 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr, 1657 CharUnits::QuantityType PoisonSize) { 1658 CodeGenFunction::SanitizerScope SanScope(&CGF); 1659 // Pass in void pointer and size of region as arguments to runtime 1660 // function 1661 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy), 1662 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)}; 1663 1664 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy}; 1665 1666 llvm::FunctionType *FnType = 1667 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false); 1668 llvm::FunctionCallee Fn = 1669 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback"); 1670 CGF.EmitNounwindRuntimeCall(Fn, Args); 1671 } 1672 1673 class SanitizeDtorMembers final : public EHScopeStack::Cleanup { 1674 const CXXDestructorDecl *Dtor; 1675 1676 public: 1677 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {} 1678 1679 // Generate function call for handling object poisoning. 1680 // Disables tail call elimination, to prevent the current stack frame 1681 // from disappearing from the stack trace. 1682 void Emit(CodeGenFunction &CGF, Flags flags) override { 1683 const ASTRecordLayout &Layout = 1684 CGF.getContext().getASTRecordLayout(Dtor->getParent()); 1685 1686 // Nothing to poison. 1687 if (Layout.getFieldCount() == 0) 1688 return; 1689 1690 // Prevent the current stack frame from disappearing from the stack trace. 1691 CGF.CurFn->addFnAttr("disable-tail-calls", "true"); 1692 1693 // Construct pointer to region to begin poisoning, and calculate poison 1694 // size, so that only members declared in this class are poisoned. 1695 ASTContext &Context = CGF.getContext(); 1696 1697 const RecordDecl *Decl = Dtor->getParent(); 1698 auto Fields = Decl->fields(); 1699 auto IsTrivial = [&](const FieldDecl *F) { 1700 return FieldHasTrivialDestructorBody(Context, F); 1701 }; 1702 1703 for (auto It = Fields.begin(); It != Fields.end();) { 1704 It = std::find_if(It, Fields.end(), IsTrivial); 1705 if (It == Fields.end()) 1706 break; 1707 auto Start = It++; 1708 It = std::find_if_not(It, Fields.end(), IsTrivial); 1709 1710 PoisonMembers(CGF, (*Start)->getFieldIndex(), 1711 It == Fields.end() ? -1 : (*It)->getFieldIndex()); 1712 } 1713 } 1714 1715 private: 1716 /// \param layoutStartOffset index of the ASTRecordLayout field to 1717 /// start poisoning (inclusive) 1718 /// \param layoutEndOffset index of the ASTRecordLayout field to 1719 /// end poisoning (exclusive) 1720 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset, 1721 unsigned layoutEndOffset) { 1722 ASTContext &Context = CGF.getContext(); 1723 const ASTRecordLayout &Layout = 1724 Context.getASTRecordLayout(Dtor->getParent()); 1725 1726 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get( 1727 CGF.SizeTy, 1728 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset)) 1729 .getQuantity()); 1730 1731 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP( 1732 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy), 1733 OffsetSizePtr); 1734 1735 CharUnits::QuantityType PoisonSize; 1736 if (layoutEndOffset >= Layout.getFieldCount()) { 1737 PoisonSize = Layout.getNonVirtualSize().getQuantity() - 1738 Context.toCharUnitsFromBits( 1739 Layout.getFieldOffset(layoutStartOffset)) 1740 .getQuantity(); 1741 } else { 1742 PoisonSize = Context.toCharUnitsFromBits( 1743 Layout.getFieldOffset(layoutEndOffset) - 1744 Layout.getFieldOffset(layoutStartOffset)) 1745 .getQuantity(); 1746 } 1747 1748 if (PoisonSize == 0) 1749 return; 1750 1751 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize); 1752 } 1753 }; 1754 1755 class SanitizeDtorVTable final : public EHScopeStack::Cleanup { 1756 const CXXDestructorDecl *Dtor; 1757 1758 public: 1759 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {} 1760 1761 // Generate function call for handling vtable pointer poisoning. 1762 void Emit(CodeGenFunction &CGF, Flags flags) override { 1763 assert(Dtor->getParent()->isDynamicClass()); 1764 (void)Dtor; 1765 ASTContext &Context = CGF.getContext(); 1766 // Poison vtable and vtable ptr if they exist for this class. 1767 llvm::Value *VTablePtr = CGF.LoadCXXThis(); 1768 1769 CharUnits::QuantityType PoisonSize = 1770 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity(); 1771 // Pass in void pointer and size of region as arguments to runtime 1772 // function 1773 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize); 1774 } 1775 }; 1776 } // end anonymous namespace 1777 1778 /// Emit all code that comes at the end of class's 1779 /// destructor. This is to call destructors on members and base classes 1780 /// in reverse order of their construction. 1781 /// 1782 /// For a deleting destructor, this also handles the case where a destroying 1783 /// operator delete completely overrides the definition. 1784 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD, 1785 CXXDtorType DtorType) { 1786 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) && 1787 "Should not emit dtor epilogue for non-exported trivial dtor!"); 1788 1789 // The deleting-destructor phase just needs to call the appropriate 1790 // operator delete that Sema picked up. 1791 if (DtorType == Dtor_Deleting) { 1792 assert(DD->getOperatorDelete() && 1793 "operator delete missing - EnterDtorCleanups"); 1794 if (CXXStructorImplicitParamValue) { 1795 // If there is an implicit param to the deleting dtor, it's a boolean 1796 // telling whether this is a deleting destructor. 1797 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) 1798 EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue, 1799 /*ReturnAfterDelete*/true); 1800 else 1801 EHStack.pushCleanup<CallDtorDeleteConditional>( 1802 NormalAndEHCleanup, CXXStructorImplicitParamValue); 1803 } else { 1804 if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) { 1805 const CXXRecordDecl *ClassDecl = DD->getParent(); 1806 EmitDeleteCall(DD->getOperatorDelete(), 1807 LoadThisForDtorDelete(*this, DD), 1808 getContext().getTagDeclType(ClassDecl)); 1809 EmitBranchThroughCleanup(ReturnBlock); 1810 } else { 1811 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup); 1812 } 1813 } 1814 return; 1815 } 1816 1817 const CXXRecordDecl *ClassDecl = DD->getParent(); 1818 1819 // Unions have no bases and do not call field destructors. 1820 if (ClassDecl->isUnion()) 1821 return; 1822 1823 // The complete-destructor phase just destructs all the virtual bases. 1824 if (DtorType == Dtor_Complete) { 1825 // Poison the vtable pointer such that access after the base 1826 // and member destructors are invoked is invalid. 1827 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor && 1828 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() && 1829 ClassDecl->isPolymorphic()) 1830 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD); 1831 1832 // We push them in the forward order so that they'll be popped in 1833 // the reverse order. 1834 for (const auto &Base : ClassDecl->vbases()) { 1835 auto *BaseClassDecl = 1836 cast<CXXRecordDecl>(Base.getType()->castAs<RecordType>()->getDecl()); 1837 1838 // Ignore trivial destructors. 1839 if (BaseClassDecl->hasTrivialDestructor()) 1840 continue; 1841 1842 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1843 BaseClassDecl, 1844 /*BaseIsVirtual*/ true); 1845 } 1846 1847 return; 1848 } 1849 1850 assert(DtorType == Dtor_Base); 1851 // Poison the vtable pointer if it has no virtual bases, but inherits 1852 // virtual functions. 1853 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor && 1854 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() && 1855 ClassDecl->isPolymorphic()) 1856 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD); 1857 1858 // Destroy non-virtual bases. 1859 for (const auto &Base : ClassDecl->bases()) { 1860 // Ignore virtual bases. 1861 if (Base.isVirtual()) 1862 continue; 1863 1864 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl(); 1865 1866 // Ignore trivial destructors. 1867 if (BaseClassDecl->hasTrivialDestructor()) 1868 continue; 1869 1870 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1871 BaseClassDecl, 1872 /*BaseIsVirtual*/ false); 1873 } 1874 1875 // Poison fields such that access after their destructors are 1876 // invoked, and before the base class destructor runs, is invalid. 1877 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor && 1878 SanOpts.has(SanitizerKind::Memory)) 1879 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD); 1880 1881 // Destroy direct fields. 1882 for (const auto *Field : ClassDecl->fields()) { 1883 QualType type = Field->getType(); 1884 QualType::DestructionKind dtorKind = type.isDestructedType(); 1885 if (!dtorKind) continue; 1886 1887 // Anonymous union members do not have their destructors called. 1888 const RecordType *RT = type->getAsUnionType(); 1889 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue; 1890 1891 CleanupKind cleanupKind = getCleanupKind(dtorKind); 1892 EHStack.pushCleanup<DestroyField>(cleanupKind, Field, 1893 getDestroyer(dtorKind), 1894 cleanupKind & EHCleanup); 1895 } 1896 } 1897 1898 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 1899 /// constructor for each of several members of an array. 1900 /// 1901 /// \param ctor the constructor to call for each element 1902 /// \param arrayType the type of the array to initialize 1903 /// \param arrayBegin an arrayType* 1904 /// \param zeroInitialize true if each element should be 1905 /// zero-initialized before it is constructed 1906 void CodeGenFunction::EmitCXXAggrConstructorCall( 1907 const CXXConstructorDecl *ctor, const ArrayType *arrayType, 1908 Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked, 1909 bool zeroInitialize) { 1910 QualType elementType; 1911 llvm::Value *numElements = 1912 emitArrayLength(arrayType, elementType, arrayBegin); 1913 1914 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, 1915 NewPointerIsChecked, zeroInitialize); 1916 } 1917 1918 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 1919 /// constructor for each of several members of an array. 1920 /// 1921 /// \param ctor the constructor to call for each element 1922 /// \param numElements the number of elements in the array; 1923 /// may be zero 1924 /// \param arrayBase a T*, where T is the type constructed by ctor 1925 /// \param zeroInitialize true if each element should be 1926 /// zero-initialized before it is constructed 1927 void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, 1928 llvm::Value *numElements, 1929 Address arrayBase, 1930 const CXXConstructExpr *E, 1931 bool NewPointerIsChecked, 1932 bool zeroInitialize) { 1933 // It's legal for numElements to be zero. This can happen both 1934 // dynamically, because x can be zero in 'new A[x]', and statically, 1935 // because of GCC extensions that permit zero-length arrays. There 1936 // are probably legitimate places where we could assume that this 1937 // doesn't happen, but it's not clear that it's worth it. 1938 llvm::BranchInst *zeroCheckBranch = nullptr; 1939 1940 // Optimize for a constant count. 1941 llvm::ConstantInt *constantCount 1942 = dyn_cast<llvm::ConstantInt>(numElements); 1943 if (constantCount) { 1944 // Just skip out if the constant count is zero. 1945 if (constantCount->isZero()) return; 1946 1947 // Otherwise, emit the check. 1948 } else { 1949 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop"); 1950 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty"); 1951 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB); 1952 EmitBlock(loopBB); 1953 } 1954 1955 // Find the end of the array. 1956 llvm::Value *arrayBegin = arrayBase.getPointer(); 1957 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements, 1958 "arrayctor.end"); 1959 1960 // Enter the loop, setting up a phi for the current location to initialize. 1961 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1962 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop"); 1963 EmitBlock(loopBB); 1964 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2, 1965 "arrayctor.cur"); 1966 cur->addIncoming(arrayBegin, entryBB); 1967 1968 // Inside the loop body, emit the constructor call on the array element. 1969 1970 // The alignment of the base, adjusted by the size of a single element, 1971 // provides a conservative estimate of the alignment of every element. 1972 // (This assumes we never start tracking offsetted alignments.) 1973 // 1974 // Note that these are complete objects and so we don't need to 1975 // use the non-virtual size or alignment. 1976 QualType type = getContext().getTypeDeclType(ctor->getParent()); 1977 CharUnits eltAlignment = 1978 arrayBase.getAlignment() 1979 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type)); 1980 Address curAddr = Address(cur, eltAlignment); 1981 1982 // Zero initialize the storage, if requested. 1983 if (zeroInitialize) 1984 EmitNullInitialization(curAddr, type); 1985 1986 // C++ [class.temporary]p4: 1987 // There are two contexts in which temporaries are destroyed at a different 1988 // point than the end of the full-expression. The first context is when a 1989 // default constructor is called to initialize an element of an array. 1990 // If the constructor has one or more default arguments, the destruction of 1991 // every temporary created in a default argument expression is sequenced 1992 // before the construction of the next array element, if any. 1993 1994 { 1995 RunCleanupsScope Scope(*this); 1996 1997 // Evaluate the constructor and its arguments in a regular 1998 // partial-destroy cleanup. 1999 if (getLangOpts().Exceptions && 2000 !ctor->getParent()->hasTrivialDestructor()) { 2001 Destroyer *destroyer = destroyCXXObject; 2002 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment, 2003 *destroyer); 2004 } 2005 auto currAVS = AggValueSlot::forAddr( 2006 curAddr, type.getQualifiers(), AggValueSlot::IsDestructed, 2007 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, 2008 AggValueSlot::DoesNotOverlap, AggValueSlot::IsNotZeroed, 2009 NewPointerIsChecked ? AggValueSlot::IsSanitizerChecked 2010 : AggValueSlot::IsNotSanitizerChecked); 2011 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false, 2012 /*Delegating=*/false, currAVS, E); 2013 } 2014 2015 // Go to the next element. 2016 llvm::Value *next = 2017 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1), 2018 "arrayctor.next"); 2019 cur->addIncoming(next, Builder.GetInsertBlock()); 2020 2021 // Check whether that's the end of the loop. 2022 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done"); 2023 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont"); 2024 Builder.CreateCondBr(done, contBB, loopBB); 2025 2026 // Patch the earlier check to skip over the loop. 2027 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB); 2028 2029 EmitBlock(contBB); 2030 } 2031 2032 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF, 2033 Address addr, 2034 QualType type) { 2035 const RecordType *rtype = type->castAs<RecordType>(); 2036 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl()); 2037 const CXXDestructorDecl *dtor = record->getDestructor(); 2038 assert(!dtor->isTrivial()); 2039 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false, 2040 /*Delegating=*/false, addr, type); 2041 } 2042 2043 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 2044 CXXCtorType Type, 2045 bool ForVirtualBase, 2046 bool Delegating, 2047 AggValueSlot ThisAVS, 2048 const CXXConstructExpr *E) { 2049 CallArgList Args; 2050 Address This = ThisAVS.getAddress(); 2051 LangAS SlotAS = ThisAVS.getQualifiers().getAddressSpace(); 2052 QualType ThisType = D->getThisType(); 2053 LangAS ThisAS = ThisType.getTypePtr()->getPointeeType().getAddressSpace(); 2054 llvm::Value *ThisPtr = This.getPointer(); 2055 2056 if (SlotAS != ThisAS) { 2057 unsigned TargetThisAS = getContext().getTargetAddressSpace(ThisAS); 2058 llvm::Type *NewType = 2059 ThisPtr->getType()->getPointerElementType()->getPointerTo(TargetThisAS); 2060 ThisPtr = getTargetHooks().performAddrSpaceCast(*this, This.getPointer(), 2061 ThisAS, SlotAS, NewType); 2062 } 2063 2064 // Push the this ptr. 2065 Args.add(RValue::get(ThisPtr), D->getThisType()); 2066 2067 // If this is a trivial constructor, emit a memcpy now before we lose 2068 // the alignment information on the argument. 2069 // FIXME: It would be better to preserve alignment information into CallArg. 2070 if (isMemcpyEquivalentSpecialMember(D)) { 2071 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor"); 2072 2073 const Expr *Arg = E->getArg(0); 2074 LValue Src = EmitLValue(Arg); 2075 QualType DestTy = getContext().getTypeDeclType(D->getParent()); 2076 LValue Dest = MakeAddrLValue(This, DestTy); 2077 EmitAggregateCopyCtor(Dest, Src, ThisAVS.mayOverlap()); 2078 return; 2079 } 2080 2081 // Add the rest of the user-supplied arguments. 2082 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 2083 EvaluationOrder Order = E->isListInitialization() 2084 ? EvaluationOrder::ForceLeftToRight 2085 : EvaluationOrder::Default; 2086 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(), 2087 /*ParamsToSkip*/ 0, Order); 2088 2089 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args, 2090 ThisAVS.mayOverlap(), E->getExprLoc(), 2091 ThisAVS.isSanitizerChecked()); 2092 } 2093 2094 static bool canEmitDelegateCallArgs(CodeGenFunction &CGF, 2095 const CXXConstructorDecl *Ctor, 2096 CXXCtorType Type, CallArgList &Args) { 2097 // We can't forward a variadic call. 2098 if (Ctor->isVariadic()) 2099 return false; 2100 2101 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 2102 // If the parameters are callee-cleanup, it's not safe to forward. 2103 for (auto *P : Ctor->parameters()) 2104 if (P->needsDestruction(CGF.getContext())) 2105 return false; 2106 2107 // Likewise if they're inalloca. 2108 const CGFunctionInfo &Info = 2109 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0); 2110 if (Info.usesInAlloca()) 2111 return false; 2112 } 2113 2114 // Anything else should be OK. 2115 return true; 2116 } 2117 2118 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 2119 CXXCtorType Type, 2120 bool ForVirtualBase, 2121 bool Delegating, 2122 Address This, 2123 CallArgList &Args, 2124 AggValueSlot::Overlap_t Overlap, 2125 SourceLocation Loc, 2126 bool NewPointerIsChecked) { 2127 const CXXRecordDecl *ClassDecl = D->getParent(); 2128 2129 if (!NewPointerIsChecked) 2130 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(), 2131 getContext().getRecordType(ClassDecl), CharUnits::Zero()); 2132 2133 if (D->isTrivial() && D->isDefaultConstructor()) { 2134 assert(Args.size() == 1 && "trivial default ctor with args"); 2135 return; 2136 } 2137 2138 // If this is a trivial constructor, just emit what's needed. If this is a 2139 // union copy constructor, we must emit a memcpy, because the AST does not 2140 // model that copy. 2141 if (isMemcpyEquivalentSpecialMember(D)) { 2142 assert(Args.size() == 2 && "unexpected argcount for trivial ctor"); 2143 2144 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType(); 2145 Address Src(Args[1].getRValue(*this).getScalarVal(), 2146 CGM.getNaturalTypeAlignment(SrcTy)); 2147 LValue SrcLVal = MakeAddrLValue(Src, SrcTy); 2148 QualType DestTy = getContext().getTypeDeclType(ClassDecl); 2149 LValue DestLVal = MakeAddrLValue(This, DestTy); 2150 EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap); 2151 return; 2152 } 2153 2154 bool PassPrototypeArgs = true; 2155 // Check whether we can actually emit the constructor before trying to do so. 2156 if (auto Inherited = D->getInheritedConstructor()) { 2157 PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type); 2158 if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) { 2159 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase, 2160 Delegating, Args); 2161 return; 2162 } 2163 } 2164 2165 // Insert any ABI-specific implicit constructor arguments. 2166 CGCXXABI::AddedStructorArgCounts ExtraArgs = 2167 CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase, 2168 Delegating, Args); 2169 2170 // Emit the call. 2171 llvm::Constant *CalleePtr = CGM.getAddrOfCXXStructor(GlobalDecl(D, Type)); 2172 const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall( 2173 Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs); 2174 CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type)); 2175 EmitCall(Info, Callee, ReturnValueSlot(), Args, nullptr, Loc); 2176 2177 // Generate vtable assumptions if we're constructing a complete object 2178 // with a vtable. We don't do this for base subobjects for two reasons: 2179 // first, it's incorrect for classes with virtual bases, and second, we're 2180 // about to overwrite the vptrs anyway. 2181 // We also have to make sure if we can refer to vtable: 2182 // - Otherwise we can refer to vtable if it's safe to speculatively emit. 2183 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are 2184 // sure that definition of vtable is not hidden, 2185 // then we are always safe to refer to it. 2186 // FIXME: It looks like InstCombine is very inefficient on dealing with 2187 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily. 2188 if (CGM.getCodeGenOpts().OptimizationLevel > 0 && 2189 ClassDecl->isDynamicClass() && Type != Ctor_Base && 2190 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) && 2191 CGM.getCodeGenOpts().StrictVTablePointers) 2192 EmitVTableAssumptionLoads(ClassDecl, This); 2193 } 2194 2195 void CodeGenFunction::EmitInheritedCXXConstructorCall( 2196 const CXXConstructorDecl *D, bool ForVirtualBase, Address This, 2197 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) { 2198 CallArgList Args; 2199 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType()); 2200 2201 // Forward the parameters. 2202 if (InheritedFromVBase && 2203 CGM.getTarget().getCXXABI().hasConstructorVariants()) { 2204 // Nothing to do; this construction is not responsible for constructing 2205 // the base class containing the inherited constructor. 2206 // FIXME: Can we just pass undef's for the remaining arguments if we don't 2207 // have constructor variants? 2208 Args.push_back(ThisArg); 2209 } else if (!CXXInheritedCtorInitExprArgs.empty()) { 2210 // The inheriting constructor was inlined; just inject its arguments. 2211 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() && 2212 "wrong number of parameters for inherited constructor call"); 2213 Args = CXXInheritedCtorInitExprArgs; 2214 Args[0] = ThisArg; 2215 } else { 2216 // The inheriting constructor was not inlined. Emit delegating arguments. 2217 Args.push_back(ThisArg); 2218 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl); 2219 assert(OuterCtor->getNumParams() == D->getNumParams()); 2220 assert(!OuterCtor->isVariadic() && "should have been inlined"); 2221 2222 for (const auto *Param : OuterCtor->parameters()) { 2223 assert(getContext().hasSameUnqualifiedType( 2224 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(), 2225 Param->getType())); 2226 EmitDelegateCallArg(Args, Param, E->getLocation()); 2227 2228 // Forward __attribute__(pass_object_size). 2229 if (Param->hasAttr<PassObjectSizeAttr>()) { 2230 auto *POSParam = SizeArguments[Param]; 2231 assert(POSParam && "missing pass_object_size value for forwarding"); 2232 EmitDelegateCallArg(Args, POSParam, E->getLocation()); 2233 } 2234 } 2235 } 2236 2237 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false, 2238 This, Args, AggValueSlot::MayOverlap, 2239 E->getLocation(), /*NewPointerIsChecked*/true); 2240 } 2241 2242 void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall( 2243 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase, 2244 bool Delegating, CallArgList &Args) { 2245 GlobalDecl GD(Ctor, CtorType); 2246 InlinedInheritingConstructorScope Scope(*this, GD); 2247 ApplyInlineDebugLocation DebugScope(*this, GD); 2248 RunCleanupsScope RunCleanups(*this); 2249 2250 // Save the arguments to be passed to the inherited constructor. 2251 CXXInheritedCtorInitExprArgs = Args; 2252 2253 FunctionArgList Params; 2254 QualType RetType = BuildFunctionArgList(CurGD, Params); 2255 FnRetTy = RetType; 2256 2257 // Insert any ABI-specific implicit constructor arguments. 2258 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType, 2259 ForVirtualBase, Delegating, Args); 2260 2261 // Emit a simplified prolog. We only need to emit the implicit params. 2262 assert(Args.size() >= Params.size() && "too few arguments for call"); 2263 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 2264 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) { 2265 const RValue &RV = Args[I].getRValue(*this); 2266 assert(!RV.isComplex() && "complex indirect params not supported"); 2267 ParamValue Val = RV.isScalar() 2268 ? ParamValue::forDirect(RV.getScalarVal()) 2269 : ParamValue::forIndirect(RV.getAggregateAddress()); 2270 EmitParmDecl(*Params[I], Val, I + 1); 2271 } 2272 } 2273 2274 // Create a return value slot if the ABI implementation wants one. 2275 // FIXME: This is dumb, we should ask the ABI not to try to set the return 2276 // value instead. 2277 if (!RetType->isVoidType()) 2278 ReturnValue = CreateIRTemp(RetType, "retval.inhctor"); 2279 2280 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 2281 CXXThisValue = CXXABIThisValue; 2282 2283 // Directly emit the constructor initializers. 2284 EmitCtorPrologue(Ctor, CtorType, Params); 2285 } 2286 2287 void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) { 2288 llvm::Value *VTableGlobal = 2289 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass); 2290 if (!VTableGlobal) 2291 return; 2292 2293 // We can just use the base offset in the complete class. 2294 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset(); 2295 2296 if (!NonVirtualOffset.isZero()) 2297 This = 2298 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr, 2299 Vptr.VTableClass, Vptr.NearestVBase); 2300 2301 llvm::Value *VPtrValue = 2302 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass); 2303 llvm::Value *Cmp = 2304 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables"); 2305 Builder.CreateAssumption(Cmp); 2306 } 2307 2308 void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, 2309 Address This) { 2310 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl)) 2311 for (const VPtr &Vptr : getVTablePointers(ClassDecl)) 2312 EmitVTableAssumptionLoad(Vptr, This); 2313 } 2314 2315 void 2316 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 2317 Address This, Address Src, 2318 const CXXConstructExpr *E) { 2319 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 2320 2321 CallArgList Args; 2322 2323 // Push the this ptr. 2324 Args.add(RValue::get(This.getPointer()), D->getThisType()); 2325 2326 // Push the src ptr. 2327 QualType QT = *(FPT->param_type_begin()); 2328 llvm::Type *t = CGM.getTypes().ConvertType(QT); 2329 Src = Builder.CreateBitCast(Src, t); 2330 Args.add(RValue::get(Src.getPointer()), QT); 2331 2332 // Skip over first argument (Src). 2333 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(), 2334 /*ParamsToSkip*/ 1); 2335 2336 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false, 2337 /*Delegating*/false, This, Args, 2338 AggValueSlot::MayOverlap, E->getExprLoc(), 2339 /*NewPointerIsChecked*/false); 2340 } 2341 2342 void 2343 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 2344 CXXCtorType CtorType, 2345 const FunctionArgList &Args, 2346 SourceLocation Loc) { 2347 CallArgList DelegateArgs; 2348 2349 FunctionArgList::const_iterator I = Args.begin(), E = Args.end(); 2350 assert(I != E && "no parameters to constructor"); 2351 2352 // this 2353 Address This = LoadCXXThisAddress(); 2354 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType()); 2355 ++I; 2356 2357 // FIXME: The location of the VTT parameter in the parameter list is 2358 // specific to the Itanium ABI and shouldn't be hardcoded here. 2359 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) { 2360 assert(I != E && "cannot skip vtt parameter, already done with args"); 2361 assert((*I)->getType()->isPointerType() && 2362 "skipping parameter not of vtt type"); 2363 ++I; 2364 } 2365 2366 // Explicit arguments. 2367 for (; I != E; ++I) { 2368 const VarDecl *param = *I; 2369 // FIXME: per-argument source location 2370 EmitDelegateCallArg(DelegateArgs, param, Loc); 2371 } 2372 2373 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false, 2374 /*Delegating=*/true, This, DelegateArgs, 2375 AggValueSlot::MayOverlap, Loc, 2376 /*NewPointerIsChecked=*/true); 2377 } 2378 2379 namespace { 2380 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup { 2381 const CXXDestructorDecl *Dtor; 2382 Address Addr; 2383 CXXDtorType Type; 2384 2385 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr, 2386 CXXDtorType Type) 2387 : Dtor(D), Addr(Addr), Type(Type) {} 2388 2389 void Emit(CodeGenFunction &CGF, Flags flags) override { 2390 // We are calling the destructor from within the constructor. 2391 // Therefore, "this" should have the expected type. 2392 QualType ThisTy = Dtor->getThisObjectType(); 2393 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false, 2394 /*Delegating=*/true, Addr, ThisTy); 2395 } 2396 }; 2397 } // end anonymous namespace 2398 2399 void 2400 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2401 const FunctionArgList &Args) { 2402 assert(Ctor->isDelegatingConstructor()); 2403 2404 Address ThisPtr = LoadCXXThisAddress(); 2405 2406 AggValueSlot AggSlot = 2407 AggValueSlot::forAddr(ThisPtr, Qualifiers(), 2408 AggValueSlot::IsDestructed, 2409 AggValueSlot::DoesNotNeedGCBarriers, 2410 AggValueSlot::IsNotAliased, 2411 AggValueSlot::MayOverlap, 2412 AggValueSlot::IsNotZeroed, 2413 // Checks are made by the code that calls constructor. 2414 AggValueSlot::IsSanitizerChecked); 2415 2416 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot); 2417 2418 const CXXRecordDecl *ClassDecl = Ctor->getParent(); 2419 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) { 2420 CXXDtorType Type = 2421 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base; 2422 2423 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup, 2424 ClassDecl->getDestructor(), 2425 ThisPtr, Type); 2426 } 2427 } 2428 2429 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD, 2430 CXXDtorType Type, 2431 bool ForVirtualBase, 2432 bool Delegating, Address This, 2433 QualType ThisTy) { 2434 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase, 2435 Delegating, This, ThisTy); 2436 } 2437 2438 namespace { 2439 struct CallLocalDtor final : EHScopeStack::Cleanup { 2440 const CXXDestructorDecl *Dtor; 2441 Address Addr; 2442 QualType Ty; 2443 2444 CallLocalDtor(const CXXDestructorDecl *D, Address Addr, QualType Ty) 2445 : Dtor(D), Addr(Addr), Ty(Ty) {} 2446 2447 void Emit(CodeGenFunction &CGF, Flags flags) override { 2448 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 2449 /*ForVirtualBase=*/false, 2450 /*Delegating=*/false, Addr, Ty); 2451 } 2452 }; 2453 } // end anonymous namespace 2454 2455 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D, 2456 QualType T, Address Addr) { 2457 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr, T); 2458 } 2459 2460 void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) { 2461 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl(); 2462 if (!ClassDecl) return; 2463 if (ClassDecl->hasTrivialDestructor()) return; 2464 2465 const CXXDestructorDecl *D = ClassDecl->getDestructor(); 2466 assert(D && D->isUsed() && "destructor not marked as used!"); 2467 PushDestructorCleanup(D, T, Addr); 2468 } 2469 2470 void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) { 2471 // Compute the address point. 2472 llvm::Value *VTableAddressPoint = 2473 CGM.getCXXABI().getVTableAddressPointInStructor( 2474 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase); 2475 2476 if (!VTableAddressPoint) 2477 return; 2478 2479 // Compute where to store the address point. 2480 llvm::Value *VirtualOffset = nullptr; 2481 CharUnits NonVirtualOffset = CharUnits::Zero(); 2482 2483 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) { 2484 // We need to use the virtual base offset offset because the virtual base 2485 // might have a different offset in the most derived class. 2486 2487 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset( 2488 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase); 2489 NonVirtualOffset = Vptr.OffsetFromNearestVBase; 2490 } else { 2491 // We can just use the base offset in the complete class. 2492 NonVirtualOffset = Vptr.Base.getBaseOffset(); 2493 } 2494 2495 // Apply the offsets. 2496 Address VTableField = LoadCXXThisAddress(); 2497 2498 if (!NonVirtualOffset.isZero() || VirtualOffset) 2499 VTableField = ApplyNonVirtualAndVirtualOffset( 2500 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass, 2501 Vptr.NearestVBase); 2502 2503 // Finally, store the address point. Use the same LLVM types as the field to 2504 // support optimization. 2505 unsigned GlobalsAS = CGM.getDataLayout().getDefaultGlobalsAddressSpace(); 2506 unsigned ProgAS = CGM.getDataLayout().getProgramAddressSpace(); 2507 llvm::Type *VTablePtrTy = 2508 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true) 2509 ->getPointerTo(ProgAS) 2510 ->getPointerTo(GlobalsAS); 2511 VTableField = Builder.CreatePointerBitCastOrAddrSpaceCast( 2512 VTableField, VTablePtrTy->getPointerTo(GlobalsAS)); 2513 VTableAddressPoint = Builder.CreatePointerBitCastOrAddrSpaceCast( 2514 VTableAddressPoint, VTablePtrTy); 2515 2516 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField); 2517 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy); 2518 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo); 2519 if (CGM.getCodeGenOpts().OptimizationLevel > 0 && 2520 CGM.getCodeGenOpts().StrictVTablePointers) 2521 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass); 2522 } 2523 2524 CodeGenFunction::VPtrsVector 2525 CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) { 2526 CodeGenFunction::VPtrsVector VPtrsResult; 2527 VisitedVirtualBasesSetTy VBases; 2528 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()), 2529 /*NearestVBase=*/nullptr, 2530 /*OffsetFromNearestVBase=*/CharUnits::Zero(), 2531 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases, 2532 VPtrsResult); 2533 return VPtrsResult; 2534 } 2535 2536 void CodeGenFunction::getVTablePointers(BaseSubobject Base, 2537 const CXXRecordDecl *NearestVBase, 2538 CharUnits OffsetFromNearestVBase, 2539 bool BaseIsNonVirtualPrimaryBase, 2540 const CXXRecordDecl *VTableClass, 2541 VisitedVirtualBasesSetTy &VBases, 2542 VPtrsVector &Vptrs) { 2543 // If this base is a non-virtual primary base the address point has already 2544 // been set. 2545 if (!BaseIsNonVirtualPrimaryBase) { 2546 // Initialize the vtable pointer for this base. 2547 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass}; 2548 Vptrs.push_back(Vptr); 2549 } 2550 2551 const CXXRecordDecl *RD = Base.getBase(); 2552 2553 // Traverse bases. 2554 for (const auto &I : RD->bases()) { 2555 auto *BaseDecl = 2556 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 2557 2558 // Ignore classes without a vtable. 2559 if (!BaseDecl->isDynamicClass()) 2560 continue; 2561 2562 CharUnits BaseOffset; 2563 CharUnits BaseOffsetFromNearestVBase; 2564 bool BaseDeclIsNonVirtualPrimaryBase; 2565 2566 if (I.isVirtual()) { 2567 // Check if we've visited this virtual base before. 2568 if (!VBases.insert(BaseDecl).second) 2569 continue; 2570 2571 const ASTRecordLayout &Layout = 2572 getContext().getASTRecordLayout(VTableClass); 2573 2574 BaseOffset = Layout.getVBaseClassOffset(BaseDecl); 2575 BaseOffsetFromNearestVBase = CharUnits::Zero(); 2576 BaseDeclIsNonVirtualPrimaryBase = false; 2577 } else { 2578 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 2579 2580 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); 2581 BaseOffsetFromNearestVBase = 2582 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl); 2583 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl; 2584 } 2585 2586 getVTablePointers( 2587 BaseSubobject(BaseDecl, BaseOffset), 2588 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase, 2589 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs); 2590 } 2591 } 2592 2593 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) { 2594 // Ignore classes without a vtable. 2595 if (!RD->isDynamicClass()) 2596 return; 2597 2598 // Initialize the vtable pointers for this class and all of its bases. 2599 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD)) 2600 for (const VPtr &Vptr : getVTablePointers(RD)) 2601 InitializeVTablePointer(Vptr); 2602 2603 if (RD->getNumVBases()) 2604 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD); 2605 } 2606 2607 llvm::Value *CodeGenFunction::GetVTablePtr(Address This, 2608 llvm::Type *VTableTy, 2609 const CXXRecordDecl *RD) { 2610 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy); 2611 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable"); 2612 TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy); 2613 CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo); 2614 2615 if (CGM.getCodeGenOpts().OptimizationLevel > 0 && 2616 CGM.getCodeGenOpts().StrictVTablePointers) 2617 CGM.DecorateInstructionWithInvariantGroup(VTable, RD); 2618 2619 return VTable; 2620 } 2621 2622 // If a class has a single non-virtual base and does not introduce or override 2623 // virtual member functions or fields, it will have the same layout as its base. 2624 // This function returns the least derived such class. 2625 // 2626 // Casting an instance of a base class to such a derived class is technically 2627 // undefined behavior, but it is a relatively common hack for introducing member 2628 // functions on class instances with specific properties (e.g. llvm::Operator) 2629 // that works under most compilers and should not have security implications, so 2630 // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict. 2631 static const CXXRecordDecl * 2632 LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) { 2633 if (!RD->field_empty()) 2634 return RD; 2635 2636 if (RD->getNumVBases() != 0) 2637 return RD; 2638 2639 if (RD->getNumBases() != 1) 2640 return RD; 2641 2642 for (const CXXMethodDecl *MD : RD->methods()) { 2643 if (MD->isVirtual()) { 2644 // Virtual member functions are only ok if they are implicit destructors 2645 // because the implicit destructor will have the same semantics as the 2646 // base class's destructor if no fields are added. 2647 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit()) 2648 continue; 2649 return RD; 2650 } 2651 } 2652 2653 return LeastDerivedClassWithSameLayout( 2654 RD->bases_begin()->getType()->getAsCXXRecordDecl()); 2655 } 2656 2657 void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, 2658 llvm::Value *VTable, 2659 SourceLocation Loc) { 2660 if (SanOpts.has(SanitizerKind::CFIVCall)) 2661 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc); 2662 else if (CGM.getCodeGenOpts().WholeProgramVTables && 2663 // Don't insert type test assumes if we are forcing public std 2664 // visibility. 2665 !CGM.HasLTOVisibilityPublicStd(RD)) { 2666 llvm::Metadata *MD = 2667 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 2668 llvm::Value *TypeId = 2669 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD); 2670 2671 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy); 2672 llvm::Value *TypeTest = 2673 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test), 2674 {CastedVTable, TypeId}); 2675 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest); 2676 } 2677 } 2678 2679 void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, 2680 llvm::Value *VTable, 2681 CFITypeCheckKind TCK, 2682 SourceLocation Loc) { 2683 if (!SanOpts.has(SanitizerKind::CFICastStrict)) 2684 RD = LeastDerivedClassWithSameLayout(RD); 2685 2686 EmitVTablePtrCheck(RD, VTable, TCK, Loc); 2687 } 2688 2689 void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T, 2690 llvm::Value *Derived, 2691 bool MayBeNull, 2692 CFITypeCheckKind TCK, 2693 SourceLocation Loc) { 2694 if (!getLangOpts().CPlusPlus) 2695 return; 2696 2697 auto *ClassTy = T->getAs<RecordType>(); 2698 if (!ClassTy) 2699 return; 2700 2701 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl()); 2702 2703 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass()) 2704 return; 2705 2706 if (!SanOpts.has(SanitizerKind::CFICastStrict)) 2707 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl); 2708 2709 llvm::BasicBlock *ContBlock = nullptr; 2710 2711 if (MayBeNull) { 2712 llvm::Value *DerivedNotNull = 2713 Builder.CreateIsNotNull(Derived, "cast.nonnull"); 2714 2715 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check"); 2716 ContBlock = createBasicBlock("cast.cont"); 2717 2718 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock); 2719 2720 EmitBlock(CheckBlock); 2721 } 2722 2723 llvm::Value *VTable; 2724 std::tie(VTable, ClassDecl) = CGM.getCXXABI().LoadVTablePtr( 2725 *this, Address(Derived, getPointerAlign()), ClassDecl); 2726 2727 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc); 2728 2729 if (MayBeNull) { 2730 Builder.CreateBr(ContBlock); 2731 EmitBlock(ContBlock); 2732 } 2733 } 2734 2735 void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD, 2736 llvm::Value *VTable, 2737 CFITypeCheckKind TCK, 2738 SourceLocation Loc) { 2739 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso && 2740 !CGM.HasHiddenLTOVisibility(RD)) 2741 return; 2742 2743 SanitizerMask M; 2744 llvm::SanitizerStatKind SSK; 2745 switch (TCK) { 2746 case CFITCK_VCall: 2747 M = SanitizerKind::CFIVCall; 2748 SSK = llvm::SanStat_CFI_VCall; 2749 break; 2750 case CFITCK_NVCall: 2751 M = SanitizerKind::CFINVCall; 2752 SSK = llvm::SanStat_CFI_NVCall; 2753 break; 2754 case CFITCK_DerivedCast: 2755 M = SanitizerKind::CFIDerivedCast; 2756 SSK = llvm::SanStat_CFI_DerivedCast; 2757 break; 2758 case CFITCK_UnrelatedCast: 2759 M = SanitizerKind::CFIUnrelatedCast; 2760 SSK = llvm::SanStat_CFI_UnrelatedCast; 2761 break; 2762 case CFITCK_ICall: 2763 case CFITCK_NVMFCall: 2764 case CFITCK_VMFCall: 2765 llvm_unreachable("unexpected sanitizer kind"); 2766 } 2767 2768 std::string TypeName = RD->getQualifiedNameAsString(); 2769 if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName)) 2770 return; 2771 2772 SanitizerScope SanScope(this); 2773 EmitSanitizerStatReport(SSK); 2774 2775 llvm::Metadata *MD = 2776 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 2777 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD); 2778 2779 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy); 2780 llvm::Value *TypeTest = Builder.CreateCall( 2781 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId}); 2782 2783 llvm::Constant *StaticData[] = { 2784 llvm::ConstantInt::get(Int8Ty, TCK), 2785 EmitCheckSourceLocation(Loc), 2786 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)), 2787 }; 2788 2789 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD); 2790 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) { 2791 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData); 2792 return; 2793 } 2794 2795 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) { 2796 EmitTrapCheck(TypeTest); 2797 return; 2798 } 2799 2800 llvm::Value *AllVtables = llvm::MetadataAsValue::get( 2801 CGM.getLLVMContext(), 2802 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables")); 2803 llvm::Value *ValidVtable = Builder.CreateCall( 2804 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables}); 2805 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail, 2806 StaticData, {CastedVTable, ValidVtable}); 2807 } 2808 2809 bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) { 2810 if (!CGM.getCodeGenOpts().WholeProgramVTables || 2811 !CGM.HasHiddenLTOVisibility(RD)) 2812 return false; 2813 2814 if (CGM.getCodeGenOpts().VirtualFunctionElimination) 2815 return true; 2816 2817 if (!SanOpts.has(SanitizerKind::CFIVCall) || 2818 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall)) 2819 return false; 2820 2821 std::string TypeName = RD->getQualifiedNameAsString(); 2822 return !getContext().getSanitizerBlacklist().isBlacklistedType( 2823 SanitizerKind::CFIVCall, TypeName); 2824 } 2825 2826 llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad( 2827 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) { 2828 SanitizerScope SanScope(this); 2829 2830 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall); 2831 2832 llvm::Metadata *MD = 2833 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 2834 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD); 2835 2836 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy); 2837 llvm::Value *CheckedLoad = Builder.CreateCall( 2838 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load), 2839 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset), 2840 TypeId}); 2841 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1); 2842 2843 std::string TypeName = RD->getQualifiedNameAsString(); 2844 if (SanOpts.has(SanitizerKind::CFIVCall) && 2845 !getContext().getSanitizerBlacklist().isBlacklistedType( 2846 SanitizerKind::CFIVCall, TypeName)) { 2847 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall), 2848 SanitizerHandler::CFICheckFail, {}, {}); 2849 } 2850 2851 return Builder.CreateBitCast( 2852 Builder.CreateExtractValue(CheckedLoad, 0), 2853 cast<llvm::PointerType>(VTable->getType())->getElementType()); 2854 } 2855 2856 void CodeGenFunction::EmitForwardingCallToLambda( 2857 const CXXMethodDecl *callOperator, 2858 CallArgList &callArgs) { 2859 // Get the address of the call operator. 2860 const CGFunctionInfo &calleeFnInfo = 2861 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator); 2862 llvm::Constant *calleePtr = 2863 CGM.GetAddrOfFunction(GlobalDecl(callOperator), 2864 CGM.getTypes().GetFunctionType(calleeFnInfo)); 2865 2866 // Prepare the return slot. 2867 const FunctionProtoType *FPT = 2868 callOperator->getType()->castAs<FunctionProtoType>(); 2869 QualType resultType = FPT->getReturnType(); 2870 ReturnValueSlot returnSlot; 2871 if (!resultType->isVoidType() && 2872 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect && 2873 !hasScalarEvaluationKind(calleeFnInfo.getReturnType())) 2874 returnSlot = 2875 ReturnValueSlot(ReturnValue, resultType.isVolatileQualified(), 2876 /*IsUnused=*/false, /*IsExternallyDestructed=*/true); 2877 2878 // We don't need to separately arrange the call arguments because 2879 // the call can't be variadic anyway --- it's impossible to forward 2880 // variadic arguments. 2881 2882 // Now emit our call. 2883 auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator)); 2884 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs); 2885 2886 // If necessary, copy the returned value into the slot. 2887 if (!resultType->isVoidType() && returnSlot.isNull()) { 2888 if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) { 2889 RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal())); 2890 } 2891 EmitReturnOfRValue(RV, resultType); 2892 } else 2893 EmitBranchThroughCleanup(ReturnBlock); 2894 } 2895 2896 void CodeGenFunction::EmitLambdaBlockInvokeBody() { 2897 const BlockDecl *BD = BlockInfo->getBlockDecl(); 2898 const VarDecl *variable = BD->capture_begin()->getVariable(); 2899 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl(); 2900 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 2901 2902 if (CallOp->isVariadic()) { 2903 // FIXME: Making this work correctly is nasty because it requires either 2904 // cloning the body of the call operator or making the call operator 2905 // forward. 2906 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function"); 2907 return; 2908 } 2909 2910 // Start building arguments for forwarding call 2911 CallArgList CallArgs; 2912 2913 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda)); 2914 Address ThisPtr = GetAddrOfBlockDecl(variable); 2915 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType); 2916 2917 // Add the rest of the parameters. 2918 for (auto param : BD->parameters()) 2919 EmitDelegateCallArg(CallArgs, param, param->getBeginLoc()); 2920 2921 assert(!Lambda->isGenericLambda() && 2922 "generic lambda interconversion to block not implemented"); 2923 EmitForwardingCallToLambda(CallOp, CallArgs); 2924 } 2925 2926 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) { 2927 const CXXRecordDecl *Lambda = MD->getParent(); 2928 2929 // Start building arguments for forwarding call 2930 CallArgList CallArgs; 2931 2932 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda)); 2933 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType)); 2934 CallArgs.add(RValue::get(ThisPtr), ThisType); 2935 2936 // Add the rest of the parameters. 2937 for (auto Param : MD->parameters()) 2938 EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc()); 2939 2940 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 2941 // For a generic lambda, find the corresponding call operator specialization 2942 // to which the call to the static-invoker shall be forwarded. 2943 if (Lambda->isGenericLambda()) { 2944 assert(MD->isFunctionTemplateSpecialization()); 2945 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 2946 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate(); 2947 void *InsertPos = nullptr; 2948 FunctionDecl *CorrespondingCallOpSpecialization = 2949 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 2950 assert(CorrespondingCallOpSpecialization); 2951 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 2952 } 2953 EmitForwardingCallToLambda(CallOp, CallArgs); 2954 } 2955 2956 void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) { 2957 if (MD->isVariadic()) { 2958 // FIXME: Making this work correctly is nasty because it requires either 2959 // cloning the body of the call operator or making the call operator forward. 2960 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function"); 2961 return; 2962 } 2963 2964 EmitLambdaDelegatingInvokeBody(MD); 2965 } 2966