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