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