17a51313dSChris Lattner //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===// 27a51313dSChris Lattner // 37a51313dSChris Lattner // The LLVM Compiler Infrastructure 47a51313dSChris Lattner // 57a51313dSChris Lattner // This file is distributed under the University of Illinois Open Source 67a51313dSChris Lattner // License. See LICENSE.TXT for details. 77a51313dSChris Lattner // 87a51313dSChris Lattner //===----------------------------------------------------------------------===// 97a51313dSChris Lattner // 107a51313dSChris Lattner // This contains code to emit Aggregate Expr nodes as LLVM code. 117a51313dSChris Lattner // 127a51313dSChris Lattner //===----------------------------------------------------------------------===// 137a51313dSChris Lattner 147a51313dSChris Lattner #include "CodeGenFunction.h" 155f21d2f6SFariborz Jahanian #include "CGObjCRuntime.h" 163a02247dSChandler Carruth #include "CodeGenModule.h" 17e0ef348cSIvan A. Kosarev #include "ConstantEmitter.h" 18ad319a73SDaniel Dunbar #include "clang/AST/ASTContext.h" 19b7f8f594SAnders Carlsson #include "clang/AST/DeclCXX.h" 20c83ed824SSebastian Redl #include "clang/AST/DeclTemplate.h" 21ad319a73SDaniel Dunbar #include "clang/AST/StmtVisitor.h" 22ffd5551bSChandler Carruth #include "llvm/IR/Constants.h" 23ffd5551bSChandler Carruth #include "llvm/IR/Function.h" 24ffd5551bSChandler Carruth #include "llvm/IR/GlobalVariable.h" 25ffd5551bSChandler Carruth #include "llvm/IR/Intrinsics.h" 267a51313dSChris Lattner using namespace clang; 277a51313dSChris Lattner using namespace CodeGen; 287a51313dSChris Lattner 297a51313dSChris Lattner //===----------------------------------------------------------------------===// 307a51313dSChris Lattner // Aggregate Expression Emitter 317a51313dSChris Lattner //===----------------------------------------------------------------------===// 327a51313dSChris Lattner 337a51313dSChris Lattner namespace { 34337e3a5fSBenjamin Kramer class AggExprEmitter : public StmtVisitor<AggExprEmitter> { 357a51313dSChris Lattner CodeGenFunction &CGF; 36cb463859SDaniel Dunbar CGBuilderTy &Builder; 377a626f63SJohn McCall AggValueSlot Dest; 386aab1117SLeny Kholodov bool IsResultUnused; 3978a15113SJohn McCall 407a626f63SJohn McCall AggValueSlot EnsureSlot(QualType T) { 417a626f63SJohn McCall if (!Dest.isIgnored()) return Dest; 427a626f63SJohn McCall return CGF.CreateAggTemp(T, "agg.tmp.ensured"); 4378a15113SJohn McCall } 444e8ca4faSJohn McCall void EnsureDest(QualType T) { 454e8ca4faSJohn McCall if (!Dest.isIgnored()) return; 464e8ca4faSJohn McCall Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured"); 474e8ca4faSJohn McCall } 48cc04e9f6SJohn McCall 49*56e5a2e1SGeorge Burgess IV // Calls `Fn` with a valid return value slot, potentially creating a temporary 50*56e5a2e1SGeorge Burgess IV // to do so. If a temporary is created, an appropriate copy into `Dest` will 51*56e5a2e1SGeorge Burgess IV // be emitted. 52*56e5a2e1SGeorge Burgess IV // 53*56e5a2e1SGeorge Burgess IV // The given function should take a ReturnValueSlot, and return an RValue that 54*56e5a2e1SGeorge Burgess IV // points to said slot. 55*56e5a2e1SGeorge Burgess IV void withReturnValueSlot(const Expr *E, 56*56e5a2e1SGeorge Burgess IV llvm::function_ref<RValue(ReturnValueSlot)> Fn); 57*56e5a2e1SGeorge Burgess IV 587a51313dSChris Lattner public: 596aab1117SLeny Kholodov AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused) 606aab1117SLeny Kholodov : CGF(cgf), Builder(CGF.Builder), Dest(Dest), 616aab1117SLeny Kholodov IsResultUnused(IsResultUnused) { } 627a51313dSChris Lattner 637a51313dSChris Lattner //===--------------------------------------------------------------------===// 647a51313dSChris Lattner // Utilities 657a51313dSChris Lattner //===--------------------------------------------------------------------===// 667a51313dSChris Lattner 677a51313dSChris Lattner /// EmitAggLoadOfLValue - Given an expression with aggregate type that 687a51313dSChris Lattner /// represents a value lvalue, this method emits the address of the lvalue, 697a51313dSChris Lattner /// then loads the result into DestPtr. 707a51313dSChris Lattner void EmitAggLoadOfLValue(const Expr *E); 717a51313dSChris Lattner 727275da0fSAkira Hatanaka enum ExprValueKind { 737275da0fSAkira Hatanaka EVK_RValue, 747275da0fSAkira Hatanaka EVK_NonRValue 757275da0fSAkira Hatanaka }; 767275da0fSAkira Hatanaka 77ca9fc09cSMike Stump /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 787275da0fSAkira Hatanaka /// SrcIsRValue is true if source comes from an RValue. 797275da0fSAkira Hatanaka void EmitFinalDestCopy(QualType type, const LValue &src, 807275da0fSAkira Hatanaka ExprValueKind SrcValueKind = EVK_NonRValue); 817f416cc4SJohn McCall void EmitFinalDestCopy(QualType type, RValue src); 824e8ca4faSJohn McCall void EmitCopy(QualType type, const AggValueSlot &dest, 834e8ca4faSJohn McCall const AggValueSlot &src); 84ca9fc09cSMike Stump 85a5efa738SJohn McCall void EmitMoveFromReturnSlot(const Expr *E, RValue Src); 86cc04e9f6SJohn McCall 877f416cc4SJohn McCall void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, 88e0ef348cSIvan A. Kosarev QualType ArrayQTy, InitListExpr *E); 89c83ed824SSebastian Redl 908d6fc958SJohn McCall AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) { 91bbafb8a7SDavid Blaikie if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T)) 928d6fc958SJohn McCall return AggValueSlot::NeedsGCBarriers; 938d6fc958SJohn McCall return AggValueSlot::DoesNotNeedGCBarriers; 948d6fc958SJohn McCall } 958d6fc958SJohn McCall 96cc04e9f6SJohn McCall bool TypeRequiresGCollection(QualType T); 97cc04e9f6SJohn McCall 987a51313dSChris Lattner //===--------------------------------------------------------------------===// 997a51313dSChris Lattner // Visitor Methods 1007a51313dSChris Lattner //===--------------------------------------------------------------------===// 1017a51313dSChris Lattner 10201fb5fb1SDavid Blaikie void Visit(Expr *E) { 1039b479666SDavid Blaikie ApplyDebugLocation DL(CGF, E); 10401fb5fb1SDavid Blaikie StmtVisitor<AggExprEmitter>::Visit(E); 10501fb5fb1SDavid Blaikie } 10601fb5fb1SDavid Blaikie 1077a51313dSChris Lattner void VisitStmt(Stmt *S) { 108a7c8cf62SDaniel Dunbar CGF.ErrorUnsupported(S, "aggregate expression"); 1097a51313dSChris Lattner } 1107a51313dSChris Lattner void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 11191147596SPeter Collingbourne void VisitGenericSelectionExpr(GenericSelectionExpr *GE) { 11291147596SPeter Collingbourne Visit(GE->getResultExpr()); 11391147596SPeter Collingbourne } 1145eb58583SGor Nishanov void VisitCoawaitExpr(CoawaitExpr *E) { 1155eb58583SGor Nishanov CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused); 1165eb58583SGor Nishanov } 1175eb58583SGor Nishanov void VisitCoyieldExpr(CoyieldExpr *E) { 1185eb58583SGor Nishanov CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused); 1195eb58583SGor Nishanov } 1205eb58583SGor Nishanov void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); } 1213f66b84cSEli Friedman void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); } 1227c454bb8SJohn McCall void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) { 1237c454bb8SJohn McCall return Visit(E->getReplacement()); 1247c454bb8SJohn McCall } 1257a51313dSChris Lattner 1267a51313dSChris Lattner // l-values. 1276cc8317cSAlex Lorenz void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); } 1287a51313dSChris Lattner void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 1297a51313dSChris Lattner void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 130d443c0a0SDaniel Dunbar void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 1319b71f0cfSDouglas Gregor void VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 1327a51313dSChris Lattner void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 1337a51313dSChris Lattner EmitAggLoadOfLValue(E); 1347a51313dSChris Lattner } 1352f343dd5SChris Lattner void VisitPredefinedExpr(const PredefinedExpr *E) { 1362f343dd5SChris Lattner EmitAggLoadOfLValue(E); 1372f343dd5SChris Lattner } 138bc7d67ceSMike Stump 1397a51313dSChris Lattner // Operators. 140ec143777SAnders Carlsson void VisitCastExpr(CastExpr *E); 1417a51313dSChris Lattner void VisitCallExpr(const CallExpr *E); 1427a51313dSChris Lattner void VisitStmtExpr(const StmtExpr *E); 1437a51313dSChris Lattner void VisitBinaryOperator(const BinaryOperator *BO); 144ffba662dSFariborz Jahanian void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO); 1457a51313dSChris Lattner void VisitBinAssign(const BinaryOperator *E); 1464b0e2a30SEli Friedman void VisitBinComma(const BinaryOperator *E); 1477a51313dSChris Lattner 148b1d329daSChris Lattner void VisitObjCMessageExpr(ObjCMessageExpr *E); 149c8317a44SDaniel Dunbar void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 150c8317a44SDaniel Dunbar EmitAggLoadOfLValue(E); 151c8317a44SDaniel Dunbar } 1527a51313dSChris Lattner 153cb77930dSYunzhong Gao void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E); 154c07a0c7eSJohn McCall void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO); 1555b2095ceSAnders Carlsson void VisitChooseExpr(const ChooseExpr *CE); 1567a51313dSChris Lattner void VisitInitListExpr(InitListExpr *E); 157939b6880SRichard Smith void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E, 158939b6880SRichard Smith llvm::Value *outerBegin = nullptr); 15918ada985SAnders Carlsson void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); 160cb77930dSYunzhong Gao void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing. 161aa9c7aedSChris Lattner void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 162aa9c7aedSChris Lattner Visit(DAE->getExpr()); 163aa9c7aedSChris Lattner } 164852c9db7SRichard Smith void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) { 165852c9db7SRichard Smith CodeGenFunction::CXXDefaultInitExprScope Scope(CGF); 166852c9db7SRichard Smith Visit(DIE->getExpr()); 167852c9db7SRichard Smith } 1683be22e27SAnders Carlsson void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); 1691619a504SAnders Carlsson void VisitCXXConstructExpr(const CXXConstructExpr *E); 1705179eb78SRichard Smith void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 171c370a7eeSEli Friedman void VisitLambdaExpr(LambdaExpr *E); 172cc1b96d3SRichard Smith void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E); 1735d413781SJohn McCall void VisitExprWithCleanups(ExprWithCleanups *E); 174747eb784SDouglas Gregor void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 1755bbbb137SMike Stump void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); } 176fe31481fSDouglas Gregor void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E); 1771bf5846aSJohn McCall void VisitOpaqueValueExpr(OpaqueValueExpr *E); 1781bf5846aSJohn McCall 179fe96e0b6SJohn McCall void VisitPseudoObjectExpr(PseudoObjectExpr *E) { 180fe96e0b6SJohn McCall if (E->isGLValue()) { 181fe96e0b6SJohn McCall LValue LV = CGF.EmitPseudoObjectLValue(E); 1824e8ca4faSJohn McCall return EmitFinalDestCopy(E->getType(), LV); 183fe96e0b6SJohn McCall } 184fe96e0b6SJohn McCall 185fe96e0b6SJohn McCall CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType())); 186fe96e0b6SJohn McCall } 187fe96e0b6SJohn McCall 18821911e89SEli Friedman void VisitVAArgExpr(VAArgExpr *E); 189579a05d7SChris Lattner 190615ed1a3SChad Rosier void EmitInitializationToLValue(Expr *E, LValue Address); 1911553b190SJohn McCall void EmitNullInitializationToLValue(LValue Address); 1927a51313dSChris Lattner // case Expr::ChooseExprClass: 193f16b8c30SMike Stump void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); } 194df14b3a8SEli Friedman void VisitAtomicExpr(AtomicExpr *E) { 195cc2a6e06STim Northover RValue Res = CGF.EmitAtomicExpr(E); 196cc2a6e06STim Northover EmitFinalDestCopy(E->getType(), Res); 197df14b3a8SEli Friedman } 1987a51313dSChris Lattner }; 1997a51313dSChris Lattner } // end anonymous namespace. 2007a51313dSChris Lattner 2017a51313dSChris Lattner //===----------------------------------------------------------------------===// 2027a51313dSChris Lattner // Utilities 2037a51313dSChris Lattner //===----------------------------------------------------------------------===// 2047a51313dSChris Lattner 2057a51313dSChris Lattner /// EmitAggLoadOfLValue - Given an expression with aggregate type that 2067a51313dSChris Lattner /// represents a value lvalue, this method emits the address of the lvalue, 2077a51313dSChris Lattner /// then loads the result into DestPtr. 2087a51313dSChris Lattner void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 2097a51313dSChris Lattner LValue LV = CGF.EmitLValue(E); 210a8ec7eb9SJohn McCall 211a8ec7eb9SJohn McCall // If the type of the l-value is atomic, then do an atomic load. 212a5b195a1SDavid Majnemer if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) { 2132d84e842SNick Lewycky CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest); 214a8ec7eb9SJohn McCall return; 215a8ec7eb9SJohn McCall } 216a8ec7eb9SJohn McCall 2174e8ca4faSJohn McCall EmitFinalDestCopy(E->getType(), LV); 218ca9fc09cSMike Stump } 219ca9fc09cSMike Stump 220cc04e9f6SJohn McCall /// \brief True if the given aggregate type requires special GC API calls. 221cc04e9f6SJohn McCall bool AggExprEmitter::TypeRequiresGCollection(QualType T) { 222cc04e9f6SJohn McCall // Only record types have members that might require garbage collection. 223cc04e9f6SJohn McCall const RecordType *RecordTy = T->getAs<RecordType>(); 224cc04e9f6SJohn McCall if (!RecordTy) return false; 225cc04e9f6SJohn McCall 226cc04e9f6SJohn McCall // Don't mess with non-trivial C++ types. 227cc04e9f6SJohn McCall RecordDecl *Record = RecordTy->getDecl(); 228cc04e9f6SJohn McCall if (isa<CXXRecordDecl>(Record) && 22916488472SRichard Smith (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() || 230cc04e9f6SJohn McCall !cast<CXXRecordDecl>(Record)->hasTrivialDestructor())) 231cc04e9f6SJohn McCall return false; 232cc04e9f6SJohn McCall 233cc04e9f6SJohn McCall // Check whether the type has an object member. 234cc04e9f6SJohn McCall return Record->hasObjectMember(); 235cc04e9f6SJohn McCall } 236cc04e9f6SJohn McCall 237*56e5a2e1SGeorge Burgess IV void AggExprEmitter::withReturnValueSlot( 238*56e5a2e1SGeorge Burgess IV const Expr *E, llvm::function_ref<RValue(ReturnValueSlot)> EmitCall) { 239*56e5a2e1SGeorge Burgess IV QualType RetTy = E->getType(); 240*56e5a2e1SGeorge Burgess IV bool RequiresDestruction = 241*56e5a2e1SGeorge Burgess IV Dest.isIgnored() && 242*56e5a2e1SGeorge Burgess IV RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct; 2437275da0fSAkira Hatanaka 244*56e5a2e1SGeorge Burgess IV // If it makes no observable difference, save a memcpy + temporary. 245*56e5a2e1SGeorge Burgess IV // 246*56e5a2e1SGeorge Burgess IV // We need to always provide our own temporary if destruction is required. 247*56e5a2e1SGeorge Burgess IV // Otherwise, EmitCall will emit its own, notice that it's "unused", and end 248*56e5a2e1SGeorge Burgess IV // its lifetime before we have the chance to emit a proper destructor call. 249*56e5a2e1SGeorge Burgess IV bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() || 250*56e5a2e1SGeorge Burgess IV (RequiresDestruction && !Dest.getAddress().isValid()); 251*56e5a2e1SGeorge Burgess IV 252*56e5a2e1SGeorge Burgess IV Address RetAddr = Address::invalid(); 253*56e5a2e1SGeorge Burgess IV if (!UseTemp) { 254*56e5a2e1SGeorge Burgess IV RetAddr = Dest.getAddress(); 255*56e5a2e1SGeorge Burgess IV } else { 256*56e5a2e1SGeorge Burgess IV RetAddr = CGF.CreateMemTemp(RetTy); 257*56e5a2e1SGeorge Burgess IV uint64_t Size = 258*56e5a2e1SGeorge Burgess IV CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy)); 259*56e5a2e1SGeorge Burgess IV if (llvm::Value *LifetimeSizePtr = 260*56e5a2e1SGeorge Burgess IV CGF.EmitLifetimeStart(Size, RetAddr.getPointer())) 261*56e5a2e1SGeorge Burgess IV CGF.pushFullExprCleanup<CodeGenFunction::CallLifetimeEnd>( 262*56e5a2e1SGeorge Burgess IV NormalEHLifetimeMarker, RetAddr, LifetimeSizePtr); 263021510e9SFariborz Jahanian } 264a5efa738SJohn McCall 265*56e5a2e1SGeorge Burgess IV RValue Src = 266*56e5a2e1SGeorge Burgess IV EmitCall(ReturnValueSlot(RetAddr, Dest.isVolatile(), IsResultUnused)); 267*56e5a2e1SGeorge Burgess IV 268*56e5a2e1SGeorge Burgess IV if (RequiresDestruction) 269*56e5a2e1SGeorge Burgess IV CGF.pushDestroy(RetTy.isDestructedType(), Src.getAggregateAddress(), RetTy); 270*56e5a2e1SGeorge Burgess IV 271*56e5a2e1SGeorge Burgess IV if (UseTemp) { 272*56e5a2e1SGeorge Burgess IV assert(Dest.getPointer() != Src.getAggregatePointer()); 273*56e5a2e1SGeorge Burgess IV EmitFinalDestCopy(E->getType(), Src); 274*56e5a2e1SGeorge Burgess IV } 275cc04e9f6SJohn McCall } 276cc04e9f6SJohn McCall 277ca9fc09cSMike Stump /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 2787f416cc4SJohn McCall void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) { 2794e8ca4faSJohn McCall assert(src.isAggregate() && "value must be aggregate value!"); 2807f416cc4SJohn McCall LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type); 2817275da0fSAkira Hatanaka EmitFinalDestCopy(type, srcLV, EVK_RValue); 2824e8ca4faSJohn McCall } 2837a51313dSChris Lattner 2844e8ca4faSJohn McCall /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 2857275da0fSAkira Hatanaka void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src, 2867275da0fSAkira Hatanaka ExprValueKind SrcValueKind) { 2877a626f63SJohn McCall // If Dest is ignored, then we're evaluating an aggregate expression 2884e8ca4faSJohn McCall // in a context that doesn't care about the result. Note that loads 2894e8ca4faSJohn McCall // from volatile l-values force the existence of a non-ignored 2904e8ca4faSJohn McCall // destination. 2914e8ca4faSJohn McCall if (Dest.isIgnored()) 292ec3cbfe8SMike Stump return; 293c123623dSFariborz Jahanian 2947275da0fSAkira Hatanaka // Copy non-trivial C structs here. 2957275da0fSAkira Hatanaka LValue DstLV = CGF.MakeAddrLValue( 2967275da0fSAkira Hatanaka Dest.getAddress(), Dest.isVolatile() ? type.withVolatile() : type); 2977275da0fSAkira Hatanaka 2987275da0fSAkira Hatanaka if (SrcValueKind == EVK_RValue) { 2997275da0fSAkira Hatanaka if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) { 3007275da0fSAkira Hatanaka if (Dest.isPotentiallyAliased()) 3017275da0fSAkira Hatanaka CGF.callCStructMoveAssignmentOperator(DstLV, src); 3027275da0fSAkira Hatanaka else 3037275da0fSAkira Hatanaka CGF.callCStructMoveConstructor(DstLV, src); 3047275da0fSAkira Hatanaka return; 3057275da0fSAkira Hatanaka } 3067275da0fSAkira Hatanaka } else { 3077275da0fSAkira Hatanaka if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) { 3087275da0fSAkira Hatanaka if (Dest.isPotentiallyAliased()) 3097275da0fSAkira Hatanaka CGF.callCStructCopyAssignmentOperator(DstLV, src); 3107275da0fSAkira Hatanaka else 3117275da0fSAkira Hatanaka CGF.callCStructCopyConstructor(DstLV, src); 3127275da0fSAkira Hatanaka return; 3137275da0fSAkira Hatanaka } 3147275da0fSAkira Hatanaka } 3157275da0fSAkira Hatanaka 3164e8ca4faSJohn McCall AggValueSlot srcAgg = 3174e8ca4faSJohn McCall AggValueSlot::forLValue(src, AggValueSlot::IsDestructed, 3184e8ca4faSJohn McCall needsGC(type), AggValueSlot::IsAliased); 3194e8ca4faSJohn McCall EmitCopy(type, Dest, srcAgg); 320332ec2ceSMike Stump } 3217a51313dSChris Lattner 3224e8ca4faSJohn McCall /// Perform a copy from the source into the destination. 3234e8ca4faSJohn McCall /// 3244e8ca4faSJohn McCall /// \param type - the type of the aggregate being copied; qualifiers are 3254e8ca4faSJohn McCall /// ignored 3264e8ca4faSJohn McCall void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest, 3274e8ca4faSJohn McCall const AggValueSlot &src) { 3284e8ca4faSJohn McCall if (dest.requiresGCollection()) { 3294e8ca4faSJohn McCall CharUnits sz = CGF.getContext().getTypeSizeInChars(type); 3304e8ca4faSJohn McCall llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity()); 331879d7266SFariborz Jahanian CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, 3327f416cc4SJohn McCall dest.getAddress(), 3337f416cc4SJohn McCall src.getAddress(), 3344e8ca4faSJohn McCall size); 335879d7266SFariborz Jahanian return; 336879d7266SFariborz Jahanian } 3374e8ca4faSJohn McCall 338ca9fc09cSMike Stump // If the result of the assignment is used, copy the LHS there also. 3394e8ca4faSJohn McCall // It's volatile if either side is. Use the minimum alignment of 3404e8ca4faSJohn McCall // the two sides. 3411860b520SIvan A. Kosarev LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type); 3421860b520SIvan A. Kosarev LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type); 3431860b520SIvan A. Kosarev CGF.EmitAggregateCopy(DestLV, SrcLV, type, 3447f416cc4SJohn McCall dest.isVolatile() || src.isVolatile()); 3457a51313dSChris Lattner } 3467a51313dSChris Lattner 347c83ed824SSebastian Redl /// \brief Emit the initializer for a std::initializer_list initialized with a 348c83ed824SSebastian Redl /// real initializer list. 349cc1b96d3SRichard Smith void 350cc1b96d3SRichard Smith AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) { 351cc1b96d3SRichard Smith // Emit an array containing the elements. The array is externally destructed 352cc1b96d3SRichard Smith // if the std::initializer_list object is. 353cc1b96d3SRichard Smith ASTContext &Ctx = CGF.getContext(); 354cc1b96d3SRichard Smith LValue Array = CGF.EmitLValue(E->getSubExpr()); 355cc1b96d3SRichard Smith assert(Array.isSimple() && "initializer_list array not a simple lvalue"); 3567f416cc4SJohn McCall Address ArrayPtr = Array.getAddress(); 357c83ed824SSebastian Redl 358cc1b96d3SRichard Smith const ConstantArrayType *ArrayType = 359cc1b96d3SRichard Smith Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 360cc1b96d3SRichard Smith assert(ArrayType && "std::initializer_list constructed from non-array"); 361c83ed824SSebastian Redl 362cc1b96d3SRichard Smith // FIXME: Perform the checks on the field types in SemaInit. 363cc1b96d3SRichard Smith RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 364cc1b96d3SRichard Smith RecordDecl::field_iterator Field = Record->field_begin(); 365cc1b96d3SRichard Smith if (Field == Record->field_end()) { 366cc1b96d3SRichard Smith CGF.ErrorUnsupported(E, "weird std::initializer_list"); 367f2e0a307SSebastian Redl return; 368c83ed824SSebastian Redl } 369c83ed824SSebastian Redl 370c83ed824SSebastian Redl // Start pointer. 371cc1b96d3SRichard Smith if (!Field->getType()->isPointerType() || 372cc1b96d3SRichard Smith !Ctx.hasSameType(Field->getType()->getPointeeType(), 373cc1b96d3SRichard Smith ArrayType->getElementType())) { 374cc1b96d3SRichard Smith CGF.ErrorUnsupported(E, "weird std::initializer_list"); 375f2e0a307SSebastian Redl return; 376c83ed824SSebastian Redl } 377c83ed824SSebastian Redl 378cc1b96d3SRichard Smith AggValueSlot Dest = EnsureSlot(E->getType()); 3797f416cc4SJohn McCall LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType()); 380cc1b96d3SRichard Smith LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field); 381cc1b96d3SRichard Smith llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0); 382cc1b96d3SRichard Smith llvm::Value *IdxStart[] = { Zero, Zero }; 383cc1b96d3SRichard Smith llvm::Value *ArrayStart = 3847f416cc4SJohn McCall Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxStart, "arraystart"); 385cc1b96d3SRichard Smith CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start); 386cc1b96d3SRichard Smith ++Field; 387cc1b96d3SRichard Smith 388cc1b96d3SRichard Smith if (Field == Record->field_end()) { 389cc1b96d3SRichard Smith CGF.ErrorUnsupported(E, "weird std::initializer_list"); 390f2e0a307SSebastian Redl return; 391c83ed824SSebastian Redl } 392cc1b96d3SRichard Smith 393cc1b96d3SRichard Smith llvm::Value *Size = Builder.getInt(ArrayType->getSize()); 394cc1b96d3SRichard Smith LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field); 395cc1b96d3SRichard Smith if (Field->getType()->isPointerType() && 396cc1b96d3SRichard Smith Ctx.hasSameType(Field->getType()->getPointeeType(), 397cc1b96d3SRichard Smith ArrayType->getElementType())) { 398c83ed824SSebastian Redl // End pointer. 399cc1b96d3SRichard Smith llvm::Value *IdxEnd[] = { Zero, Size }; 400cc1b96d3SRichard Smith llvm::Value *ArrayEnd = 4017f416cc4SJohn McCall Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxEnd, "arrayend"); 402cc1b96d3SRichard Smith CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength); 403cc1b96d3SRichard Smith } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) { 404c83ed824SSebastian Redl // Length. 405cc1b96d3SRichard Smith CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength); 406c83ed824SSebastian Redl } else { 407cc1b96d3SRichard Smith CGF.ErrorUnsupported(E, "weird std::initializer_list"); 408f2e0a307SSebastian Redl return; 409c83ed824SSebastian Redl } 410c83ed824SSebastian Redl } 411c83ed824SSebastian Redl 4128edda962SRichard Smith /// \brief Determine if E is a trivial array filler, that is, one that is 4138edda962SRichard Smith /// equivalent to zero-initialization. 4148edda962SRichard Smith static bool isTrivialFiller(Expr *E) { 4158edda962SRichard Smith if (!E) 4168edda962SRichard Smith return true; 4178edda962SRichard Smith 4188edda962SRichard Smith if (isa<ImplicitValueInitExpr>(E)) 4198edda962SRichard Smith return true; 4208edda962SRichard Smith 4218edda962SRichard Smith if (auto *ILE = dyn_cast<InitListExpr>(E)) { 4228edda962SRichard Smith if (ILE->getNumInits()) 4238edda962SRichard Smith return false; 4248edda962SRichard Smith return isTrivialFiller(ILE->getArrayFiller()); 4258edda962SRichard Smith } 4268edda962SRichard Smith 4278edda962SRichard Smith if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E)) 4288edda962SRichard Smith return Cons->getConstructor()->isDefaultConstructor() && 4298edda962SRichard Smith Cons->getConstructor()->isTrivial(); 4308edda962SRichard Smith 4318edda962SRichard Smith // FIXME: Are there other cases where we can avoid emitting an initializer? 4328edda962SRichard Smith return false; 4338edda962SRichard Smith } 4348edda962SRichard Smith 435c83ed824SSebastian Redl /// \brief Emit initialization of an array from an initializer list. 4367f416cc4SJohn McCall void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, 437e0ef348cSIvan A. Kosarev QualType ArrayQTy, InitListExpr *E) { 438c83ed824SSebastian Redl uint64_t NumInitElements = E->getNumInits(); 439c83ed824SSebastian Redl 440c83ed824SSebastian Redl uint64_t NumArrayElements = AType->getNumElements(); 441c83ed824SSebastian Redl assert(NumInitElements <= NumArrayElements); 442c83ed824SSebastian Redl 443e0ef348cSIvan A. Kosarev QualType elementType = 444e0ef348cSIvan A. Kosarev CGF.getContext().getAsArrayType(ArrayQTy)->getElementType(); 445e0ef348cSIvan A. Kosarev 446c83ed824SSebastian Redl // DestPtr is an array*. Construct an elementType* by drilling 447c83ed824SSebastian Redl // down a level. 448c83ed824SSebastian Redl llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0); 449c83ed824SSebastian Redl llvm::Value *indices[] = { zero, zero }; 450c83ed824SSebastian Redl llvm::Value *begin = 4517f416cc4SJohn McCall Builder.CreateInBoundsGEP(DestPtr.getPointer(), indices, "arrayinit.begin"); 4527f416cc4SJohn McCall 4537f416cc4SJohn McCall CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType); 4547f416cc4SJohn McCall CharUnits elementAlign = 4557f416cc4SJohn McCall DestPtr.getAlignment().alignmentOfArrayElement(elementSize); 456c83ed824SSebastian Redl 457e0ef348cSIvan A. Kosarev // Consider initializing the array by copying from a global. For this to be 458e0ef348cSIvan A. Kosarev // more efficient than per-element initialization, the size of the elements 459e0ef348cSIvan A. Kosarev // with explicit initializers should be large enough. 460e0ef348cSIvan A. Kosarev if (NumInitElements * elementSize.getQuantity() > 16 && 461e0ef348cSIvan A. Kosarev elementType.isTriviallyCopyableType(CGF.getContext())) { 462e0ef348cSIvan A. Kosarev CodeGen::CodeGenModule &CGM = CGF.CGM; 463e0ef348cSIvan A. Kosarev ConstantEmitter Emitter(CGM); 464e0ef348cSIvan A. Kosarev LangAS AS = ArrayQTy.getAddressSpace(); 465e0ef348cSIvan A. Kosarev if (llvm::Constant *C = Emitter.tryEmitForInitializer(E, AS, ArrayQTy)) { 466e0ef348cSIvan A. Kosarev auto GV = new llvm::GlobalVariable( 467e0ef348cSIvan A. Kosarev CGM.getModule(), C->getType(), 468e0ef348cSIvan A. Kosarev CGM.isTypeConstant(ArrayQTy, /* ExcludeCtorDtor= */ true), 469e0ef348cSIvan A. Kosarev llvm::GlobalValue::PrivateLinkage, C, "constinit", 470e0ef348cSIvan A. Kosarev /* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal, 471e0ef348cSIvan A. Kosarev CGM.getContext().getTargetAddressSpace(AS)); 472e0ef348cSIvan A. Kosarev Emitter.finalize(GV); 473e0ef348cSIvan A. Kosarev CharUnits Align = CGM.getContext().getTypeAlignInChars(ArrayQTy); 474e0ef348cSIvan A. Kosarev GV->setAlignment(Align.getQuantity()); 475e0ef348cSIvan A. Kosarev EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GV, ArrayQTy, Align)); 476e0ef348cSIvan A. Kosarev return; 477e0ef348cSIvan A. Kosarev } 478e0ef348cSIvan A. Kosarev } 479e0ef348cSIvan A. Kosarev 480c83ed824SSebastian Redl // Exception safety requires us to destroy all the 481c83ed824SSebastian Redl // already-constructed members if an initializer throws. 482c83ed824SSebastian Redl // For that, we'll need an EH cleanup. 483c83ed824SSebastian Redl QualType::DestructionKind dtorKind = elementType.isDestructedType(); 4847f416cc4SJohn McCall Address endOfInit = Address::invalid(); 485c83ed824SSebastian Redl EHScopeStack::stable_iterator cleanup; 4868a13c418SCraig Topper llvm::Instruction *cleanupDominator = nullptr; 487c83ed824SSebastian Redl if (CGF.needsEHCleanup(dtorKind)) { 488c83ed824SSebastian Redl // In principle we could tell the cleanup where we are more 489c83ed824SSebastian Redl // directly, but the control flow can get so varied here that it 490c83ed824SSebastian Redl // would actually be quite complex. Therefore we go through an 491c83ed824SSebastian Redl // alloca. 4927f416cc4SJohn McCall endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(), 493c83ed824SSebastian Redl "arrayinit.endOfInit"); 494c83ed824SSebastian Redl cleanupDominator = Builder.CreateStore(begin, endOfInit); 495c83ed824SSebastian Redl CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType, 4967f416cc4SJohn McCall elementAlign, 497c83ed824SSebastian Redl CGF.getDestroyer(dtorKind)); 498c83ed824SSebastian Redl cleanup = CGF.EHStack.stable_begin(); 499c83ed824SSebastian Redl 500c83ed824SSebastian Redl // Otherwise, remember that we didn't need a cleanup. 501c83ed824SSebastian Redl } else { 502c83ed824SSebastian Redl dtorKind = QualType::DK_none; 503c83ed824SSebastian Redl } 504c83ed824SSebastian Redl 505c83ed824SSebastian Redl llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1); 506c83ed824SSebastian Redl 507c83ed824SSebastian Redl // The 'current element to initialize'. The invariants on this 508c83ed824SSebastian Redl // variable are complicated. Essentially, after each iteration of 509c83ed824SSebastian Redl // the loop, it points to the last initialized element, except 510c83ed824SSebastian Redl // that it points to the beginning of the array before any 511c83ed824SSebastian Redl // elements have been initialized. 512c83ed824SSebastian Redl llvm::Value *element = begin; 513c83ed824SSebastian Redl 514c83ed824SSebastian Redl // Emit the explicit initializers. 515c83ed824SSebastian Redl for (uint64_t i = 0; i != NumInitElements; ++i) { 516c83ed824SSebastian Redl // Advance to the next element. 517c83ed824SSebastian Redl if (i > 0) { 518c83ed824SSebastian Redl element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element"); 519c83ed824SSebastian Redl 520c83ed824SSebastian Redl // Tell the cleanup that it needs to destroy up to this 521c83ed824SSebastian Redl // element. TODO: some of these stores can be trivially 522c83ed824SSebastian Redl // observed to be unnecessary. 5237f416cc4SJohn McCall if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit); 524c83ed824SSebastian Redl } 525c83ed824SSebastian Redl 5267f416cc4SJohn McCall LValue elementLV = 5277f416cc4SJohn McCall CGF.MakeAddrLValue(Address(element, elementAlign), elementType); 528615ed1a3SChad Rosier EmitInitializationToLValue(E->getInit(i), elementLV); 529c83ed824SSebastian Redl } 530c83ed824SSebastian Redl 531c83ed824SSebastian Redl // Check whether there's a non-trivial array-fill expression. 532c83ed824SSebastian Redl Expr *filler = E->getArrayFiller(); 5338edda962SRichard Smith bool hasTrivialFiller = isTrivialFiller(filler); 534c83ed824SSebastian Redl 535c83ed824SSebastian Redl // Any remaining elements need to be zero-initialized, possibly 536c83ed824SSebastian Redl // using the filler expression. We can skip this if the we're 537c83ed824SSebastian Redl // emitting to zeroed memory. 538c83ed824SSebastian Redl if (NumInitElements != NumArrayElements && 539c83ed824SSebastian Redl !(Dest.isZeroed() && hasTrivialFiller && 540c83ed824SSebastian Redl CGF.getTypes().isZeroInitializable(elementType))) { 541c83ed824SSebastian Redl 542c83ed824SSebastian Redl // Use an actual loop. This is basically 543c83ed824SSebastian Redl // do { *array++ = filler; } while (array != end); 544c83ed824SSebastian Redl 545c83ed824SSebastian Redl // Advance to the start of the rest of the array. 546c83ed824SSebastian Redl if (NumInitElements) { 547c83ed824SSebastian Redl element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start"); 5487f416cc4SJohn McCall if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit); 549c83ed824SSebastian Redl } 550c83ed824SSebastian Redl 551c83ed824SSebastian Redl // Compute the end of the array. 552c83ed824SSebastian Redl llvm::Value *end = Builder.CreateInBoundsGEP(begin, 553c83ed824SSebastian Redl llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements), 554c83ed824SSebastian Redl "arrayinit.end"); 555c83ed824SSebastian Redl 556c83ed824SSebastian Redl llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 557c83ed824SSebastian Redl llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body"); 558c83ed824SSebastian Redl 559c83ed824SSebastian Redl // Jump into the body. 560c83ed824SSebastian Redl CGF.EmitBlock(bodyBB); 561c83ed824SSebastian Redl llvm::PHINode *currentElement = 562c83ed824SSebastian Redl Builder.CreatePHI(element->getType(), 2, "arrayinit.cur"); 563c83ed824SSebastian Redl currentElement->addIncoming(element, entryBB); 564c83ed824SSebastian Redl 565c83ed824SSebastian Redl // Emit the actual filler expression. 56672236372SRichard Smith { 56772236372SRichard Smith // C++1z [class.temporary]p5: 56872236372SRichard Smith // when a default constructor is called to initialize an element of 56972236372SRichard Smith // an array with no corresponding initializer [...] the destruction of 57072236372SRichard Smith // every temporary created in a default argument is sequenced before 57172236372SRichard Smith // the construction of the next array element, if any 57272236372SRichard Smith CodeGenFunction::RunCleanupsScope CleanupsScope(CGF); 5737f416cc4SJohn McCall LValue elementLV = 5747f416cc4SJohn McCall CGF.MakeAddrLValue(Address(currentElement, elementAlign), elementType); 575c83ed824SSebastian Redl if (filler) 576615ed1a3SChad Rosier EmitInitializationToLValue(filler, elementLV); 577c83ed824SSebastian Redl else 578c83ed824SSebastian Redl EmitNullInitializationToLValue(elementLV); 57972236372SRichard Smith } 580c83ed824SSebastian Redl 581c83ed824SSebastian Redl // Move on to the next element. 582c83ed824SSebastian Redl llvm::Value *nextElement = 583c83ed824SSebastian Redl Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next"); 584c83ed824SSebastian Redl 585c83ed824SSebastian Redl // Tell the EH cleanup that we finished with the last element. 5867f416cc4SJohn McCall if (endOfInit.isValid()) Builder.CreateStore(nextElement, endOfInit); 587c83ed824SSebastian Redl 588c83ed824SSebastian Redl // Leave the loop if we're done. 589c83ed824SSebastian Redl llvm::Value *done = Builder.CreateICmpEQ(nextElement, end, 590c83ed824SSebastian Redl "arrayinit.done"); 591c83ed824SSebastian Redl llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end"); 592c83ed824SSebastian Redl Builder.CreateCondBr(done, endBB, bodyBB); 593c83ed824SSebastian Redl currentElement->addIncoming(nextElement, Builder.GetInsertBlock()); 594c83ed824SSebastian Redl 595c83ed824SSebastian Redl CGF.EmitBlock(endBB); 596c83ed824SSebastian Redl } 597c83ed824SSebastian Redl 598c83ed824SSebastian Redl // Leave the partial-array cleanup if we entered one. 599c83ed824SSebastian Redl if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator); 600c83ed824SSebastian Redl } 601c83ed824SSebastian Redl 6027a51313dSChris Lattner //===----------------------------------------------------------------------===// 6037a51313dSChris Lattner // Visitor Methods 6047a51313dSChris Lattner //===----------------------------------------------------------------------===// 6057a51313dSChris Lattner 606fe31481fSDouglas Gregor void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){ 607fe31481fSDouglas Gregor Visit(E->GetTemporaryExpr()); 608fe31481fSDouglas Gregor } 609fe31481fSDouglas Gregor 6101bf5846aSJohn McCall void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) { 6114e8ca4faSJohn McCall EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e)); 6121bf5846aSJohn McCall } 6131bf5846aSJohn McCall 6149b71f0cfSDouglas Gregor void 6159b71f0cfSDouglas Gregor AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 616bea4c3d8SJohn McCall if (Dest.isPotentiallyAliased() && 617bea4c3d8SJohn McCall E->getType().isPODType(CGF.getContext())) { 6186c9d31ebSDouglas Gregor // For a POD type, just emit a load of the lvalue + a copy, because our 6196c9d31ebSDouglas Gregor // compound literal might alias the destination. 6206c9d31ebSDouglas Gregor EmitAggLoadOfLValue(E); 6216c9d31ebSDouglas Gregor return; 6226c9d31ebSDouglas Gregor } 6236c9d31ebSDouglas Gregor 6249b71f0cfSDouglas Gregor AggValueSlot Slot = EnsureSlot(E->getType()); 6259b71f0cfSDouglas Gregor CGF.EmitAggExpr(E->getInitializer(), Slot); 6269b71f0cfSDouglas Gregor } 6279b71f0cfSDouglas Gregor 628a8ec7eb9SJohn McCall /// Attempt to look through various unimportant expressions to find a 629a8ec7eb9SJohn McCall /// cast of the given kind. 630a8ec7eb9SJohn McCall static Expr *findPeephole(Expr *op, CastKind kind) { 631a8ec7eb9SJohn McCall while (true) { 632a8ec7eb9SJohn McCall op = op->IgnoreParens(); 633a8ec7eb9SJohn McCall if (CastExpr *castE = dyn_cast<CastExpr>(op)) { 634a8ec7eb9SJohn McCall if (castE->getCastKind() == kind) 635a8ec7eb9SJohn McCall return castE->getSubExpr(); 636a8ec7eb9SJohn McCall if (castE->getCastKind() == CK_NoOp) 637a8ec7eb9SJohn McCall continue; 638a8ec7eb9SJohn McCall } 6398a13c418SCraig Topper return nullptr; 640a8ec7eb9SJohn McCall } 641a8ec7eb9SJohn McCall } 6429b71f0cfSDouglas Gregor 643ec143777SAnders Carlsson void AggExprEmitter::VisitCastExpr(CastExpr *E) { 6442bf9b4c0SAlexey Bataev if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E)) 6452bf9b4c0SAlexey Bataev CGF.CGM.EmitExplicitCastExprType(ECE, &CGF); 6461fb7ae9eSAnders Carlsson switch (E->getCastKind()) { 6478a01a751SAnders Carlsson case CK_Dynamic: { 64869d0d262SRichard Smith // FIXME: Can this actually happen? We have no test coverage for it. 6491c073f47SDouglas Gregor assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?"); 65069d0d262SRichard Smith LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(), 6514d1458edSRichard Smith CodeGenFunction::TCK_Load); 6521c073f47SDouglas Gregor // FIXME: Do we also need to handle property references here? 6531c073f47SDouglas Gregor if (LV.isSimple()) 6541c073f47SDouglas Gregor CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E)); 6551c073f47SDouglas Gregor else 6561c073f47SDouglas Gregor CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast"); 6571c073f47SDouglas Gregor 6587a626f63SJohn McCall if (!Dest.isIgnored()) 6591c073f47SDouglas Gregor CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination"); 6601c073f47SDouglas Gregor break; 6611c073f47SDouglas Gregor } 6621c073f47SDouglas Gregor 663e302792bSJohn McCall case CK_ToUnion: { 664892bb0caSReid Kleckner // Evaluate even if the destination is ignored. 665892bb0caSReid Kleckner if (Dest.isIgnored()) { 666892bb0caSReid Kleckner CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(), 667892bb0caSReid Kleckner /*ignoreResult=*/true); 668892bb0caSReid Kleckner break; 669892bb0caSReid Kleckner } 67058989b71SJohn McCall 6717ffcf93bSNuno Lopes // GCC union extension 6722e442a00SDaniel Dunbar QualType Ty = E->getSubExpr()->getType(); 6737f416cc4SJohn McCall Address CastPtr = 6747f416cc4SJohn McCall Builder.CreateElementBitCast(Dest.getAddress(), CGF.ConvertType(Ty)); 6751553b190SJohn McCall EmitInitializationToLValue(E->getSubExpr(), 676615ed1a3SChad Rosier CGF.MakeAddrLValue(CastPtr, Ty)); 6771fb7ae9eSAnders Carlsson break; 6787ffcf93bSNuno Lopes } 6797ffcf93bSNuno Lopes 680e302792bSJohn McCall case CK_DerivedToBase: 681e302792bSJohn McCall case CK_BaseToDerived: 682e302792bSJohn McCall case CK_UncheckedDerivedToBase: { 68383d382b1SDavid Blaikie llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: " 684aae38d66SDouglas Gregor "should have been unpacked before we got here"); 685aae38d66SDouglas Gregor } 686aae38d66SDouglas Gregor 687a8ec7eb9SJohn McCall case CK_NonAtomicToAtomic: 688a8ec7eb9SJohn McCall case CK_AtomicToNonAtomic: { 689a8ec7eb9SJohn McCall bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic); 690a8ec7eb9SJohn McCall 691a8ec7eb9SJohn McCall // Determine the atomic and value types. 692a8ec7eb9SJohn McCall QualType atomicType = E->getSubExpr()->getType(); 693a8ec7eb9SJohn McCall QualType valueType = E->getType(); 694a8ec7eb9SJohn McCall if (isToAtomic) std::swap(atomicType, valueType); 695a8ec7eb9SJohn McCall 696a8ec7eb9SJohn McCall assert(atomicType->isAtomicType()); 697a8ec7eb9SJohn McCall assert(CGF.getContext().hasSameUnqualifiedType(valueType, 698a8ec7eb9SJohn McCall atomicType->castAs<AtomicType>()->getValueType())); 699a8ec7eb9SJohn McCall 700a8ec7eb9SJohn McCall // Just recurse normally if we're ignoring the result or the 701a8ec7eb9SJohn McCall // atomic type doesn't change representation. 702a8ec7eb9SJohn McCall if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) { 703a8ec7eb9SJohn McCall return Visit(E->getSubExpr()); 704a8ec7eb9SJohn McCall } 705a8ec7eb9SJohn McCall 706a8ec7eb9SJohn McCall CastKind peepholeTarget = 707a8ec7eb9SJohn McCall (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic); 708a8ec7eb9SJohn McCall 709a8ec7eb9SJohn McCall // These two cases are reverses of each other; try to peephole them. 710a8ec7eb9SJohn McCall if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) { 711a8ec7eb9SJohn McCall assert(CGF.getContext().hasSameUnqualifiedType(op->getType(), 712a8ec7eb9SJohn McCall E->getType()) && 713a8ec7eb9SJohn McCall "peephole significantly changed types?"); 714a8ec7eb9SJohn McCall return Visit(op); 715a8ec7eb9SJohn McCall } 716a8ec7eb9SJohn McCall 717a8ec7eb9SJohn McCall // If we're converting an r-value of non-atomic type to an r-value 718be4504dfSEli Friedman // of atomic type, just emit directly into the relevant sub-object. 719a8ec7eb9SJohn McCall if (isToAtomic) { 720be4504dfSEli Friedman AggValueSlot valueDest = Dest; 721be4504dfSEli Friedman if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) { 722be4504dfSEli Friedman // Zero-initialize. (Strictly speaking, we only need to intialize 723be4504dfSEli Friedman // the padding at the end, but this is simpler.) 724be4504dfSEli Friedman if (!Dest.isZeroed()) 7257f416cc4SJohn McCall CGF.EmitNullInitialization(Dest.getAddress(), atomicType); 726be4504dfSEli Friedman 727be4504dfSEli Friedman // Build a GEP to refer to the subobject. 7287f416cc4SJohn McCall Address valueAddr = 7297f416cc4SJohn McCall CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0, 7307f416cc4SJohn McCall CharUnits()); 731be4504dfSEli Friedman valueDest = AggValueSlot::forAddr(valueAddr, 732be4504dfSEli Friedman valueDest.getQualifiers(), 733be4504dfSEli Friedman valueDest.isExternallyDestructed(), 734be4504dfSEli Friedman valueDest.requiresGCollection(), 735be4504dfSEli Friedman valueDest.isPotentiallyAliased(), 736be4504dfSEli Friedman AggValueSlot::IsZeroed); 737be4504dfSEli Friedman } 738be4504dfSEli Friedman 739035b39e3SEli Friedman CGF.EmitAggExpr(E->getSubExpr(), valueDest); 740a8ec7eb9SJohn McCall return; 741a8ec7eb9SJohn McCall } 742a8ec7eb9SJohn McCall 743a8ec7eb9SJohn McCall // Otherwise, we're converting an atomic type to a non-atomic type. 744be4504dfSEli Friedman // Make an atomic temporary, emit into that, and then copy the value out. 745a8ec7eb9SJohn McCall AggValueSlot atomicSlot = 746a8ec7eb9SJohn McCall CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp"); 747a8ec7eb9SJohn McCall CGF.EmitAggExpr(E->getSubExpr(), atomicSlot); 748a8ec7eb9SJohn McCall 7497f416cc4SJohn McCall Address valueAddr = 7507f416cc4SJohn McCall Builder.CreateStructGEP(atomicSlot.getAddress(), 0, CharUnits()); 751a8ec7eb9SJohn McCall RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile()); 752a8ec7eb9SJohn McCall return EmitFinalDestCopy(valueType, rvalue); 753a8ec7eb9SJohn McCall } 754a8ec7eb9SJohn McCall 7554e8ca4faSJohn McCall case CK_LValueToRValue: 7564e8ca4faSJohn McCall // If we're loading from a volatile type, force the destination 7574e8ca4faSJohn McCall // into existence. 7584e8ca4faSJohn McCall if (E->getSubExpr()->getType().isVolatileQualified()) { 7594e8ca4faSJohn McCall EnsureDest(E->getType()); 7604e8ca4faSJohn McCall return Visit(E->getSubExpr()); 7614e8ca4faSJohn McCall } 762a8ec7eb9SJohn McCall 763f3b3ccdaSAdrian Prantl LLVM_FALLTHROUGH; 7644e8ca4faSJohn McCall 765e302792bSJohn McCall case CK_NoOp: 766e302792bSJohn McCall case CK_UserDefinedConversion: 767e302792bSJohn McCall case CK_ConstructorConversion: 7682a69547fSEli Friedman assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(), 7692a69547fSEli Friedman E->getType()) && 7700f398c44SChris Lattner "Implicit cast types must be compatible"); 7717a51313dSChris Lattner Visit(E->getSubExpr()); 7721fb7ae9eSAnders Carlsson break; 773b05a3e55SAnders Carlsson 774e302792bSJohn McCall case CK_LValueBitCast: 775f3735e01SJohn McCall llvm_unreachable("should not be emitting lvalue bitcast as rvalue"); 77631996343SJohn McCall 777f3735e01SJohn McCall case CK_Dependent: 778f3735e01SJohn McCall case CK_BitCast: 779f3735e01SJohn McCall case CK_ArrayToPointerDecay: 780f3735e01SJohn McCall case CK_FunctionToPointerDecay: 781f3735e01SJohn McCall case CK_NullToPointer: 782f3735e01SJohn McCall case CK_NullToMemberPointer: 783f3735e01SJohn McCall case CK_BaseToDerivedMemberPointer: 784f3735e01SJohn McCall case CK_DerivedToBaseMemberPointer: 785f3735e01SJohn McCall case CK_MemberPointerToBoolean: 786c62bb391SJohn McCall case CK_ReinterpretMemberPointer: 787f3735e01SJohn McCall case CK_IntegralToPointer: 788f3735e01SJohn McCall case CK_PointerToIntegral: 789f3735e01SJohn McCall case CK_PointerToBoolean: 790f3735e01SJohn McCall case CK_ToVoid: 791f3735e01SJohn McCall case CK_VectorSplat: 792f3735e01SJohn McCall case CK_IntegralCast: 793df1ed009SGeorge Burgess IV case CK_BooleanToSignedIntegral: 794f3735e01SJohn McCall case CK_IntegralToBoolean: 795f3735e01SJohn McCall case CK_IntegralToFloating: 796f3735e01SJohn McCall case CK_FloatingToIntegral: 797f3735e01SJohn McCall case CK_FloatingToBoolean: 798f3735e01SJohn McCall case CK_FloatingCast: 7999320b87cSJohn McCall case CK_CPointerToObjCPointerCast: 8009320b87cSJohn McCall case CK_BlockPointerToObjCPointerCast: 801f3735e01SJohn McCall case CK_AnyPointerToBlockPointerCast: 802f3735e01SJohn McCall case CK_ObjCObjectLValueCast: 803f3735e01SJohn McCall case CK_FloatingRealToComplex: 804f3735e01SJohn McCall case CK_FloatingComplexToReal: 805f3735e01SJohn McCall case CK_FloatingComplexToBoolean: 806f3735e01SJohn McCall case CK_FloatingComplexCast: 807f3735e01SJohn McCall case CK_FloatingComplexToIntegralComplex: 808f3735e01SJohn McCall case CK_IntegralRealToComplex: 809f3735e01SJohn McCall case CK_IntegralComplexToReal: 810f3735e01SJohn McCall case CK_IntegralComplexToBoolean: 811f3735e01SJohn McCall case CK_IntegralComplexCast: 812f3735e01SJohn McCall case CK_IntegralComplexToFloatingComplex: 8132d637d2eSJohn McCall case CK_ARCProduceObject: 8142d637d2eSJohn McCall case CK_ARCConsumeObject: 8152d637d2eSJohn McCall case CK_ARCReclaimReturnedObject: 8162d637d2eSJohn McCall case CK_ARCExtendBlockObject: 817ed90df38SDouglas Gregor case CK_CopyAndAutoreleaseBlockObject: 81834866c77SEli Friedman case CK_BuiltinFnToFnPtr: 8191b4fb3e0SGuy Benyei case CK_ZeroToOCLEvent: 82089831421SEgor Churaev case CK_ZeroToOCLQueue: 821e1468322SDavid Tweed case CK_AddressSpaceConversion: 8220bc4b2d3SYaxun Liu case CK_IntToOCLSampler: 823f3735e01SJohn McCall llvm_unreachable("cast kind invalid for aggregate types"); 8241fb7ae9eSAnders Carlsson } 8257a51313dSChris Lattner } 8267a51313dSChris Lattner 8270f398c44SChris Lattner void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 828ced8bdf7SDavid Majnemer if (E->getCallReturnType(CGF.getContext())->isReferenceType()) { 829ddcbfe7bSAnders Carlsson EmitAggLoadOfLValue(E); 830ddcbfe7bSAnders Carlsson return; 831ddcbfe7bSAnders Carlsson } 832ddcbfe7bSAnders Carlsson 833*56e5a2e1SGeorge Burgess IV withReturnValueSlot(E, [&](ReturnValueSlot Slot) { 834*56e5a2e1SGeorge Burgess IV return CGF.EmitCallExpr(E, Slot); 835*56e5a2e1SGeorge Burgess IV }); 8367a51313dSChris Lattner } 8370f398c44SChris Lattner 8380f398c44SChris Lattner void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 839*56e5a2e1SGeorge Burgess IV withReturnValueSlot(E, [&](ReturnValueSlot Slot) { 840*56e5a2e1SGeorge Burgess IV return CGF.EmitObjCMessageExpr(E, Slot); 841*56e5a2e1SGeorge Burgess IV }); 842b1d329daSChris Lattner } 8437a51313dSChris Lattner 8440f398c44SChris Lattner void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 845a2342eb8SJohn McCall CGF.EmitIgnoredExpr(E->getLHS()); 8467a626f63SJohn McCall Visit(E->getRHS()); 8474b0e2a30SEli Friedman } 8484b0e2a30SEli Friedman 8497a51313dSChris Lattner void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 850ce1de617SJohn McCall CodeGenFunction::StmtExprEvaluation eval(CGF); 8517a626f63SJohn McCall CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest); 8527a51313dSChris Lattner } 8537a51313dSChris Lattner 8547a51313dSChris Lattner void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 855e302792bSJohn McCall if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI) 856ffba662dSFariborz Jahanian VisitPointerToDataMemberBinaryOperator(E); 857ffba662dSFariborz Jahanian else 858a7c8cf62SDaniel Dunbar CGF.ErrorUnsupported(E, "aggregate binary expression"); 8597a51313dSChris Lattner } 8607a51313dSChris Lattner 861ffba662dSFariborz Jahanian void AggExprEmitter::VisitPointerToDataMemberBinaryOperator( 862ffba662dSFariborz Jahanian const BinaryOperator *E) { 863ffba662dSFariborz Jahanian LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E); 8644e8ca4faSJohn McCall EmitFinalDestCopy(E->getType(), LV); 8654e8ca4faSJohn McCall } 8664e8ca4faSJohn McCall 8674e8ca4faSJohn McCall /// Is the value of the given expression possibly a reference to or 8684e8ca4faSJohn McCall /// into a __block variable? 8694e8ca4faSJohn McCall static bool isBlockVarRef(const Expr *E) { 8704e8ca4faSJohn McCall // Make sure we look through parens. 8714e8ca4faSJohn McCall E = E->IgnoreParens(); 8724e8ca4faSJohn McCall 8734e8ca4faSJohn McCall // Check for a direct reference to a __block variable. 8744e8ca4faSJohn McCall if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 8754e8ca4faSJohn McCall const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8764e8ca4faSJohn McCall return (var && var->hasAttr<BlocksAttr>()); 8774e8ca4faSJohn McCall } 8784e8ca4faSJohn McCall 8794e8ca4faSJohn McCall // More complicated stuff. 8804e8ca4faSJohn McCall 8814e8ca4faSJohn McCall // Binary operators. 8824e8ca4faSJohn McCall if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) { 8834e8ca4faSJohn McCall // For an assignment or pointer-to-member operation, just care 8844e8ca4faSJohn McCall // about the LHS. 8854e8ca4faSJohn McCall if (op->isAssignmentOp() || op->isPtrMemOp()) 8864e8ca4faSJohn McCall return isBlockVarRef(op->getLHS()); 8874e8ca4faSJohn McCall 8884e8ca4faSJohn McCall // For a comma, just care about the RHS. 8894e8ca4faSJohn McCall if (op->getOpcode() == BO_Comma) 8904e8ca4faSJohn McCall return isBlockVarRef(op->getRHS()); 8914e8ca4faSJohn McCall 8924e8ca4faSJohn McCall // FIXME: pointer arithmetic? 8934e8ca4faSJohn McCall return false; 8944e8ca4faSJohn McCall 8954e8ca4faSJohn McCall // Check both sides of a conditional operator. 8964e8ca4faSJohn McCall } else if (const AbstractConditionalOperator *op 8974e8ca4faSJohn McCall = dyn_cast<AbstractConditionalOperator>(E)) { 8984e8ca4faSJohn McCall return isBlockVarRef(op->getTrueExpr()) 8994e8ca4faSJohn McCall || isBlockVarRef(op->getFalseExpr()); 9004e8ca4faSJohn McCall 9014e8ca4faSJohn McCall // OVEs are required to support BinaryConditionalOperators. 9024e8ca4faSJohn McCall } else if (const OpaqueValueExpr *op 9034e8ca4faSJohn McCall = dyn_cast<OpaqueValueExpr>(E)) { 9044e8ca4faSJohn McCall if (const Expr *src = op->getSourceExpr()) 9054e8ca4faSJohn McCall return isBlockVarRef(src); 9064e8ca4faSJohn McCall 9074e8ca4faSJohn McCall // Casts are necessary to get things like (*(int*)&var) = foo(). 9084e8ca4faSJohn McCall // We don't really care about the kind of cast here, except 9094e8ca4faSJohn McCall // we don't want to look through l2r casts, because it's okay 9104e8ca4faSJohn McCall // to get the *value* in a __block variable. 9114e8ca4faSJohn McCall } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) { 9124e8ca4faSJohn McCall if (cast->getCastKind() == CK_LValueToRValue) 9134e8ca4faSJohn McCall return false; 9144e8ca4faSJohn McCall return isBlockVarRef(cast->getSubExpr()); 9154e8ca4faSJohn McCall 9164e8ca4faSJohn McCall // Handle unary operators. Again, just aggressively look through 9174e8ca4faSJohn McCall // it, ignoring the operation. 9184e8ca4faSJohn McCall } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) { 9194e8ca4faSJohn McCall return isBlockVarRef(uop->getSubExpr()); 9204e8ca4faSJohn McCall 9214e8ca4faSJohn McCall // Look into the base of a field access. 9224e8ca4faSJohn McCall } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 9234e8ca4faSJohn McCall return isBlockVarRef(mem->getBase()); 9244e8ca4faSJohn McCall 9254e8ca4faSJohn McCall // Look into the base of a subscript. 9264e8ca4faSJohn McCall } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) { 9274e8ca4faSJohn McCall return isBlockVarRef(sub->getBase()); 9284e8ca4faSJohn McCall } 9294e8ca4faSJohn McCall 9304e8ca4faSJohn McCall return false; 931ffba662dSFariborz Jahanian } 932ffba662dSFariborz Jahanian 9337a51313dSChris Lattner void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 9347a51313dSChris Lattner // For an assignment to work, the value on the right has 9357a51313dSChris Lattner // to be compatible with the value on the left. 9362a69547fSEli Friedman assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(), 9372a69547fSEli Friedman E->getRHS()->getType()) 9387a51313dSChris Lattner && "Invalid assignment"); 939d0a30016SJohn McCall 9404e8ca4faSJohn McCall // If the LHS might be a __block variable, and the RHS can 9414e8ca4faSJohn McCall // potentially cause a block copy, we need to evaluate the RHS first 9424e8ca4faSJohn McCall // so that the assignment goes the right place. 9434e8ca4faSJohn McCall // This is pretty semantically fragile. 9444e8ca4faSJohn McCall if (isBlockVarRef(E->getLHS()) && 94599514b91SFariborz Jahanian E->getRHS()->HasSideEffects(CGF.getContext())) { 9464e8ca4faSJohn McCall // Ensure that we have a destination, and evaluate the RHS into that. 9474e8ca4faSJohn McCall EnsureDest(E->getRHS()->getType()); 9484e8ca4faSJohn McCall Visit(E->getRHS()); 9494e8ca4faSJohn McCall 9504e8ca4faSJohn McCall // Now emit the LHS and copy into it. 951e30752c9SRichard Smith LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store); 9524e8ca4faSJohn McCall 953a8ec7eb9SJohn McCall // That copy is an atomic copy if the LHS is atomic. 954a5b195a1SDavid Majnemer if (LHS.getType()->isAtomicType() || 955a5b195a1SDavid Majnemer CGF.LValueIsSuitableForInlineAtomic(LHS)) { 956a8ec7eb9SJohn McCall CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false); 957a8ec7eb9SJohn McCall return; 958a8ec7eb9SJohn McCall } 959a8ec7eb9SJohn McCall 9604e8ca4faSJohn McCall EmitCopy(E->getLHS()->getType(), 9614e8ca4faSJohn McCall AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed, 96246759f4fSJohn McCall needsGC(E->getLHS()->getType()), 9634e8ca4faSJohn McCall AggValueSlot::IsAliased), 9644e8ca4faSJohn McCall Dest); 96599514b91SFariborz Jahanian return; 96699514b91SFariborz Jahanian } 96799514b91SFariborz Jahanian 9687a51313dSChris Lattner LValue LHS = CGF.EmitLValue(E->getLHS()); 9697a51313dSChris Lattner 970a8ec7eb9SJohn McCall // If we have an atomic type, evaluate into the destination and then 971a8ec7eb9SJohn McCall // do an atomic copy. 972a5b195a1SDavid Majnemer if (LHS.getType()->isAtomicType() || 973a5b195a1SDavid Majnemer CGF.LValueIsSuitableForInlineAtomic(LHS)) { 974a8ec7eb9SJohn McCall EnsureDest(E->getRHS()->getType()); 975a8ec7eb9SJohn McCall Visit(E->getRHS()); 976a8ec7eb9SJohn McCall CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false); 977a8ec7eb9SJohn McCall return; 978a8ec7eb9SJohn McCall } 979a8ec7eb9SJohn McCall 9807a51313dSChris Lattner // Codegen the RHS so that it stores directly into the LHS. 9818d6fc958SJohn McCall AggValueSlot LHSSlot = 9828d6fc958SJohn McCall AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed, 98346759f4fSJohn McCall needsGC(E->getLHS()->getType()), 984615ed1a3SChad Rosier AggValueSlot::IsAliased); 9857865220dSFariborz Jahanian // A non-volatile aggregate destination might have volatile member. 9867865220dSFariborz Jahanian if (!LHSSlot.isVolatile() && 9877865220dSFariborz Jahanian CGF.hasVolatileMember(E->getLHS()->getType())) 9887865220dSFariborz Jahanian LHSSlot.setVolatile(true); 9897865220dSFariborz Jahanian 9904e8ca4faSJohn McCall CGF.EmitAggExpr(E->getRHS(), LHSSlot); 9914e8ca4faSJohn McCall 9924e8ca4faSJohn McCall // Copy into the destination if the assignment isn't ignored. 9934e8ca4faSJohn McCall EmitFinalDestCopy(E->getType(), LHS); 9947a51313dSChris Lattner } 9957a51313dSChris Lattner 996c07a0c7eSJohn McCall void AggExprEmitter:: 997c07a0c7eSJohn McCall VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 998a612e79bSDaniel Dunbar llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 999a612e79bSDaniel Dunbar llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 1000a612e79bSDaniel Dunbar llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 10017a51313dSChris Lattner 1002c07a0c7eSJohn McCall // Bind the common expression if necessary. 100348fd89adSEli Friedman CodeGenFunction::OpaqueValueMapping binding(CGF, E); 1004c07a0c7eSJohn McCall 1005ce1de617SJohn McCall CodeGenFunction::ConditionalEvaluation eval(CGF); 100666242d6cSJustin Bogner CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock, 100766242d6cSJustin Bogner CGF.getProfileCount(E)); 10087a51313dSChris Lattner 10095b26f65bSJohn McCall // Save whether the destination's lifetime is externally managed. 1010cac93853SJohn McCall bool isExternallyDestructed = Dest.isExternallyDestructed(); 10117a51313dSChris Lattner 1012ce1de617SJohn McCall eval.begin(CGF); 1013ce1de617SJohn McCall CGF.EmitBlock(LHSBlock); 101466242d6cSJustin Bogner CGF.incrementProfileCounter(E); 1015c07a0c7eSJohn McCall Visit(E->getTrueExpr()); 1016ce1de617SJohn McCall eval.end(CGF); 10177a51313dSChris Lattner 1018ce1de617SJohn McCall assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!"); 1019ce1de617SJohn McCall CGF.Builder.CreateBr(ContBlock); 10207a51313dSChris Lattner 10215b26f65bSJohn McCall // If the result of an agg expression is unused, then the emission 10225b26f65bSJohn McCall // of the LHS might need to create a destination slot. That's fine 10235b26f65bSJohn McCall // with us, and we can safely emit the RHS into the same slot, but 1024cac93853SJohn McCall // we shouldn't claim that it's already being destructed. 1025cac93853SJohn McCall Dest.setExternallyDestructed(isExternallyDestructed); 10265b26f65bSJohn McCall 1027ce1de617SJohn McCall eval.begin(CGF); 1028ce1de617SJohn McCall CGF.EmitBlock(RHSBlock); 1029c07a0c7eSJohn McCall Visit(E->getFalseExpr()); 1030ce1de617SJohn McCall eval.end(CGF); 10317a51313dSChris Lattner 10327a51313dSChris Lattner CGF.EmitBlock(ContBlock); 10337a51313dSChris Lattner } 10347a51313dSChris Lattner 10355b2095ceSAnders Carlsson void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 103675807f23SEli Friedman Visit(CE->getChosenSubExpr()); 10375b2095ceSAnders Carlsson } 10385b2095ceSAnders Carlsson 103921911e89SEli Friedman void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 1040c7d5c94fSCharles Davis Address ArgValue = Address::invalid(); 1041c7d5c94fSCharles Davis Address ArgPtr = CGF.EmitVAArg(VE, ArgValue); 104213abd7e9SAnders Carlsson 104329b5f086SJames Y Knight // If EmitVAArg fails, emit an error. 10447f416cc4SJohn McCall if (!ArgPtr.isValid()) { 104529b5f086SJames Y Knight CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 1046020cddcfSSebastian Redl return; 1047020cddcfSSebastian Redl } 104813abd7e9SAnders Carlsson 10494e8ca4faSJohn McCall EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType())); 105021911e89SEli Friedman } 105121911e89SEli Friedman 10523be22e27SAnders Carlsson void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 10537a626f63SJohn McCall // Ensure that we have a slot, but if we already do, remember 1054cac93853SJohn McCall // whether it was externally destructed. 1055cac93853SJohn McCall bool wasExternallyDestructed = Dest.isExternallyDestructed(); 10564e8ca4faSJohn McCall EnsureDest(E->getType()); 1057cac93853SJohn McCall 1058cac93853SJohn McCall // We're going to push a destructor if there isn't already one. 1059cac93853SJohn McCall Dest.setExternallyDestructed(); 10603be22e27SAnders Carlsson 10613be22e27SAnders Carlsson Visit(E->getSubExpr()); 10623be22e27SAnders Carlsson 1063cac93853SJohn McCall // Push that destructor we promised. 1064cac93853SJohn McCall if (!wasExternallyDestructed) 10657f416cc4SJohn McCall CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress()); 10663be22e27SAnders Carlsson } 10673be22e27SAnders Carlsson 1068b7f8f594SAnders Carlsson void 10691619a504SAnders Carlsson AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 10707a626f63SJohn McCall AggValueSlot Slot = EnsureSlot(E->getType()); 10717a626f63SJohn McCall CGF.EmitCXXConstructExpr(E, Slot); 1072c82b86dfSAnders Carlsson } 1073c82b86dfSAnders Carlsson 10745179eb78SRichard Smith void AggExprEmitter::VisitCXXInheritedCtorInitExpr( 10755179eb78SRichard Smith const CXXInheritedCtorInitExpr *E) { 10765179eb78SRichard Smith AggValueSlot Slot = EnsureSlot(E->getType()); 10775179eb78SRichard Smith CGF.EmitInheritedCXXConstructorCall( 10785179eb78SRichard Smith E->getConstructor(), E->constructsVBase(), Slot.getAddress(), 10795179eb78SRichard Smith E->inheritedFromVBase(), E); 10805179eb78SRichard Smith } 10815179eb78SRichard Smith 1082c370a7eeSEli Friedman void 1083c370a7eeSEli Friedman AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) { 1084c370a7eeSEli Friedman AggValueSlot Slot = EnsureSlot(E->getType()); 1085c370a7eeSEli Friedman CGF.EmitLambdaExpr(E, Slot); 1086c370a7eeSEli Friedman } 1087c370a7eeSEli Friedman 10885d413781SJohn McCall void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) { 108908ef4660SJohn McCall CGF.enterFullExpression(E); 109008ef4660SJohn McCall CodeGenFunction::RunCleanupsScope cleanups(CGF); 109108ef4660SJohn McCall Visit(E->getSubExpr()); 1092b7f8f594SAnders Carlsson } 1093b7f8f594SAnders Carlsson 1094747eb784SDouglas Gregor void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 10957a626f63SJohn McCall QualType T = E->getType(); 10967a626f63SJohn McCall AggValueSlot Slot = EnsureSlot(T); 10977f416cc4SJohn McCall EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T)); 109818ada985SAnders Carlsson } 109918ada985SAnders Carlsson 110018ada985SAnders Carlsson void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 11017a626f63SJohn McCall QualType T = E->getType(); 11027a626f63SJohn McCall AggValueSlot Slot = EnsureSlot(T); 11037f416cc4SJohn McCall EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T)); 1104ff3507b9SNuno Lopes } 1105ff3507b9SNuno Lopes 110627a3631bSChris Lattner /// isSimpleZero - If emitting this value will obviously just cause a store of 110727a3631bSChris Lattner /// zero to memory, return true. This can return false if uncertain, so it just 110827a3631bSChris Lattner /// handles simple cases. 110927a3631bSChris Lattner static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) { 111091147596SPeter Collingbourne E = E->IgnoreParens(); 111191147596SPeter Collingbourne 111227a3631bSChris Lattner // 0 111327a3631bSChris Lattner if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) 111427a3631bSChris Lattner return IL->getValue() == 0; 111527a3631bSChris Lattner // +0.0 111627a3631bSChris Lattner if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) 111727a3631bSChris Lattner return FL->getValue().isPosZero(); 111827a3631bSChris Lattner // int() 111927a3631bSChris Lattner if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) && 112027a3631bSChris Lattner CGF.getTypes().isZeroInitializable(E->getType())) 112127a3631bSChris Lattner return true; 112227a3631bSChris Lattner // (int*)0 - Null pointer expressions. 112327a3631bSChris Lattner if (const CastExpr *ICE = dyn_cast<CastExpr>(E)) 1124402804b6SYaxun Liu return ICE->getCastKind() == CK_NullToPointer && 1125402804b6SYaxun Liu CGF.getTypes().isPointerZeroInitializable(E->getType()); 112627a3631bSChris Lattner // '\0' 112727a3631bSChris Lattner if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) 112827a3631bSChris Lattner return CL->getValue() == 0; 112927a3631bSChris Lattner 113027a3631bSChris Lattner // Otherwise, hard case: conservatively return false. 113127a3631bSChris Lattner return false; 113227a3631bSChris Lattner } 113327a3631bSChris Lattner 113427a3631bSChris Lattner 1135b247350eSAnders Carlsson void 1136615ed1a3SChad Rosier AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) { 11371553b190SJohn McCall QualType type = LV.getType(); 1138df0fe27bSMike Stump // FIXME: Ignore result? 1139579a05d7SChris Lattner // FIXME: Are initializers affected by volatile? 114027a3631bSChris Lattner if (Dest.isZeroed() && isSimpleZero(E, CGF)) { 114127a3631bSChris Lattner // Storing "i32 0" to a zero'd memory location is a noop. 114247fb9508SJohn McCall return; 1143d82a2ce3SRichard Smith } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) { 114447fb9508SJohn McCall return EmitNullInitializationToLValue(LV); 1145cb77930dSYunzhong Gao } else if (isa<NoInitExpr>(E)) { 1146cb77930dSYunzhong Gao // Do nothing. 1147cb77930dSYunzhong Gao return; 11481553b190SJohn McCall } else if (type->isReferenceType()) { 1149a1c9d4d9SRichard Smith RValue RV = CGF.EmitReferenceBindingToExpr(E); 115047fb9508SJohn McCall return CGF.EmitStoreThroughLValue(RV, LV); 115147fb9508SJohn McCall } 115247fb9508SJohn McCall 115347fb9508SJohn McCall switch (CGF.getEvaluationKind(type)) { 115447fb9508SJohn McCall case TEK_Complex: 115547fb9508SJohn McCall CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true); 115647fb9508SJohn McCall return; 115747fb9508SJohn McCall case TEK_Aggregate: 11588d6fc958SJohn McCall CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV, 11598d6fc958SJohn McCall AggValueSlot::IsDestructed, 11608d6fc958SJohn McCall AggValueSlot::DoesNotNeedGCBarriers, 1161a5efa738SJohn McCall AggValueSlot::IsNotAliased, 11621553b190SJohn McCall Dest.isZeroed())); 116347fb9508SJohn McCall return; 116447fb9508SJohn McCall case TEK_Scalar: 116547fb9508SJohn McCall if (LV.isSimple()) { 11668a13c418SCraig Topper CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false); 11676e313210SEli Friedman } else { 116855e1fbc8SJohn McCall CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV); 11697a51313dSChris Lattner } 117047fb9508SJohn McCall return; 117147fb9508SJohn McCall } 117247fb9508SJohn McCall llvm_unreachable("bad evaluation kind"); 1173579a05d7SChris Lattner } 1174579a05d7SChris Lattner 11751553b190SJohn McCall void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) { 11761553b190SJohn McCall QualType type = lv.getType(); 11771553b190SJohn McCall 117827a3631bSChris Lattner // If the destination slot is already zeroed out before the aggregate is 117927a3631bSChris Lattner // copied into it, we don't have to emit any zeros here. 11801553b190SJohn McCall if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type)) 118127a3631bSChris Lattner return; 118227a3631bSChris Lattner 118347fb9508SJohn McCall if (CGF.hasScalarEvaluationKind(type)) { 1184d82a2ce3SRichard Smith // For non-aggregates, we can store the appropriate null constant. 1185d82a2ce3SRichard Smith llvm::Value *null = CGF.CGM.EmitNullConstant(type); 118691d5bb1eSEli Friedman // Note that the following is not equivalent to 118791d5bb1eSEli Friedman // EmitStoreThroughBitfieldLValue for ARC types. 1188cb3785e4SEli Friedman if (lv.isBitField()) { 118991d5bb1eSEli Friedman CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv); 1190cb3785e4SEli Friedman } else { 119191d5bb1eSEli Friedman assert(lv.isSimple()); 119291d5bb1eSEli Friedman CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true); 1193cb3785e4SEli Friedman } 1194579a05d7SChris Lattner } else { 1195579a05d7SChris Lattner // There's a potential optimization opportunity in combining 1196579a05d7SChris Lattner // memsets; that would be easy for arrays, but relatively 1197579a05d7SChris Lattner // difficult for structures with the current code. 11981553b190SJohn McCall CGF.EmitNullInitialization(lv.getAddress(), lv.getType()); 1199579a05d7SChris Lattner } 1200579a05d7SChris Lattner } 1201579a05d7SChris Lattner 1202579a05d7SChris Lattner void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 1203f5d08c9eSEli Friedman #if 0 12046d11ec8cSEli Friedman // FIXME: Assess perf here? Figure out what cases are worth optimizing here 12056d11ec8cSEli Friedman // (Length of globals? Chunks of zeroed-out space?). 1206f5d08c9eSEli Friedman // 120718bb9284SMike Stump // If we can, prefer a copy from a global; this is a lot less code for long 120818bb9284SMike Stump // globals, and it's easier for the current optimizers to analyze. 12096d11ec8cSEli Friedman if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) { 1210c59bb48eSEli Friedman llvm::GlobalVariable* GV = 12116d11ec8cSEli Friedman new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true, 12126d11ec8cSEli Friedman llvm::GlobalValue::InternalLinkage, C, ""); 12134e8ca4faSJohn McCall EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType())); 1214c59bb48eSEli Friedman return; 1215c59bb48eSEli Friedman } 1216f5d08c9eSEli Friedman #endif 1217f53c0968SChris Lattner if (E->hadArrayRangeDesignator()) 1218bf7207a1SDouglas Gregor CGF.ErrorUnsupported(E, "GNU array range designator extension"); 1219bf7207a1SDouglas Gregor 1220122f88d4SRichard Smith if (E->isTransparent()) 1221122f88d4SRichard Smith return Visit(E->getInit(0)); 1222122f88d4SRichard Smith 1223be93c00aSRichard Smith AggValueSlot Dest = EnsureSlot(E->getType()); 1224be93c00aSRichard Smith 12257f416cc4SJohn McCall LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType()); 12267a626f63SJohn McCall 1227579a05d7SChris Lattner // Handle initialization of an array. 1228579a05d7SChris Lattner if (E->getType()->isArrayType()) { 12297f416cc4SJohn McCall auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType()); 1230e0ef348cSIvan A. Kosarev EmitArrayInit(Dest.getAddress(), AType, E->getType(), E); 1231579a05d7SChris Lattner return; 1232579a05d7SChris Lattner } 1233579a05d7SChris Lattner 1234579a05d7SChris Lattner assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 1235579a05d7SChris Lattner 1236579a05d7SChris Lattner // Do struct initialization; this code just sets each individual member 1237579a05d7SChris Lattner // to the approprate value. This makes bitfield support automatic; 1238579a05d7SChris Lattner // the disadvantage is that the generated code is more difficult for 1239579a05d7SChris Lattner // the optimizer, especially with bitfields. 1240579a05d7SChris Lattner unsigned NumInitElements = E->getNumInits(); 12413b935d33SJohn McCall RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl(); 124252bcf963SChris Lattner 1243872307e2SRichard Smith // We'll need to enter cleanup scopes in case any of the element 1244872307e2SRichard Smith // initializers throws an exception. 1245872307e2SRichard Smith SmallVector<EHScopeStack::stable_iterator, 16> cleanups; 1246872307e2SRichard Smith llvm::Instruction *cleanupDominator = nullptr; 1247872307e2SRichard Smith 1248872307e2SRichard Smith unsigned curInitIndex = 0; 1249872307e2SRichard Smith 1250872307e2SRichard Smith // Emit initialization of base classes. 1251872307e2SRichard Smith if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) { 1252872307e2SRichard Smith assert(E->getNumInits() >= CXXRD->getNumBases() && 1253872307e2SRichard Smith "missing initializer for base class"); 1254872307e2SRichard Smith for (auto &Base : CXXRD->bases()) { 1255872307e2SRichard Smith assert(!Base.isVirtual() && "should not see vbases here"); 1256872307e2SRichard Smith auto *BaseRD = Base.getType()->getAsCXXRecordDecl(); 1257872307e2SRichard Smith Address V = CGF.GetAddressOfDirectBaseInCompleteClass( 1258872307e2SRichard Smith Dest.getAddress(), CXXRD, BaseRD, 1259872307e2SRichard Smith /*isBaseVirtual*/ false); 1260872307e2SRichard Smith AggValueSlot AggSlot = 1261872307e2SRichard Smith AggValueSlot::forAddr(V, Qualifiers(), 1262872307e2SRichard Smith AggValueSlot::IsDestructed, 1263872307e2SRichard Smith AggValueSlot::DoesNotNeedGCBarriers, 1264872307e2SRichard Smith AggValueSlot::IsNotAliased); 1265872307e2SRichard Smith CGF.EmitAggExpr(E->getInit(curInitIndex++), AggSlot); 1266872307e2SRichard Smith 1267872307e2SRichard Smith if (QualType::DestructionKind dtorKind = 1268872307e2SRichard Smith Base.getType().isDestructedType()) { 1269872307e2SRichard Smith CGF.pushDestroy(dtorKind, V, Base.getType()); 1270872307e2SRichard Smith cleanups.push_back(CGF.EHStack.stable_begin()); 1271872307e2SRichard Smith } 1272872307e2SRichard Smith } 1273872307e2SRichard Smith } 1274872307e2SRichard Smith 1275852c9db7SRichard Smith // Prepare a 'this' for CXXDefaultInitExprs. 12767f416cc4SJohn McCall CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress()); 1277852c9db7SRichard Smith 12783b935d33SJohn McCall if (record->isUnion()) { 12795169570eSDouglas Gregor // Only initialize one field of a union. The field itself is 12805169570eSDouglas Gregor // specified by the initializer list. 12815169570eSDouglas Gregor if (!E->getInitializedFieldInUnion()) { 12825169570eSDouglas Gregor // Empty union; we have nothing to do. 12835169570eSDouglas Gregor 12845169570eSDouglas Gregor #ifndef NDEBUG 12855169570eSDouglas Gregor // Make sure that it's really an empty and not a failure of 12865169570eSDouglas Gregor // semantic analysis. 1287e8a8baefSAaron Ballman for (const auto *Field : record->fields()) 12885169570eSDouglas Gregor assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 12895169570eSDouglas Gregor #endif 12905169570eSDouglas Gregor return; 12915169570eSDouglas Gregor } 12925169570eSDouglas Gregor 12935169570eSDouglas Gregor // FIXME: volatility 12945169570eSDouglas Gregor FieldDecl *Field = E->getInitializedFieldInUnion(); 12955169570eSDouglas Gregor 12967f1ff600SEli Friedman LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field); 12975169570eSDouglas Gregor if (NumInitElements) { 12985169570eSDouglas Gregor // Store the initializer into the field 1299615ed1a3SChad Rosier EmitInitializationToLValue(E->getInit(0), FieldLoc); 13005169570eSDouglas Gregor } else { 130127a3631bSChris Lattner // Default-initialize to null. 13021553b190SJohn McCall EmitNullInitializationToLValue(FieldLoc); 13035169570eSDouglas Gregor } 13045169570eSDouglas Gregor 13055169570eSDouglas Gregor return; 13065169570eSDouglas Gregor } 1307579a05d7SChris Lattner 1308579a05d7SChris Lattner // Here we iterate over the fields; this makes it simpler to both 1309579a05d7SChris Lattner // default-initialize fields and skip over unnamed fields. 1310e8a8baefSAaron Ballman for (const auto *field : record->fields()) { 13113b935d33SJohn McCall // We're done once we hit the flexible array member. 13123b935d33SJohn McCall if (field->getType()->isIncompleteArrayType()) 131391f84216SDouglas Gregor break; 131491f84216SDouglas Gregor 13153b935d33SJohn McCall // Always skip anonymous bitfields. 13163b935d33SJohn McCall if (field->isUnnamedBitfield()) 1317579a05d7SChris Lattner continue; 131817bd094aSDouglas Gregor 13193b935d33SJohn McCall // We're done if we reach the end of the explicit initializers, we 13203b935d33SJohn McCall // have a zeroed object, and the rest of the fields are 13213b935d33SJohn McCall // zero-initializable. 13223b935d33SJohn McCall if (curInitIndex == NumInitElements && Dest.isZeroed() && 132327a3631bSChris Lattner CGF.getTypes().isZeroInitializable(E->getType())) 132427a3631bSChris Lattner break; 132527a3631bSChris Lattner 13267f1ff600SEli Friedman 1327e8a8baefSAaron Ballman LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field); 13287c1baf46SFariborz Jahanian // We never generate write-barries for initialized fields. 13293b935d33SJohn McCall LV.setNonGC(true); 133027a3631bSChris Lattner 13313b935d33SJohn McCall if (curInitIndex < NumInitElements) { 1332e18aaf2cSChris Lattner // Store the initializer into the field. 1333615ed1a3SChad Rosier EmitInitializationToLValue(E->getInit(curInitIndex++), LV); 1334579a05d7SChris Lattner } else { 13352c51880aSSimon Pilgrim // We're out of initializers; default-initialize to null 13363b935d33SJohn McCall EmitNullInitializationToLValue(LV); 13373b935d33SJohn McCall } 13383b935d33SJohn McCall 13393b935d33SJohn McCall // Push a destructor if necessary. 13403b935d33SJohn McCall // FIXME: if we have an array of structures, all explicitly 13413b935d33SJohn McCall // initialized, we can end up pushing a linear number of cleanups. 13423b935d33SJohn McCall bool pushedCleanup = false; 13433b935d33SJohn McCall if (QualType::DestructionKind dtorKind 13443b935d33SJohn McCall = field->getType().isDestructedType()) { 13453b935d33SJohn McCall assert(LV.isSimple()); 13463b935d33SJohn McCall if (CGF.needsEHCleanup(dtorKind)) { 1347f4beacd0SJohn McCall if (!cleanupDominator) 13487f416cc4SJohn McCall cleanupDominator = CGF.Builder.CreateAlignedLoad( 13495ee4b9a1SReid Kleckner CGF.Int8Ty, 13507f416cc4SJohn McCall llvm::Constant::getNullValue(CGF.Int8PtrTy), 13517f416cc4SJohn McCall CharUnits::One()); // placeholder 1352f4beacd0SJohn McCall 13533b935d33SJohn McCall CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(), 13543b935d33SJohn McCall CGF.getDestroyer(dtorKind), false); 13553b935d33SJohn McCall cleanups.push_back(CGF.EHStack.stable_begin()); 13563b935d33SJohn McCall pushedCleanup = true; 13573b935d33SJohn McCall } 1358579a05d7SChris Lattner } 135927a3631bSChris Lattner 136027a3631bSChris Lattner // If the GEP didn't get used because of a dead zero init or something 136127a3631bSChris Lattner // else, clean it up for -O0 builds and general tidiness. 13623b935d33SJohn McCall if (!pushedCleanup && LV.isSimple()) 136327a3631bSChris Lattner if (llvm::GetElementPtrInst *GEP = 13647f416cc4SJohn McCall dyn_cast<llvm::GetElementPtrInst>(LV.getPointer())) 136527a3631bSChris Lattner if (GEP->use_empty()) 136627a3631bSChris Lattner GEP->eraseFromParent(); 13677a51313dSChris Lattner } 13683b935d33SJohn McCall 13693b935d33SJohn McCall // Deactivate all the partial cleanups in reverse order, which 13703b935d33SJohn McCall // generally means popping them. 13713b935d33SJohn McCall for (unsigned i = cleanups.size(); i != 0; --i) 1372f4beacd0SJohn McCall CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator); 1373f4beacd0SJohn McCall 1374f4beacd0SJohn McCall // Destroy the placeholder if we made one. 1375f4beacd0SJohn McCall if (cleanupDominator) 1376f4beacd0SJohn McCall cleanupDominator->eraseFromParent(); 13777a51313dSChris Lattner } 13787a51313dSChris Lattner 1379939b6880SRichard Smith void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E, 1380939b6880SRichard Smith llvm::Value *outerBegin) { 1381410306bfSRichard Smith // Emit the common subexpression. 1382410306bfSRichard Smith CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr()); 1383410306bfSRichard Smith 1384410306bfSRichard Smith Address destPtr = EnsureSlot(E->getType()).getAddress(); 1385410306bfSRichard Smith uint64_t numElements = E->getArraySize().getZExtValue(); 1386410306bfSRichard Smith 1387410306bfSRichard Smith if (!numElements) 1388410306bfSRichard Smith return; 1389410306bfSRichard Smith 1390410306bfSRichard Smith // destPtr is an array*. Construct an elementType* by drilling down a level. 1391410306bfSRichard Smith llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0); 1392410306bfSRichard Smith llvm::Value *indices[] = {zero, zero}; 1393410306bfSRichard Smith llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getPointer(), indices, 1394410306bfSRichard Smith "arrayinit.begin"); 1395410306bfSRichard Smith 1396939b6880SRichard Smith // Prepare to special-case multidimensional array initialization: we avoid 1397939b6880SRichard Smith // emitting multiple destructor loops in that case. 1398939b6880SRichard Smith if (!outerBegin) 1399939b6880SRichard Smith outerBegin = begin; 1400939b6880SRichard Smith ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr()); 1401939b6880SRichard Smith 140230e304e2SRichard Smith QualType elementType = 140330e304e2SRichard Smith CGF.getContext().getAsArrayType(E->getType())->getElementType(); 1404410306bfSRichard Smith CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType); 1405410306bfSRichard Smith CharUnits elementAlign = 1406410306bfSRichard Smith destPtr.getAlignment().alignmentOfArrayElement(elementSize); 1407410306bfSRichard Smith 1408410306bfSRichard Smith llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1409410306bfSRichard Smith llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body"); 1410410306bfSRichard Smith 1411410306bfSRichard Smith // Jump into the body. 1412410306bfSRichard Smith CGF.EmitBlock(bodyBB); 1413410306bfSRichard Smith llvm::PHINode *index = 1414410306bfSRichard Smith Builder.CreatePHI(zero->getType(), 2, "arrayinit.index"); 1415410306bfSRichard Smith index->addIncoming(zero, entryBB); 1416410306bfSRichard Smith llvm::Value *element = Builder.CreateInBoundsGEP(begin, index); 1417410306bfSRichard Smith 141830e304e2SRichard Smith // Prepare for a cleanup. 141930e304e2SRichard Smith QualType::DestructionKind dtorKind = elementType.isDestructedType(); 142030e304e2SRichard Smith EHScopeStack::stable_iterator cleanup; 1421939b6880SRichard Smith if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) { 1422939b6880SRichard Smith if (outerBegin->getType() != element->getType()) 1423939b6880SRichard Smith outerBegin = Builder.CreateBitCast(outerBegin, element->getType()); 1424939b6880SRichard Smith CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType, 1425939b6880SRichard Smith elementAlign, 1426939b6880SRichard Smith CGF.getDestroyer(dtorKind)); 142730e304e2SRichard Smith cleanup = CGF.EHStack.stable_begin(); 142830e304e2SRichard Smith } else { 142930e304e2SRichard Smith dtorKind = QualType::DK_none; 143030e304e2SRichard Smith } 1431410306bfSRichard Smith 1432410306bfSRichard Smith // Emit the actual filler expression. 1433410306bfSRichard Smith { 143430e304e2SRichard Smith // Temporaries created in an array initialization loop are destroyed 143530e304e2SRichard Smith // at the end of each iteration. 143630e304e2SRichard Smith CodeGenFunction::RunCleanupsScope CleanupsScope(CGF); 1437410306bfSRichard Smith CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index); 1438410306bfSRichard Smith LValue elementLV = 1439410306bfSRichard Smith CGF.MakeAddrLValue(Address(element, elementAlign), elementType); 1440939b6880SRichard Smith 1441939b6880SRichard Smith if (InnerLoop) { 1442939b6880SRichard Smith // If the subexpression is an ArrayInitLoopExpr, share its cleanup. 1443939b6880SRichard Smith auto elementSlot = AggValueSlot::forLValue( 1444939b6880SRichard Smith elementLV, AggValueSlot::IsDestructed, 1445939b6880SRichard Smith AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased); 1446939b6880SRichard Smith AggExprEmitter(CGF, elementSlot, false) 1447939b6880SRichard Smith .VisitArrayInitLoopExpr(InnerLoop, outerBegin); 1448939b6880SRichard Smith } else 1449410306bfSRichard Smith EmitInitializationToLValue(E->getSubExpr(), elementLV); 1450410306bfSRichard Smith } 1451410306bfSRichard Smith 1452410306bfSRichard Smith // Move on to the next element. 1453410306bfSRichard Smith llvm::Value *nextIndex = Builder.CreateNUWAdd( 1454410306bfSRichard Smith index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next"); 1455410306bfSRichard Smith index->addIncoming(nextIndex, Builder.GetInsertBlock()); 1456410306bfSRichard Smith 1457410306bfSRichard Smith // Leave the loop if we're done. 1458410306bfSRichard Smith llvm::Value *done = Builder.CreateICmpEQ( 1459410306bfSRichard Smith nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements), 1460410306bfSRichard Smith "arrayinit.done"); 1461410306bfSRichard Smith llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end"); 1462410306bfSRichard Smith Builder.CreateCondBr(done, endBB, bodyBB); 1463410306bfSRichard Smith 1464410306bfSRichard Smith CGF.EmitBlock(endBB); 1465410306bfSRichard Smith 1466410306bfSRichard Smith // Leave the partial-array cleanup if we entered one. 146730e304e2SRichard Smith if (dtorKind) 146830e304e2SRichard Smith CGF.DeactivateCleanupBlock(cleanup, index); 1469410306bfSRichard Smith } 1470410306bfSRichard Smith 1471cb77930dSYunzhong Gao void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) { 1472cb77930dSYunzhong Gao AggValueSlot Dest = EnsureSlot(E->getType()); 1473cb77930dSYunzhong Gao 14747f416cc4SJohn McCall LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType()); 1475cb77930dSYunzhong Gao EmitInitializationToLValue(E->getBase(), DestLV); 1476cb77930dSYunzhong Gao VisitInitListExpr(E->getUpdater()); 1477cb77930dSYunzhong Gao } 1478cb77930dSYunzhong Gao 14797a51313dSChris Lattner //===----------------------------------------------------------------------===// 14807a51313dSChris Lattner // Entry Points into this File 14817a51313dSChris Lattner //===----------------------------------------------------------------------===// 14827a51313dSChris Lattner 148327a3631bSChris Lattner /// GetNumNonZeroBytesInInit - Get an approximate count of the number of 148427a3631bSChris Lattner /// non-zero bytes that will be stored when outputting the initializer for the 148527a3631bSChris Lattner /// specified initializer expression. 1486df94cb7dSKen Dyck static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { 148791147596SPeter Collingbourne E = E->IgnoreParens(); 148827a3631bSChris Lattner 148927a3631bSChris Lattner // 0 and 0.0 won't require any non-zero stores! 1490df94cb7dSKen Dyck if (isSimpleZero(E, CGF)) return CharUnits::Zero(); 149127a3631bSChris Lattner 149227a3631bSChris Lattner // If this is an initlist expr, sum up the size of sizes of the (present) 149327a3631bSChris Lattner // elements. If this is something weird, assume the whole thing is non-zero. 149427a3631bSChris Lattner const InitListExpr *ILE = dyn_cast<InitListExpr>(E); 14958a13c418SCraig Topper if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType())) 1496df94cb7dSKen Dyck return CGF.getContext().getTypeSizeInChars(E->getType()); 149727a3631bSChris Lattner 1498c5cc2fb9SChris Lattner // InitListExprs for structs have to be handled carefully. If there are 1499c5cc2fb9SChris Lattner // reference members, we need to consider the size of the reference, not the 1500c5cc2fb9SChris Lattner // referencee. InitListExprs for unions and arrays can't have references. 15015cd84755SChris Lattner if (const RecordType *RT = E->getType()->getAs<RecordType>()) { 15025cd84755SChris Lattner if (!RT->isUnionType()) { 1503c5cc2fb9SChris Lattner RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 1504df94cb7dSKen Dyck CharUnits NumNonZeroBytes = CharUnits::Zero(); 1505c5cc2fb9SChris Lattner 1506c5cc2fb9SChris Lattner unsigned ILEElement = 0; 1507872307e2SRichard Smith if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD)) 15086365e464SRichard Smith while (ILEElement != CXXRD->getNumBases()) 1509872307e2SRichard Smith NumNonZeroBytes += 1510872307e2SRichard Smith GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF); 1511e8a8baefSAaron Ballman for (const auto *Field : SD->fields()) { 1512c5cc2fb9SChris Lattner // We're done once we hit the flexible array member or run out of 1513c5cc2fb9SChris Lattner // InitListExpr elements. 1514c5cc2fb9SChris Lattner if (Field->getType()->isIncompleteArrayType() || 1515c5cc2fb9SChris Lattner ILEElement == ILE->getNumInits()) 1516c5cc2fb9SChris Lattner break; 1517c5cc2fb9SChris Lattner if (Field->isUnnamedBitfield()) 1518c5cc2fb9SChris Lattner continue; 1519c5cc2fb9SChris Lattner 1520c5cc2fb9SChris Lattner const Expr *E = ILE->getInit(ILEElement++); 1521c5cc2fb9SChris Lattner 1522c5cc2fb9SChris Lattner // Reference values are always non-null and have the width of a pointer. 15235cd84755SChris Lattner if (Field->getType()->isReferenceType()) 1524df94cb7dSKen Dyck NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits( 1525c8e01705SJohn McCall CGF.getTarget().getPointerWidth(0)); 15265cd84755SChris Lattner else 1527c5cc2fb9SChris Lattner NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF); 1528c5cc2fb9SChris Lattner } 1529c5cc2fb9SChris Lattner 1530c5cc2fb9SChris Lattner return NumNonZeroBytes; 1531c5cc2fb9SChris Lattner } 15325cd84755SChris Lattner } 1533c5cc2fb9SChris Lattner 1534c5cc2fb9SChris Lattner 1535df94cb7dSKen Dyck CharUnits NumNonZeroBytes = CharUnits::Zero(); 153627a3631bSChris Lattner for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) 153727a3631bSChris Lattner NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF); 153827a3631bSChris Lattner return NumNonZeroBytes; 153927a3631bSChris Lattner } 154027a3631bSChris Lattner 154127a3631bSChris Lattner /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of 154227a3631bSChris Lattner /// zeros in it, emit a memset and avoid storing the individual zeros. 154327a3631bSChris Lattner /// 154427a3631bSChris Lattner static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E, 154527a3631bSChris Lattner CodeGenFunction &CGF) { 154627a3631bSChris Lattner // If the slot is already known to be zeroed, nothing to do. Don't mess with 154727a3631bSChris Lattner // volatile stores. 15487f416cc4SJohn McCall if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid()) 15498a13c418SCraig Topper return; 155027a3631bSChris Lattner 155103535265SArgyrios Kyrtzidis // C++ objects with a user-declared constructor don't need zero'ing. 15529c6890a7SRichard Smith if (CGF.getLangOpts().CPlusPlus) 155303535265SArgyrios Kyrtzidis if (const RecordType *RT = CGF.getContext() 155403535265SArgyrios Kyrtzidis .getBaseElementType(E->getType())->getAs<RecordType>()) { 155503535265SArgyrios Kyrtzidis const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 155603535265SArgyrios Kyrtzidis if (RD->hasUserDeclaredConstructor()) 155703535265SArgyrios Kyrtzidis return; 155803535265SArgyrios Kyrtzidis } 155903535265SArgyrios Kyrtzidis 156027a3631bSChris Lattner // If the type is 16-bytes or smaller, prefer individual stores over memset. 15617f416cc4SJohn McCall CharUnits Size = CGF.getContext().getTypeSizeInChars(E->getType()); 15627f416cc4SJohn McCall if (Size <= CharUnits::fromQuantity(16)) 156327a3631bSChris Lattner return; 156427a3631bSChris Lattner 156527a3631bSChris Lattner // Check to see if over 3/4 of the initializer are known to be zero. If so, 156627a3631bSChris Lattner // we prefer to emit memset + individual stores for the rest. 1567239a3357SKen Dyck CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF); 15687f416cc4SJohn McCall if (NumNonZeroBytes*4 > Size) 156927a3631bSChris Lattner return; 157027a3631bSChris Lattner 157127a3631bSChris Lattner // Okay, it seems like a good idea to use an initial memset, emit the call. 15727f416cc4SJohn McCall llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity()); 157327a3631bSChris Lattner 15747f416cc4SJohn McCall Address Loc = Slot.getAddress(); 15757f416cc4SJohn McCall Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty); 15767f416cc4SJohn McCall CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false); 157727a3631bSChris Lattner 157827a3631bSChris Lattner // Tell the AggExprEmitter that the slot is known zero. 157927a3631bSChris Lattner Slot.setZeroed(); 158027a3631bSChris Lattner } 158127a3631bSChris Lattner 158227a3631bSChris Lattner 158327a3631bSChris Lattner 158427a3631bSChris Lattner 158525306cacSMike Stump /// EmitAggExpr - Emit the computation of the specified expression of aggregate 158625306cacSMike Stump /// type. The result is computed into DestPtr. Note that if DestPtr is null, 158725306cacSMike Stump /// the value of the aggregate expression is not needed. If VolatileDest is 158825306cacSMike Stump /// true, DestPtr cannot be 0. 15894e8ca4faSJohn McCall void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) { 159047fb9508SJohn McCall assert(E && hasAggregateEvaluationKind(E->getType()) && 15917a51313dSChris Lattner "Invalid aggregate expression to emit"); 15927f416cc4SJohn McCall assert((Slot.getAddress().isValid() || Slot.isIgnored()) && 159327a3631bSChris Lattner "slot has bits but no address"); 15947a51313dSChris Lattner 159527a3631bSChris Lattner // Optimize the slot if possible. 159627a3631bSChris Lattner CheckAggExprForMemSetUse(Slot, E, *this); 159727a3631bSChris Lattner 15986aab1117SLeny Kholodov AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E)); 15997a51313dSChris Lattner } 16000bc8e86dSDaniel Dunbar 1601d0bc7b9dSDaniel Dunbar LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) { 160247fb9508SJohn McCall assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!"); 16037f416cc4SJohn McCall Address Temp = CreateMemTemp(E->getType()); 16042e442a00SDaniel Dunbar LValue LV = MakeAddrLValue(Temp, E->getType()); 16058d6fc958SJohn McCall EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed, 160646759f4fSJohn McCall AggValueSlot::DoesNotNeedGCBarriers, 1607615ed1a3SChad Rosier AggValueSlot::IsNotAliased)); 16082e442a00SDaniel Dunbar return LV; 1609d0bc7b9dSDaniel Dunbar } 1610d0bc7b9dSDaniel Dunbar 16111860b520SIvan A. Kosarev void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, 16121860b520SIvan A. Kosarev QualType Ty, bool isVolatile, 16131ca66919SBenjamin Kramer bool isAssignment) { 1614615ed1a3SChad Rosier assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 16150bc8e86dSDaniel Dunbar 16161860b520SIvan A. Kosarev Address DestPtr = Dest.getAddress(); 16171860b520SIvan A. Kosarev Address SrcPtr = Src.getAddress(); 16181860b520SIvan A. Kosarev 16199c6890a7SRichard Smith if (getLangOpts().CPlusPlus) { 1620615ed1a3SChad Rosier if (const RecordType *RT = Ty->getAs<RecordType>()) { 1621615ed1a3SChad Rosier CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 1622615ed1a3SChad Rosier assert((Record->hasTrivialCopyConstructor() || 1623615ed1a3SChad Rosier Record->hasTrivialCopyAssignment() || 1624615ed1a3SChad Rosier Record->hasTrivialMoveConstructor() || 1625419bd094SRichard Smith Record->hasTrivialMoveAssignment() || 1626419bd094SRichard Smith Record->isUnion()) && 162716488472SRichard Smith "Trying to aggregate-copy a type without a trivial copy/move " 1628f22101a0SDouglas Gregor "constructor or assignment operator"); 1629615ed1a3SChad Rosier // Ignore empty classes in C++. 1630615ed1a3SChad Rosier if (Record->isEmpty()) 163116e94af6SAnders Carlsson return; 163216e94af6SAnders Carlsson } 163316e94af6SAnders Carlsson } 163416e94af6SAnders Carlsson 1635ca05dfefSChris Lattner // Aggregate assignment turns into llvm.memcpy. This is almost valid per 16363ef668c2SChris Lattner // C99 6.5.16.1p3, which states "If the value being stored in an object is 16373ef668c2SChris Lattner // read from another object that overlaps in anyway the storage of the first 16383ef668c2SChris Lattner // object, then the overlap shall be exact and the two objects shall have 16393ef668c2SChris Lattner // qualified or unqualified versions of a compatible type." 16403ef668c2SChris Lattner // 1641ca05dfefSChris Lattner // memcpy is not defined if the source and destination pointers are exactly 16423ef668c2SChris Lattner // equal, but other compilers do this optimization, and almost every memcpy 16433ef668c2SChris Lattner // implementation handles this case safely. If there is a libc that does not 16443ef668c2SChris Lattner // safely handle this, we can add a target hook. 16450bc8e86dSDaniel Dunbar 16467f416cc4SJohn McCall // Get data size info for this aggregate. If this is an assignment, 16477f416cc4SJohn McCall // don't copy the tail padding, because we might be assigning into a 16487f416cc4SJohn McCall // base subobject where the tail padding is claimed. Otherwise, 16497f416cc4SJohn McCall // copying it is fine. 16501ca66919SBenjamin Kramer std::pair<CharUnits, CharUnits> TypeInfo; 16511ca66919SBenjamin Kramer if (isAssignment) 16521ca66919SBenjamin Kramer TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty); 16531ca66919SBenjamin Kramer else 16541ca66919SBenjamin Kramer TypeInfo = getContext().getTypeInfoInChars(Ty); 1655615ed1a3SChad Rosier 165616dc7b68SAlexey Bataev llvm::Value *SizeVal = nullptr; 165716dc7b68SAlexey Bataev if (TypeInfo.first.isZero()) { 165816dc7b68SAlexey Bataev // But note that getTypeInfo returns 0 for a VLA. 165916dc7b68SAlexey Bataev if (auto *VAT = dyn_cast_or_null<VariableArrayType>( 166016dc7b68SAlexey Bataev getContext().getAsArrayType(Ty))) { 166116dc7b68SAlexey Bataev QualType BaseEltTy; 166216dc7b68SAlexey Bataev SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr); 166316dc7b68SAlexey Bataev TypeInfo = getContext().getTypeInfoDataSizeInChars(BaseEltTy); 166416dc7b68SAlexey Bataev std::pair<CharUnits, CharUnits> LastElementTypeInfo; 166516dc7b68SAlexey Bataev if (!isAssignment) 166616dc7b68SAlexey Bataev LastElementTypeInfo = getContext().getTypeInfoInChars(BaseEltTy); 166716dc7b68SAlexey Bataev assert(!TypeInfo.first.isZero()); 166816dc7b68SAlexey Bataev SizeVal = Builder.CreateNUWMul( 166916dc7b68SAlexey Bataev SizeVal, 167016dc7b68SAlexey Bataev llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity())); 167116dc7b68SAlexey Bataev if (!isAssignment) { 167216dc7b68SAlexey Bataev SizeVal = Builder.CreateNUWSub( 167316dc7b68SAlexey Bataev SizeVal, 167416dc7b68SAlexey Bataev llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity())); 167516dc7b68SAlexey Bataev SizeVal = Builder.CreateNUWAdd( 167616dc7b68SAlexey Bataev SizeVal, llvm::ConstantInt::get( 167716dc7b68SAlexey Bataev SizeTy, LastElementTypeInfo.first.getQuantity())); 167816dc7b68SAlexey Bataev } 167916dc7b68SAlexey Bataev } 168016dc7b68SAlexey Bataev } 168116dc7b68SAlexey Bataev if (!SizeVal) { 168216dc7b68SAlexey Bataev SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()); 168316dc7b68SAlexey Bataev } 1684615ed1a3SChad Rosier 1685615ed1a3SChad Rosier // FIXME: If we have a volatile struct, the optimizer can remove what might 1686615ed1a3SChad Rosier // appear to be `extra' memory ops: 1687615ed1a3SChad Rosier // 1688615ed1a3SChad Rosier // volatile struct { int i; } a, b; 1689615ed1a3SChad Rosier // 1690615ed1a3SChad Rosier // int main() { 1691615ed1a3SChad Rosier // a = b; 1692615ed1a3SChad Rosier // a = b; 1693615ed1a3SChad Rosier // } 1694615ed1a3SChad Rosier // 1695615ed1a3SChad Rosier // we need to use a different call here. We use isVolatile to indicate when 1696615ed1a3SChad Rosier // either the source or the destination is volatile. 1697615ed1a3SChad Rosier 16987f416cc4SJohn McCall DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty); 16997f416cc4SJohn McCall SrcPtr = Builder.CreateElementBitCast(SrcPtr, Int8Ty); 1700615ed1a3SChad Rosier 1701615ed1a3SChad Rosier // Don't do any of the memmove_collectable tests if GC isn't set. 1702615ed1a3SChad Rosier if (CGM.getLangOpts().getGC() == LangOptions::NonGC) { 1703615ed1a3SChad Rosier // fall through 1704615ed1a3SChad Rosier } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 1705615ed1a3SChad Rosier RecordDecl *Record = RecordTy->getDecl(); 1706615ed1a3SChad Rosier if (Record->hasObjectMember()) { 1707615ed1a3SChad Rosier CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 1708615ed1a3SChad Rosier SizeVal); 1709615ed1a3SChad Rosier return; 1710615ed1a3SChad Rosier } 1711615ed1a3SChad Rosier } else if (Ty->isArrayType()) { 1712615ed1a3SChad Rosier QualType BaseType = getContext().getBaseElementType(Ty); 1713615ed1a3SChad Rosier if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 1714615ed1a3SChad Rosier if (RecordTy->getDecl()->hasObjectMember()) { 1715615ed1a3SChad Rosier CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 1716615ed1a3SChad Rosier SizeVal); 1717615ed1a3SChad Rosier return; 1718615ed1a3SChad Rosier } 1719615ed1a3SChad Rosier } 1720615ed1a3SChad Rosier } 1721615ed1a3SChad Rosier 17227f416cc4SJohn McCall auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile); 17237f416cc4SJohn McCall 172422695fceSDan Gohman // Determine the metadata to describe the position of any padding in this 172522695fceSDan Gohman // memcpy, as well as the TBAA tags for the members of the struct, in case 172622695fceSDan Gohman // the optimizer wishes to expand it in to scalar memory operations. 17277f416cc4SJohn McCall if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty)) 17287f416cc4SJohn McCall Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag); 17291860b520SIvan A. Kosarev 17301860b520SIvan A. Kosarev if (CGM.getCodeGenOpts().NewStructPathTBAA) { 17311860b520SIvan A. Kosarev TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer( 17321860b520SIvan A. Kosarev Dest.getTBAAInfo(), Src.getTBAAInfo()); 17331860b520SIvan A. Kosarev CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo); 17341860b520SIvan A. Kosarev } 17350bc8e86dSDaniel Dunbar } 1736