1 //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===// 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 code generation of C++ expressions 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGDebugInfo.h" 18 #include "CGObjCRuntime.h" 19 #include "clang/CodeGen/CGFunctionInfo.h" 20 #include "clang/Frontend/CodeGenOptions.h" 21 #include "llvm/IR/CallSite.h" 22 #include "llvm/IR/Intrinsics.h" 23 24 using namespace clang; 25 using namespace CodeGen; 26 27 static RequiredArgs 28 commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD, 29 llvm::Value *This, llvm::Value *ImplicitParam, 30 QualType ImplicitParamTy, const CallExpr *CE, 31 CallArgList &Args, CallArgList *RtlArgs) { 32 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) || 33 isa<CXXOperatorCallExpr>(CE)); 34 assert(MD->isInstance() && 35 "Trying to emit a member or operator call expr on a static method!"); 36 ASTContext &C = CGF.getContext(); 37 38 // Push the this ptr. 39 const CXXRecordDecl *RD = 40 CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD); 41 Args.add(RValue::get(This), 42 RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy); 43 44 // If there is an implicit parameter (e.g. VTT), emit it. 45 if (ImplicitParam) { 46 Args.add(RValue::get(ImplicitParam), ImplicitParamTy); 47 } 48 49 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 50 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD); 51 52 // And the rest of the call args. 53 if (RtlArgs) { 54 // Special case: if the caller emitted the arguments right-to-left already 55 // (prior to emitting the *this argument), we're done. This happens for 56 // assignment operators. 57 Args.addFrom(*RtlArgs); 58 } else if (CE) { 59 // Special case: skip first argument of CXXOperatorCall (it is "this"). 60 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0; 61 CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip), 62 CE->getDirectCallee()); 63 } else { 64 assert( 65 FPT->getNumParams() == 0 && 66 "No CallExpr specified for function with non-zero number of arguments"); 67 } 68 return required; 69 } 70 71 RValue CodeGenFunction::EmitCXXMemberOrOperatorCall( 72 const CXXMethodDecl *MD, const CGCallee &Callee, 73 ReturnValueSlot ReturnValue, 74 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy, 75 const CallExpr *CE, CallArgList *RtlArgs) { 76 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 77 CallArgList Args; 78 RequiredArgs required = commonEmitCXXMemberOrOperatorCall( 79 *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs); 80 auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required); 81 return EmitCall(FnInfo, Callee, ReturnValue, Args); 82 } 83 84 RValue CodeGenFunction::EmitCXXDestructorCall( 85 const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This, 86 llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE, 87 StructorType Type) { 88 CallArgList Args; 89 commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam, 90 ImplicitParamTy, CE, Args, nullptr); 91 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type), 92 Callee, ReturnValueSlot(), Args); 93 } 94 95 RValue CodeGenFunction::EmitCXXPseudoDestructorExpr( 96 const CXXPseudoDestructorExpr *E) { 97 QualType DestroyedType = E->getDestroyedType(); 98 if (DestroyedType.hasStrongOrWeakObjCLifetime()) { 99 // Automatic Reference Counting: 100 // If the pseudo-expression names a retainable object with weak or 101 // strong lifetime, the object shall be released. 102 Expr *BaseExpr = E->getBase(); 103 Address BaseValue = Address::invalid(); 104 Qualifiers BaseQuals; 105 106 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar. 107 if (E->isArrow()) { 108 BaseValue = EmitPointerWithAlignment(BaseExpr); 109 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>(); 110 BaseQuals = PTy->getPointeeType().getQualifiers(); 111 } else { 112 LValue BaseLV = EmitLValue(BaseExpr); 113 BaseValue = BaseLV.getAddress(); 114 QualType BaseTy = BaseExpr->getType(); 115 BaseQuals = BaseTy.getQualifiers(); 116 } 117 118 switch (DestroyedType.getObjCLifetime()) { 119 case Qualifiers::OCL_None: 120 case Qualifiers::OCL_ExplicitNone: 121 case Qualifiers::OCL_Autoreleasing: 122 break; 123 124 case Qualifiers::OCL_Strong: 125 EmitARCRelease(Builder.CreateLoad(BaseValue, 126 DestroyedType.isVolatileQualified()), 127 ARCPreciseLifetime); 128 break; 129 130 case Qualifiers::OCL_Weak: 131 EmitARCDestroyWeak(BaseValue); 132 break; 133 } 134 } else { 135 // C++ [expr.pseudo]p1: 136 // The result shall only be used as the operand for the function call 137 // operator (), and the result of such a call has type void. The only 138 // effect is the evaluation of the postfix-expression before the dot or 139 // arrow. 140 EmitIgnoredExpr(E->getBase()); 141 } 142 143 return RValue::get(nullptr); 144 } 145 146 static CXXRecordDecl *getCXXRecord(const Expr *E) { 147 QualType T = E->getType(); 148 if (const PointerType *PTy = T->getAs<PointerType>()) 149 T = PTy->getPointeeType(); 150 const RecordType *Ty = T->castAs<RecordType>(); 151 return cast<CXXRecordDecl>(Ty->getDecl()); 152 } 153 154 // Note: This function also emit constructor calls to support a MSVC 155 // extensions allowing explicit constructor function call. 156 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE, 157 ReturnValueSlot ReturnValue) { 158 const Expr *callee = CE->getCallee()->IgnoreParens(); 159 160 if (isa<BinaryOperator>(callee)) 161 return EmitCXXMemberPointerCallExpr(CE, ReturnValue); 162 163 const MemberExpr *ME = cast<MemberExpr>(callee); 164 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl()); 165 166 if (MD->isStatic()) { 167 // The method is static, emit it as we would a regular call. 168 CGCallee callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD), MD); 169 return EmitCall(getContext().getPointerType(MD->getType()), callee, CE, 170 ReturnValue); 171 } 172 173 bool HasQualifier = ME->hasQualifier(); 174 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr; 175 bool IsArrow = ME->isArrow(); 176 const Expr *Base = ME->getBase(); 177 178 return EmitCXXMemberOrOperatorMemberCallExpr( 179 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base); 180 } 181 182 RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( 183 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, 184 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow, 185 const Expr *Base) { 186 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE)); 187 188 // Compute the object pointer. 189 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier; 190 191 const CXXMethodDecl *DevirtualizedMethod = nullptr; 192 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) { 193 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); 194 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl); 195 assert(DevirtualizedMethod); 196 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent(); 197 const Expr *Inner = Base->ignoreParenBaseCasts(); 198 if (DevirtualizedMethod->getReturnType().getCanonicalType() != 199 MD->getReturnType().getCanonicalType()) 200 // If the return types are not the same, this might be a case where more 201 // code needs to run to compensate for it. For example, the derived 202 // method might return a type that inherits form from the return 203 // type of MD and has a prefix. 204 // For now we just avoid devirtualizing these covariant cases. 205 DevirtualizedMethod = nullptr; 206 else if (getCXXRecord(Inner) == DevirtualizedClass) 207 // If the class of the Inner expression is where the dynamic method 208 // is defined, build the this pointer from it. 209 Base = Inner; 210 else if (getCXXRecord(Base) != DevirtualizedClass) { 211 // If the method is defined in a class that is not the best dynamic 212 // one or the one of the full expression, we would have to build 213 // a derived-to-base cast to compute the correct this pointer, but 214 // we don't have support for that yet, so do a virtual call. 215 DevirtualizedMethod = nullptr; 216 } 217 } 218 219 // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment 220 // operator before the LHS. 221 CallArgList RtlArgStorage; 222 CallArgList *RtlArgs = nullptr; 223 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 224 if (OCE->isAssignmentOp()) { 225 RtlArgs = &RtlArgStorage; 226 EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(), 227 drop_begin(CE->arguments(), 1), CE->getDirectCallee(), 228 /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft); 229 } 230 } 231 232 Address This = Address::invalid(); 233 if (IsArrow) 234 This = EmitPointerWithAlignment(Base); 235 else 236 This = EmitLValue(Base).getAddress(); 237 238 239 if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) { 240 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr); 241 if (isa<CXXConstructorDecl>(MD) && 242 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) 243 return RValue::get(nullptr); 244 245 if (!MD->getParent()->mayInsertExtraPadding()) { 246 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) { 247 // We don't like to generate the trivial copy/move assignment operator 248 // when it isn't necessary; just produce the proper effect here. 249 LValue RHS = isa<CXXOperatorCallExpr>(CE) 250 ? MakeNaturalAlignAddrLValue( 251 (*RtlArgs)[0].RV.getScalarVal(), 252 (*(CE->arg_begin() + 1))->getType()) 253 : EmitLValue(*CE->arg_begin()); 254 EmitAggregateAssign(This, RHS.getAddress(), CE->getType()); 255 return RValue::get(This.getPointer()); 256 } 257 258 if (isa<CXXConstructorDecl>(MD) && 259 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) { 260 // Trivial move and copy ctor are the same. 261 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor"); 262 Address RHS = EmitLValue(*CE->arg_begin()).getAddress(); 263 EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType()); 264 return RValue::get(This.getPointer()); 265 } 266 llvm_unreachable("unknown trivial member function"); 267 } 268 } 269 270 // Compute the function type we're calling. 271 const CXXMethodDecl *CalleeDecl = 272 DevirtualizedMethod ? DevirtualizedMethod : MD; 273 const CGFunctionInfo *FInfo = nullptr; 274 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) 275 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 276 Dtor, StructorType::Complete); 277 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl)) 278 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 279 Ctor, StructorType::Complete); 280 else 281 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl); 282 283 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo); 284 285 // C++11 [class.mfct.non-static]p2: 286 // If a non-static member function of a class X is called for an object that 287 // is not of type X, or of a type derived from X, the behavior is undefined. 288 SourceLocation CallLoc; 289 ASTContext &C = getContext(); 290 if (CE) 291 CallLoc = CE->getExprLoc(); 292 293 EmitTypeCheck(isa<CXXConstructorDecl>(CalleeDecl) 294 ? CodeGenFunction::TCK_ConstructorCall 295 : CodeGenFunction::TCK_MemberCall, 296 CallLoc, This.getPointer(), C.getRecordType(CalleeDecl->getParent())); 297 298 // FIXME: Uses of 'MD' past this point need to be audited. We may need to use 299 // 'CalleeDecl' instead. 300 301 // C++ [class.virtual]p12: 302 // Explicit qualification with the scope operator (5.1) suppresses the 303 // virtual call mechanism. 304 // 305 // We also don't emit a virtual call if the base expression has a record type 306 // because then we know what the type is. 307 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod; 308 309 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) { 310 assert(CE->arg_begin() == CE->arg_end() && 311 "Destructor shouldn't have explicit parameters"); 312 assert(ReturnValue.isNull() && "Destructor shouldn't have return value"); 313 if (UseVirtualCall) { 314 CGM.getCXXABI().EmitVirtualDestructorCall( 315 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE)); 316 } else { 317 CGCallee Callee; 318 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier) 319 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty); 320 else if (!DevirtualizedMethod) 321 Callee = CGCallee::forDirect( 322 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty), 323 Dtor); 324 else { 325 const CXXDestructorDecl *DDtor = 326 cast<CXXDestructorDecl>(DevirtualizedMethod); 327 Callee = CGCallee::forDirect( 328 CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty), 329 DDtor); 330 } 331 EmitCXXMemberOrOperatorCall( 332 CalleeDecl, Callee, ReturnValue, This.getPointer(), 333 /*ImplicitParam=*/nullptr, QualType(), CE, nullptr); 334 } 335 return RValue::get(nullptr); 336 } 337 338 CGCallee Callee; 339 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 340 Callee = CGCallee::forDirect( 341 CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty), 342 Ctor); 343 } else if (UseVirtualCall) { 344 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty, 345 CE->getLocStart()); 346 } else { 347 if (SanOpts.has(SanitizerKind::CFINVCall) && 348 MD->getParent()->isDynamicClass()) { 349 llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent()); 350 EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall, 351 CE->getLocStart()); 352 } 353 354 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier) 355 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty); 356 else if (!DevirtualizedMethod) 357 Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), MD); 358 else { 359 Callee = CGCallee::forDirect( 360 CGM.GetAddrOfFunction(DevirtualizedMethod, Ty), 361 DevirtualizedMethod); 362 } 363 } 364 365 if (MD->isVirtual()) { 366 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall( 367 *this, CalleeDecl, This, UseVirtualCall); 368 } 369 370 return EmitCXXMemberOrOperatorCall( 371 CalleeDecl, Callee, ReturnValue, This.getPointer(), 372 /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs); 373 } 374 375 RValue 376 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 377 ReturnValueSlot ReturnValue) { 378 const BinaryOperator *BO = 379 cast<BinaryOperator>(E->getCallee()->IgnoreParens()); 380 const Expr *BaseExpr = BO->getLHS(); 381 const Expr *MemFnExpr = BO->getRHS(); 382 383 const MemberPointerType *MPT = 384 MemFnExpr->getType()->castAs<MemberPointerType>(); 385 386 const FunctionProtoType *FPT = 387 MPT->getPointeeType()->castAs<FunctionProtoType>(); 388 const CXXRecordDecl *RD = 389 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 390 391 // Emit the 'this' pointer. 392 Address This = Address::invalid(); 393 if (BO->getOpcode() == BO_PtrMemI) 394 This = EmitPointerWithAlignment(BaseExpr); 395 else 396 This = EmitLValue(BaseExpr).getAddress(); 397 398 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(), 399 QualType(MPT->getClass(), 0)); 400 401 // Get the member function pointer. 402 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr); 403 404 // Ask the ABI to load the callee. Note that This is modified. 405 llvm::Value *ThisPtrForCall = nullptr; 406 CGCallee Callee = 407 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, 408 ThisPtrForCall, MemFnPtr, MPT); 409 410 CallArgList Args; 411 412 QualType ThisType = 413 getContext().getPointerType(getContext().getTagDeclType(RD)); 414 415 // Push the this ptr. 416 Args.add(RValue::get(ThisPtrForCall), ThisType); 417 418 RequiredArgs required = 419 RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr); 420 421 // And the rest of the call args 422 EmitCallArgs(Args, FPT, E->arguments()); 423 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), 424 Callee, ReturnValue, Args); 425 } 426 427 RValue 428 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 429 const CXXMethodDecl *MD, 430 ReturnValueSlot ReturnValue) { 431 assert(MD->isInstance() && 432 "Trying to emit a member call expr on a static method!"); 433 return EmitCXXMemberOrOperatorMemberCallExpr( 434 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr, 435 /*IsArrow=*/false, E->getArg(0)); 436 } 437 438 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 439 ReturnValueSlot ReturnValue) { 440 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue); 441 } 442 443 static void EmitNullBaseClassInitialization(CodeGenFunction &CGF, 444 Address DestPtr, 445 const CXXRecordDecl *Base) { 446 if (Base->isEmpty()) 447 return; 448 449 DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty); 450 451 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base); 452 CharUnits NVSize = Layout.getNonVirtualSize(); 453 454 // We cannot simply zero-initialize the entire base sub-object if vbptrs are 455 // present, they are initialized by the most derived class before calling the 456 // constructor. 457 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores; 458 Stores.emplace_back(CharUnits::Zero(), NVSize); 459 460 // Each store is split by the existence of a vbptr. 461 CharUnits VBPtrWidth = CGF.getPointerSize(); 462 std::vector<CharUnits> VBPtrOffsets = 463 CGF.CGM.getCXXABI().getVBPtrOffsets(Base); 464 for (CharUnits VBPtrOffset : VBPtrOffsets) { 465 // Stop before we hit any virtual base pointers located in virtual bases. 466 if (VBPtrOffset >= NVSize) 467 break; 468 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val(); 469 CharUnits LastStoreOffset = LastStore.first; 470 CharUnits LastStoreSize = LastStore.second; 471 472 CharUnits SplitBeforeOffset = LastStoreOffset; 473 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset; 474 assert(!SplitBeforeSize.isNegative() && "negative store size!"); 475 if (!SplitBeforeSize.isZero()) 476 Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize); 477 478 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth; 479 CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset; 480 assert(!SplitAfterSize.isNegative() && "negative store size!"); 481 if (!SplitAfterSize.isZero()) 482 Stores.emplace_back(SplitAfterOffset, SplitAfterSize); 483 } 484 485 // If the type contains a pointer to data member we can't memset it to zero. 486 // Instead, create a null constant and copy it to the destination. 487 // TODO: there are other patterns besides zero that we can usefully memset, 488 // like -1, which happens to be the pattern used by member-pointers. 489 // TODO: isZeroInitializable can be over-conservative in the case where a 490 // virtual base contains a member pointer. 491 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base); 492 if (!NullConstantForBase->isNullValue()) { 493 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable( 494 CGF.CGM.getModule(), NullConstantForBase->getType(), 495 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, 496 NullConstantForBase, Twine()); 497 498 CharUnits Align = std::max(Layout.getNonVirtualAlignment(), 499 DestPtr.getAlignment()); 500 NullVariable->setAlignment(Align.getQuantity()); 501 502 Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align); 503 504 // Get and call the appropriate llvm.memcpy overload. 505 for (std::pair<CharUnits, CharUnits> Store : Stores) { 506 CharUnits StoreOffset = Store.first; 507 CharUnits StoreSize = Store.second; 508 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 509 CGF.Builder.CreateMemCpy( 510 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 511 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset), 512 StoreSizeVal); 513 } 514 515 // Otherwise, just memset the whole thing to zero. This is legal 516 // because in LLVM, all default initializers (other than the ones we just 517 // handled above) are guaranteed to have a bit pattern of all zeros. 518 } else { 519 for (std::pair<CharUnits, CharUnits> Store : Stores) { 520 CharUnits StoreOffset = Store.first; 521 CharUnits StoreSize = Store.second; 522 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 523 CGF.Builder.CreateMemSet( 524 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 525 CGF.Builder.getInt8(0), StoreSizeVal); 526 } 527 } 528 } 529 530 void 531 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, 532 AggValueSlot Dest) { 533 assert(!Dest.isIgnored() && "Must have a destination!"); 534 const CXXConstructorDecl *CD = E->getConstructor(); 535 536 // If we require zero initialization before (or instead of) calling the 537 // constructor, as can be the case with a non-user-provided default 538 // constructor, emit the zero initialization now, unless destination is 539 // already zeroed. 540 if (E->requiresZeroInitialization() && !Dest.isZeroed()) { 541 switch (E->getConstructionKind()) { 542 case CXXConstructExpr::CK_Delegating: 543 case CXXConstructExpr::CK_Complete: 544 EmitNullInitialization(Dest.getAddress(), E->getType()); 545 break; 546 case CXXConstructExpr::CK_VirtualBase: 547 case CXXConstructExpr::CK_NonVirtualBase: 548 EmitNullBaseClassInitialization(*this, Dest.getAddress(), 549 CD->getParent()); 550 break; 551 } 552 } 553 554 // If this is a call to a trivial default constructor, do nothing. 555 if (CD->isTrivial() && CD->isDefaultConstructor()) 556 return; 557 558 // Elide the constructor if we're constructing from a temporary. 559 // The temporary check is required because Sema sets this on NRVO 560 // returns. 561 if (getLangOpts().ElideConstructors && E->isElidable()) { 562 assert(getContext().hasSameUnqualifiedType(E->getType(), 563 E->getArg(0)->getType())); 564 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) { 565 EmitAggExpr(E->getArg(0), Dest); 566 return; 567 } 568 } 569 570 if (const ArrayType *arrayType 571 = getContext().getAsArrayType(E->getType())) { 572 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E); 573 } else { 574 CXXCtorType Type = Ctor_Complete; 575 bool ForVirtualBase = false; 576 bool Delegating = false; 577 578 switch (E->getConstructionKind()) { 579 case CXXConstructExpr::CK_Delegating: 580 // We should be emitting a constructor; GlobalDecl will assert this 581 Type = CurGD.getCtorType(); 582 Delegating = true; 583 break; 584 585 case CXXConstructExpr::CK_Complete: 586 Type = Ctor_Complete; 587 break; 588 589 case CXXConstructExpr::CK_VirtualBase: 590 ForVirtualBase = true; 591 // fall-through 592 593 case CXXConstructExpr::CK_NonVirtualBase: 594 Type = Ctor_Base; 595 } 596 597 // Call the constructor. 598 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, 599 Dest.getAddress(), E); 600 } 601 } 602 603 void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, 604 const Expr *Exp) { 605 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp)) 606 Exp = E->getSubExpr(); 607 assert(isa<CXXConstructExpr>(Exp) && 608 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr"); 609 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp); 610 const CXXConstructorDecl *CD = E->getConstructor(); 611 RunCleanupsScope Scope(*this); 612 613 // If we require zero initialization before (or instead of) calling the 614 // constructor, as can be the case with a non-user-provided default 615 // constructor, emit the zero initialization now. 616 // FIXME. Do I still need this for a copy ctor synthesis? 617 if (E->requiresZeroInitialization()) 618 EmitNullInitialization(Dest, E->getType()); 619 620 assert(!getContext().getAsConstantArrayType(E->getType()) 621 && "EmitSynthesizedCXXCopyCtor - Copied-in Array"); 622 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E); 623 } 624 625 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF, 626 const CXXNewExpr *E) { 627 if (!E->isArray()) 628 return CharUnits::Zero(); 629 630 // No cookie is required if the operator new[] being used is the 631 // reserved placement operator new[]. 632 if (E->getOperatorNew()->isReservedGlobalPlacementOperator()) 633 return CharUnits::Zero(); 634 635 return CGF.CGM.getCXXABI().GetArrayCookieSize(E); 636 } 637 638 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, 639 const CXXNewExpr *e, 640 unsigned minElements, 641 llvm::Value *&numElements, 642 llvm::Value *&sizeWithoutCookie) { 643 QualType type = e->getAllocatedType(); 644 645 if (!e->isArray()) { 646 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 647 sizeWithoutCookie 648 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity()); 649 return sizeWithoutCookie; 650 } 651 652 // The width of size_t. 653 unsigned sizeWidth = CGF.SizeTy->getBitWidth(); 654 655 // Figure out the cookie size. 656 llvm::APInt cookieSize(sizeWidth, 657 CalculateCookiePadding(CGF, e).getQuantity()); 658 659 // Emit the array size expression. 660 // We multiply the size of all dimensions for NumElements. 661 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6. 662 numElements = CGF.CGM.EmitConstantExpr(e->getArraySize(), 663 CGF.getContext().getSizeType(), &CGF); 664 if (!numElements) 665 numElements = CGF.EmitScalarExpr(e->getArraySize()); 666 assert(isa<llvm::IntegerType>(numElements->getType())); 667 668 // The number of elements can be have an arbitrary integer type; 669 // essentially, we need to multiply it by a constant factor, add a 670 // cookie size, and verify that the result is representable as a 671 // size_t. That's just a gloss, though, and it's wrong in one 672 // important way: if the count is negative, it's an error even if 673 // the cookie size would bring the total size >= 0. 674 bool isSigned 675 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType(); 676 llvm::IntegerType *numElementsType 677 = cast<llvm::IntegerType>(numElements->getType()); 678 unsigned numElementsWidth = numElementsType->getBitWidth(); 679 680 // Compute the constant factor. 681 llvm::APInt arraySizeMultiplier(sizeWidth, 1); 682 while (const ConstantArrayType *CAT 683 = CGF.getContext().getAsConstantArrayType(type)) { 684 type = CAT->getElementType(); 685 arraySizeMultiplier *= CAT->getSize(); 686 } 687 688 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 689 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity()); 690 typeSizeMultiplier *= arraySizeMultiplier; 691 692 // This will be a size_t. 693 llvm::Value *size; 694 695 // If someone is doing 'new int[42]' there is no need to do a dynamic check. 696 // Don't bloat the -O0 code. 697 if (llvm::ConstantInt *numElementsC = 698 dyn_cast<llvm::ConstantInt>(numElements)) { 699 const llvm::APInt &count = numElementsC->getValue(); 700 701 bool hasAnyOverflow = false; 702 703 // If 'count' was a negative number, it's an overflow. 704 if (isSigned && count.isNegative()) 705 hasAnyOverflow = true; 706 707 // We want to do all this arithmetic in size_t. If numElements is 708 // wider than that, check whether it's already too big, and if so, 709 // overflow. 710 else if (numElementsWidth > sizeWidth && 711 numElementsWidth - sizeWidth > count.countLeadingZeros()) 712 hasAnyOverflow = true; 713 714 // Okay, compute a count at the right width. 715 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth); 716 717 // If there is a brace-initializer, we cannot allocate fewer elements than 718 // there are initializers. If we do, that's treated like an overflow. 719 if (adjustedCount.ult(minElements)) 720 hasAnyOverflow = true; 721 722 // Scale numElements by that. This might overflow, but we don't 723 // care because it only overflows if allocationSize does, too, and 724 // if that overflows then we shouldn't use this. 725 numElements = llvm::ConstantInt::get(CGF.SizeTy, 726 adjustedCount * arraySizeMultiplier); 727 728 // Compute the size before cookie, and track whether it overflowed. 729 bool overflow; 730 llvm::APInt allocationSize 731 = adjustedCount.umul_ov(typeSizeMultiplier, overflow); 732 hasAnyOverflow |= overflow; 733 734 // Add in the cookie, and check whether it's overflowed. 735 if (cookieSize != 0) { 736 // Save the current size without a cookie. This shouldn't be 737 // used if there was overflow. 738 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 739 740 allocationSize = allocationSize.uadd_ov(cookieSize, overflow); 741 hasAnyOverflow |= overflow; 742 } 743 744 // On overflow, produce a -1 so operator new will fail. 745 if (hasAnyOverflow) { 746 size = llvm::Constant::getAllOnesValue(CGF.SizeTy); 747 } else { 748 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 749 } 750 751 // Otherwise, we might need to use the overflow intrinsics. 752 } else { 753 // There are up to five conditions we need to test for: 754 // 1) if isSigned, we need to check whether numElements is negative; 755 // 2) if numElementsWidth > sizeWidth, we need to check whether 756 // numElements is larger than something representable in size_t; 757 // 3) if minElements > 0, we need to check whether numElements is smaller 758 // than that. 759 // 4) we need to compute 760 // sizeWithoutCookie := numElements * typeSizeMultiplier 761 // and check whether it overflows; and 762 // 5) if we need a cookie, we need to compute 763 // size := sizeWithoutCookie + cookieSize 764 // and check whether it overflows. 765 766 llvm::Value *hasOverflow = nullptr; 767 768 // If numElementsWidth > sizeWidth, then one way or another, we're 769 // going to have to do a comparison for (2), and this happens to 770 // take care of (1), too. 771 if (numElementsWidth > sizeWidth) { 772 llvm::APInt threshold(numElementsWidth, 1); 773 threshold <<= sizeWidth; 774 775 llvm::Value *thresholdV 776 = llvm::ConstantInt::get(numElementsType, threshold); 777 778 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV); 779 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy); 780 781 // Otherwise, if we're signed, we want to sext up to size_t. 782 } else if (isSigned) { 783 if (numElementsWidth < sizeWidth) 784 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy); 785 786 // If there's a non-1 type size multiplier, then we can do the 787 // signedness check at the same time as we do the multiply 788 // because a negative number times anything will cause an 789 // unsigned overflow. Otherwise, we have to do it here. But at least 790 // in this case, we can subsume the >= minElements check. 791 if (typeSizeMultiplier == 1) 792 hasOverflow = CGF.Builder.CreateICmpSLT(numElements, 793 llvm::ConstantInt::get(CGF.SizeTy, minElements)); 794 795 // Otherwise, zext up to size_t if necessary. 796 } else if (numElementsWidth < sizeWidth) { 797 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy); 798 } 799 800 assert(numElements->getType() == CGF.SizeTy); 801 802 if (minElements) { 803 // Don't allow allocation of fewer elements than we have initializers. 804 if (!hasOverflow) { 805 hasOverflow = CGF.Builder.CreateICmpULT(numElements, 806 llvm::ConstantInt::get(CGF.SizeTy, minElements)); 807 } else if (numElementsWidth > sizeWidth) { 808 // The other existing overflow subsumes this check. 809 // We do an unsigned comparison, since any signed value < -1 is 810 // taken care of either above or below. 811 hasOverflow = CGF.Builder.CreateOr(hasOverflow, 812 CGF.Builder.CreateICmpULT(numElements, 813 llvm::ConstantInt::get(CGF.SizeTy, minElements))); 814 } 815 } 816 817 size = numElements; 818 819 // Multiply by the type size if necessary. This multiplier 820 // includes all the factors for nested arrays. 821 // 822 // This step also causes numElements to be scaled up by the 823 // nested-array factor if necessary. Overflow on this computation 824 // can be ignored because the result shouldn't be used if 825 // allocation fails. 826 if (typeSizeMultiplier != 1) { 827 llvm::Value *umul_with_overflow 828 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy); 829 830 llvm::Value *tsmV = 831 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier); 832 llvm::Value *result = 833 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV}); 834 835 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 836 if (hasOverflow) 837 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 838 else 839 hasOverflow = overflowed; 840 841 size = CGF.Builder.CreateExtractValue(result, 0); 842 843 // Also scale up numElements by the array size multiplier. 844 if (arraySizeMultiplier != 1) { 845 // If the base element type size is 1, then we can re-use the 846 // multiply we just did. 847 if (typeSize.isOne()) { 848 assert(arraySizeMultiplier == typeSizeMultiplier); 849 numElements = size; 850 851 // Otherwise we need a separate multiply. 852 } else { 853 llvm::Value *asmV = 854 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier); 855 numElements = CGF.Builder.CreateMul(numElements, asmV); 856 } 857 } 858 } else { 859 // numElements doesn't need to be scaled. 860 assert(arraySizeMultiplier == 1); 861 } 862 863 // Add in the cookie size if necessary. 864 if (cookieSize != 0) { 865 sizeWithoutCookie = size; 866 867 llvm::Value *uadd_with_overflow 868 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy); 869 870 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize); 871 llvm::Value *result = 872 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV}); 873 874 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 875 if (hasOverflow) 876 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 877 else 878 hasOverflow = overflowed; 879 880 size = CGF.Builder.CreateExtractValue(result, 0); 881 } 882 883 // If we had any possibility of dynamic overflow, make a select to 884 // overwrite 'size' with an all-ones value, which should cause 885 // operator new to throw. 886 if (hasOverflow) 887 size = CGF.Builder.CreateSelect(hasOverflow, 888 llvm::Constant::getAllOnesValue(CGF.SizeTy), 889 size); 890 } 891 892 if (cookieSize == 0) 893 sizeWithoutCookie = size; 894 else 895 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?"); 896 897 return size; 898 } 899 900 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init, 901 QualType AllocType, Address NewPtr) { 902 // FIXME: Refactor with EmitExprAsInit. 903 switch (CGF.getEvaluationKind(AllocType)) { 904 case TEK_Scalar: 905 CGF.EmitScalarInit(Init, nullptr, 906 CGF.MakeAddrLValue(NewPtr, AllocType), false); 907 return; 908 case TEK_Complex: 909 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType), 910 /*isInit*/ true); 911 return; 912 case TEK_Aggregate: { 913 AggValueSlot Slot 914 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(), 915 AggValueSlot::IsDestructed, 916 AggValueSlot::DoesNotNeedGCBarriers, 917 AggValueSlot::IsNotAliased); 918 CGF.EmitAggExpr(Init, Slot); 919 return; 920 } 921 } 922 llvm_unreachable("bad evaluation kind"); 923 } 924 925 void CodeGenFunction::EmitNewArrayInitializer( 926 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy, 927 Address BeginPtr, llvm::Value *NumElements, 928 llvm::Value *AllocSizeWithoutCookie) { 929 // If we have a type with trivial initialization and no initializer, 930 // there's nothing to do. 931 if (!E->hasInitializer()) 932 return; 933 934 Address CurPtr = BeginPtr; 935 936 unsigned InitListElements = 0; 937 938 const Expr *Init = E->getInitializer(); 939 Address EndOfInit = Address::invalid(); 940 QualType::DestructionKind DtorKind = ElementType.isDestructedType(); 941 EHScopeStack::stable_iterator Cleanup; 942 llvm::Instruction *CleanupDominator = nullptr; 943 944 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType); 945 CharUnits ElementAlign = 946 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize); 947 948 // Attempt to perform zero-initialization using memset. 949 auto TryMemsetInitialization = [&]() -> bool { 950 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI, 951 // we can initialize with a memset to -1. 952 if (!CGM.getTypes().isZeroInitializable(ElementType)) 953 return false; 954 955 // Optimization: since zero initialization will just set the memory 956 // to all zeroes, generate a single memset to do it in one shot. 957 958 // Subtract out the size of any elements we've already initialized. 959 auto *RemainingSize = AllocSizeWithoutCookie; 960 if (InitListElements) { 961 // We know this can't overflow; we check this when doing the allocation. 962 auto *InitializedSize = llvm::ConstantInt::get( 963 RemainingSize->getType(), 964 getContext().getTypeSizeInChars(ElementType).getQuantity() * 965 InitListElements); 966 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize); 967 } 968 969 // Create the memset. 970 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false); 971 return true; 972 }; 973 974 // If the initializer is an initializer list, first do the explicit elements. 975 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 976 // Initializing from a (braced) string literal is a special case; the init 977 // list element does not initialize a (single) array element. 978 if (ILE->isStringLiteralInit()) { 979 // Initialize the initial portion of length equal to that of the string 980 // literal. The allocation must be for at least this much; we emitted a 981 // check for that earlier. 982 AggValueSlot Slot = 983 AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(), 984 AggValueSlot::IsDestructed, 985 AggValueSlot::DoesNotNeedGCBarriers, 986 AggValueSlot::IsNotAliased); 987 EmitAggExpr(ILE->getInit(0), Slot); 988 989 // Move past these elements. 990 InitListElements = 991 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe()) 992 ->getSize().getZExtValue(); 993 CurPtr = 994 Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(), 995 Builder.getSize(InitListElements), 996 "string.init.end"), 997 CurPtr.getAlignment().alignmentAtOffset(InitListElements * 998 ElementSize)); 999 1000 // Zero out the rest, if any remain. 1001 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 1002 if (!ConstNum || !ConstNum->equalsInt(InitListElements)) { 1003 bool OK = TryMemsetInitialization(); 1004 (void)OK; 1005 assert(OK && "couldn't memset character type?"); 1006 } 1007 return; 1008 } 1009 1010 InitListElements = ILE->getNumInits(); 1011 1012 // If this is a multi-dimensional array new, we will initialize multiple 1013 // elements with each init list element. 1014 QualType AllocType = E->getAllocatedType(); 1015 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>( 1016 AllocType->getAsArrayTypeUnsafe())) { 1017 ElementTy = ConvertTypeForMem(AllocType); 1018 CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy); 1019 InitListElements *= getContext().getConstantArrayElementCount(CAT); 1020 } 1021 1022 // Enter a partial-destruction Cleanup if necessary. 1023 if (needsEHCleanup(DtorKind)) { 1024 // In principle we could tell the Cleanup where we are more 1025 // directly, but the control flow can get so varied here that it 1026 // would actually be quite complex. Therefore we go through an 1027 // alloca. 1028 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(), 1029 "array.init.end"); 1030 CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit); 1031 pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit, 1032 ElementType, ElementAlign, 1033 getDestroyer(DtorKind)); 1034 Cleanup = EHStack.stable_begin(); 1035 } 1036 1037 CharUnits StartAlign = CurPtr.getAlignment(); 1038 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) { 1039 // Tell the cleanup that it needs to destroy up to this 1040 // element. TODO: some of these stores can be trivially 1041 // observed to be unnecessary. 1042 if (EndOfInit.isValid()) { 1043 auto FinishedPtr = 1044 Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType()); 1045 Builder.CreateStore(FinishedPtr, EndOfInit); 1046 } 1047 // FIXME: If the last initializer is an incomplete initializer list for 1048 // an array, and we have an array filler, we can fold together the two 1049 // initialization loops. 1050 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), 1051 ILE->getInit(i)->getType(), CurPtr); 1052 CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(), 1053 Builder.getSize(1), 1054 "array.exp.next"), 1055 StartAlign.alignmentAtOffset((i + 1) * ElementSize)); 1056 } 1057 1058 // The remaining elements are filled with the array filler expression. 1059 Init = ILE->getArrayFiller(); 1060 1061 // Extract the initializer for the individual array elements by pulling 1062 // out the array filler from all the nested initializer lists. This avoids 1063 // generating a nested loop for the initialization. 1064 while (Init && Init->getType()->isConstantArrayType()) { 1065 auto *SubILE = dyn_cast<InitListExpr>(Init); 1066 if (!SubILE) 1067 break; 1068 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?"); 1069 Init = SubILE->getArrayFiller(); 1070 } 1071 1072 // Switch back to initializing one base element at a time. 1073 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType()); 1074 } 1075 1076 // If all elements have already been initialized, skip any further 1077 // initialization. 1078 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 1079 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) { 1080 // If there was a Cleanup, deactivate it. 1081 if (CleanupDominator) 1082 DeactivateCleanupBlock(Cleanup, CleanupDominator); 1083 return; 1084 } 1085 1086 assert(Init && "have trailing elements to initialize but no initializer"); 1087 1088 // If this is a constructor call, try to optimize it out, and failing that 1089 // emit a single loop to initialize all remaining elements. 1090 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 1091 CXXConstructorDecl *Ctor = CCE->getConstructor(); 1092 if (Ctor->isTrivial()) { 1093 // If new expression did not specify value-initialization, then there 1094 // is no initialization. 1095 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty()) 1096 return; 1097 1098 if (TryMemsetInitialization()) 1099 return; 1100 } 1101 1102 // Store the new Cleanup position for irregular Cleanups. 1103 // 1104 // FIXME: Share this cleanup with the constructor call emission rather than 1105 // having it create a cleanup of its own. 1106 if (EndOfInit.isValid()) 1107 Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 1108 1109 // Emit a constructor call loop to initialize the remaining elements. 1110 if (InitListElements) 1111 NumElements = Builder.CreateSub( 1112 NumElements, 1113 llvm::ConstantInt::get(NumElements->getType(), InitListElements)); 1114 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE, 1115 CCE->requiresZeroInitialization()); 1116 return; 1117 } 1118 1119 // If this is value-initialization, we can usually use memset. 1120 ImplicitValueInitExpr IVIE(ElementType); 1121 if (isa<ImplicitValueInitExpr>(Init)) { 1122 if (TryMemsetInitialization()) 1123 return; 1124 1125 // Switch to an ImplicitValueInitExpr for the element type. This handles 1126 // only one case: multidimensional array new of pointers to members. In 1127 // all other cases, we already have an initializer for the array element. 1128 Init = &IVIE; 1129 } 1130 1131 // At this point we should have found an initializer for the individual 1132 // elements of the array. 1133 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) && 1134 "got wrong type of element to initialize"); 1135 1136 // If we have an empty initializer list, we can usually use memset. 1137 if (auto *ILE = dyn_cast<InitListExpr>(Init)) 1138 if (ILE->getNumInits() == 0 && TryMemsetInitialization()) 1139 return; 1140 1141 // If we have a struct whose every field is value-initialized, we can 1142 // usually use memset. 1143 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 1144 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 1145 if (RType->getDecl()->isStruct()) { 1146 unsigned NumElements = 0; 1147 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl())) 1148 NumElements = CXXRD->getNumBases(); 1149 for (auto *Field : RType->getDecl()->fields()) 1150 if (!Field->isUnnamedBitfield()) 1151 ++NumElements; 1152 // FIXME: Recurse into nested InitListExprs. 1153 if (ILE->getNumInits() == NumElements) 1154 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) 1155 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i))) 1156 --NumElements; 1157 if (ILE->getNumInits() == NumElements && TryMemsetInitialization()) 1158 return; 1159 } 1160 } 1161 } 1162 1163 // Create the loop blocks. 1164 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock(); 1165 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop"); 1166 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end"); 1167 1168 // Find the end of the array, hoisted out of the loop. 1169 llvm::Value *EndPtr = 1170 Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end"); 1171 1172 // If the number of elements isn't constant, we have to now check if there is 1173 // anything left to initialize. 1174 if (!ConstNum) { 1175 llvm::Value *IsEmpty = 1176 Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty"); 1177 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB); 1178 } 1179 1180 // Enter the loop. 1181 EmitBlock(LoopBB); 1182 1183 // Set up the current-element phi. 1184 llvm::PHINode *CurPtrPhi = 1185 Builder.CreatePHI(CurPtr.getType(), 2, "array.cur"); 1186 CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB); 1187 1188 CurPtr = Address(CurPtrPhi, ElementAlign); 1189 1190 // Store the new Cleanup position for irregular Cleanups. 1191 if (EndOfInit.isValid()) 1192 Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 1193 1194 // Enter a partial-destruction Cleanup if necessary. 1195 if (!CleanupDominator && needsEHCleanup(DtorKind)) { 1196 pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(), 1197 ElementType, ElementAlign, 1198 getDestroyer(DtorKind)); 1199 Cleanup = EHStack.stable_begin(); 1200 CleanupDominator = Builder.CreateUnreachable(); 1201 } 1202 1203 // Emit the initializer into this element. 1204 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr); 1205 1206 // Leave the Cleanup if we entered one. 1207 if (CleanupDominator) { 1208 DeactivateCleanupBlock(Cleanup, CleanupDominator); 1209 CleanupDominator->eraseFromParent(); 1210 } 1211 1212 // Advance to the next element by adjusting the pointer type as necessary. 1213 llvm::Value *NextPtr = 1214 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1, 1215 "array.next"); 1216 1217 // Check whether we've gotten to the end of the array and, if so, 1218 // exit the loop. 1219 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend"); 1220 Builder.CreateCondBr(IsEnd, ContBB, LoopBB); 1221 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock()); 1222 1223 EmitBlock(ContBB); 1224 } 1225 1226 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E, 1227 QualType ElementType, llvm::Type *ElementTy, 1228 Address NewPtr, llvm::Value *NumElements, 1229 llvm::Value *AllocSizeWithoutCookie) { 1230 ApplyDebugLocation DL(CGF, E); 1231 if (E->isArray()) 1232 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements, 1233 AllocSizeWithoutCookie); 1234 else if (const Expr *Init = E->getInitializer()) 1235 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr); 1236 } 1237 1238 /// Emit a call to an operator new or operator delete function, as implicitly 1239 /// created by new-expressions and delete-expressions. 1240 static RValue EmitNewDeleteCall(CodeGenFunction &CGF, 1241 const FunctionDecl *CalleeDecl, 1242 const FunctionProtoType *CalleeType, 1243 const CallArgList &Args) { 1244 llvm::Instruction *CallOrInvoke; 1245 llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl); 1246 CGCallee Callee = CGCallee::forDirect(CalleePtr, CalleeDecl); 1247 RValue RV = 1248 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall( 1249 Args, CalleeType, /*chainCall=*/false), 1250 Callee, ReturnValueSlot(), Args, &CallOrInvoke); 1251 1252 /// C++1y [expr.new]p10: 1253 /// [In a new-expression,] an implementation is allowed to omit a call 1254 /// to a replaceable global allocation function. 1255 /// 1256 /// We model such elidable calls with the 'builtin' attribute. 1257 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr); 1258 if (CalleeDecl->isReplaceableGlobalAllocationFunction() && 1259 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) { 1260 // FIXME: Add addAttribute to CallSite. 1261 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke)) 1262 CI->addAttribute(llvm::AttributeSet::FunctionIndex, 1263 llvm::Attribute::Builtin); 1264 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke)) 1265 II->addAttribute(llvm::AttributeSet::FunctionIndex, 1266 llvm::Attribute::Builtin); 1267 else 1268 llvm_unreachable("unexpected kind of call instruction"); 1269 } 1270 1271 return RV; 1272 } 1273 1274 RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 1275 const Expr *Arg, 1276 bool IsDelete) { 1277 CallArgList Args; 1278 const Stmt *ArgS = Arg; 1279 EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS)); 1280 // Find the allocation or deallocation function that we're calling. 1281 ASTContext &Ctx = getContext(); 1282 DeclarationName Name = Ctx.DeclarationNames 1283 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New); 1284 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name)) 1285 if (auto *FD = dyn_cast<FunctionDecl>(Decl)) 1286 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0))) 1287 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args); 1288 llvm_unreachable("predeclared global operator new/delete is missing"); 1289 } 1290 1291 static std::pair<bool, bool> 1292 shouldPassSizeAndAlignToUsualDelete(const FunctionProtoType *FPT) { 1293 auto AI = FPT->param_type_begin(), AE = FPT->param_type_end(); 1294 1295 // The first argument is always a void*. 1296 ++AI; 1297 1298 // Figure out what other parameters we should be implicitly passing. 1299 bool PassSize = false; 1300 bool PassAlignment = false; 1301 1302 if (AI != AE && (*AI)->isIntegerType()) { 1303 PassSize = true; 1304 ++AI; 1305 } 1306 1307 if (AI != AE && (*AI)->isAlignValT()) { 1308 PassAlignment = true; 1309 ++AI; 1310 } 1311 1312 assert(AI == AE && "unexpected usual deallocation function parameter"); 1313 return {PassSize, PassAlignment}; 1314 } 1315 1316 namespace { 1317 /// A cleanup to call the given 'operator delete' function upon abnormal 1318 /// exit from a new expression. Templated on a traits type that deals with 1319 /// ensuring that the arguments dominate the cleanup if necessary. 1320 template<typename Traits> 1321 class CallDeleteDuringNew final : public EHScopeStack::Cleanup { 1322 /// Type used to hold llvm::Value*s. 1323 typedef typename Traits::ValueTy ValueTy; 1324 /// Type used to hold RValues. 1325 typedef typename Traits::RValueTy RValueTy; 1326 struct PlacementArg { 1327 RValueTy ArgValue; 1328 QualType ArgType; 1329 }; 1330 1331 unsigned NumPlacementArgs : 31; 1332 unsigned PassAlignmentToPlacementDelete : 1; 1333 const FunctionDecl *OperatorDelete; 1334 ValueTy Ptr; 1335 ValueTy AllocSize; 1336 CharUnits AllocAlign; 1337 1338 PlacementArg *getPlacementArgs() { 1339 return reinterpret_cast<PlacementArg *>(this + 1); 1340 } 1341 1342 public: 1343 static size_t getExtraSize(size_t NumPlacementArgs) { 1344 return NumPlacementArgs * sizeof(PlacementArg); 1345 } 1346 1347 CallDeleteDuringNew(size_t NumPlacementArgs, 1348 const FunctionDecl *OperatorDelete, ValueTy Ptr, 1349 ValueTy AllocSize, bool PassAlignmentToPlacementDelete, 1350 CharUnits AllocAlign) 1351 : NumPlacementArgs(NumPlacementArgs), 1352 PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete), 1353 OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize), 1354 AllocAlign(AllocAlign) {} 1355 1356 void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) { 1357 assert(I < NumPlacementArgs && "index out of range"); 1358 getPlacementArgs()[I] = {Arg, Type}; 1359 } 1360 1361 void Emit(CodeGenFunction &CGF, Flags flags) override { 1362 const FunctionProtoType *FPT = 1363 OperatorDelete->getType()->getAs<FunctionProtoType>(); 1364 CallArgList DeleteArgs; 1365 1366 // The first argument is always a void*. 1367 DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0)); 1368 1369 // Figure out what other parameters we should be implicitly passing. 1370 bool PassSize = false; 1371 bool PassAlignment = false; 1372 if (NumPlacementArgs) { 1373 // A placement deallocation function is implicitly passed an alignment 1374 // if the placement allocation function was, but is never passed a size. 1375 PassAlignment = PassAlignmentToPlacementDelete; 1376 } else { 1377 // For a non-placement new-expression, 'operator delete' can take a 1378 // size and/or an alignment if it has the right parameters. 1379 std::tie(PassSize, PassAlignment) = 1380 shouldPassSizeAndAlignToUsualDelete(FPT); 1381 } 1382 1383 // The second argument can be a std::size_t (for non-placement delete). 1384 if (PassSize) 1385 DeleteArgs.add(Traits::get(CGF, AllocSize), 1386 CGF.getContext().getSizeType()); 1387 1388 // The next (second or third) argument can be a std::align_val_t, which 1389 // is an enum whose underlying type is std::size_t. 1390 // FIXME: Use the right type as the parameter type. Note that in a call 1391 // to operator delete(size_t, ...), we may not have it available. 1392 if (PassAlignment) 1393 DeleteArgs.add(RValue::get(llvm::ConstantInt::get( 1394 CGF.SizeTy, AllocAlign.getQuantity())), 1395 CGF.getContext().getSizeType()); 1396 1397 // Pass the rest of the arguments, which must match exactly. 1398 for (unsigned I = 0; I != NumPlacementArgs; ++I) { 1399 auto Arg = getPlacementArgs()[I]; 1400 DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType); 1401 } 1402 1403 // Call 'operator delete'. 1404 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs); 1405 } 1406 }; 1407 } 1408 1409 /// Enter a cleanup to call 'operator delete' if the initializer in a 1410 /// new-expression throws. 1411 static void EnterNewDeleteCleanup(CodeGenFunction &CGF, 1412 const CXXNewExpr *E, 1413 Address NewPtr, 1414 llvm::Value *AllocSize, 1415 CharUnits AllocAlign, 1416 const CallArgList &NewArgs) { 1417 unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1; 1418 1419 // If we're not inside a conditional branch, then the cleanup will 1420 // dominate and we can do the easier (and more efficient) thing. 1421 if (!CGF.isInConditionalBranch()) { 1422 struct DirectCleanupTraits { 1423 typedef llvm::Value *ValueTy; 1424 typedef RValue RValueTy; 1425 static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); } 1426 static RValue get(CodeGenFunction &, RValueTy V) { return V; } 1427 }; 1428 1429 typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup; 1430 1431 DirectCleanup *Cleanup = CGF.EHStack 1432 .pushCleanupWithExtra<DirectCleanup>(EHCleanup, 1433 E->getNumPlacementArgs(), 1434 E->getOperatorDelete(), 1435 NewPtr.getPointer(), 1436 AllocSize, 1437 E->passAlignment(), 1438 AllocAlign); 1439 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) { 1440 auto &Arg = NewArgs[I + NumNonPlacementArgs]; 1441 Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty); 1442 } 1443 1444 return; 1445 } 1446 1447 // Otherwise, we need to save all this stuff. 1448 DominatingValue<RValue>::saved_type SavedNewPtr = 1449 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer())); 1450 DominatingValue<RValue>::saved_type SavedAllocSize = 1451 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize)); 1452 1453 struct ConditionalCleanupTraits { 1454 typedef DominatingValue<RValue>::saved_type ValueTy; 1455 typedef DominatingValue<RValue>::saved_type RValueTy; 1456 static RValue get(CodeGenFunction &CGF, ValueTy V) { 1457 return V.restore(CGF); 1458 } 1459 }; 1460 typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup; 1461 1462 ConditionalCleanup *Cleanup = CGF.EHStack 1463 .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup, 1464 E->getNumPlacementArgs(), 1465 E->getOperatorDelete(), 1466 SavedNewPtr, 1467 SavedAllocSize, 1468 E->passAlignment(), 1469 AllocAlign); 1470 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) { 1471 auto &Arg = NewArgs[I + NumNonPlacementArgs]; 1472 Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV), 1473 Arg.Ty); 1474 } 1475 1476 CGF.initFullExprCleanup(); 1477 } 1478 1479 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { 1480 // The element type being allocated. 1481 QualType allocType = getContext().getBaseElementType(E->getAllocatedType()); 1482 1483 // 1. Build a call to the allocation function. 1484 FunctionDecl *allocator = E->getOperatorNew(); 1485 1486 // If there is a brace-initializer, cannot allocate fewer elements than inits. 1487 unsigned minElements = 0; 1488 if (E->isArray() && E->hasInitializer()) { 1489 const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()); 1490 if (ILE && ILE->isStringLiteralInit()) 1491 minElements = 1492 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe()) 1493 ->getSize().getZExtValue(); 1494 else if (ILE) 1495 minElements = ILE->getNumInits(); 1496 } 1497 1498 llvm::Value *numElements = nullptr; 1499 llvm::Value *allocSizeWithoutCookie = nullptr; 1500 llvm::Value *allocSize = 1501 EmitCXXNewAllocSize(*this, E, minElements, numElements, 1502 allocSizeWithoutCookie); 1503 CharUnits allocAlign = getContext().getTypeAlignInChars(allocType); 1504 1505 // Emit the allocation call. If the allocator is a global placement 1506 // operator, just "inline" it directly. 1507 Address allocation = Address::invalid(); 1508 CallArgList allocatorArgs; 1509 if (allocator->isReservedGlobalPlacementOperator()) { 1510 assert(E->getNumPlacementArgs() == 1); 1511 const Expr *arg = *E->placement_arguments().begin(); 1512 1513 AlignmentSource alignSource; 1514 allocation = EmitPointerWithAlignment(arg, &alignSource); 1515 1516 // The pointer expression will, in many cases, be an opaque void*. 1517 // In these cases, discard the computed alignment and use the 1518 // formal alignment of the allocated type. 1519 if (alignSource != AlignmentSource::Decl) 1520 allocation = Address(allocation.getPointer(), allocAlign); 1521 1522 // Set up allocatorArgs for the call to operator delete if it's not 1523 // the reserved global operator. 1524 if (E->getOperatorDelete() && 1525 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 1526 allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType()); 1527 allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType()); 1528 } 1529 1530 } else { 1531 const FunctionProtoType *allocatorType = 1532 allocator->getType()->castAs<FunctionProtoType>(); 1533 unsigned ParamsToSkip = 0; 1534 1535 // The allocation size is the first argument. 1536 QualType sizeType = getContext().getSizeType(); 1537 allocatorArgs.add(RValue::get(allocSize), sizeType); 1538 ++ParamsToSkip; 1539 1540 if (allocSize != allocSizeWithoutCookie) { 1541 CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI. 1542 allocAlign = std::max(allocAlign, cookieAlign); 1543 } 1544 1545 // The allocation alignment may be passed as the second argument. 1546 if (E->passAlignment()) { 1547 QualType AlignValT = sizeType; 1548 if (allocatorType->getNumParams() > 1) { 1549 AlignValT = allocatorType->getParamType(1); 1550 assert(getContext().hasSameUnqualifiedType( 1551 AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(), 1552 sizeType) && 1553 "wrong type for alignment parameter"); 1554 ++ParamsToSkip; 1555 } else { 1556 // Corner case, passing alignment to 'operator new(size_t, ...)'. 1557 assert(allocator->isVariadic() && "can't pass alignment to allocator"); 1558 } 1559 allocatorArgs.add( 1560 RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())), 1561 AlignValT); 1562 } 1563 1564 // FIXME: Why do we not pass a CalleeDecl here? 1565 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(), 1566 /*CalleeDecl*/nullptr, /*ParamsToSkip*/ParamsToSkip); 1567 1568 RValue RV = 1569 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs); 1570 1571 // If this was a call to a global replaceable allocation function that does 1572 // not take an alignment argument, the allocator is known to produce 1573 // storage that's suitably aligned for any object that fits, up to a known 1574 // threshold. Otherwise assume it's suitably aligned for the allocated type. 1575 CharUnits allocationAlign = allocAlign; 1576 if (!E->passAlignment() && 1577 allocator->isReplaceableGlobalAllocationFunction()) { 1578 unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>( 1579 Target.getNewAlign(), getContext().getTypeSize(allocType))); 1580 allocationAlign = std::max( 1581 allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign)); 1582 } 1583 1584 allocation = Address(RV.getScalarVal(), allocationAlign); 1585 } 1586 1587 // Emit a null check on the allocation result if the allocation 1588 // function is allowed to return null (because it has a non-throwing 1589 // exception spec or is the reserved placement new) and we have an 1590 // interesting initializer. 1591 bool nullCheck = E->shouldNullCheckAllocation(getContext()) && 1592 (!allocType.isPODType(getContext()) || E->hasInitializer()); 1593 1594 llvm::BasicBlock *nullCheckBB = nullptr; 1595 llvm::BasicBlock *contBB = nullptr; 1596 1597 // The null-check means that the initializer is conditionally 1598 // evaluated. 1599 ConditionalEvaluation conditional(*this); 1600 1601 if (nullCheck) { 1602 conditional.begin(*this); 1603 1604 nullCheckBB = Builder.GetInsertBlock(); 1605 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull"); 1606 contBB = createBasicBlock("new.cont"); 1607 1608 llvm::Value *isNull = 1609 Builder.CreateIsNull(allocation.getPointer(), "new.isnull"); 1610 Builder.CreateCondBr(isNull, contBB, notNullBB); 1611 EmitBlock(notNullBB); 1612 } 1613 1614 // If there's an operator delete, enter a cleanup to call it if an 1615 // exception is thrown. 1616 EHScopeStack::stable_iterator operatorDeleteCleanup; 1617 llvm::Instruction *cleanupDominator = nullptr; 1618 if (E->getOperatorDelete() && 1619 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 1620 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign, 1621 allocatorArgs); 1622 operatorDeleteCleanup = EHStack.stable_begin(); 1623 cleanupDominator = Builder.CreateUnreachable(); 1624 } 1625 1626 assert((allocSize == allocSizeWithoutCookie) == 1627 CalculateCookiePadding(*this, E).isZero()); 1628 if (allocSize != allocSizeWithoutCookie) { 1629 assert(E->isArray()); 1630 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation, 1631 numElements, 1632 E, allocType); 1633 } 1634 1635 llvm::Type *elementTy = ConvertTypeForMem(allocType); 1636 Address result = Builder.CreateElementBitCast(allocation, elementTy); 1637 1638 // Passing pointer through invariant.group.barrier to avoid propagation of 1639 // vptrs information which may be included in previous type. 1640 if (CGM.getCodeGenOpts().StrictVTablePointers && 1641 CGM.getCodeGenOpts().OptimizationLevel > 0 && 1642 allocator->isReservedGlobalPlacementOperator()) 1643 result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()), 1644 result.getAlignment()); 1645 1646 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements, 1647 allocSizeWithoutCookie); 1648 if (E->isArray()) { 1649 // NewPtr is a pointer to the base element type. If we're 1650 // allocating an array of arrays, we'll need to cast back to the 1651 // array pointer type. 1652 llvm::Type *resultType = ConvertTypeForMem(E->getType()); 1653 if (result.getType() != resultType) 1654 result = Builder.CreateBitCast(result, resultType); 1655 } 1656 1657 // Deactivate the 'operator delete' cleanup if we finished 1658 // initialization. 1659 if (operatorDeleteCleanup.isValid()) { 1660 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator); 1661 cleanupDominator->eraseFromParent(); 1662 } 1663 1664 llvm::Value *resultPtr = result.getPointer(); 1665 if (nullCheck) { 1666 conditional.end(*this); 1667 1668 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock(); 1669 EmitBlock(contBB); 1670 1671 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2); 1672 PHI->addIncoming(resultPtr, notNullBB); 1673 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()), 1674 nullCheckBB); 1675 1676 resultPtr = PHI; 1677 } 1678 1679 return resultPtr; 1680 } 1681 1682 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD, 1683 llvm::Value *Ptr, QualType DeleteTy, 1684 llvm::Value *NumElements, 1685 CharUnits CookieSize) { 1686 assert((!NumElements && CookieSize.isZero()) || 1687 DeleteFD->getOverloadedOperator() == OO_Array_Delete); 1688 1689 const FunctionProtoType *DeleteFTy = 1690 DeleteFD->getType()->getAs<FunctionProtoType>(); 1691 1692 CallArgList DeleteArgs; 1693 1694 std::pair<bool, bool> PassSizeAndAlign = 1695 shouldPassSizeAndAlignToUsualDelete(DeleteFTy); 1696 1697 auto ParamTypeIt = DeleteFTy->param_type_begin(); 1698 1699 // Pass the pointer itself. 1700 QualType ArgTy = *ParamTypeIt++; 1701 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy)); 1702 DeleteArgs.add(RValue::get(DeletePtr), ArgTy); 1703 1704 // Pass the size if the delete function has a size_t parameter. 1705 if (PassSizeAndAlign.first) { 1706 QualType SizeType = *ParamTypeIt++; 1707 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy); 1708 llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType), 1709 DeleteTypeSize.getQuantity()); 1710 1711 // For array new, multiply by the number of elements. 1712 if (NumElements) 1713 Size = Builder.CreateMul(Size, NumElements); 1714 1715 // If there is a cookie, add the cookie size. 1716 if (!CookieSize.isZero()) 1717 Size = Builder.CreateAdd( 1718 Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity())); 1719 1720 DeleteArgs.add(RValue::get(Size), SizeType); 1721 } 1722 1723 // Pass the alignment if the delete function has an align_val_t parameter. 1724 if (PassSizeAndAlign.second) { 1725 QualType AlignValType = *ParamTypeIt++; 1726 CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits( 1727 getContext().getTypeAlignIfKnown(DeleteTy)); 1728 llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType), 1729 DeleteTypeAlign.getQuantity()); 1730 DeleteArgs.add(RValue::get(Align), AlignValType); 1731 } 1732 1733 assert(ParamTypeIt == DeleteFTy->param_type_end() && 1734 "unknown parameter to usual delete function"); 1735 1736 // Emit the call to delete. 1737 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs); 1738 } 1739 1740 namespace { 1741 /// Calls the given 'operator delete' on a single object. 1742 struct CallObjectDelete final : EHScopeStack::Cleanup { 1743 llvm::Value *Ptr; 1744 const FunctionDecl *OperatorDelete; 1745 QualType ElementType; 1746 1747 CallObjectDelete(llvm::Value *Ptr, 1748 const FunctionDecl *OperatorDelete, 1749 QualType ElementType) 1750 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {} 1751 1752 void Emit(CodeGenFunction &CGF, Flags flags) override { 1753 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType); 1754 } 1755 }; 1756 } 1757 1758 void 1759 CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 1760 llvm::Value *CompletePtr, 1761 QualType ElementType) { 1762 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr, 1763 OperatorDelete, ElementType); 1764 } 1765 1766 /// Emit the code for deleting a single object. 1767 static void EmitObjectDelete(CodeGenFunction &CGF, 1768 const CXXDeleteExpr *DE, 1769 Address Ptr, 1770 QualType ElementType) { 1771 // C++11 [expr.delete]p3: 1772 // If the static type of the object to be deleted is different from its 1773 // dynamic type, the static type shall be a base class of the dynamic type 1774 // of the object to be deleted and the static type shall have a virtual 1775 // destructor or the behavior is undefined. 1776 CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall, 1777 DE->getExprLoc(), Ptr.getPointer(), 1778 ElementType); 1779 1780 // Find the destructor for the type, if applicable. If the 1781 // destructor is virtual, we'll just emit the vcall and return. 1782 const CXXDestructorDecl *Dtor = nullptr; 1783 if (const RecordType *RT = ElementType->getAs<RecordType>()) { 1784 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1785 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) { 1786 Dtor = RD->getDestructor(); 1787 1788 if (Dtor->isVirtual()) { 1789 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType, 1790 Dtor); 1791 return; 1792 } 1793 } 1794 } 1795 1796 // Make sure that we call delete even if the dtor throws. 1797 // This doesn't have to a conditional cleanup because we're going 1798 // to pop it off in a second. 1799 const FunctionDecl *OperatorDelete = DE->getOperatorDelete(); 1800 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, 1801 Ptr.getPointer(), 1802 OperatorDelete, ElementType); 1803 1804 if (Dtor) 1805 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 1806 /*ForVirtualBase=*/false, 1807 /*Delegating=*/false, 1808 Ptr); 1809 else if (auto Lifetime = ElementType.getObjCLifetime()) { 1810 switch (Lifetime) { 1811 case Qualifiers::OCL_None: 1812 case Qualifiers::OCL_ExplicitNone: 1813 case Qualifiers::OCL_Autoreleasing: 1814 break; 1815 1816 case Qualifiers::OCL_Strong: 1817 CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime); 1818 break; 1819 1820 case Qualifiers::OCL_Weak: 1821 CGF.EmitARCDestroyWeak(Ptr); 1822 break; 1823 } 1824 } 1825 1826 CGF.PopCleanupBlock(); 1827 } 1828 1829 namespace { 1830 /// Calls the given 'operator delete' on an array of objects. 1831 struct CallArrayDelete final : EHScopeStack::Cleanup { 1832 llvm::Value *Ptr; 1833 const FunctionDecl *OperatorDelete; 1834 llvm::Value *NumElements; 1835 QualType ElementType; 1836 CharUnits CookieSize; 1837 1838 CallArrayDelete(llvm::Value *Ptr, 1839 const FunctionDecl *OperatorDelete, 1840 llvm::Value *NumElements, 1841 QualType ElementType, 1842 CharUnits CookieSize) 1843 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements), 1844 ElementType(ElementType), CookieSize(CookieSize) {} 1845 1846 void Emit(CodeGenFunction &CGF, Flags flags) override { 1847 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements, 1848 CookieSize); 1849 } 1850 }; 1851 } 1852 1853 /// Emit the code for deleting an array of objects. 1854 static void EmitArrayDelete(CodeGenFunction &CGF, 1855 const CXXDeleteExpr *E, 1856 Address deletedPtr, 1857 QualType elementType) { 1858 llvm::Value *numElements = nullptr; 1859 llvm::Value *allocatedPtr = nullptr; 1860 CharUnits cookieSize; 1861 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType, 1862 numElements, allocatedPtr, cookieSize); 1863 1864 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer"); 1865 1866 // Make sure that we call delete even if one of the dtors throws. 1867 const FunctionDecl *operatorDelete = E->getOperatorDelete(); 1868 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup, 1869 allocatedPtr, operatorDelete, 1870 numElements, elementType, 1871 cookieSize); 1872 1873 // Destroy the elements. 1874 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) { 1875 assert(numElements && "no element count for a type with a destructor!"); 1876 1877 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType); 1878 CharUnits elementAlign = 1879 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize); 1880 1881 llvm::Value *arrayBegin = deletedPtr.getPointer(); 1882 llvm::Value *arrayEnd = 1883 CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end"); 1884 1885 // Note that it is legal to allocate a zero-length array, and we 1886 // can never fold the check away because the length should always 1887 // come from a cookie. 1888 CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign, 1889 CGF.getDestroyer(dtorKind), 1890 /*checkZeroLength*/ true, 1891 CGF.needsEHCleanup(dtorKind)); 1892 } 1893 1894 // Pop the cleanup block. 1895 CGF.PopCleanupBlock(); 1896 } 1897 1898 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) { 1899 const Expr *Arg = E->getArgument(); 1900 Address Ptr = EmitPointerWithAlignment(Arg); 1901 1902 // Null check the pointer. 1903 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull"); 1904 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end"); 1905 1906 llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull"); 1907 1908 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull); 1909 EmitBlock(DeleteNotNull); 1910 1911 // We might be deleting a pointer to array. If so, GEP down to the 1912 // first non-array element. 1913 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*) 1914 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType(); 1915 if (DeleteTy->isConstantArrayType()) { 1916 llvm::Value *Zero = Builder.getInt32(0); 1917 SmallVector<llvm::Value*,8> GEP; 1918 1919 GEP.push_back(Zero); // point at the outermost array 1920 1921 // For each layer of array type we're pointing at: 1922 while (const ConstantArrayType *Arr 1923 = getContext().getAsConstantArrayType(DeleteTy)) { 1924 // 1. Unpeel the array type. 1925 DeleteTy = Arr->getElementType(); 1926 1927 // 2. GEP to the first element of the array. 1928 GEP.push_back(Zero); 1929 } 1930 1931 Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"), 1932 Ptr.getAlignment()); 1933 } 1934 1935 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType()); 1936 1937 if (E->isArrayForm()) { 1938 EmitArrayDelete(*this, E, Ptr, DeleteTy); 1939 } else { 1940 EmitObjectDelete(*this, E, Ptr, DeleteTy); 1941 } 1942 1943 EmitBlock(DeleteEnd); 1944 } 1945 1946 static bool isGLValueFromPointerDeref(const Expr *E) { 1947 E = E->IgnoreParens(); 1948 1949 if (const auto *CE = dyn_cast<CastExpr>(E)) { 1950 if (!CE->getSubExpr()->isGLValue()) 1951 return false; 1952 return isGLValueFromPointerDeref(CE->getSubExpr()); 1953 } 1954 1955 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 1956 return isGLValueFromPointerDeref(OVE->getSourceExpr()); 1957 1958 if (const auto *BO = dyn_cast<BinaryOperator>(E)) 1959 if (BO->getOpcode() == BO_Comma) 1960 return isGLValueFromPointerDeref(BO->getRHS()); 1961 1962 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E)) 1963 return isGLValueFromPointerDeref(ACO->getTrueExpr()) || 1964 isGLValueFromPointerDeref(ACO->getFalseExpr()); 1965 1966 // C++11 [expr.sub]p1: 1967 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)) 1968 if (isa<ArraySubscriptExpr>(E)) 1969 return true; 1970 1971 if (const auto *UO = dyn_cast<UnaryOperator>(E)) 1972 if (UO->getOpcode() == UO_Deref) 1973 return true; 1974 1975 return false; 1976 } 1977 1978 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E, 1979 llvm::Type *StdTypeInfoPtrTy) { 1980 // Get the vtable pointer. 1981 Address ThisPtr = CGF.EmitLValue(E).getAddress(); 1982 1983 // C++ [expr.typeid]p2: 1984 // If the glvalue expression is obtained by applying the unary * operator to 1985 // a pointer and the pointer is a null pointer value, the typeid expression 1986 // throws the std::bad_typeid exception. 1987 // 1988 // However, this paragraph's intent is not clear. We choose a very generous 1989 // interpretation which implores us to consider comma operators, conditional 1990 // operators, parentheses and other such constructs. 1991 QualType SrcRecordTy = E->getType(); 1992 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked( 1993 isGLValueFromPointerDeref(E), SrcRecordTy)) { 1994 llvm::BasicBlock *BadTypeidBlock = 1995 CGF.createBasicBlock("typeid.bad_typeid"); 1996 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end"); 1997 1998 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer()); 1999 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock); 2000 2001 CGF.EmitBlock(BadTypeidBlock); 2002 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF); 2003 CGF.EmitBlock(EndBlock); 2004 } 2005 2006 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr, 2007 StdTypeInfoPtrTy); 2008 } 2009 2010 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) { 2011 llvm::Type *StdTypeInfoPtrTy = 2012 ConvertType(E->getType())->getPointerTo(); 2013 2014 if (E->isTypeOperand()) { 2015 llvm::Constant *TypeInfo = 2016 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext())); 2017 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy); 2018 } 2019 2020 // C++ [expr.typeid]p2: 2021 // When typeid is applied to a glvalue expression whose type is a 2022 // polymorphic class type, the result refers to a std::type_info object 2023 // representing the type of the most derived object (that is, the dynamic 2024 // type) to which the glvalue refers. 2025 if (E->isPotentiallyEvaluated()) 2026 return EmitTypeidFromVTable(*this, E->getExprOperand(), 2027 StdTypeInfoPtrTy); 2028 2029 QualType OperandTy = E->getExprOperand()->getType(); 2030 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy), 2031 StdTypeInfoPtrTy); 2032 } 2033 2034 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF, 2035 QualType DestTy) { 2036 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 2037 if (DestTy->isPointerType()) 2038 return llvm::Constant::getNullValue(DestLTy); 2039 2040 /// C++ [expr.dynamic.cast]p9: 2041 /// A failed cast to reference type throws std::bad_cast 2042 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF)) 2043 return nullptr; 2044 2045 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end")); 2046 return llvm::UndefValue::get(DestLTy); 2047 } 2048 2049 llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr, 2050 const CXXDynamicCastExpr *DCE) { 2051 CGM.EmitExplicitCastExprType(DCE, this); 2052 QualType DestTy = DCE->getTypeAsWritten(); 2053 2054 if (DCE->isAlwaysNull()) 2055 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy)) 2056 return T; 2057 2058 QualType SrcTy = DCE->getSubExpr()->getType(); 2059 2060 // C++ [expr.dynamic.cast]p7: 2061 // If T is "pointer to cv void," then the result is a pointer to the most 2062 // derived object pointed to by v. 2063 const PointerType *DestPTy = DestTy->getAs<PointerType>(); 2064 2065 bool isDynamicCastToVoid; 2066 QualType SrcRecordTy; 2067 QualType DestRecordTy; 2068 if (DestPTy) { 2069 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType(); 2070 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType(); 2071 DestRecordTy = DestPTy->getPointeeType(); 2072 } else { 2073 isDynamicCastToVoid = false; 2074 SrcRecordTy = SrcTy; 2075 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType(); 2076 } 2077 2078 assert(SrcRecordTy->isRecordType() && "source type must be a record type!"); 2079 2080 // C++ [expr.dynamic.cast]p4: 2081 // If the value of v is a null pointer value in the pointer case, the result 2082 // is the null pointer value of type T. 2083 bool ShouldNullCheckSrcValue = 2084 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(), 2085 SrcRecordTy); 2086 2087 llvm::BasicBlock *CastNull = nullptr; 2088 llvm::BasicBlock *CastNotNull = nullptr; 2089 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end"); 2090 2091 if (ShouldNullCheckSrcValue) { 2092 CastNull = createBasicBlock("dynamic_cast.null"); 2093 CastNotNull = createBasicBlock("dynamic_cast.notnull"); 2094 2095 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer()); 2096 Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 2097 EmitBlock(CastNotNull); 2098 } 2099 2100 llvm::Value *Value; 2101 if (isDynamicCastToVoid) { 2102 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy, 2103 DestTy); 2104 } else { 2105 assert(DestRecordTy->isRecordType() && 2106 "destination type must be a record type!"); 2107 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy, 2108 DestTy, DestRecordTy, CastEnd); 2109 CastNotNull = Builder.GetInsertBlock(); 2110 } 2111 2112 if (ShouldNullCheckSrcValue) { 2113 EmitBranch(CastEnd); 2114 2115 EmitBlock(CastNull); 2116 EmitBranch(CastEnd); 2117 } 2118 2119 EmitBlock(CastEnd); 2120 2121 if (ShouldNullCheckSrcValue) { 2122 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 2123 PHI->addIncoming(Value, CastNotNull); 2124 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull); 2125 2126 Value = PHI; 2127 } 2128 2129 return Value; 2130 } 2131 2132 void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) { 2133 RunCleanupsScope Scope(*this); 2134 LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType()); 2135 2136 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin(); 2137 for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(), 2138 e = E->capture_init_end(); 2139 i != e; ++i, ++CurField) { 2140 // Emit initialization 2141 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField); 2142 if (CurField->hasCapturedVLAType()) { 2143 auto VAT = CurField->getCapturedVLAType(); 2144 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV); 2145 } else { 2146 EmitInitializerForField(*CurField, LV, *i); 2147 } 2148 } 2149 } 2150