1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This contains code to emit Aggregate Expr nodes as LLVM code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGCXXABI.h" 14 #include "CGObjCRuntime.h" 15 #include "CodeGenFunction.h" 16 #include "CodeGenModule.h" 17 #include "ConstantEmitter.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/StmtVisitor.h" 23 #include "llvm/IR/Constants.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/GlobalVariable.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/Intrinsics.h" 28 using namespace clang; 29 using namespace CodeGen; 30 31 //===----------------------------------------------------------------------===// 32 // Aggregate Expression Emitter 33 //===----------------------------------------------------------------------===// 34 35 namespace { 36 class AggExprEmitter : public StmtVisitor<AggExprEmitter> { 37 CodeGenFunction &CGF; 38 CGBuilderTy &Builder; 39 AggValueSlot Dest; 40 bool IsResultUnused; 41 42 AggValueSlot EnsureSlot(QualType T) { 43 if (!Dest.isIgnored()) return Dest; 44 return CGF.CreateAggTemp(T, "agg.tmp.ensured"); 45 } 46 void EnsureDest(QualType T) { 47 if (!Dest.isIgnored()) return; 48 Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured"); 49 } 50 51 // Calls `Fn` with a valid return value slot, potentially creating a temporary 52 // to do so. If a temporary is created, an appropriate copy into `Dest` will 53 // be emitted, as will lifetime markers. 54 // 55 // The given function should take a ReturnValueSlot, and return an RValue that 56 // points to said slot. 57 void withReturnValueSlot(const Expr *E, 58 llvm::function_ref<RValue(ReturnValueSlot)> Fn); 59 60 public: 61 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused) 62 : CGF(cgf), Builder(CGF.Builder), Dest(Dest), 63 IsResultUnused(IsResultUnused) { } 64 65 //===--------------------------------------------------------------------===// 66 // Utilities 67 //===--------------------------------------------------------------------===// 68 69 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 70 /// represents a value lvalue, this method emits the address of the lvalue, 71 /// then loads the result into DestPtr. 72 void EmitAggLoadOfLValue(const Expr *E); 73 74 enum ExprValueKind { 75 EVK_RValue, 76 EVK_NonRValue 77 }; 78 79 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 80 /// SrcIsRValue is true if source comes from an RValue. 81 void EmitFinalDestCopy(QualType type, const LValue &src, 82 ExprValueKind SrcValueKind = EVK_NonRValue); 83 void EmitFinalDestCopy(QualType type, RValue src); 84 void EmitCopy(QualType type, const AggValueSlot &dest, 85 const AggValueSlot &src); 86 87 void EmitMoveFromReturnSlot(const Expr *E, RValue Src); 88 89 void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, 90 QualType ArrayQTy, InitListExpr *E); 91 92 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) { 93 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T)) 94 return AggValueSlot::NeedsGCBarriers; 95 return AggValueSlot::DoesNotNeedGCBarriers; 96 } 97 98 bool TypeRequiresGCollection(QualType T); 99 100 //===--------------------------------------------------------------------===// 101 // Visitor Methods 102 //===--------------------------------------------------------------------===// 103 104 void Visit(Expr *E) { 105 ApplyDebugLocation DL(CGF, E); 106 StmtVisitor<AggExprEmitter>::Visit(E); 107 } 108 109 void VisitStmt(Stmt *S) { 110 CGF.ErrorUnsupported(S, "aggregate expression"); 111 } 112 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 113 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) { 114 Visit(GE->getResultExpr()); 115 } 116 void VisitCoawaitExpr(CoawaitExpr *E) { 117 CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused); 118 } 119 void VisitCoyieldExpr(CoyieldExpr *E) { 120 CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused); 121 } 122 void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); } 123 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); } 124 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) { 125 return Visit(E->getReplacement()); 126 } 127 128 void VisitConstantExpr(ConstantExpr *E) { 129 return Visit(E->getSubExpr()); 130 } 131 132 // l-values. 133 void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); } 134 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 135 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 136 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 137 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 138 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 139 EmitAggLoadOfLValue(E); 140 } 141 void VisitPredefinedExpr(const PredefinedExpr *E) { 142 EmitAggLoadOfLValue(E); 143 } 144 145 // Operators. 146 void VisitCastExpr(CastExpr *E); 147 void VisitCallExpr(const CallExpr *E); 148 void VisitStmtExpr(const StmtExpr *E); 149 void VisitBinaryOperator(const BinaryOperator *BO); 150 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO); 151 void VisitBinAssign(const BinaryOperator *E); 152 void VisitBinComma(const BinaryOperator *E); 153 void VisitBinCmp(const BinaryOperator *E); 154 void VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) { 155 Visit(E->getSemanticForm()); 156 } 157 158 void VisitObjCMessageExpr(ObjCMessageExpr *E); 159 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 160 EmitAggLoadOfLValue(E); 161 } 162 163 void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E); 164 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO); 165 void VisitChooseExpr(const ChooseExpr *CE); 166 void VisitInitListExpr(InitListExpr *E); 167 void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E, 168 llvm::Value *outerBegin = nullptr); 169 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); 170 void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing. 171 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 172 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE); 173 Visit(DAE->getExpr()); 174 } 175 void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) { 176 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE); 177 Visit(DIE->getExpr()); 178 } 179 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); 180 void VisitCXXConstructExpr(const CXXConstructExpr *E); 181 void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 182 void VisitLambdaExpr(LambdaExpr *E); 183 void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E); 184 void VisitExprWithCleanups(ExprWithCleanups *E); 185 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 186 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); } 187 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E); 188 void VisitOpaqueValueExpr(OpaqueValueExpr *E); 189 190 void VisitPseudoObjectExpr(PseudoObjectExpr *E) { 191 if (E->isGLValue()) { 192 LValue LV = CGF.EmitPseudoObjectLValue(E); 193 return EmitFinalDestCopy(E->getType(), LV); 194 } 195 196 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType())); 197 } 198 199 void VisitVAArgExpr(VAArgExpr *E); 200 201 void EmitInitializationToLValue(Expr *E, LValue Address); 202 void EmitNullInitializationToLValue(LValue Address); 203 // case Expr::ChooseExprClass: 204 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); } 205 void VisitAtomicExpr(AtomicExpr *E) { 206 RValue Res = CGF.EmitAtomicExpr(E); 207 EmitFinalDestCopy(E->getType(), Res); 208 } 209 }; 210 } // end anonymous namespace. 211 212 //===----------------------------------------------------------------------===// 213 // Utilities 214 //===----------------------------------------------------------------------===// 215 216 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 217 /// represents a value lvalue, this method emits the address of the lvalue, 218 /// then loads the result into DestPtr. 219 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 220 LValue LV = CGF.EmitLValue(E); 221 222 // If the type of the l-value is atomic, then do an atomic load. 223 if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) { 224 CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest); 225 return; 226 } 227 228 EmitFinalDestCopy(E->getType(), LV); 229 } 230 231 /// True if the given aggregate type requires special GC API calls. 232 bool AggExprEmitter::TypeRequiresGCollection(QualType T) { 233 // Only record types have members that might require garbage collection. 234 const RecordType *RecordTy = T->getAs<RecordType>(); 235 if (!RecordTy) return false; 236 237 // Don't mess with non-trivial C++ types. 238 RecordDecl *Record = RecordTy->getDecl(); 239 if (isa<CXXRecordDecl>(Record) && 240 (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() || 241 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor())) 242 return false; 243 244 // Check whether the type has an object member. 245 return Record->hasObjectMember(); 246 } 247 248 void AggExprEmitter::withReturnValueSlot( 249 const Expr *E, llvm::function_ref<RValue(ReturnValueSlot)> EmitCall) { 250 QualType RetTy = E->getType(); 251 bool RequiresDestruction = 252 Dest.isIgnored() && 253 RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct; 254 255 // If it makes no observable difference, save a memcpy + temporary. 256 // 257 // We need to always provide our own temporary if destruction is required. 258 // Otherwise, EmitCall will emit its own, notice that it's "unused", and end 259 // its lifetime before we have the chance to emit a proper destructor call. 260 bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() || 261 (RequiresDestruction && !Dest.getAddress().isValid()); 262 263 Address RetAddr = Address::invalid(); 264 Address RetAllocaAddr = Address::invalid(); 265 266 EHScopeStack::stable_iterator LifetimeEndBlock; 267 llvm::Value *LifetimeSizePtr = nullptr; 268 llvm::IntrinsicInst *LifetimeStartInst = nullptr; 269 if (!UseTemp) { 270 RetAddr = Dest.getAddress(); 271 } else { 272 RetAddr = CGF.CreateMemTemp(RetTy, "tmp", &RetAllocaAddr); 273 uint64_t Size = 274 CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy)); 275 LifetimeSizePtr = CGF.EmitLifetimeStart(Size, RetAllocaAddr.getPointer()); 276 if (LifetimeSizePtr) { 277 LifetimeStartInst = 278 cast<llvm::IntrinsicInst>(std::prev(Builder.GetInsertPoint())); 279 assert(LifetimeStartInst->getIntrinsicID() == 280 llvm::Intrinsic::lifetime_start && 281 "Last insertion wasn't a lifetime.start?"); 282 283 CGF.pushFullExprCleanup<CodeGenFunction::CallLifetimeEnd>( 284 NormalEHLifetimeMarker, RetAllocaAddr, LifetimeSizePtr); 285 LifetimeEndBlock = CGF.EHStack.stable_begin(); 286 } 287 } 288 289 RValue Src = 290 EmitCall(ReturnValueSlot(RetAddr, Dest.isVolatile(), IsResultUnused)); 291 292 if (RequiresDestruction) 293 CGF.pushDestroy(RetTy.isDestructedType(), Src.getAggregateAddress(), RetTy); 294 295 if (!UseTemp) 296 return; 297 298 assert(Dest.getPointer() != Src.getAggregatePointer()); 299 EmitFinalDestCopy(E->getType(), Src); 300 301 if (!RequiresDestruction && LifetimeStartInst) { 302 // If there's no dtor to run, the copy was the last use of our temporary. 303 // Since we're not guaranteed to be in an ExprWithCleanups, clean up 304 // eagerly. 305 CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst); 306 CGF.EmitLifetimeEnd(LifetimeSizePtr, RetAllocaAddr.getPointer()); 307 } 308 } 309 310 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 311 void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) { 312 assert(src.isAggregate() && "value must be aggregate value!"); 313 LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type); 314 EmitFinalDestCopy(type, srcLV, EVK_RValue); 315 } 316 317 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 318 void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src, 319 ExprValueKind SrcValueKind) { 320 // If Dest is ignored, then we're evaluating an aggregate expression 321 // in a context that doesn't care about the result. Note that loads 322 // from volatile l-values force the existence of a non-ignored 323 // destination. 324 if (Dest.isIgnored()) 325 return; 326 327 // Copy non-trivial C structs here. 328 LValue DstLV = CGF.MakeAddrLValue( 329 Dest.getAddress(), Dest.isVolatile() ? type.withVolatile() : type); 330 331 if (SrcValueKind == EVK_RValue) { 332 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) { 333 if (Dest.isPotentiallyAliased()) 334 CGF.callCStructMoveAssignmentOperator(DstLV, src); 335 else 336 CGF.callCStructMoveConstructor(DstLV, src); 337 return; 338 } 339 } else { 340 if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) { 341 if (Dest.isPotentiallyAliased()) 342 CGF.callCStructCopyAssignmentOperator(DstLV, src); 343 else 344 CGF.callCStructCopyConstructor(DstLV, src); 345 return; 346 } 347 } 348 349 AggValueSlot srcAgg = AggValueSlot::forLValue( 350 src, CGF, AggValueSlot::IsDestructed, needsGC(type), 351 AggValueSlot::IsAliased, AggValueSlot::MayOverlap); 352 EmitCopy(type, Dest, srcAgg); 353 } 354 355 /// Perform a copy from the source into the destination. 356 /// 357 /// \param type - the type of the aggregate being copied; qualifiers are 358 /// ignored 359 void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest, 360 const AggValueSlot &src) { 361 if (dest.requiresGCollection()) { 362 CharUnits sz = dest.getPreferredSize(CGF.getContext(), type); 363 llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity()); 364 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, 365 dest.getAddress(), 366 src.getAddress(), 367 size); 368 return; 369 } 370 371 // If the result of the assignment is used, copy the LHS there also. 372 // It's volatile if either side is. Use the minimum alignment of 373 // the two sides. 374 LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type); 375 LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type); 376 CGF.EmitAggregateCopy(DestLV, SrcLV, type, dest.mayOverlap(), 377 dest.isVolatile() || src.isVolatile()); 378 } 379 380 /// Emit the initializer for a std::initializer_list initialized with a 381 /// real initializer list. 382 void 383 AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) { 384 // Emit an array containing the elements. The array is externally destructed 385 // if the std::initializer_list object is. 386 ASTContext &Ctx = CGF.getContext(); 387 LValue Array = CGF.EmitLValue(E->getSubExpr()); 388 assert(Array.isSimple() && "initializer_list array not a simple lvalue"); 389 Address ArrayPtr = Array.getAddress(CGF); 390 391 const ConstantArrayType *ArrayType = 392 Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 393 assert(ArrayType && "std::initializer_list constructed from non-array"); 394 395 // FIXME: Perform the checks on the field types in SemaInit. 396 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 397 RecordDecl::field_iterator Field = Record->field_begin(); 398 if (Field == Record->field_end()) { 399 CGF.ErrorUnsupported(E, "weird std::initializer_list"); 400 return; 401 } 402 403 // Start pointer. 404 if (!Field->getType()->isPointerType() || 405 !Ctx.hasSameType(Field->getType()->getPointeeType(), 406 ArrayType->getElementType())) { 407 CGF.ErrorUnsupported(E, "weird std::initializer_list"); 408 return; 409 } 410 411 AggValueSlot Dest = EnsureSlot(E->getType()); 412 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType()); 413 LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field); 414 llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0); 415 llvm::Value *IdxStart[] = { Zero, Zero }; 416 llvm::Value *ArrayStart = 417 Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxStart, "arraystart"); 418 CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start); 419 ++Field; 420 421 if (Field == Record->field_end()) { 422 CGF.ErrorUnsupported(E, "weird std::initializer_list"); 423 return; 424 } 425 426 llvm::Value *Size = Builder.getInt(ArrayType->getSize()); 427 LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field); 428 if (Field->getType()->isPointerType() && 429 Ctx.hasSameType(Field->getType()->getPointeeType(), 430 ArrayType->getElementType())) { 431 // End pointer. 432 llvm::Value *IdxEnd[] = { Zero, Size }; 433 llvm::Value *ArrayEnd = 434 Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxEnd, "arrayend"); 435 CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength); 436 } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) { 437 // Length. 438 CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength); 439 } else { 440 CGF.ErrorUnsupported(E, "weird std::initializer_list"); 441 return; 442 } 443 } 444 445 /// Determine if E is a trivial array filler, that is, one that is 446 /// equivalent to zero-initialization. 447 static bool isTrivialFiller(Expr *E) { 448 if (!E) 449 return true; 450 451 if (isa<ImplicitValueInitExpr>(E)) 452 return true; 453 454 if (auto *ILE = dyn_cast<InitListExpr>(E)) { 455 if (ILE->getNumInits()) 456 return false; 457 return isTrivialFiller(ILE->getArrayFiller()); 458 } 459 460 if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E)) 461 return Cons->getConstructor()->isDefaultConstructor() && 462 Cons->getConstructor()->isTrivial(); 463 464 // FIXME: Are there other cases where we can avoid emitting an initializer? 465 return false; 466 } 467 468 /// Emit initialization of an array from an initializer list. 469 void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, 470 QualType ArrayQTy, InitListExpr *E) { 471 uint64_t NumInitElements = E->getNumInits(); 472 473 uint64_t NumArrayElements = AType->getNumElements(); 474 assert(NumInitElements <= NumArrayElements); 475 476 QualType elementType = 477 CGF.getContext().getAsArrayType(ArrayQTy)->getElementType(); 478 479 // DestPtr is an array*. Construct an elementType* by drilling 480 // down a level. 481 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0); 482 llvm::Value *indices[] = { zero, zero }; 483 llvm::Value *begin = 484 Builder.CreateInBoundsGEP(DestPtr.getPointer(), indices, "arrayinit.begin"); 485 486 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType); 487 CharUnits elementAlign = 488 DestPtr.getAlignment().alignmentOfArrayElement(elementSize); 489 490 // Consider initializing the array by copying from a global. For this to be 491 // more efficient than per-element initialization, the size of the elements 492 // with explicit initializers should be large enough. 493 if (NumInitElements * elementSize.getQuantity() > 16 && 494 elementType.isTriviallyCopyableType(CGF.getContext())) { 495 CodeGen::CodeGenModule &CGM = CGF.CGM; 496 ConstantEmitter Emitter(CGF); 497 LangAS AS = ArrayQTy.getAddressSpace(); 498 if (llvm::Constant *C = Emitter.tryEmitForInitializer(E, AS, ArrayQTy)) { 499 auto GV = new llvm::GlobalVariable( 500 CGM.getModule(), C->getType(), 501 CGM.isTypeConstant(ArrayQTy, /* ExcludeCtorDtor= */ true), 502 llvm::GlobalValue::PrivateLinkage, C, "constinit", 503 /* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal, 504 CGM.getContext().getTargetAddressSpace(AS)); 505 Emitter.finalize(GV); 506 CharUnits Align = CGM.getContext().getTypeAlignInChars(ArrayQTy); 507 GV->setAlignment(Align.getAsAlign()); 508 EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GV, ArrayQTy, Align)); 509 return; 510 } 511 } 512 513 // Exception safety requires us to destroy all the 514 // already-constructed members if an initializer throws. 515 // For that, we'll need an EH cleanup. 516 QualType::DestructionKind dtorKind = elementType.isDestructedType(); 517 Address endOfInit = Address::invalid(); 518 EHScopeStack::stable_iterator cleanup; 519 llvm::Instruction *cleanupDominator = nullptr; 520 if (CGF.needsEHCleanup(dtorKind)) { 521 // In principle we could tell the cleanup where we are more 522 // directly, but the control flow can get so varied here that it 523 // would actually be quite complex. Therefore we go through an 524 // alloca. 525 endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(), 526 "arrayinit.endOfInit"); 527 cleanupDominator = Builder.CreateStore(begin, endOfInit); 528 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType, 529 elementAlign, 530 CGF.getDestroyer(dtorKind)); 531 cleanup = CGF.EHStack.stable_begin(); 532 533 // Otherwise, remember that we didn't need a cleanup. 534 } else { 535 dtorKind = QualType::DK_none; 536 } 537 538 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1); 539 540 // The 'current element to initialize'. The invariants on this 541 // variable are complicated. Essentially, after each iteration of 542 // the loop, it points to the last initialized element, except 543 // that it points to the beginning of the array before any 544 // elements have been initialized. 545 llvm::Value *element = begin; 546 547 // Emit the explicit initializers. 548 for (uint64_t i = 0; i != NumInitElements; ++i) { 549 // Advance to the next element. 550 if (i > 0) { 551 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element"); 552 553 // Tell the cleanup that it needs to destroy up to this 554 // element. TODO: some of these stores can be trivially 555 // observed to be unnecessary. 556 if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit); 557 } 558 559 LValue elementLV = 560 CGF.MakeAddrLValue(Address(element, elementAlign), elementType); 561 EmitInitializationToLValue(E->getInit(i), elementLV); 562 } 563 564 // Check whether there's a non-trivial array-fill expression. 565 Expr *filler = E->getArrayFiller(); 566 bool hasTrivialFiller = isTrivialFiller(filler); 567 568 // Any remaining elements need to be zero-initialized, possibly 569 // using the filler expression. We can skip this if the we're 570 // emitting to zeroed memory. 571 if (NumInitElements != NumArrayElements && 572 !(Dest.isZeroed() && hasTrivialFiller && 573 CGF.getTypes().isZeroInitializable(elementType))) { 574 575 // Use an actual loop. This is basically 576 // do { *array++ = filler; } while (array != end); 577 578 // Advance to the start of the rest of the array. 579 if (NumInitElements) { 580 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start"); 581 if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit); 582 } 583 584 // Compute the end of the array. 585 llvm::Value *end = Builder.CreateInBoundsGEP(begin, 586 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements), 587 "arrayinit.end"); 588 589 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 590 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body"); 591 592 // Jump into the body. 593 CGF.EmitBlock(bodyBB); 594 llvm::PHINode *currentElement = 595 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur"); 596 currentElement->addIncoming(element, entryBB); 597 598 // Emit the actual filler expression. 599 { 600 // C++1z [class.temporary]p5: 601 // when a default constructor is called to initialize an element of 602 // an array with no corresponding initializer [...] the destruction of 603 // every temporary created in a default argument is sequenced before 604 // the construction of the next array element, if any 605 CodeGenFunction::RunCleanupsScope CleanupsScope(CGF); 606 LValue elementLV = 607 CGF.MakeAddrLValue(Address(currentElement, elementAlign), elementType); 608 if (filler) 609 EmitInitializationToLValue(filler, elementLV); 610 else 611 EmitNullInitializationToLValue(elementLV); 612 } 613 614 // Move on to the next element. 615 llvm::Value *nextElement = 616 Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next"); 617 618 // Tell the EH cleanup that we finished with the last element. 619 if (endOfInit.isValid()) Builder.CreateStore(nextElement, endOfInit); 620 621 // Leave the loop if we're done. 622 llvm::Value *done = Builder.CreateICmpEQ(nextElement, end, 623 "arrayinit.done"); 624 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end"); 625 Builder.CreateCondBr(done, endBB, bodyBB); 626 currentElement->addIncoming(nextElement, Builder.GetInsertBlock()); 627 628 CGF.EmitBlock(endBB); 629 } 630 631 // Leave the partial-array cleanup if we entered one. 632 if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator); 633 } 634 635 //===----------------------------------------------------------------------===// 636 // Visitor Methods 637 //===----------------------------------------------------------------------===// 638 639 void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){ 640 Visit(E->getSubExpr()); 641 } 642 643 void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) { 644 // If this is a unique OVE, just visit its source expression. 645 if (e->isUnique()) 646 Visit(e->getSourceExpr()); 647 else 648 EmitFinalDestCopy(e->getType(), CGF.getOrCreateOpaqueLValueMapping(e)); 649 } 650 651 void 652 AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 653 if (Dest.isPotentiallyAliased() && 654 E->getType().isPODType(CGF.getContext())) { 655 // For a POD type, just emit a load of the lvalue + a copy, because our 656 // compound literal might alias the destination. 657 EmitAggLoadOfLValue(E); 658 return; 659 } 660 661 AggValueSlot Slot = EnsureSlot(E->getType()); 662 663 // Block-scope compound literals are destroyed at the end of the enclosing 664 // scope in C. 665 bool Destruct = 666 !CGF.getLangOpts().CPlusPlus && !Slot.isExternallyDestructed(); 667 if (Destruct) 668 Slot.setExternallyDestructed(); 669 670 CGF.EmitAggExpr(E->getInitializer(), Slot); 671 672 if (Destruct) 673 if (QualType::DestructionKind DtorKind = E->getType().isDestructedType()) 674 CGF.pushLifetimeExtendedDestroy( 675 CGF.getCleanupKind(DtorKind), Slot.getAddress(), E->getType(), 676 CGF.getDestroyer(DtorKind), DtorKind & EHCleanup); 677 } 678 679 /// Attempt to look through various unimportant expressions to find a 680 /// cast of the given kind. 681 static Expr *findPeephole(Expr *op, CastKind kind) { 682 while (true) { 683 op = op->IgnoreParens(); 684 if (CastExpr *castE = dyn_cast<CastExpr>(op)) { 685 if (castE->getCastKind() == kind) 686 return castE->getSubExpr(); 687 if (castE->getCastKind() == CK_NoOp) 688 continue; 689 } 690 return nullptr; 691 } 692 } 693 694 void AggExprEmitter::VisitCastExpr(CastExpr *E) { 695 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E)) 696 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF); 697 switch (E->getCastKind()) { 698 case CK_Dynamic: { 699 // FIXME: Can this actually happen? We have no test coverage for it. 700 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?"); 701 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(), 702 CodeGenFunction::TCK_Load); 703 // FIXME: Do we also need to handle property references here? 704 if (LV.isSimple()) 705 CGF.EmitDynamicCast(LV.getAddress(CGF), cast<CXXDynamicCastExpr>(E)); 706 else 707 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast"); 708 709 if (!Dest.isIgnored()) 710 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination"); 711 break; 712 } 713 714 case CK_ToUnion: { 715 // Evaluate even if the destination is ignored. 716 if (Dest.isIgnored()) { 717 CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(), 718 /*ignoreResult=*/true); 719 break; 720 } 721 722 // GCC union extension 723 QualType Ty = E->getSubExpr()->getType(); 724 Address CastPtr = 725 Builder.CreateElementBitCast(Dest.getAddress(), CGF.ConvertType(Ty)); 726 EmitInitializationToLValue(E->getSubExpr(), 727 CGF.MakeAddrLValue(CastPtr, Ty)); 728 break; 729 } 730 731 case CK_LValueToRValueBitCast: { 732 if (Dest.isIgnored()) { 733 CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(), 734 /*ignoreResult=*/true); 735 break; 736 } 737 738 LValue SourceLV = CGF.EmitLValue(E->getSubExpr()); 739 Address SourceAddress = 740 Builder.CreateElementBitCast(SourceLV.getAddress(CGF), CGF.Int8Ty); 741 Address DestAddress = 742 Builder.CreateElementBitCast(Dest.getAddress(), CGF.Int8Ty); 743 llvm::Value *SizeVal = llvm::ConstantInt::get( 744 CGF.SizeTy, 745 CGF.getContext().getTypeSizeInChars(E->getType()).getQuantity()); 746 Builder.CreateMemCpy(DestAddress, SourceAddress, SizeVal); 747 break; 748 } 749 750 case CK_DerivedToBase: 751 case CK_BaseToDerived: 752 case CK_UncheckedDerivedToBase: { 753 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: " 754 "should have been unpacked before we got here"); 755 } 756 757 case CK_NonAtomicToAtomic: 758 case CK_AtomicToNonAtomic: { 759 bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic); 760 761 // Determine the atomic and value types. 762 QualType atomicType = E->getSubExpr()->getType(); 763 QualType valueType = E->getType(); 764 if (isToAtomic) std::swap(atomicType, valueType); 765 766 assert(atomicType->isAtomicType()); 767 assert(CGF.getContext().hasSameUnqualifiedType(valueType, 768 atomicType->castAs<AtomicType>()->getValueType())); 769 770 // Just recurse normally if we're ignoring the result or the 771 // atomic type doesn't change representation. 772 if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) { 773 return Visit(E->getSubExpr()); 774 } 775 776 CastKind peepholeTarget = 777 (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic); 778 779 // These two cases are reverses of each other; try to peephole them. 780 if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) { 781 assert(CGF.getContext().hasSameUnqualifiedType(op->getType(), 782 E->getType()) && 783 "peephole significantly changed types?"); 784 return Visit(op); 785 } 786 787 // If we're converting an r-value of non-atomic type to an r-value 788 // of atomic type, just emit directly into the relevant sub-object. 789 if (isToAtomic) { 790 AggValueSlot valueDest = Dest; 791 if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) { 792 // Zero-initialize. (Strictly speaking, we only need to initialize 793 // the padding at the end, but this is simpler.) 794 if (!Dest.isZeroed()) 795 CGF.EmitNullInitialization(Dest.getAddress(), atomicType); 796 797 // Build a GEP to refer to the subobject. 798 Address valueAddr = 799 CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0); 800 valueDest = AggValueSlot::forAddr(valueAddr, 801 valueDest.getQualifiers(), 802 valueDest.isExternallyDestructed(), 803 valueDest.requiresGCollection(), 804 valueDest.isPotentiallyAliased(), 805 AggValueSlot::DoesNotOverlap, 806 AggValueSlot::IsZeroed); 807 } 808 809 CGF.EmitAggExpr(E->getSubExpr(), valueDest); 810 return; 811 } 812 813 // Otherwise, we're converting an atomic type to a non-atomic type. 814 // Make an atomic temporary, emit into that, and then copy the value out. 815 AggValueSlot atomicSlot = 816 CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp"); 817 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot); 818 819 Address valueAddr = Builder.CreateStructGEP(atomicSlot.getAddress(), 0); 820 RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile()); 821 return EmitFinalDestCopy(valueType, rvalue); 822 } 823 case CK_AddressSpaceConversion: 824 return Visit(E->getSubExpr()); 825 826 case CK_LValueToRValue: 827 // If we're loading from a volatile type, force the destination 828 // into existence. 829 if (E->getSubExpr()->getType().isVolatileQualified()) { 830 EnsureDest(E->getType()); 831 return Visit(E->getSubExpr()); 832 } 833 834 LLVM_FALLTHROUGH; 835 836 837 case CK_NoOp: 838 case CK_UserDefinedConversion: 839 case CK_ConstructorConversion: 840 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(), 841 E->getType()) && 842 "Implicit cast types must be compatible"); 843 Visit(E->getSubExpr()); 844 break; 845 846 case CK_LValueBitCast: 847 llvm_unreachable("should not be emitting lvalue bitcast as rvalue"); 848 849 case CK_Dependent: 850 case CK_BitCast: 851 case CK_ArrayToPointerDecay: 852 case CK_FunctionToPointerDecay: 853 case CK_NullToPointer: 854 case CK_NullToMemberPointer: 855 case CK_BaseToDerivedMemberPointer: 856 case CK_DerivedToBaseMemberPointer: 857 case CK_MemberPointerToBoolean: 858 case CK_ReinterpretMemberPointer: 859 case CK_IntegralToPointer: 860 case CK_PointerToIntegral: 861 case CK_PointerToBoolean: 862 case CK_ToVoid: 863 case CK_VectorSplat: 864 case CK_IntegralCast: 865 case CK_BooleanToSignedIntegral: 866 case CK_IntegralToBoolean: 867 case CK_IntegralToFloating: 868 case CK_FloatingToIntegral: 869 case CK_FloatingToBoolean: 870 case CK_FloatingCast: 871 case CK_CPointerToObjCPointerCast: 872 case CK_BlockPointerToObjCPointerCast: 873 case CK_AnyPointerToBlockPointerCast: 874 case CK_ObjCObjectLValueCast: 875 case CK_FloatingRealToComplex: 876 case CK_FloatingComplexToReal: 877 case CK_FloatingComplexToBoolean: 878 case CK_FloatingComplexCast: 879 case CK_FloatingComplexToIntegralComplex: 880 case CK_IntegralRealToComplex: 881 case CK_IntegralComplexToReal: 882 case CK_IntegralComplexToBoolean: 883 case CK_IntegralComplexCast: 884 case CK_IntegralComplexToFloatingComplex: 885 case CK_ARCProduceObject: 886 case CK_ARCConsumeObject: 887 case CK_ARCReclaimReturnedObject: 888 case CK_ARCExtendBlockObject: 889 case CK_CopyAndAutoreleaseBlockObject: 890 case CK_BuiltinFnToFnPtr: 891 case CK_ZeroToOCLOpaqueType: 892 893 case CK_IntToOCLSampler: 894 case CK_FixedPointCast: 895 case CK_FixedPointToBoolean: 896 case CK_FixedPointToIntegral: 897 case CK_IntegralToFixedPoint: 898 llvm_unreachable("cast kind invalid for aggregate types"); 899 } 900 } 901 902 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 903 if (E->getCallReturnType(CGF.getContext())->isReferenceType()) { 904 EmitAggLoadOfLValue(E); 905 return; 906 } 907 908 withReturnValueSlot(E, [&](ReturnValueSlot Slot) { 909 return CGF.EmitCallExpr(E, Slot); 910 }); 911 } 912 913 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 914 withReturnValueSlot(E, [&](ReturnValueSlot Slot) { 915 return CGF.EmitObjCMessageExpr(E, Slot); 916 }); 917 } 918 919 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 920 CGF.EmitIgnoredExpr(E->getLHS()); 921 Visit(E->getRHS()); 922 } 923 924 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 925 CodeGenFunction::StmtExprEvaluation eval(CGF); 926 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest); 927 } 928 929 enum CompareKind { 930 CK_Less, 931 CK_Greater, 932 CK_Equal, 933 }; 934 935 static llvm::Value *EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF, 936 const BinaryOperator *E, llvm::Value *LHS, 937 llvm::Value *RHS, CompareKind Kind, 938 const char *NameSuffix = "") { 939 QualType ArgTy = E->getLHS()->getType(); 940 if (const ComplexType *CT = ArgTy->getAs<ComplexType>()) 941 ArgTy = CT->getElementType(); 942 943 if (const auto *MPT = ArgTy->getAs<MemberPointerType>()) { 944 assert(Kind == CK_Equal && 945 "member pointers may only be compared for equality"); 946 return CGF.CGM.getCXXABI().EmitMemberPointerComparison( 947 CGF, LHS, RHS, MPT, /*IsInequality*/ false); 948 } 949 950 // Compute the comparison instructions for the specified comparison kind. 951 struct CmpInstInfo { 952 const char *Name; 953 llvm::CmpInst::Predicate FCmp; 954 llvm::CmpInst::Predicate SCmp; 955 llvm::CmpInst::Predicate UCmp; 956 }; 957 CmpInstInfo InstInfo = [&]() -> CmpInstInfo { 958 using FI = llvm::FCmpInst; 959 using II = llvm::ICmpInst; 960 switch (Kind) { 961 case CK_Less: 962 return {"cmp.lt", FI::FCMP_OLT, II::ICMP_SLT, II::ICMP_ULT}; 963 case CK_Greater: 964 return {"cmp.gt", FI::FCMP_OGT, II::ICMP_SGT, II::ICMP_UGT}; 965 case CK_Equal: 966 return {"cmp.eq", FI::FCMP_OEQ, II::ICMP_EQ, II::ICMP_EQ}; 967 } 968 llvm_unreachable("Unrecognised CompareKind enum"); 969 }(); 970 971 if (ArgTy->hasFloatingRepresentation()) 972 return Builder.CreateFCmp(InstInfo.FCmp, LHS, RHS, 973 llvm::Twine(InstInfo.Name) + NameSuffix); 974 if (ArgTy->isIntegralOrEnumerationType() || ArgTy->isPointerType()) { 975 auto Inst = 976 ArgTy->hasSignedIntegerRepresentation() ? InstInfo.SCmp : InstInfo.UCmp; 977 return Builder.CreateICmp(Inst, LHS, RHS, 978 llvm::Twine(InstInfo.Name) + NameSuffix); 979 } 980 981 llvm_unreachable("unsupported aggregate binary expression should have " 982 "already been handled"); 983 } 984 985 void AggExprEmitter::VisitBinCmp(const BinaryOperator *E) { 986 using llvm::BasicBlock; 987 using llvm::PHINode; 988 using llvm::Value; 989 assert(CGF.getContext().hasSameType(E->getLHS()->getType(), 990 E->getRHS()->getType())); 991 const ComparisonCategoryInfo &CmpInfo = 992 CGF.getContext().CompCategories.getInfoForType(E->getType()); 993 assert(CmpInfo.Record->isTriviallyCopyable() && 994 "cannot copy non-trivially copyable aggregate"); 995 996 QualType ArgTy = E->getLHS()->getType(); 997 998 if (!ArgTy->isIntegralOrEnumerationType() && !ArgTy->isRealFloatingType() && 999 !ArgTy->isNullPtrType() && !ArgTy->isPointerType() && 1000 !ArgTy->isMemberPointerType() && !ArgTy->isAnyComplexType()) { 1001 return CGF.ErrorUnsupported(E, "aggregate three-way comparison"); 1002 } 1003 bool IsComplex = ArgTy->isAnyComplexType(); 1004 1005 // Evaluate the operands to the expression and extract their values. 1006 auto EmitOperand = [&](Expr *E) -> std::pair<Value *, Value *> { 1007 RValue RV = CGF.EmitAnyExpr(E); 1008 if (RV.isScalar()) 1009 return {RV.getScalarVal(), nullptr}; 1010 if (RV.isAggregate()) 1011 return {RV.getAggregatePointer(), nullptr}; 1012 assert(RV.isComplex()); 1013 return RV.getComplexVal(); 1014 }; 1015 auto LHSValues = EmitOperand(E->getLHS()), 1016 RHSValues = EmitOperand(E->getRHS()); 1017 1018 auto EmitCmp = [&](CompareKind K) { 1019 Value *Cmp = EmitCompare(Builder, CGF, E, LHSValues.first, RHSValues.first, 1020 K, IsComplex ? ".r" : ""); 1021 if (!IsComplex) 1022 return Cmp; 1023 assert(K == CompareKind::CK_Equal); 1024 Value *CmpImag = EmitCompare(Builder, CGF, E, LHSValues.second, 1025 RHSValues.second, K, ".i"); 1026 return Builder.CreateAnd(Cmp, CmpImag, "and.eq"); 1027 }; 1028 auto EmitCmpRes = [&](const ComparisonCategoryInfo::ValueInfo *VInfo) { 1029 return Builder.getInt(VInfo->getIntValue()); 1030 }; 1031 1032 Value *Select; 1033 if (ArgTy->isNullPtrType()) { 1034 Select = EmitCmpRes(CmpInfo.getEqualOrEquiv()); 1035 } else if (!CmpInfo.isPartial()) { 1036 Value *SelectOne = 1037 Builder.CreateSelect(EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()), 1038 EmitCmpRes(CmpInfo.getGreater()), "sel.lt"); 1039 Select = Builder.CreateSelect(EmitCmp(CK_Equal), 1040 EmitCmpRes(CmpInfo.getEqualOrEquiv()), 1041 SelectOne, "sel.eq"); 1042 } else { 1043 Value *SelectEq = Builder.CreateSelect( 1044 EmitCmp(CK_Equal), EmitCmpRes(CmpInfo.getEqualOrEquiv()), 1045 EmitCmpRes(CmpInfo.getUnordered()), "sel.eq"); 1046 Value *SelectGT = Builder.CreateSelect(EmitCmp(CK_Greater), 1047 EmitCmpRes(CmpInfo.getGreater()), 1048 SelectEq, "sel.gt"); 1049 Select = Builder.CreateSelect( 1050 EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()), SelectGT, "sel.lt"); 1051 } 1052 // Create the return value in the destination slot. 1053 EnsureDest(E->getType()); 1054 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType()); 1055 1056 // Emit the address of the first (and only) field in the comparison category 1057 // type, and initialize it from the constant integer value selected above. 1058 LValue FieldLV = CGF.EmitLValueForFieldInitialization( 1059 DestLV, *CmpInfo.Record->field_begin()); 1060 CGF.EmitStoreThroughLValue(RValue::get(Select), FieldLV, /*IsInit*/ true); 1061 1062 // All done! The result is in the Dest slot. 1063 } 1064 1065 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 1066 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI) 1067 VisitPointerToDataMemberBinaryOperator(E); 1068 else 1069 CGF.ErrorUnsupported(E, "aggregate binary expression"); 1070 } 1071 1072 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator( 1073 const BinaryOperator *E) { 1074 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E); 1075 EmitFinalDestCopy(E->getType(), LV); 1076 } 1077 1078 /// Is the value of the given expression possibly a reference to or 1079 /// into a __block variable? 1080 static bool isBlockVarRef(const Expr *E) { 1081 // Make sure we look through parens. 1082 E = E->IgnoreParens(); 1083 1084 // Check for a direct reference to a __block variable. 1085 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 1086 const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 1087 return (var && var->hasAttr<BlocksAttr>()); 1088 } 1089 1090 // More complicated stuff. 1091 1092 // Binary operators. 1093 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) { 1094 // For an assignment or pointer-to-member operation, just care 1095 // about the LHS. 1096 if (op->isAssignmentOp() || op->isPtrMemOp()) 1097 return isBlockVarRef(op->getLHS()); 1098 1099 // For a comma, just care about the RHS. 1100 if (op->getOpcode() == BO_Comma) 1101 return isBlockVarRef(op->getRHS()); 1102 1103 // FIXME: pointer arithmetic? 1104 return false; 1105 1106 // Check both sides of a conditional operator. 1107 } else if (const AbstractConditionalOperator *op 1108 = dyn_cast<AbstractConditionalOperator>(E)) { 1109 return isBlockVarRef(op->getTrueExpr()) 1110 || isBlockVarRef(op->getFalseExpr()); 1111 1112 // OVEs are required to support BinaryConditionalOperators. 1113 } else if (const OpaqueValueExpr *op 1114 = dyn_cast<OpaqueValueExpr>(E)) { 1115 if (const Expr *src = op->getSourceExpr()) 1116 return isBlockVarRef(src); 1117 1118 // Casts are necessary to get things like (*(int*)&var) = foo(). 1119 // We don't really care about the kind of cast here, except 1120 // we don't want to look through l2r casts, because it's okay 1121 // to get the *value* in a __block variable. 1122 } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) { 1123 if (cast->getCastKind() == CK_LValueToRValue) 1124 return false; 1125 return isBlockVarRef(cast->getSubExpr()); 1126 1127 // Handle unary operators. Again, just aggressively look through 1128 // it, ignoring the operation. 1129 } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) { 1130 return isBlockVarRef(uop->getSubExpr()); 1131 1132 // Look into the base of a field access. 1133 } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 1134 return isBlockVarRef(mem->getBase()); 1135 1136 // Look into the base of a subscript. 1137 } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) { 1138 return isBlockVarRef(sub->getBase()); 1139 } 1140 1141 return false; 1142 } 1143 1144 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 1145 // For an assignment to work, the value on the right has 1146 // to be compatible with the value on the left. 1147 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(), 1148 E->getRHS()->getType()) 1149 && "Invalid assignment"); 1150 1151 // If the LHS might be a __block variable, and the RHS can 1152 // potentially cause a block copy, we need to evaluate the RHS first 1153 // so that the assignment goes the right place. 1154 // This is pretty semantically fragile. 1155 if (isBlockVarRef(E->getLHS()) && 1156 E->getRHS()->HasSideEffects(CGF.getContext())) { 1157 // Ensure that we have a destination, and evaluate the RHS into that. 1158 EnsureDest(E->getRHS()->getType()); 1159 Visit(E->getRHS()); 1160 1161 // Now emit the LHS and copy into it. 1162 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 1163 1164 // That copy is an atomic copy if the LHS is atomic. 1165 if (LHS.getType()->isAtomicType() || 1166 CGF.LValueIsSuitableForInlineAtomic(LHS)) { 1167 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false); 1168 return; 1169 } 1170 1171 EmitCopy(E->getLHS()->getType(), 1172 AggValueSlot::forLValue(LHS, CGF, AggValueSlot::IsDestructed, 1173 needsGC(E->getLHS()->getType()), 1174 AggValueSlot::IsAliased, 1175 AggValueSlot::MayOverlap), 1176 Dest); 1177 return; 1178 } 1179 1180 LValue LHS = CGF.EmitLValue(E->getLHS()); 1181 1182 // If we have an atomic type, evaluate into the destination and then 1183 // do an atomic copy. 1184 if (LHS.getType()->isAtomicType() || 1185 CGF.LValueIsSuitableForInlineAtomic(LHS)) { 1186 EnsureDest(E->getRHS()->getType()); 1187 Visit(E->getRHS()); 1188 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false); 1189 return; 1190 } 1191 1192 // Codegen the RHS so that it stores directly into the LHS. 1193 AggValueSlot LHSSlot = AggValueSlot::forLValue( 1194 LHS, CGF, AggValueSlot::IsDestructed, needsGC(E->getLHS()->getType()), 1195 AggValueSlot::IsAliased, AggValueSlot::MayOverlap); 1196 // A non-volatile aggregate destination might have volatile member. 1197 if (!LHSSlot.isVolatile() && 1198 CGF.hasVolatileMember(E->getLHS()->getType())) 1199 LHSSlot.setVolatile(true); 1200 1201 CGF.EmitAggExpr(E->getRHS(), LHSSlot); 1202 1203 // Copy into the destination if the assignment isn't ignored. 1204 EmitFinalDestCopy(E->getType(), LHS); 1205 } 1206 1207 void AggExprEmitter:: 1208 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 1209 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 1210 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 1211 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 1212 1213 // Bind the common expression if necessary. 1214 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 1215 1216 CodeGenFunction::ConditionalEvaluation eval(CGF); 1217 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock, 1218 CGF.getProfileCount(E)); 1219 1220 // Save whether the destination's lifetime is externally managed. 1221 bool isExternallyDestructed = Dest.isExternallyDestructed(); 1222 1223 eval.begin(CGF); 1224 CGF.EmitBlock(LHSBlock); 1225 CGF.incrementProfileCounter(E); 1226 Visit(E->getTrueExpr()); 1227 eval.end(CGF); 1228 1229 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!"); 1230 CGF.Builder.CreateBr(ContBlock); 1231 1232 // If the result of an agg expression is unused, then the emission 1233 // of the LHS might need to create a destination slot. That's fine 1234 // with us, and we can safely emit the RHS into the same slot, but 1235 // we shouldn't claim that it's already being destructed. 1236 Dest.setExternallyDestructed(isExternallyDestructed); 1237 1238 eval.begin(CGF); 1239 CGF.EmitBlock(RHSBlock); 1240 Visit(E->getFalseExpr()); 1241 eval.end(CGF); 1242 1243 CGF.EmitBlock(ContBlock); 1244 } 1245 1246 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 1247 Visit(CE->getChosenSubExpr()); 1248 } 1249 1250 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 1251 Address ArgValue = Address::invalid(); 1252 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue); 1253 1254 // If EmitVAArg fails, emit an error. 1255 if (!ArgPtr.isValid()) { 1256 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 1257 return; 1258 } 1259 1260 EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType())); 1261 } 1262 1263 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 1264 // Ensure that we have a slot, but if we already do, remember 1265 // whether it was externally destructed. 1266 bool wasExternallyDestructed = Dest.isExternallyDestructed(); 1267 EnsureDest(E->getType()); 1268 1269 // We're going to push a destructor if there isn't already one. 1270 Dest.setExternallyDestructed(); 1271 1272 Visit(E->getSubExpr()); 1273 1274 // Push that destructor we promised. 1275 if (!wasExternallyDestructed) 1276 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress()); 1277 } 1278 1279 void 1280 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 1281 AggValueSlot Slot = EnsureSlot(E->getType()); 1282 CGF.EmitCXXConstructExpr(E, Slot); 1283 } 1284 1285 void AggExprEmitter::VisitCXXInheritedCtorInitExpr( 1286 const CXXInheritedCtorInitExpr *E) { 1287 AggValueSlot Slot = EnsureSlot(E->getType()); 1288 CGF.EmitInheritedCXXConstructorCall( 1289 E->getConstructor(), E->constructsVBase(), Slot.getAddress(), 1290 E->inheritedFromVBase(), E); 1291 } 1292 1293 void 1294 AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) { 1295 AggValueSlot Slot = EnsureSlot(E->getType()); 1296 LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType()); 1297 1298 // We'll need to enter cleanup scopes in case any of the element 1299 // initializers throws an exception. 1300 SmallVector<EHScopeStack::stable_iterator, 16> Cleanups; 1301 llvm::Instruction *CleanupDominator = nullptr; 1302 1303 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin(); 1304 for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(), 1305 e = E->capture_init_end(); 1306 i != e; ++i, ++CurField) { 1307 // Emit initialization 1308 LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField); 1309 if (CurField->hasCapturedVLAType()) { 1310 CGF.EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV); 1311 continue; 1312 } 1313 1314 EmitInitializationToLValue(*i, LV); 1315 1316 // Push a destructor if necessary. 1317 if (QualType::DestructionKind DtorKind = 1318 CurField->getType().isDestructedType()) { 1319 assert(LV.isSimple()); 1320 if (CGF.needsEHCleanup(DtorKind)) { 1321 if (!CleanupDominator) 1322 CleanupDominator = CGF.Builder.CreateAlignedLoad( 1323 CGF.Int8Ty, 1324 llvm::Constant::getNullValue(CGF.Int8PtrTy), 1325 CharUnits::One()); // placeholder 1326 1327 CGF.pushDestroy(EHCleanup, LV.getAddress(CGF), CurField->getType(), 1328 CGF.getDestroyer(DtorKind), false); 1329 Cleanups.push_back(CGF.EHStack.stable_begin()); 1330 } 1331 } 1332 } 1333 1334 // Deactivate all the partial cleanups in reverse order, which 1335 // generally means popping them. 1336 for (unsigned i = Cleanups.size(); i != 0; --i) 1337 CGF.DeactivateCleanupBlock(Cleanups[i-1], CleanupDominator); 1338 1339 // Destroy the placeholder if we made one. 1340 if (CleanupDominator) 1341 CleanupDominator->eraseFromParent(); 1342 } 1343 1344 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) { 1345 CGF.enterFullExpression(E); 1346 CodeGenFunction::RunCleanupsScope cleanups(CGF); 1347 Visit(E->getSubExpr()); 1348 } 1349 1350 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 1351 QualType T = E->getType(); 1352 AggValueSlot Slot = EnsureSlot(T); 1353 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T)); 1354 } 1355 1356 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 1357 QualType T = E->getType(); 1358 AggValueSlot Slot = EnsureSlot(T); 1359 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T)); 1360 } 1361 1362 /// isSimpleZero - If emitting this value will obviously just cause a store of 1363 /// zero to memory, return true. This can return false if uncertain, so it just 1364 /// handles simple cases. 1365 static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) { 1366 E = E->IgnoreParens(); 1367 1368 // 0 1369 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) 1370 return IL->getValue() == 0; 1371 // +0.0 1372 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) 1373 return FL->getValue().isPosZero(); 1374 // int() 1375 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) && 1376 CGF.getTypes().isZeroInitializable(E->getType())) 1377 return true; 1378 // (int*)0 - Null pointer expressions. 1379 if (const CastExpr *ICE = dyn_cast<CastExpr>(E)) 1380 return ICE->getCastKind() == CK_NullToPointer && 1381 CGF.getTypes().isPointerZeroInitializable(E->getType()) && 1382 !E->HasSideEffects(CGF.getContext()); 1383 // '\0' 1384 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) 1385 return CL->getValue() == 0; 1386 1387 // Otherwise, hard case: conservatively return false. 1388 return false; 1389 } 1390 1391 1392 void 1393 AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) { 1394 QualType type = LV.getType(); 1395 // FIXME: Ignore result? 1396 // FIXME: Are initializers affected by volatile? 1397 if (Dest.isZeroed() && isSimpleZero(E, CGF)) { 1398 // Storing "i32 0" to a zero'd memory location is a noop. 1399 return; 1400 } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) { 1401 return EmitNullInitializationToLValue(LV); 1402 } else if (isa<NoInitExpr>(E)) { 1403 // Do nothing. 1404 return; 1405 } else if (type->isReferenceType()) { 1406 RValue RV = CGF.EmitReferenceBindingToExpr(E); 1407 return CGF.EmitStoreThroughLValue(RV, LV); 1408 } 1409 1410 switch (CGF.getEvaluationKind(type)) { 1411 case TEK_Complex: 1412 CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true); 1413 return; 1414 case TEK_Aggregate: 1415 CGF.EmitAggExpr( 1416 E, AggValueSlot::forLValue(LV, CGF, AggValueSlot::IsDestructed, 1417 AggValueSlot::DoesNotNeedGCBarriers, 1418 AggValueSlot::IsNotAliased, 1419 AggValueSlot::MayOverlap, Dest.isZeroed())); 1420 return; 1421 case TEK_Scalar: 1422 if (LV.isSimple()) { 1423 CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false); 1424 } else { 1425 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV); 1426 } 1427 return; 1428 } 1429 llvm_unreachable("bad evaluation kind"); 1430 } 1431 1432 void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) { 1433 QualType type = lv.getType(); 1434 1435 // If the destination slot is already zeroed out before the aggregate is 1436 // copied into it, we don't have to emit any zeros here. 1437 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type)) 1438 return; 1439 1440 if (CGF.hasScalarEvaluationKind(type)) { 1441 // For non-aggregates, we can store the appropriate null constant. 1442 llvm::Value *null = CGF.CGM.EmitNullConstant(type); 1443 // Note that the following is not equivalent to 1444 // EmitStoreThroughBitfieldLValue for ARC types. 1445 if (lv.isBitField()) { 1446 CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv); 1447 } else { 1448 assert(lv.isSimple()); 1449 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true); 1450 } 1451 } else { 1452 // There's a potential optimization opportunity in combining 1453 // memsets; that would be easy for arrays, but relatively 1454 // difficult for structures with the current code. 1455 CGF.EmitNullInitialization(lv.getAddress(CGF), lv.getType()); 1456 } 1457 } 1458 1459 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 1460 #if 0 1461 // FIXME: Assess perf here? Figure out what cases are worth optimizing here 1462 // (Length of globals? Chunks of zeroed-out space?). 1463 // 1464 // If we can, prefer a copy from a global; this is a lot less code for long 1465 // globals, and it's easier for the current optimizers to analyze. 1466 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) { 1467 llvm::GlobalVariable* GV = 1468 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true, 1469 llvm::GlobalValue::InternalLinkage, C, ""); 1470 EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType())); 1471 return; 1472 } 1473 #endif 1474 if (E->hadArrayRangeDesignator()) 1475 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 1476 1477 if (E->isTransparent()) 1478 return Visit(E->getInit(0)); 1479 1480 AggValueSlot Dest = EnsureSlot(E->getType()); 1481 1482 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType()); 1483 1484 // Handle initialization of an array. 1485 if (E->getType()->isArrayType()) { 1486 auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType()); 1487 EmitArrayInit(Dest.getAddress(), AType, E->getType(), E); 1488 return; 1489 } 1490 1491 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 1492 1493 // Do struct initialization; this code just sets each individual member 1494 // to the approprate value. This makes bitfield support automatic; 1495 // the disadvantage is that the generated code is more difficult for 1496 // the optimizer, especially with bitfields. 1497 unsigned NumInitElements = E->getNumInits(); 1498 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl(); 1499 1500 // We'll need to enter cleanup scopes in case any of the element 1501 // initializers throws an exception. 1502 SmallVector<EHScopeStack::stable_iterator, 16> cleanups; 1503 llvm::Instruction *cleanupDominator = nullptr; 1504 auto addCleanup = [&](const EHScopeStack::stable_iterator &cleanup) { 1505 cleanups.push_back(cleanup); 1506 if (!cleanupDominator) // create placeholder once needed 1507 cleanupDominator = CGF.Builder.CreateAlignedLoad( 1508 CGF.Int8Ty, llvm::Constant::getNullValue(CGF.Int8PtrTy), 1509 CharUnits::One()); 1510 }; 1511 1512 unsigned curInitIndex = 0; 1513 1514 // Emit initialization of base classes. 1515 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) { 1516 assert(E->getNumInits() >= CXXRD->getNumBases() && 1517 "missing initializer for base class"); 1518 for (auto &Base : CXXRD->bases()) { 1519 assert(!Base.isVirtual() && "should not see vbases here"); 1520 auto *BaseRD = Base.getType()->getAsCXXRecordDecl(); 1521 Address V = CGF.GetAddressOfDirectBaseInCompleteClass( 1522 Dest.getAddress(), CXXRD, BaseRD, 1523 /*isBaseVirtual*/ false); 1524 AggValueSlot AggSlot = AggValueSlot::forAddr( 1525 V, Qualifiers(), 1526 AggValueSlot::IsDestructed, 1527 AggValueSlot::DoesNotNeedGCBarriers, 1528 AggValueSlot::IsNotAliased, 1529 CGF.getOverlapForBaseInit(CXXRD, BaseRD, Base.isVirtual())); 1530 CGF.EmitAggExpr(E->getInit(curInitIndex++), AggSlot); 1531 1532 if (QualType::DestructionKind dtorKind = 1533 Base.getType().isDestructedType()) { 1534 CGF.pushDestroy(dtorKind, V, Base.getType()); 1535 addCleanup(CGF.EHStack.stable_begin()); 1536 } 1537 } 1538 } 1539 1540 // Prepare a 'this' for CXXDefaultInitExprs. 1541 CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress()); 1542 1543 if (record->isUnion()) { 1544 // Only initialize one field of a union. The field itself is 1545 // specified by the initializer list. 1546 if (!E->getInitializedFieldInUnion()) { 1547 // Empty union; we have nothing to do. 1548 1549 #ifndef NDEBUG 1550 // Make sure that it's really an empty and not a failure of 1551 // semantic analysis. 1552 for (const auto *Field : record->fields()) 1553 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 1554 #endif 1555 return; 1556 } 1557 1558 // FIXME: volatility 1559 FieldDecl *Field = E->getInitializedFieldInUnion(); 1560 1561 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field); 1562 if (NumInitElements) { 1563 // Store the initializer into the field 1564 EmitInitializationToLValue(E->getInit(0), FieldLoc); 1565 } else { 1566 // Default-initialize to null. 1567 EmitNullInitializationToLValue(FieldLoc); 1568 } 1569 1570 return; 1571 } 1572 1573 // Here we iterate over the fields; this makes it simpler to both 1574 // default-initialize fields and skip over unnamed fields. 1575 for (const auto *field : record->fields()) { 1576 // We're done once we hit the flexible array member. 1577 if (field->getType()->isIncompleteArrayType()) 1578 break; 1579 1580 // Always skip anonymous bitfields. 1581 if (field->isUnnamedBitfield()) 1582 continue; 1583 1584 // We're done if we reach the end of the explicit initializers, we 1585 // have a zeroed object, and the rest of the fields are 1586 // zero-initializable. 1587 if (curInitIndex == NumInitElements && Dest.isZeroed() && 1588 CGF.getTypes().isZeroInitializable(E->getType())) 1589 break; 1590 1591 1592 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field); 1593 // We never generate write-barries for initialized fields. 1594 LV.setNonGC(true); 1595 1596 if (curInitIndex < NumInitElements) { 1597 // Store the initializer into the field. 1598 EmitInitializationToLValue(E->getInit(curInitIndex++), LV); 1599 } else { 1600 // We're out of initializers; default-initialize to null 1601 EmitNullInitializationToLValue(LV); 1602 } 1603 1604 // Push a destructor if necessary. 1605 // FIXME: if we have an array of structures, all explicitly 1606 // initialized, we can end up pushing a linear number of cleanups. 1607 bool pushedCleanup = false; 1608 if (QualType::DestructionKind dtorKind 1609 = field->getType().isDestructedType()) { 1610 assert(LV.isSimple()); 1611 if (CGF.needsEHCleanup(dtorKind)) { 1612 CGF.pushDestroy(EHCleanup, LV.getAddress(CGF), field->getType(), 1613 CGF.getDestroyer(dtorKind), false); 1614 addCleanup(CGF.EHStack.stable_begin()); 1615 pushedCleanup = true; 1616 } 1617 } 1618 1619 // If the GEP didn't get used because of a dead zero init or something 1620 // else, clean it up for -O0 builds and general tidiness. 1621 if (!pushedCleanup && LV.isSimple()) 1622 if (llvm::GetElementPtrInst *GEP = 1623 dyn_cast<llvm::GetElementPtrInst>(LV.getPointer(CGF))) 1624 if (GEP->use_empty()) 1625 GEP->eraseFromParent(); 1626 } 1627 1628 // Deactivate all the partial cleanups in reverse order, which 1629 // generally means popping them. 1630 assert((cleanupDominator || cleanups.empty()) && 1631 "Missing cleanupDominator before deactivating cleanup blocks"); 1632 for (unsigned i = cleanups.size(); i != 0; --i) 1633 CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator); 1634 1635 // Destroy the placeholder if we made one. 1636 if (cleanupDominator) 1637 cleanupDominator->eraseFromParent(); 1638 } 1639 1640 void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E, 1641 llvm::Value *outerBegin) { 1642 // Emit the common subexpression. 1643 CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr()); 1644 1645 Address destPtr = EnsureSlot(E->getType()).getAddress(); 1646 uint64_t numElements = E->getArraySize().getZExtValue(); 1647 1648 if (!numElements) 1649 return; 1650 1651 // destPtr is an array*. Construct an elementType* by drilling down a level. 1652 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0); 1653 llvm::Value *indices[] = {zero, zero}; 1654 llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getPointer(), indices, 1655 "arrayinit.begin"); 1656 1657 // Prepare to special-case multidimensional array initialization: we avoid 1658 // emitting multiple destructor loops in that case. 1659 if (!outerBegin) 1660 outerBegin = begin; 1661 ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr()); 1662 1663 QualType elementType = 1664 CGF.getContext().getAsArrayType(E->getType())->getElementType(); 1665 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType); 1666 CharUnits elementAlign = 1667 destPtr.getAlignment().alignmentOfArrayElement(elementSize); 1668 1669 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1670 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body"); 1671 1672 // Jump into the body. 1673 CGF.EmitBlock(bodyBB); 1674 llvm::PHINode *index = 1675 Builder.CreatePHI(zero->getType(), 2, "arrayinit.index"); 1676 index->addIncoming(zero, entryBB); 1677 llvm::Value *element = Builder.CreateInBoundsGEP(begin, index); 1678 1679 // Prepare for a cleanup. 1680 QualType::DestructionKind dtorKind = elementType.isDestructedType(); 1681 EHScopeStack::stable_iterator cleanup; 1682 if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) { 1683 if (outerBegin->getType() != element->getType()) 1684 outerBegin = Builder.CreateBitCast(outerBegin, element->getType()); 1685 CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType, 1686 elementAlign, 1687 CGF.getDestroyer(dtorKind)); 1688 cleanup = CGF.EHStack.stable_begin(); 1689 } else { 1690 dtorKind = QualType::DK_none; 1691 } 1692 1693 // Emit the actual filler expression. 1694 { 1695 // Temporaries created in an array initialization loop are destroyed 1696 // at the end of each iteration. 1697 CodeGenFunction::RunCleanupsScope CleanupsScope(CGF); 1698 CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index); 1699 LValue elementLV = 1700 CGF.MakeAddrLValue(Address(element, elementAlign), elementType); 1701 1702 if (InnerLoop) { 1703 // If the subexpression is an ArrayInitLoopExpr, share its cleanup. 1704 auto elementSlot = AggValueSlot::forLValue( 1705 elementLV, CGF, AggValueSlot::IsDestructed, 1706 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased, 1707 AggValueSlot::DoesNotOverlap); 1708 AggExprEmitter(CGF, elementSlot, false) 1709 .VisitArrayInitLoopExpr(InnerLoop, outerBegin); 1710 } else 1711 EmitInitializationToLValue(E->getSubExpr(), elementLV); 1712 } 1713 1714 // Move on to the next element. 1715 llvm::Value *nextIndex = Builder.CreateNUWAdd( 1716 index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next"); 1717 index->addIncoming(nextIndex, Builder.GetInsertBlock()); 1718 1719 // Leave the loop if we're done. 1720 llvm::Value *done = Builder.CreateICmpEQ( 1721 nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements), 1722 "arrayinit.done"); 1723 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end"); 1724 Builder.CreateCondBr(done, endBB, bodyBB); 1725 1726 CGF.EmitBlock(endBB); 1727 1728 // Leave the partial-array cleanup if we entered one. 1729 if (dtorKind) 1730 CGF.DeactivateCleanupBlock(cleanup, index); 1731 } 1732 1733 void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) { 1734 AggValueSlot Dest = EnsureSlot(E->getType()); 1735 1736 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType()); 1737 EmitInitializationToLValue(E->getBase(), DestLV); 1738 VisitInitListExpr(E->getUpdater()); 1739 } 1740 1741 //===----------------------------------------------------------------------===// 1742 // Entry Points into this File 1743 //===----------------------------------------------------------------------===// 1744 1745 /// GetNumNonZeroBytesInInit - Get an approximate count of the number of 1746 /// non-zero bytes that will be stored when outputting the initializer for the 1747 /// specified initializer expression. 1748 static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { 1749 E = E->IgnoreParens(); 1750 1751 // 0 and 0.0 won't require any non-zero stores! 1752 if (isSimpleZero(E, CGF)) return CharUnits::Zero(); 1753 1754 // If this is an initlist expr, sum up the size of sizes of the (present) 1755 // elements. If this is something weird, assume the whole thing is non-zero. 1756 const InitListExpr *ILE = dyn_cast<InitListExpr>(E); 1757 while (ILE && ILE->isTransparent()) 1758 ILE = dyn_cast<InitListExpr>(ILE->getInit(0)); 1759 if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType())) 1760 return CGF.getContext().getTypeSizeInChars(E->getType()); 1761 1762 // InitListExprs for structs have to be handled carefully. If there are 1763 // reference members, we need to consider the size of the reference, not the 1764 // referencee. InitListExprs for unions and arrays can't have references. 1765 if (const RecordType *RT = E->getType()->getAs<RecordType>()) { 1766 if (!RT->isUnionType()) { 1767 RecordDecl *SD = RT->getDecl(); 1768 CharUnits NumNonZeroBytes = CharUnits::Zero(); 1769 1770 unsigned ILEElement = 0; 1771 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD)) 1772 while (ILEElement != CXXRD->getNumBases()) 1773 NumNonZeroBytes += 1774 GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF); 1775 for (const auto *Field : SD->fields()) { 1776 // We're done once we hit the flexible array member or run out of 1777 // InitListExpr elements. 1778 if (Field->getType()->isIncompleteArrayType() || 1779 ILEElement == ILE->getNumInits()) 1780 break; 1781 if (Field->isUnnamedBitfield()) 1782 continue; 1783 1784 const Expr *E = ILE->getInit(ILEElement++); 1785 1786 // Reference values are always non-null and have the width of a pointer. 1787 if (Field->getType()->isReferenceType()) 1788 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits( 1789 CGF.getTarget().getPointerWidth(0)); 1790 else 1791 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF); 1792 } 1793 1794 return NumNonZeroBytes; 1795 } 1796 } 1797 1798 1799 CharUnits NumNonZeroBytes = CharUnits::Zero(); 1800 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) 1801 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF); 1802 return NumNonZeroBytes; 1803 } 1804 1805 /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of 1806 /// zeros in it, emit a memset and avoid storing the individual zeros. 1807 /// 1808 static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E, 1809 CodeGenFunction &CGF) { 1810 // If the slot is already known to be zeroed, nothing to do. Don't mess with 1811 // volatile stores. 1812 if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid()) 1813 return; 1814 1815 // C++ objects with a user-declared constructor don't need zero'ing. 1816 if (CGF.getLangOpts().CPlusPlus) 1817 if (const RecordType *RT = CGF.getContext() 1818 .getBaseElementType(E->getType())->getAs<RecordType>()) { 1819 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1820 if (RD->hasUserDeclaredConstructor()) 1821 return; 1822 } 1823 1824 // If the type is 16-bytes or smaller, prefer individual stores over memset. 1825 CharUnits Size = Slot.getPreferredSize(CGF.getContext(), E->getType()); 1826 if (Size <= CharUnits::fromQuantity(16)) 1827 return; 1828 1829 // Check to see if over 3/4 of the initializer are known to be zero. If so, 1830 // we prefer to emit memset + individual stores for the rest. 1831 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF); 1832 if (NumNonZeroBytes*4 > Size) 1833 return; 1834 1835 // Okay, it seems like a good idea to use an initial memset, emit the call. 1836 llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity()); 1837 1838 Address Loc = Slot.getAddress(); 1839 Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty); 1840 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false); 1841 1842 // Tell the AggExprEmitter that the slot is known zero. 1843 Slot.setZeroed(); 1844 } 1845 1846 1847 1848 1849 /// EmitAggExpr - Emit the computation of the specified expression of aggregate 1850 /// type. The result is computed into DestPtr. Note that if DestPtr is null, 1851 /// the value of the aggregate expression is not needed. If VolatileDest is 1852 /// true, DestPtr cannot be 0. 1853 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) { 1854 assert(E && hasAggregateEvaluationKind(E->getType()) && 1855 "Invalid aggregate expression to emit"); 1856 assert((Slot.getAddress().isValid() || Slot.isIgnored()) && 1857 "slot has bits but no address"); 1858 1859 // Optimize the slot if possible. 1860 CheckAggExprForMemSetUse(Slot, E, *this); 1861 1862 AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E)); 1863 } 1864 1865 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) { 1866 assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!"); 1867 Address Temp = CreateMemTemp(E->getType()); 1868 LValue LV = MakeAddrLValue(Temp, E->getType()); 1869 EmitAggExpr(E, AggValueSlot::forLValue( 1870 LV, *this, AggValueSlot::IsNotDestructed, 1871 AggValueSlot::DoesNotNeedGCBarriers, 1872 AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap)); 1873 return LV; 1874 } 1875 1876 AggValueSlot::Overlap_t 1877 CodeGenFunction::getOverlapForFieldInit(const FieldDecl *FD) { 1878 if (!FD->hasAttr<NoUniqueAddressAttr>() || !FD->getType()->isRecordType()) 1879 return AggValueSlot::DoesNotOverlap; 1880 1881 // If the field lies entirely within the enclosing class's nvsize, its tail 1882 // padding cannot overlap any already-initialized object. (The only subobjects 1883 // with greater addresses that might already be initialized are vbases.) 1884 const RecordDecl *ClassRD = FD->getParent(); 1885 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassRD); 1886 if (Layout.getFieldOffset(FD->getFieldIndex()) + 1887 getContext().getTypeSize(FD->getType()) <= 1888 (uint64_t)getContext().toBits(Layout.getNonVirtualSize())) 1889 return AggValueSlot::DoesNotOverlap; 1890 1891 // The tail padding may contain values we need to preserve. 1892 return AggValueSlot::MayOverlap; 1893 } 1894 1895 AggValueSlot::Overlap_t CodeGenFunction::getOverlapForBaseInit( 1896 const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual) { 1897 // If the most-derived object is a field declared with [[no_unique_address]], 1898 // the tail padding of any virtual base could be reused for other subobjects 1899 // of that field's class. 1900 if (IsVirtual) 1901 return AggValueSlot::MayOverlap; 1902 1903 // If the base class is laid out entirely within the nvsize of the derived 1904 // class, its tail padding cannot yet be initialized, so we can issue 1905 // stores at the full width of the base class. 1906 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 1907 if (Layout.getBaseClassOffset(BaseRD) + 1908 getContext().getASTRecordLayout(BaseRD).getSize() <= 1909 Layout.getNonVirtualSize()) 1910 return AggValueSlot::DoesNotOverlap; 1911 1912 // The tail padding may contain values we need to preserve. 1913 return AggValueSlot::MayOverlap; 1914 } 1915 1916 void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty, 1917 AggValueSlot::Overlap_t MayOverlap, 1918 bool isVolatile) { 1919 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 1920 1921 Address DestPtr = Dest.getAddress(*this); 1922 Address SrcPtr = Src.getAddress(*this); 1923 1924 if (getLangOpts().CPlusPlus) { 1925 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1926 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 1927 assert((Record->hasTrivialCopyConstructor() || 1928 Record->hasTrivialCopyAssignment() || 1929 Record->hasTrivialMoveConstructor() || 1930 Record->hasTrivialMoveAssignment() || 1931 Record->isUnion()) && 1932 "Trying to aggregate-copy a type without a trivial copy/move " 1933 "constructor or assignment operator"); 1934 // Ignore empty classes in C++. 1935 if (Record->isEmpty()) 1936 return; 1937 } 1938 } 1939 1940 // Aggregate assignment turns into llvm.memcpy. This is almost valid per 1941 // C99 6.5.16.1p3, which states "If the value being stored in an object is 1942 // read from another object that overlaps in anyway the storage of the first 1943 // object, then the overlap shall be exact and the two objects shall have 1944 // qualified or unqualified versions of a compatible type." 1945 // 1946 // memcpy is not defined if the source and destination pointers are exactly 1947 // equal, but other compilers do this optimization, and almost every memcpy 1948 // implementation handles this case safely. If there is a libc that does not 1949 // safely handle this, we can add a target hook. 1950 1951 // Get data size info for this aggregate. Don't copy the tail padding if this 1952 // might be a potentially-overlapping subobject, since the tail padding might 1953 // be occupied by a different object. Otherwise, copying it is fine. 1954 std::pair<CharUnits, CharUnits> TypeInfo; 1955 if (MayOverlap) 1956 TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty); 1957 else 1958 TypeInfo = getContext().getTypeInfoInChars(Ty); 1959 1960 llvm::Value *SizeVal = nullptr; 1961 if (TypeInfo.first.isZero()) { 1962 // But note that getTypeInfo returns 0 for a VLA. 1963 if (auto *VAT = dyn_cast_or_null<VariableArrayType>( 1964 getContext().getAsArrayType(Ty))) { 1965 QualType BaseEltTy; 1966 SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr); 1967 TypeInfo = getContext().getTypeInfoInChars(BaseEltTy); 1968 assert(!TypeInfo.first.isZero()); 1969 SizeVal = Builder.CreateNUWMul( 1970 SizeVal, 1971 llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity())); 1972 } 1973 } 1974 if (!SizeVal) { 1975 SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()); 1976 } 1977 1978 // FIXME: If we have a volatile struct, the optimizer can remove what might 1979 // appear to be `extra' memory ops: 1980 // 1981 // volatile struct { int i; } a, b; 1982 // 1983 // int main() { 1984 // a = b; 1985 // a = b; 1986 // } 1987 // 1988 // we need to use a different call here. We use isVolatile to indicate when 1989 // either the source or the destination is volatile. 1990 1991 DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty); 1992 SrcPtr = Builder.CreateElementBitCast(SrcPtr, Int8Ty); 1993 1994 // Don't do any of the memmove_collectable tests if GC isn't set. 1995 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) { 1996 // fall through 1997 } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 1998 RecordDecl *Record = RecordTy->getDecl(); 1999 if (Record->hasObjectMember()) { 2000 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 2001 SizeVal); 2002 return; 2003 } 2004 } else if (Ty->isArrayType()) { 2005 QualType BaseType = getContext().getBaseElementType(Ty); 2006 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 2007 if (RecordTy->getDecl()->hasObjectMember()) { 2008 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 2009 SizeVal); 2010 return; 2011 } 2012 } 2013 } 2014 2015 auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile); 2016 2017 // Determine the metadata to describe the position of any padding in this 2018 // memcpy, as well as the TBAA tags for the members of the struct, in case 2019 // the optimizer wishes to expand it in to scalar memory operations. 2020 if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty)) 2021 Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag); 2022 2023 if (CGM.getCodeGenOpts().NewStructPathTBAA) { 2024 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer( 2025 Dest.getTBAAInfo(), Src.getTBAAInfo()); 2026 CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo); 2027 } 2028 } 2029