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