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