Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGExprAgg.cpp
35234 views
//===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This contains code to emit Aggregate Expr nodes as LLVM code.9//10//===----------------------------------------------------------------------===//1112#include "CGCXXABI.h"13#include "CGObjCRuntime.h"14#include "CodeGenFunction.h"15#include "CodeGenModule.h"16#include "ConstantEmitter.h"17#include "EHScopeStack.h"18#include "TargetInfo.h"19#include "clang/AST/ASTContext.h"20#include "clang/AST/Attr.h"21#include "clang/AST/DeclCXX.h"22#include "clang/AST/DeclTemplate.h"23#include "clang/AST/StmtVisitor.h"24#include "llvm/IR/Constants.h"25#include "llvm/IR/Function.h"26#include "llvm/IR/GlobalVariable.h"27#include "llvm/IR/Instruction.h"28#include "llvm/IR/IntrinsicInst.h"29#include "llvm/IR/Intrinsics.h"30using namespace clang;31using namespace CodeGen;3233//===----------------------------------------------------------------------===//34// Aggregate Expression Emitter35//===----------------------------------------------------------------------===//3637namespace llvm {38extern cl::opt<bool> EnableSingleByteCoverage;39} // namespace llvm4041namespace {42class AggExprEmitter : public StmtVisitor<AggExprEmitter> {43CodeGenFunction &CGF;44CGBuilderTy &Builder;45AggValueSlot Dest;46bool IsResultUnused;4748AggValueSlot EnsureSlot(QualType T) {49if (!Dest.isIgnored()) return Dest;50return CGF.CreateAggTemp(T, "agg.tmp.ensured");51}52void EnsureDest(QualType T) {53if (!Dest.isIgnored()) return;54Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");55}5657// Calls `Fn` with a valid return value slot, potentially creating a temporary58// to do so. If a temporary is created, an appropriate copy into `Dest` will59// be emitted, as will lifetime markers.60//61// The given function should take a ReturnValueSlot, and return an RValue that62// points to said slot.63void withReturnValueSlot(const Expr *E,64llvm::function_ref<RValue(ReturnValueSlot)> Fn);6566public:67AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)68: CGF(cgf), Builder(CGF.Builder), Dest(Dest),69IsResultUnused(IsResultUnused) { }7071//===--------------------------------------------------------------------===//72// Utilities73//===--------------------------------------------------------------------===//7475/// EmitAggLoadOfLValue - Given an expression with aggregate type that76/// represents a value lvalue, this method emits the address of the lvalue,77/// then loads the result into DestPtr.78void EmitAggLoadOfLValue(const Expr *E);7980/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.81/// SrcIsRValue is true if source comes from an RValue.82void EmitFinalDestCopy(QualType type, const LValue &src,83CodeGenFunction::ExprValueKind SrcValueKind =84CodeGenFunction::EVK_NonRValue);85void EmitFinalDestCopy(QualType type, RValue src);86void EmitCopy(QualType type, const AggValueSlot &dest,87const AggValueSlot &src);8889void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, QualType ArrayQTy,90Expr *ExprToVisit, ArrayRef<Expr *> Args,91Expr *ArrayFiller);9293AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {94if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))95return AggValueSlot::NeedsGCBarriers;96return AggValueSlot::DoesNotNeedGCBarriers;97}9899bool TypeRequiresGCollection(QualType T);100101//===--------------------------------------------------------------------===//102// Visitor Methods103//===--------------------------------------------------------------------===//104105void Visit(Expr *E) {106ApplyDebugLocation DL(CGF, E);107StmtVisitor<AggExprEmitter>::Visit(E);108}109110void VisitStmt(Stmt *S) {111CGF.ErrorUnsupported(S, "aggregate expression");112}113void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }114void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {115Visit(GE->getResultExpr());116}117void VisitCoawaitExpr(CoawaitExpr *E) {118CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused);119}120void VisitCoyieldExpr(CoyieldExpr *E) {121CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused);122}123void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); }124void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }125void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {126return Visit(E->getReplacement());127}128129void VisitConstantExpr(ConstantExpr *E) {130EnsureDest(E->getType());131132if (llvm::Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {133CGF.CreateCoercedStore(134Result, Dest.getAddress(),135llvm::TypeSize::getFixed(136Dest.getPreferredSize(CGF.getContext(), E->getType())137.getQuantity()),138E->getType().isVolatileQualified());139return;140}141return Visit(E->getSubExpr());142}143144// l-values.145void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); }146void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }147void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }148void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }149void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);150void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {151EmitAggLoadOfLValue(E);152}153void VisitPredefinedExpr(const PredefinedExpr *E) {154EmitAggLoadOfLValue(E);155}156157// Operators.158void VisitCastExpr(CastExpr *E);159void VisitCallExpr(const CallExpr *E);160void VisitStmtExpr(const StmtExpr *E);161void VisitBinaryOperator(const BinaryOperator *BO);162void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);163void VisitBinAssign(const BinaryOperator *E);164void VisitBinComma(const BinaryOperator *E);165void VisitBinCmp(const BinaryOperator *E);166void VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {167Visit(E->getSemanticForm());168}169170void VisitObjCMessageExpr(ObjCMessageExpr *E);171void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {172EmitAggLoadOfLValue(E);173}174175void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);176void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);177void VisitChooseExpr(const ChooseExpr *CE);178void VisitInitListExpr(InitListExpr *E);179void VisitCXXParenListOrInitListExpr(Expr *ExprToVisit, ArrayRef<Expr *> Args,180FieldDecl *InitializedFieldInUnion,181Expr *ArrayFiller);182void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,183llvm::Value *outerBegin = nullptr);184void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);185void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.186void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {187CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);188Visit(DAE->getExpr());189}190void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {191CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);192Visit(DIE->getExpr());193}194void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);195void VisitCXXConstructExpr(const CXXConstructExpr *E);196void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);197void VisitLambdaExpr(LambdaExpr *E);198void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);199void VisitExprWithCleanups(ExprWithCleanups *E);200void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);201void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }202void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);203void VisitOpaqueValueExpr(OpaqueValueExpr *E);204205void VisitPseudoObjectExpr(PseudoObjectExpr *E) {206if (E->isGLValue()) {207LValue LV = CGF.EmitPseudoObjectLValue(E);208return EmitFinalDestCopy(E->getType(), LV);209}210211AggValueSlot Slot = EnsureSlot(E->getType());212bool NeedsDestruction =213!Slot.isExternallyDestructed() &&214E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;215if (NeedsDestruction)216Slot.setExternallyDestructed();217CGF.EmitPseudoObjectRValue(E, Slot);218if (NeedsDestruction)219CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Slot.getAddress(),220E->getType());221}222223void VisitVAArgExpr(VAArgExpr *E);224void VisitCXXParenListInitExpr(CXXParenListInitExpr *E);225void VisitCXXParenListOrInitListExpr(Expr *ExprToVisit, ArrayRef<Expr *> Args,226Expr *ArrayFiller);227228void EmitInitializationToLValue(Expr *E, LValue Address);229void EmitNullInitializationToLValue(LValue Address);230// case Expr::ChooseExprClass:231void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }232void VisitAtomicExpr(AtomicExpr *E) {233RValue Res = CGF.EmitAtomicExpr(E);234EmitFinalDestCopy(E->getType(), Res);235}236void VisitPackIndexingExpr(PackIndexingExpr *E) {237Visit(E->getSelectedExpr());238}239};240} // end anonymous namespace.241242//===----------------------------------------------------------------------===//243// Utilities244//===----------------------------------------------------------------------===//245246/// EmitAggLoadOfLValue - Given an expression with aggregate type that247/// represents a value lvalue, this method emits the address of the lvalue,248/// then loads the result into DestPtr.249void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {250LValue LV = CGF.EmitLValue(E);251252// If the type of the l-value is atomic, then do an atomic load.253if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {254CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);255return;256}257258EmitFinalDestCopy(E->getType(), LV);259}260261/// True if the given aggregate type requires special GC API calls.262bool AggExprEmitter::TypeRequiresGCollection(QualType T) {263// Only record types have members that might require garbage collection.264const RecordType *RecordTy = T->getAs<RecordType>();265if (!RecordTy) return false;266267// Don't mess with non-trivial C++ types.268RecordDecl *Record = RecordTy->getDecl();269if (isa<CXXRecordDecl>(Record) &&270(cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||271!cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))272return false;273274// Check whether the type has an object member.275return Record->hasObjectMember();276}277278void AggExprEmitter::withReturnValueSlot(279const Expr *E, llvm::function_ref<RValue(ReturnValueSlot)> EmitCall) {280QualType RetTy = E->getType();281bool RequiresDestruction =282!Dest.isExternallyDestructed() &&283RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct;284285// If it makes no observable difference, save a memcpy + temporary.286//287// We need to always provide our own temporary if destruction is required.288// Otherwise, EmitCall will emit its own, notice that it's "unused", and end289// its lifetime before we have the chance to emit a proper destructor call.290bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() ||291(RequiresDestruction && Dest.isIgnored());292293Address RetAddr = Address::invalid();294RawAddress RetAllocaAddr = RawAddress::invalid();295296EHScopeStack::stable_iterator LifetimeEndBlock;297llvm::Value *LifetimeSizePtr = nullptr;298llvm::IntrinsicInst *LifetimeStartInst = nullptr;299if (!UseTemp) {300RetAddr = Dest.getAddress();301} else {302RetAddr = CGF.CreateMemTemp(RetTy, "tmp", &RetAllocaAddr);303llvm::TypeSize Size =304CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy));305LifetimeSizePtr = CGF.EmitLifetimeStart(Size, RetAllocaAddr.getPointer());306if (LifetimeSizePtr) {307LifetimeStartInst =308cast<llvm::IntrinsicInst>(std::prev(Builder.GetInsertPoint()));309assert(LifetimeStartInst->getIntrinsicID() ==310llvm::Intrinsic::lifetime_start &&311"Last insertion wasn't a lifetime.start?");312313CGF.pushFullExprCleanup<CodeGenFunction::CallLifetimeEnd>(314NormalEHLifetimeMarker, RetAllocaAddr, LifetimeSizePtr);315LifetimeEndBlock = CGF.EHStack.stable_begin();316}317}318319RValue Src =320EmitCall(ReturnValueSlot(RetAddr, Dest.isVolatile(), IsResultUnused,321Dest.isExternallyDestructed()));322323if (!UseTemp)324return;325326assert(Dest.isIgnored() || Dest.emitRawPointer(CGF) !=327Src.getAggregatePointer(E->getType(), CGF));328EmitFinalDestCopy(E->getType(), Src);329330if (!RequiresDestruction && LifetimeStartInst) {331// If there's no dtor to run, the copy was the last use of our temporary.332// Since we're not guaranteed to be in an ExprWithCleanups, clean up333// eagerly.334CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst);335CGF.EmitLifetimeEnd(LifetimeSizePtr, RetAllocaAddr.getPointer());336}337}338339/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.340void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {341assert(src.isAggregate() && "value must be aggregate value!");342LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);343EmitFinalDestCopy(type, srcLV, CodeGenFunction::EVK_RValue);344}345346/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.347void AggExprEmitter::EmitFinalDestCopy(348QualType type, const LValue &src,349CodeGenFunction::ExprValueKind SrcValueKind) {350// If Dest is ignored, then we're evaluating an aggregate expression351// in a context that doesn't care about the result. Note that loads352// from volatile l-values force the existence of a non-ignored353// destination.354if (Dest.isIgnored())355return;356357// Copy non-trivial C structs here.358LValue DstLV = CGF.MakeAddrLValue(359Dest.getAddress(), Dest.isVolatile() ? type.withVolatile() : type);360361if (SrcValueKind == CodeGenFunction::EVK_RValue) {362if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) {363if (Dest.isPotentiallyAliased())364CGF.callCStructMoveAssignmentOperator(DstLV, src);365else366CGF.callCStructMoveConstructor(DstLV, src);367return;368}369} else {370if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {371if (Dest.isPotentiallyAliased())372CGF.callCStructCopyAssignmentOperator(DstLV, src);373else374CGF.callCStructCopyConstructor(DstLV, src);375return;376}377}378379AggValueSlot srcAgg = AggValueSlot::forLValue(380src, AggValueSlot::IsDestructed, needsGC(type), AggValueSlot::IsAliased,381AggValueSlot::MayOverlap);382EmitCopy(type, Dest, srcAgg);383}384385/// Perform a copy from the source into the destination.386///387/// \param type - the type of the aggregate being copied; qualifiers are388/// ignored389void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,390const AggValueSlot &src) {391if (dest.requiresGCollection()) {392CharUnits sz = dest.getPreferredSize(CGF.getContext(), type);393llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());394CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,395dest.getAddress(),396src.getAddress(),397size);398return;399}400401// If the result of the assignment is used, copy the LHS there also.402// It's volatile if either side is. Use the minimum alignment of403// the two sides.404LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type);405LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type);406CGF.EmitAggregateCopy(DestLV, SrcLV, type, dest.mayOverlap(),407dest.isVolatile() || src.isVolatile());408}409410/// Emit the initializer for a std::initializer_list initialized with a411/// real initializer list.412void413AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {414// Emit an array containing the elements. The array is externally destructed415// if the std::initializer_list object is.416ASTContext &Ctx = CGF.getContext();417LValue Array = CGF.EmitLValue(E->getSubExpr());418assert(Array.isSimple() && "initializer_list array not a simple lvalue");419Address ArrayPtr = Array.getAddress();420421const ConstantArrayType *ArrayType =422Ctx.getAsConstantArrayType(E->getSubExpr()->getType());423assert(ArrayType && "std::initializer_list constructed from non-array");424425RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();426RecordDecl::field_iterator Field = Record->field_begin();427assert(Field != Record->field_end() &&428Ctx.hasSameType(Field->getType()->getPointeeType(),429ArrayType->getElementType()) &&430"Expected std::initializer_list first field to be const E *");431432// Start pointer.433AggValueSlot Dest = EnsureSlot(E->getType());434LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());435LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);436llvm::Value *ArrayStart = ArrayPtr.emitRawPointer(CGF);437CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);438++Field;439assert(Field != Record->field_end() &&440"Expected std::initializer_list to have two fields");441442llvm::Value *Size = Builder.getInt(ArrayType->getSize());443LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);444if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {445// Length.446CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);447448} else {449// End pointer.450assert(Field->getType()->isPointerType() &&451Ctx.hasSameType(Field->getType()->getPointeeType(),452ArrayType->getElementType()) &&453"Expected std::initializer_list second field to be const E *");454llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);455llvm::Value *IdxEnd[] = { Zero, Size };456llvm::Value *ArrayEnd = Builder.CreateInBoundsGEP(457ArrayPtr.getElementType(), ArrayPtr.emitRawPointer(CGF), IdxEnd,458"arrayend");459CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);460}461462assert(++Field == Record->field_end() &&463"Expected std::initializer_list to only have two fields");464}465466/// Determine if E is a trivial array filler, that is, one that is467/// equivalent to zero-initialization.468static bool isTrivialFiller(Expr *E) {469if (!E)470return true;471472if (isa<ImplicitValueInitExpr>(E))473return true;474475if (auto *ILE = dyn_cast<InitListExpr>(E)) {476if (ILE->getNumInits())477return false;478return isTrivialFiller(ILE->getArrayFiller());479}480481if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))482return Cons->getConstructor()->isDefaultConstructor() &&483Cons->getConstructor()->isTrivial();484485// FIXME: Are there other cases where we can avoid emitting an initializer?486return false;487}488489/// Emit initialization of an array from an initializer list. ExprToVisit must490/// be either an InitListEpxr a CXXParenInitListExpr.491void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,492QualType ArrayQTy, Expr *ExprToVisit,493ArrayRef<Expr *> Args, Expr *ArrayFiller) {494uint64_t NumInitElements = Args.size();495496uint64_t NumArrayElements = AType->getNumElements();497for (const auto *Init : Args) {498if (const auto *Embed = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {499NumInitElements += Embed->getDataElementCount() - 1;500if (NumInitElements > NumArrayElements) {501NumInitElements = NumArrayElements;502break;503}504}505}506507assert(NumInitElements <= NumArrayElements);508509QualType elementType =510CGF.getContext().getAsArrayType(ArrayQTy)->getElementType();511CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);512CharUnits elementAlign =513DestPtr.getAlignment().alignmentOfArrayElement(elementSize);514llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);515516// Consider initializing the array by copying from a global. For this to be517// more efficient than per-element initialization, the size of the elements518// with explicit initializers should be large enough.519if (NumInitElements * elementSize.getQuantity() > 16 &&520elementType.isTriviallyCopyableType(CGF.getContext())) {521CodeGen::CodeGenModule &CGM = CGF.CGM;522ConstantEmitter Emitter(CGF);523QualType GVArrayQTy = CGM.getContext().getAddrSpaceQualType(524CGM.getContext().removeAddrSpaceQualType(ArrayQTy),525CGM.GetGlobalConstantAddressSpace());526LangAS AS = GVArrayQTy.getAddressSpace();527if (llvm::Constant *C =528Emitter.tryEmitForInitializer(ExprToVisit, AS, GVArrayQTy)) {529auto GV = new llvm::GlobalVariable(530CGM.getModule(), C->getType(),531/* isConstant= */ true, llvm::GlobalValue::PrivateLinkage, C,532"constinit",533/* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal,534CGM.getContext().getTargetAddressSpace(AS));535Emitter.finalize(GV);536CharUnits Align = CGM.getContext().getTypeAlignInChars(GVArrayQTy);537GV->setAlignment(Align.getAsAlign());538Address GVAddr(GV, GV->getValueType(), Align);539EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GVAddr, GVArrayQTy));540return;541}542}543544// Exception safety requires us to destroy all the545// already-constructed members if an initializer throws.546// For that, we'll need an EH cleanup.547QualType::DestructionKind dtorKind = elementType.isDestructedType();548Address endOfInit = Address::invalid();549CodeGenFunction::CleanupDeactivationScope deactivation(CGF);550551llvm::Value *begin = DestPtr.emitRawPointer(CGF);552if (dtorKind) {553CodeGenFunction::AllocaTrackerRAII allocaTracker(CGF);554// In principle we could tell the cleanup where we are more555// directly, but the control flow can get so varied here that it556// would actually be quite complex. Therefore we go through an557// alloca.558llvm::Instruction *dominatingIP =559Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(CGF.Int8PtrTy));560endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),561"arrayinit.endOfInit");562Builder.CreateStore(begin, endOfInit);563CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,564elementAlign,565CGF.getDestroyer(dtorKind));566cast<EHCleanupScope>(*CGF.EHStack.find(CGF.EHStack.stable_begin()))567.AddAuxAllocas(allocaTracker.Take());568569CGF.DeferredDeactivationCleanupStack.push_back(570{CGF.EHStack.stable_begin(), dominatingIP});571}572573llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);574575auto Emit = [&](Expr *Init, uint64_t ArrayIndex) {576llvm::Value *element = begin;577if (ArrayIndex > 0) {578element = Builder.CreateInBoundsGEP(579llvmElementType, begin,580llvm::ConstantInt::get(CGF.SizeTy, ArrayIndex), "arrayinit.element");581582// Tell the cleanup that it needs to destroy up to this583// element. TODO: some of these stores can be trivially584// observed to be unnecessary.585if (endOfInit.isValid())586Builder.CreateStore(element, endOfInit);587}588589LValue elementLV = CGF.MakeAddrLValue(590Address(element, llvmElementType, elementAlign), elementType);591EmitInitializationToLValue(Init, elementLV);592return true;593};594595unsigned ArrayIndex = 0;596// Emit the explicit initializers.597for (uint64_t i = 0; i != NumInitElements; ++i) {598if (ArrayIndex >= NumInitElements)599break;600if (auto *EmbedS = dyn_cast<EmbedExpr>(Args[i]->IgnoreParenImpCasts())) {601EmbedS->doForEachDataElement(Emit, ArrayIndex);602} else {603Emit(Args[i], ArrayIndex);604ArrayIndex++;605}606}607608// Check whether there's a non-trivial array-fill expression.609bool hasTrivialFiller = isTrivialFiller(ArrayFiller);610611// Any remaining elements need to be zero-initialized, possibly612// using the filler expression. We can skip this if the we're613// emitting to zeroed memory.614if (NumInitElements != NumArrayElements &&615!(Dest.isZeroed() && hasTrivialFiller &&616CGF.getTypes().isZeroInitializable(elementType))) {617618// Use an actual loop. This is basically619// do { *array++ = filler; } while (array != end);620621// Advance to the start of the rest of the array.622llvm::Value *element = begin;623if (NumInitElements) {624element = Builder.CreateInBoundsGEP(625llvmElementType, element,626llvm::ConstantInt::get(CGF.SizeTy, NumInitElements),627"arrayinit.start");628if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);629}630631// Compute the end of the array.632llvm::Value *end = Builder.CreateInBoundsGEP(633llvmElementType, begin,634llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements), "arrayinit.end");635636llvm::BasicBlock *entryBB = Builder.GetInsertBlock();637llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");638639// Jump into the body.640CGF.EmitBlock(bodyBB);641llvm::PHINode *currentElement =642Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");643currentElement->addIncoming(element, entryBB);644645// Emit the actual filler expression.646{647// C++1z [class.temporary]p5:648// when a default constructor is called to initialize an element of649// an array with no corresponding initializer [...] the destruction of650// every temporary created in a default argument is sequenced before651// the construction of the next array element, if any652CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);653LValue elementLV = CGF.MakeAddrLValue(654Address(currentElement, llvmElementType, elementAlign), elementType);655if (ArrayFiller)656EmitInitializationToLValue(ArrayFiller, elementLV);657else658EmitNullInitializationToLValue(elementLV);659}660661// Move on to the next element.662llvm::Value *nextElement = Builder.CreateInBoundsGEP(663llvmElementType, currentElement, one, "arrayinit.next");664665// Tell the EH cleanup that we finished with the last element.666if (endOfInit.isValid()) Builder.CreateStore(nextElement, endOfInit);667668// Leave the loop if we're done.669llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,670"arrayinit.done");671llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");672Builder.CreateCondBr(done, endBB, bodyBB);673currentElement->addIncoming(nextElement, Builder.GetInsertBlock());674675CGF.EmitBlock(endBB);676}677}678679//===----------------------------------------------------------------------===//680// Visitor Methods681//===----------------------------------------------------------------------===//682683void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){684Visit(E->getSubExpr());685}686687void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {688// If this is a unique OVE, just visit its source expression.689if (e->isUnique())690Visit(e->getSourceExpr());691else692EmitFinalDestCopy(e->getType(), CGF.getOrCreateOpaqueLValueMapping(e));693}694695void696AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {697if (Dest.isPotentiallyAliased() &&698E->getType().isPODType(CGF.getContext())) {699// For a POD type, just emit a load of the lvalue + a copy, because our700// compound literal might alias the destination.701EmitAggLoadOfLValue(E);702return;703}704705AggValueSlot Slot = EnsureSlot(E->getType());706707// Block-scope compound literals are destroyed at the end of the enclosing708// scope in C.709bool Destruct =710!CGF.getLangOpts().CPlusPlus && !Slot.isExternallyDestructed();711if (Destruct)712Slot.setExternallyDestructed();713714CGF.EmitAggExpr(E->getInitializer(), Slot);715716if (Destruct)717if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())718CGF.pushLifetimeExtendedDestroy(719CGF.getCleanupKind(DtorKind), Slot.getAddress(), E->getType(),720CGF.getDestroyer(DtorKind), DtorKind & EHCleanup);721}722723/// Attempt to look through various unimportant expressions to find a724/// cast of the given kind.725static Expr *findPeephole(Expr *op, CastKind kind, const ASTContext &ctx) {726op = op->IgnoreParenNoopCasts(ctx);727if (auto castE = dyn_cast<CastExpr>(op)) {728if (castE->getCastKind() == kind)729return castE->getSubExpr();730}731return nullptr;732}733734void AggExprEmitter::VisitCastExpr(CastExpr *E) {735if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))736CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);737switch (E->getCastKind()) {738case CK_Dynamic: {739// FIXME: Can this actually happen? We have no test coverage for it.740assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");741LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),742CodeGenFunction::TCK_Load);743// FIXME: Do we also need to handle property references here?744if (LV.isSimple())745CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));746else747CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");748749if (!Dest.isIgnored())750CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");751break;752}753754case CK_ToUnion: {755// Evaluate even if the destination is ignored.756if (Dest.isIgnored()) {757CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),758/*ignoreResult=*/true);759break;760}761762// GCC union extension763QualType Ty = E->getSubExpr()->getType();764Address CastPtr = Dest.getAddress().withElementType(CGF.ConvertType(Ty));765EmitInitializationToLValue(E->getSubExpr(),766CGF.MakeAddrLValue(CastPtr, Ty));767break;768}769770case CK_LValueToRValueBitCast: {771if (Dest.isIgnored()) {772CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),773/*ignoreResult=*/true);774break;775}776777LValue SourceLV = CGF.EmitLValue(E->getSubExpr());778Address SourceAddress = SourceLV.getAddress().withElementType(CGF.Int8Ty);779Address DestAddress = Dest.getAddress().withElementType(CGF.Int8Ty);780llvm::Value *SizeVal = llvm::ConstantInt::get(781CGF.SizeTy,782CGF.getContext().getTypeSizeInChars(E->getType()).getQuantity());783Builder.CreateMemCpy(DestAddress, SourceAddress, SizeVal);784break;785}786787case CK_DerivedToBase:788case CK_BaseToDerived:789case CK_UncheckedDerivedToBase: {790llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "791"should have been unpacked before we got here");792}793794case CK_NonAtomicToAtomic:795case CK_AtomicToNonAtomic: {796bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);797798// Determine the atomic and value types.799QualType atomicType = E->getSubExpr()->getType();800QualType valueType = E->getType();801if (isToAtomic) std::swap(atomicType, valueType);802803assert(atomicType->isAtomicType());804assert(CGF.getContext().hasSameUnqualifiedType(valueType,805atomicType->castAs<AtomicType>()->getValueType()));806807// Just recurse normally if we're ignoring the result or the808// atomic type doesn't change representation.809if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {810return Visit(E->getSubExpr());811}812813CastKind peepholeTarget =814(isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);815816// These two cases are reverses of each other; try to peephole them.817if (Expr *op =818findPeephole(E->getSubExpr(), peepholeTarget, CGF.getContext())) {819assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),820E->getType()) &&821"peephole significantly changed types?");822return Visit(op);823}824825// If we're converting an r-value of non-atomic type to an r-value826// of atomic type, just emit directly into the relevant sub-object.827if (isToAtomic) {828AggValueSlot valueDest = Dest;829if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {830// Zero-initialize. (Strictly speaking, we only need to initialize831// the padding at the end, but this is simpler.)832if (!Dest.isZeroed())833CGF.EmitNullInitialization(Dest.getAddress(), atomicType);834835// Build a GEP to refer to the subobject.836Address valueAddr =837CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0);838valueDest = AggValueSlot::forAddr(valueAddr,839valueDest.getQualifiers(),840valueDest.isExternallyDestructed(),841valueDest.requiresGCollection(),842valueDest.isPotentiallyAliased(),843AggValueSlot::DoesNotOverlap,844AggValueSlot::IsZeroed);845}846847CGF.EmitAggExpr(E->getSubExpr(), valueDest);848return;849}850851// Otherwise, we're converting an atomic type to a non-atomic type.852// Make an atomic temporary, emit into that, and then copy the value out.853AggValueSlot atomicSlot =854CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");855CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);856857Address valueAddr = Builder.CreateStructGEP(atomicSlot.getAddress(), 0);858RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());859return EmitFinalDestCopy(valueType, rvalue);860}861case CK_AddressSpaceConversion:862return Visit(E->getSubExpr());863864case CK_LValueToRValue:865// If we're loading from a volatile type, force the destination866// into existence.867if (E->getSubExpr()->getType().isVolatileQualified()) {868bool Destruct =869!Dest.isExternallyDestructed() &&870E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;871if (Destruct)872Dest.setExternallyDestructed();873EnsureDest(E->getType());874Visit(E->getSubExpr());875876if (Destruct)877CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),878E->getType());879880return;881}882883[[fallthrough]];884885case CK_HLSLArrayRValue:886Visit(E->getSubExpr());887break;888889case CK_NoOp:890case CK_UserDefinedConversion:891case CK_ConstructorConversion:892assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),893E->getType()) &&894"Implicit cast types must be compatible");895Visit(E->getSubExpr());896break;897898case CK_LValueBitCast:899llvm_unreachable("should not be emitting lvalue bitcast as rvalue");900901case CK_Dependent:902case CK_BitCast:903case CK_ArrayToPointerDecay:904case CK_FunctionToPointerDecay:905case CK_NullToPointer:906case CK_NullToMemberPointer:907case CK_BaseToDerivedMemberPointer:908case CK_DerivedToBaseMemberPointer:909case CK_MemberPointerToBoolean:910case CK_ReinterpretMemberPointer:911case CK_IntegralToPointer:912case CK_PointerToIntegral:913case CK_PointerToBoolean:914case CK_ToVoid:915case CK_VectorSplat:916case CK_IntegralCast:917case CK_BooleanToSignedIntegral:918case CK_IntegralToBoolean:919case CK_IntegralToFloating:920case CK_FloatingToIntegral:921case CK_FloatingToBoolean:922case CK_FloatingCast:923case CK_CPointerToObjCPointerCast:924case CK_BlockPointerToObjCPointerCast:925case CK_AnyPointerToBlockPointerCast:926case CK_ObjCObjectLValueCast:927case CK_FloatingRealToComplex:928case CK_FloatingComplexToReal:929case CK_FloatingComplexToBoolean:930case CK_FloatingComplexCast:931case CK_FloatingComplexToIntegralComplex:932case CK_IntegralRealToComplex:933case CK_IntegralComplexToReal:934case CK_IntegralComplexToBoolean:935case CK_IntegralComplexCast:936case CK_IntegralComplexToFloatingComplex:937case CK_ARCProduceObject:938case CK_ARCConsumeObject:939case CK_ARCReclaimReturnedObject:940case CK_ARCExtendBlockObject:941case CK_CopyAndAutoreleaseBlockObject:942case CK_BuiltinFnToFnPtr:943case CK_ZeroToOCLOpaqueType:944case CK_MatrixCast:945case CK_HLSLVectorTruncation:946947case CK_IntToOCLSampler:948case CK_FloatingToFixedPoint:949case CK_FixedPointToFloating:950case CK_FixedPointCast:951case CK_FixedPointToBoolean:952case CK_FixedPointToIntegral:953case CK_IntegralToFixedPoint:954llvm_unreachable("cast kind invalid for aggregate types");955}956}957958void AggExprEmitter::VisitCallExpr(const CallExpr *E) {959if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {960EmitAggLoadOfLValue(E);961return;962}963964withReturnValueSlot(E, [&](ReturnValueSlot Slot) {965return CGF.EmitCallExpr(E, Slot);966});967}968969void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {970withReturnValueSlot(E, [&](ReturnValueSlot Slot) {971return CGF.EmitObjCMessageExpr(E, Slot);972});973}974975void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {976CGF.EmitIgnoredExpr(E->getLHS());977Visit(E->getRHS());978}979980void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {981CodeGenFunction::StmtExprEvaluation eval(CGF);982CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);983}984985enum CompareKind {986CK_Less,987CK_Greater,988CK_Equal,989};990991static llvm::Value *EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF,992const BinaryOperator *E, llvm::Value *LHS,993llvm::Value *RHS, CompareKind Kind,994const char *NameSuffix = "") {995QualType ArgTy = E->getLHS()->getType();996if (const ComplexType *CT = ArgTy->getAs<ComplexType>())997ArgTy = CT->getElementType();998999if (const auto *MPT = ArgTy->getAs<MemberPointerType>()) {1000assert(Kind == CK_Equal &&1001"member pointers may only be compared for equality");1002return CGF.CGM.getCXXABI().EmitMemberPointerComparison(1003CGF, LHS, RHS, MPT, /*IsInequality*/ false);1004}10051006// Compute the comparison instructions for the specified comparison kind.1007struct CmpInstInfo {1008const char *Name;1009llvm::CmpInst::Predicate FCmp;1010llvm::CmpInst::Predicate SCmp;1011llvm::CmpInst::Predicate UCmp;1012};1013CmpInstInfo InstInfo = [&]() -> CmpInstInfo {1014using FI = llvm::FCmpInst;1015using II = llvm::ICmpInst;1016switch (Kind) {1017case CK_Less:1018return {"cmp.lt", FI::FCMP_OLT, II::ICMP_SLT, II::ICMP_ULT};1019case CK_Greater:1020return {"cmp.gt", FI::FCMP_OGT, II::ICMP_SGT, II::ICMP_UGT};1021case CK_Equal:1022return {"cmp.eq", FI::FCMP_OEQ, II::ICMP_EQ, II::ICMP_EQ};1023}1024llvm_unreachable("Unrecognised CompareKind enum");1025}();10261027if (ArgTy->hasFloatingRepresentation())1028return Builder.CreateFCmp(InstInfo.FCmp, LHS, RHS,1029llvm::Twine(InstInfo.Name) + NameSuffix);1030if (ArgTy->isIntegralOrEnumerationType() || ArgTy->isPointerType()) {1031auto Inst =1032ArgTy->hasSignedIntegerRepresentation() ? InstInfo.SCmp : InstInfo.UCmp;1033return Builder.CreateICmp(Inst, LHS, RHS,1034llvm::Twine(InstInfo.Name) + NameSuffix);1035}10361037llvm_unreachable("unsupported aggregate binary expression should have "1038"already been handled");1039}10401041void AggExprEmitter::VisitBinCmp(const BinaryOperator *E) {1042using llvm::BasicBlock;1043using llvm::PHINode;1044using llvm::Value;1045assert(CGF.getContext().hasSameType(E->getLHS()->getType(),1046E->getRHS()->getType()));1047const ComparisonCategoryInfo &CmpInfo =1048CGF.getContext().CompCategories.getInfoForType(E->getType());1049assert(CmpInfo.Record->isTriviallyCopyable() &&1050"cannot copy non-trivially copyable aggregate");10511052QualType ArgTy = E->getLHS()->getType();10531054if (!ArgTy->isIntegralOrEnumerationType() && !ArgTy->isRealFloatingType() &&1055!ArgTy->isNullPtrType() && !ArgTy->isPointerType() &&1056!ArgTy->isMemberPointerType() && !ArgTy->isAnyComplexType()) {1057return CGF.ErrorUnsupported(E, "aggregate three-way comparison");1058}1059bool IsComplex = ArgTy->isAnyComplexType();10601061// Evaluate the operands to the expression and extract their values.1062auto EmitOperand = [&](Expr *E) -> std::pair<Value *, Value *> {1063RValue RV = CGF.EmitAnyExpr(E);1064if (RV.isScalar())1065return {RV.getScalarVal(), nullptr};1066if (RV.isAggregate())1067return {RV.getAggregatePointer(E->getType(), CGF), nullptr};1068assert(RV.isComplex());1069return RV.getComplexVal();1070};1071auto LHSValues = EmitOperand(E->getLHS()),1072RHSValues = EmitOperand(E->getRHS());10731074auto EmitCmp = [&](CompareKind K) {1075Value *Cmp = EmitCompare(Builder, CGF, E, LHSValues.first, RHSValues.first,1076K, IsComplex ? ".r" : "");1077if (!IsComplex)1078return Cmp;1079assert(K == CompareKind::CK_Equal);1080Value *CmpImag = EmitCompare(Builder, CGF, E, LHSValues.second,1081RHSValues.second, K, ".i");1082return Builder.CreateAnd(Cmp, CmpImag, "and.eq");1083};1084auto EmitCmpRes = [&](const ComparisonCategoryInfo::ValueInfo *VInfo) {1085return Builder.getInt(VInfo->getIntValue());1086};10871088Value *Select;1089if (ArgTy->isNullPtrType()) {1090Select = EmitCmpRes(CmpInfo.getEqualOrEquiv());1091} else if (!CmpInfo.isPartial()) {1092Value *SelectOne =1093Builder.CreateSelect(EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()),1094EmitCmpRes(CmpInfo.getGreater()), "sel.lt");1095Select = Builder.CreateSelect(EmitCmp(CK_Equal),1096EmitCmpRes(CmpInfo.getEqualOrEquiv()),1097SelectOne, "sel.eq");1098} else {1099Value *SelectEq = Builder.CreateSelect(1100EmitCmp(CK_Equal), EmitCmpRes(CmpInfo.getEqualOrEquiv()),1101EmitCmpRes(CmpInfo.getUnordered()), "sel.eq");1102Value *SelectGT = Builder.CreateSelect(EmitCmp(CK_Greater),1103EmitCmpRes(CmpInfo.getGreater()),1104SelectEq, "sel.gt");1105Select = Builder.CreateSelect(1106EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()), SelectGT, "sel.lt");1107}1108// Create the return value in the destination slot.1109EnsureDest(E->getType());1110LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());11111112// Emit the address of the first (and only) field in the comparison category1113// type, and initialize it from the constant integer value selected above.1114LValue FieldLV = CGF.EmitLValueForFieldInitialization(1115DestLV, *CmpInfo.Record->field_begin());1116CGF.EmitStoreThroughLValue(RValue::get(Select), FieldLV, /*IsInit*/ true);11171118// All done! The result is in the Dest slot.1119}11201121void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {1122if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)1123VisitPointerToDataMemberBinaryOperator(E);1124else1125CGF.ErrorUnsupported(E, "aggregate binary expression");1126}11271128void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(1129const BinaryOperator *E) {1130LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);1131EmitFinalDestCopy(E->getType(), LV);1132}11331134/// Is the value of the given expression possibly a reference to or1135/// into a __block variable?1136static bool isBlockVarRef(const Expr *E) {1137// Make sure we look through parens.1138E = E->IgnoreParens();11391140// Check for a direct reference to a __block variable.1141if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {1142const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());1143return (var && var->hasAttr<BlocksAttr>());1144}11451146// More complicated stuff.11471148// Binary operators.1149if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {1150// For an assignment or pointer-to-member operation, just care1151// about the LHS.1152if (op->isAssignmentOp() || op->isPtrMemOp())1153return isBlockVarRef(op->getLHS());11541155// For a comma, just care about the RHS.1156if (op->getOpcode() == BO_Comma)1157return isBlockVarRef(op->getRHS());11581159// FIXME: pointer arithmetic?1160return false;11611162// Check both sides of a conditional operator.1163} else if (const AbstractConditionalOperator *op1164= dyn_cast<AbstractConditionalOperator>(E)) {1165return isBlockVarRef(op->getTrueExpr())1166|| isBlockVarRef(op->getFalseExpr());11671168// OVEs are required to support BinaryConditionalOperators.1169} else if (const OpaqueValueExpr *op1170= dyn_cast<OpaqueValueExpr>(E)) {1171if (const Expr *src = op->getSourceExpr())1172return isBlockVarRef(src);11731174// Casts are necessary to get things like (*(int*)&var) = foo().1175// We don't really care about the kind of cast here, except1176// we don't want to look through l2r casts, because it's okay1177// to get the *value* in a __block variable.1178} else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {1179if (cast->getCastKind() == CK_LValueToRValue)1180return false;1181return isBlockVarRef(cast->getSubExpr());11821183// Handle unary operators. Again, just aggressively look through1184// it, ignoring the operation.1185} else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {1186return isBlockVarRef(uop->getSubExpr());11871188// Look into the base of a field access.1189} else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {1190return isBlockVarRef(mem->getBase());11911192// Look into the base of a subscript.1193} else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {1194return isBlockVarRef(sub->getBase());1195}11961197return false;1198}11991200void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {1201// For an assignment to work, the value on the right has1202// to be compatible with the value on the left.1203assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),1204E->getRHS()->getType())1205&& "Invalid assignment");12061207// If the LHS might be a __block variable, and the RHS can1208// potentially cause a block copy, we need to evaluate the RHS first1209// so that the assignment goes the right place.1210// This is pretty semantically fragile.1211if (isBlockVarRef(E->getLHS()) &&1212E->getRHS()->HasSideEffects(CGF.getContext())) {1213// Ensure that we have a destination, and evaluate the RHS into that.1214EnsureDest(E->getRHS()->getType());1215Visit(E->getRHS());12161217// Now emit the LHS and copy into it.1218LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);12191220// That copy is an atomic copy if the LHS is atomic.1221if (LHS.getType()->isAtomicType() ||1222CGF.LValueIsSuitableForInlineAtomic(LHS)) {1223CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);1224return;1225}12261227EmitCopy(E->getLHS()->getType(),1228AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,1229needsGC(E->getLHS()->getType()),1230AggValueSlot::IsAliased,1231AggValueSlot::MayOverlap),1232Dest);1233return;1234}12351236LValue LHS = CGF.EmitLValue(E->getLHS());12371238// If we have an atomic type, evaluate into the destination and then1239// do an atomic copy.1240if (LHS.getType()->isAtomicType() ||1241CGF.LValueIsSuitableForInlineAtomic(LHS)) {1242EnsureDest(E->getRHS()->getType());1243Visit(E->getRHS());1244CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);1245return;1246}12471248// Codegen the RHS so that it stores directly into the LHS.1249AggValueSlot LHSSlot = AggValueSlot::forLValue(1250LHS, AggValueSlot::IsDestructed, needsGC(E->getLHS()->getType()),1251AggValueSlot::IsAliased, AggValueSlot::MayOverlap);1252// A non-volatile aggregate destination might have volatile member.1253if (!LHSSlot.isVolatile() &&1254CGF.hasVolatileMember(E->getLHS()->getType()))1255LHSSlot.setVolatile(true);12561257CGF.EmitAggExpr(E->getRHS(), LHSSlot);12581259// Copy into the destination if the assignment isn't ignored.1260EmitFinalDestCopy(E->getType(), LHS);12611262if (!Dest.isIgnored() && !Dest.isExternallyDestructed() &&1263E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)1264CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),1265E->getType());1266}12671268void AggExprEmitter::1269VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {1270llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");1271llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");1272llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");12731274// Bind the common expression if necessary.1275CodeGenFunction::OpaqueValueMapping binding(CGF, E);12761277CodeGenFunction::ConditionalEvaluation eval(CGF);1278CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,1279CGF.getProfileCount(E));12801281// Save whether the destination's lifetime is externally managed.1282bool isExternallyDestructed = Dest.isExternallyDestructed();1283bool destructNonTrivialCStruct =1284!isExternallyDestructed &&1285E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;1286isExternallyDestructed |= destructNonTrivialCStruct;1287Dest.setExternallyDestructed(isExternallyDestructed);12881289eval.begin(CGF);1290CGF.EmitBlock(LHSBlock);1291if (llvm::EnableSingleByteCoverage)1292CGF.incrementProfileCounter(E->getTrueExpr());1293else1294CGF.incrementProfileCounter(E);1295Visit(E->getTrueExpr());1296eval.end(CGF);12971298assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");1299CGF.Builder.CreateBr(ContBlock);13001301// If the result of an agg expression is unused, then the emission1302// of the LHS might need to create a destination slot. That's fine1303// with us, and we can safely emit the RHS into the same slot, but1304// we shouldn't claim that it's already being destructed.1305Dest.setExternallyDestructed(isExternallyDestructed);13061307eval.begin(CGF);1308CGF.EmitBlock(RHSBlock);1309if (llvm::EnableSingleByteCoverage)1310CGF.incrementProfileCounter(E->getFalseExpr());1311Visit(E->getFalseExpr());1312eval.end(CGF);13131314if (destructNonTrivialCStruct)1315CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),1316E->getType());13171318CGF.EmitBlock(ContBlock);1319if (llvm::EnableSingleByteCoverage)1320CGF.incrementProfileCounter(E);1321}13221323void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {1324Visit(CE->getChosenSubExpr());1325}13261327void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {1328Address ArgValue = Address::invalid();1329CGF.EmitVAArg(VE, ArgValue, Dest);13301331// If EmitVAArg fails, emit an error.1332if (!ArgValue.isValid()) {1333CGF.ErrorUnsupported(VE, "aggregate va_arg expression");1334return;1335}1336}13371338void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {1339// Ensure that we have a slot, but if we already do, remember1340// whether it was externally destructed.1341bool wasExternallyDestructed = Dest.isExternallyDestructed();1342EnsureDest(E->getType());13431344// We're going to push a destructor if there isn't already one.1345Dest.setExternallyDestructed();13461347Visit(E->getSubExpr());13481349// Push that destructor we promised.1350if (!wasExternallyDestructed)1351CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());1352}13531354void1355AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {1356AggValueSlot Slot = EnsureSlot(E->getType());1357CGF.EmitCXXConstructExpr(E, Slot);1358}13591360void AggExprEmitter::VisitCXXInheritedCtorInitExpr(1361const CXXInheritedCtorInitExpr *E) {1362AggValueSlot Slot = EnsureSlot(E->getType());1363CGF.EmitInheritedCXXConstructorCall(1364E->getConstructor(), E->constructsVBase(), Slot.getAddress(),1365E->inheritedFromVBase(), E);1366}13671368void1369AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {1370AggValueSlot Slot = EnsureSlot(E->getType());1371LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType());13721373// We'll need to enter cleanup scopes in case any of the element1374// initializers throws an exception or contains branch out of the expressions.1375CodeGenFunction::CleanupDeactivationScope scope(CGF);13761377CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();1378for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),1379e = E->capture_init_end();1380i != e; ++i, ++CurField) {1381// Emit initialization1382LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);1383if (CurField->hasCapturedVLAType()) {1384CGF.EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);1385continue;1386}13871388EmitInitializationToLValue(*i, LV);13891390// Push a destructor if necessary.1391if (QualType::DestructionKind DtorKind =1392CurField->getType().isDestructedType()) {1393assert(LV.isSimple());1394if (DtorKind)1395CGF.pushDestroyAndDeferDeactivation(NormalAndEHCleanup, LV.getAddress(),1396CurField->getType(),1397CGF.getDestroyer(DtorKind), false);1398}1399}1400}14011402void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {1403CodeGenFunction::RunCleanupsScope cleanups(CGF);1404Visit(E->getSubExpr());1405}14061407void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {1408QualType T = E->getType();1409AggValueSlot Slot = EnsureSlot(T);1410EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));1411}14121413void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {1414QualType T = E->getType();1415AggValueSlot Slot = EnsureSlot(T);1416EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));1417}14181419/// Determine whether the given cast kind is known to always convert values1420/// with all zero bits in their value representation to values with all zero1421/// bits in their value representation.1422static bool castPreservesZero(const CastExpr *CE) {1423switch (CE->getCastKind()) {1424// No-ops.1425case CK_NoOp:1426case CK_UserDefinedConversion:1427case CK_ConstructorConversion:1428case CK_BitCast:1429case CK_ToUnion:1430case CK_ToVoid:1431// Conversions between (possibly-complex) integral, (possibly-complex)1432// floating-point, and bool.1433case CK_BooleanToSignedIntegral:1434case CK_FloatingCast:1435case CK_FloatingComplexCast:1436case CK_FloatingComplexToBoolean:1437case CK_FloatingComplexToIntegralComplex:1438case CK_FloatingComplexToReal:1439case CK_FloatingRealToComplex:1440case CK_FloatingToBoolean:1441case CK_FloatingToIntegral:1442case CK_IntegralCast:1443case CK_IntegralComplexCast:1444case CK_IntegralComplexToBoolean:1445case CK_IntegralComplexToFloatingComplex:1446case CK_IntegralComplexToReal:1447case CK_IntegralRealToComplex:1448case CK_IntegralToBoolean:1449case CK_IntegralToFloating:1450// Reinterpreting integers as pointers and vice versa.1451case CK_IntegralToPointer:1452case CK_PointerToIntegral:1453// Language extensions.1454case CK_VectorSplat:1455case CK_MatrixCast:1456case CK_NonAtomicToAtomic:1457case CK_AtomicToNonAtomic:1458case CK_HLSLVectorTruncation:1459return true;14601461case CK_BaseToDerivedMemberPointer:1462case CK_DerivedToBaseMemberPointer:1463case CK_MemberPointerToBoolean:1464case CK_NullToMemberPointer:1465case CK_ReinterpretMemberPointer:1466// FIXME: ABI-dependent.1467return false;14681469case CK_AnyPointerToBlockPointerCast:1470case CK_BlockPointerToObjCPointerCast:1471case CK_CPointerToObjCPointerCast:1472case CK_ObjCObjectLValueCast:1473case CK_IntToOCLSampler:1474case CK_ZeroToOCLOpaqueType:1475// FIXME: Check these.1476return false;14771478case CK_FixedPointCast:1479case CK_FixedPointToBoolean:1480case CK_FixedPointToFloating:1481case CK_FixedPointToIntegral:1482case CK_FloatingToFixedPoint:1483case CK_IntegralToFixedPoint:1484// FIXME: Do all fixed-point types represent zero as all 0 bits?1485return false;14861487case CK_AddressSpaceConversion:1488case CK_BaseToDerived:1489case CK_DerivedToBase:1490case CK_Dynamic:1491case CK_NullToPointer:1492case CK_PointerToBoolean:1493// FIXME: Preserves zeroes only if zero pointers and null pointers have the1494// same representation in all involved address spaces.1495return false;14961497case CK_ARCConsumeObject:1498case CK_ARCExtendBlockObject:1499case CK_ARCProduceObject:1500case CK_ARCReclaimReturnedObject:1501case CK_CopyAndAutoreleaseBlockObject:1502case CK_ArrayToPointerDecay:1503case CK_FunctionToPointerDecay:1504case CK_BuiltinFnToFnPtr:1505case CK_Dependent:1506case CK_LValueBitCast:1507case CK_LValueToRValue:1508case CK_LValueToRValueBitCast:1509case CK_UncheckedDerivedToBase:1510case CK_HLSLArrayRValue:1511return false;1512}1513llvm_unreachable("Unhandled clang::CastKind enum");1514}15151516/// isSimpleZero - If emitting this value will obviously just cause a store of1517/// zero to memory, return true. This can return false if uncertain, so it just1518/// handles simple cases.1519static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {1520E = E->IgnoreParens();1521while (auto *CE = dyn_cast<CastExpr>(E)) {1522if (!castPreservesZero(CE))1523break;1524E = CE->getSubExpr()->IgnoreParens();1525}15261527// 01528if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))1529return IL->getValue() == 0;1530// +0.01531if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))1532return FL->getValue().isPosZero();1533// int()1534if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&1535CGF.getTypes().isZeroInitializable(E->getType()))1536return true;1537// (int*)0 - Null pointer expressions.1538if (const CastExpr *ICE = dyn_cast<CastExpr>(E))1539return ICE->getCastKind() == CK_NullToPointer &&1540CGF.getTypes().isPointerZeroInitializable(E->getType()) &&1541!E->HasSideEffects(CGF.getContext());1542// '\0'1543if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))1544return CL->getValue() == 0;15451546// Otherwise, hard case: conservatively return false.1547return false;1548}154915501551void1552AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {1553QualType type = LV.getType();1554// FIXME: Ignore result?1555// FIXME: Are initializers affected by volatile?1556if (Dest.isZeroed() && isSimpleZero(E, CGF)) {1557// Storing "i32 0" to a zero'd memory location is a noop.1558return;1559} else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {1560return EmitNullInitializationToLValue(LV);1561} else if (isa<NoInitExpr>(E)) {1562// Do nothing.1563return;1564} else if (type->isReferenceType()) {1565RValue RV = CGF.EmitReferenceBindingToExpr(E);1566return CGF.EmitStoreThroughLValue(RV, LV);1567}15681569switch (CGF.getEvaluationKind(type)) {1570case TEK_Complex:1571CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);1572return;1573case TEK_Aggregate:1574CGF.EmitAggExpr(1575E, AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,1576AggValueSlot::DoesNotNeedGCBarriers,1577AggValueSlot::IsNotAliased,1578AggValueSlot::MayOverlap, Dest.isZeroed()));1579return;1580case TEK_Scalar:1581if (LV.isSimple()) {1582CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);1583} else {1584CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);1585}1586return;1587}1588llvm_unreachable("bad evaluation kind");1589}15901591void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {1592QualType type = lv.getType();15931594// If the destination slot is already zeroed out before the aggregate is1595// copied into it, we don't have to emit any zeros here.1596if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))1597return;15981599if (CGF.hasScalarEvaluationKind(type)) {1600// For non-aggregates, we can store the appropriate null constant.1601llvm::Value *null = CGF.CGM.EmitNullConstant(type);1602// Note that the following is not equivalent to1603// EmitStoreThroughBitfieldLValue for ARC types.1604if (lv.isBitField()) {1605CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);1606} else {1607assert(lv.isSimple());1608CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);1609}1610} else {1611// There's a potential optimization opportunity in combining1612// memsets; that would be easy for arrays, but relatively1613// difficult for structures with the current code.1614CGF.EmitNullInitialization(lv.getAddress(), lv.getType());1615}1616}16171618void AggExprEmitter::VisitCXXParenListInitExpr(CXXParenListInitExpr *E) {1619VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),1620E->getInitializedFieldInUnion(),1621E->getArrayFiller());1622}16231624void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {1625if (E->hadArrayRangeDesignator())1626CGF.ErrorUnsupported(E, "GNU array range designator extension");16271628if (E->isTransparent())1629return Visit(E->getInit(0));16301631VisitCXXParenListOrInitListExpr(1632E, E->inits(), E->getInitializedFieldInUnion(), E->getArrayFiller());1633}16341635void AggExprEmitter::VisitCXXParenListOrInitListExpr(1636Expr *ExprToVisit, ArrayRef<Expr *> InitExprs,1637FieldDecl *InitializedFieldInUnion, Expr *ArrayFiller) {1638#if 01639// FIXME: Assess perf here? Figure out what cases are worth optimizing here1640// (Length of globals? Chunks of zeroed-out space?).1641//1642// If we can, prefer a copy from a global; this is a lot less code for long1643// globals, and it's easier for the current optimizers to analyze.1644if (llvm::Constant *C =1645CGF.CGM.EmitConstantExpr(ExprToVisit, ExprToVisit->getType(), &CGF)) {1646llvm::GlobalVariable* GV =1647new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,1648llvm::GlobalValue::InternalLinkage, C, "");1649EmitFinalDestCopy(ExprToVisit->getType(),1650CGF.MakeAddrLValue(GV, ExprToVisit->getType()));1651return;1652}1653#endif16541655AggValueSlot Dest = EnsureSlot(ExprToVisit->getType());16561657LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), ExprToVisit->getType());16581659// Handle initialization of an array.1660if (ExprToVisit->getType()->isConstantArrayType()) {1661auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());1662EmitArrayInit(Dest.getAddress(), AType, ExprToVisit->getType(), ExprToVisit,1663InitExprs, ArrayFiller);1664return;1665} else if (ExprToVisit->getType()->isVariableArrayType()) {1666// A variable array type that has an initializer can only do empty1667// initialization. And because this feature is not exposed as an extension1668// in C++, we can safely memset the array memory to zero.1669assert(InitExprs.size() == 0 &&1670"you can only use an empty initializer with VLAs");1671CGF.EmitNullInitialization(Dest.getAddress(), ExprToVisit->getType());1672return;1673}16741675assert(ExprToVisit->getType()->isRecordType() &&1676"Only support structs/unions here!");16771678// Do struct initialization; this code just sets each individual member1679// to the approprate value. This makes bitfield support automatic;1680// the disadvantage is that the generated code is more difficult for1681// the optimizer, especially with bitfields.1682unsigned NumInitElements = InitExprs.size();1683RecordDecl *record = ExprToVisit->getType()->castAs<RecordType>()->getDecl();16841685// We'll need to enter cleanup scopes in case any of the element1686// initializers throws an exception.1687SmallVector<EHScopeStack::stable_iterator, 16> cleanups;1688CodeGenFunction::CleanupDeactivationScope DeactivateCleanups(CGF);16891690unsigned curInitIndex = 0;16911692// Emit initialization of base classes.1693if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {1694assert(NumInitElements >= CXXRD->getNumBases() &&1695"missing initializer for base class");1696for (auto &Base : CXXRD->bases()) {1697assert(!Base.isVirtual() && "should not see vbases here");1698auto *BaseRD = Base.getType()->getAsCXXRecordDecl();1699Address V = CGF.GetAddressOfDirectBaseInCompleteClass(1700Dest.getAddress(), CXXRD, BaseRD,1701/*isBaseVirtual*/ false);1702AggValueSlot AggSlot = AggValueSlot::forAddr(1703V, Qualifiers(),1704AggValueSlot::IsDestructed,1705AggValueSlot::DoesNotNeedGCBarriers,1706AggValueSlot::IsNotAliased,1707CGF.getOverlapForBaseInit(CXXRD, BaseRD, Base.isVirtual()));1708CGF.EmitAggExpr(InitExprs[curInitIndex++], AggSlot);17091710if (QualType::DestructionKind dtorKind =1711Base.getType().isDestructedType())1712CGF.pushDestroyAndDeferDeactivation(dtorKind, V, Base.getType());1713}1714}17151716// Prepare a 'this' for CXXDefaultInitExprs.1717CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());17181719if (record->isUnion()) {1720// Only initialize one field of a union. The field itself is1721// specified by the initializer list.1722if (!InitializedFieldInUnion) {1723// Empty union; we have nothing to do.17241725#ifndef NDEBUG1726// Make sure that it's really an empty and not a failure of1727// semantic analysis.1728for (const auto *Field : record->fields())1729assert(1730(Field->isUnnamedBitField() || Field->isAnonymousStructOrUnion()) &&1731"Only unnamed bitfields or anonymous class allowed");1732#endif1733return;1734}17351736// FIXME: volatility1737FieldDecl *Field = InitializedFieldInUnion;17381739LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);1740if (NumInitElements) {1741// Store the initializer into the field1742EmitInitializationToLValue(InitExprs[0], FieldLoc);1743} else {1744// Default-initialize to null.1745EmitNullInitializationToLValue(FieldLoc);1746}17471748return;1749}17501751// Here we iterate over the fields; this makes it simpler to both1752// default-initialize fields and skip over unnamed fields.1753for (const auto *field : record->fields()) {1754// We're done once we hit the flexible array member.1755if (field->getType()->isIncompleteArrayType())1756break;17571758// Always skip anonymous bitfields.1759if (field->isUnnamedBitField())1760continue;17611762// We're done if we reach the end of the explicit initializers, we1763// have a zeroed object, and the rest of the fields are1764// zero-initializable.1765if (curInitIndex == NumInitElements && Dest.isZeroed() &&1766CGF.getTypes().isZeroInitializable(ExprToVisit->getType()))1767break;176817691770LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);1771// We never generate write-barries for initialized fields.1772LV.setNonGC(true);17731774if (curInitIndex < NumInitElements) {1775// Store the initializer into the field.1776EmitInitializationToLValue(InitExprs[curInitIndex++], LV);1777} else {1778// We're out of initializers; default-initialize to null1779EmitNullInitializationToLValue(LV);1780}17811782// Push a destructor if necessary.1783// FIXME: if we have an array of structures, all explicitly1784// initialized, we can end up pushing a linear number of cleanups.1785if (QualType::DestructionKind dtorKind1786= field->getType().isDestructedType()) {1787assert(LV.isSimple());1788if (dtorKind) {1789CGF.pushDestroyAndDeferDeactivation(NormalAndEHCleanup, LV.getAddress(),1790field->getType(),1791CGF.getDestroyer(dtorKind), false);1792}1793}1794}1795}17961797void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,1798llvm::Value *outerBegin) {1799// Emit the common subexpression.1800CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());18011802Address destPtr = EnsureSlot(E->getType()).getAddress();1803uint64_t numElements = E->getArraySize().getZExtValue();18041805if (!numElements)1806return;18071808// destPtr is an array*. Construct an elementType* by drilling down a level.1809llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);1810llvm::Value *indices[] = {zero, zero};1811llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getElementType(),1812destPtr.emitRawPointer(CGF),1813indices, "arrayinit.begin");18141815// Prepare to special-case multidimensional array initialization: we avoid1816// emitting multiple destructor loops in that case.1817if (!outerBegin)1818outerBegin = begin;1819ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());18201821QualType elementType =1822CGF.getContext().getAsArrayType(E->getType())->getElementType();1823CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);1824CharUnits elementAlign =1825destPtr.getAlignment().alignmentOfArrayElement(elementSize);1826llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);18271828llvm::BasicBlock *entryBB = Builder.GetInsertBlock();1829llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");18301831// Jump into the body.1832CGF.EmitBlock(bodyBB);1833llvm::PHINode *index =1834Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");1835index->addIncoming(zero, entryBB);1836llvm::Value *element =1837Builder.CreateInBoundsGEP(llvmElementType, begin, index);18381839// Prepare for a cleanup.1840QualType::DestructionKind dtorKind = elementType.isDestructedType();1841EHScopeStack::stable_iterator cleanup;1842if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) {1843if (outerBegin->getType() != element->getType())1844outerBegin = Builder.CreateBitCast(outerBegin, element->getType());1845CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,1846elementAlign,1847CGF.getDestroyer(dtorKind));1848cleanup = CGF.EHStack.stable_begin();1849} else {1850dtorKind = QualType::DK_none;1851}18521853// Emit the actual filler expression.1854{1855// Temporaries created in an array initialization loop are destroyed1856// at the end of each iteration.1857CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);1858CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);1859LValue elementLV = CGF.MakeAddrLValue(1860Address(element, llvmElementType, elementAlign), elementType);18611862if (InnerLoop) {1863// If the subexpression is an ArrayInitLoopExpr, share its cleanup.1864auto elementSlot = AggValueSlot::forLValue(1865elementLV, AggValueSlot::IsDestructed,1866AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,1867AggValueSlot::DoesNotOverlap);1868AggExprEmitter(CGF, elementSlot, false)1869.VisitArrayInitLoopExpr(InnerLoop, outerBegin);1870} else1871EmitInitializationToLValue(E->getSubExpr(), elementLV);1872}18731874// Move on to the next element.1875llvm::Value *nextIndex = Builder.CreateNUWAdd(1876index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");1877index->addIncoming(nextIndex, Builder.GetInsertBlock());18781879// Leave the loop if we're done.1880llvm::Value *done = Builder.CreateICmpEQ(1881nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),1882"arrayinit.done");1883llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");1884Builder.CreateCondBr(done, endBB, bodyBB);18851886CGF.EmitBlock(endBB);18871888// Leave the partial-array cleanup if we entered one.1889if (dtorKind)1890CGF.DeactivateCleanupBlock(cleanup, index);1891}18921893void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {1894AggValueSlot Dest = EnsureSlot(E->getType());18951896LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());1897EmitInitializationToLValue(E->getBase(), DestLV);1898VisitInitListExpr(E->getUpdater());1899}19001901//===----------------------------------------------------------------------===//1902// Entry Points into this File1903//===----------------------------------------------------------------------===//19041905/// GetNumNonZeroBytesInInit - Get an approximate count of the number of1906/// non-zero bytes that will be stored when outputting the initializer for the1907/// specified initializer expression.1908static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {1909if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))1910E = MTE->getSubExpr();1911E = E->IgnoreParenNoopCasts(CGF.getContext());19121913// 0 and 0.0 won't require any non-zero stores!1914if (isSimpleZero(E, CGF)) return CharUnits::Zero();19151916// If this is an initlist expr, sum up the size of sizes of the (present)1917// elements. If this is something weird, assume the whole thing is non-zero.1918const InitListExpr *ILE = dyn_cast<InitListExpr>(E);1919while (ILE && ILE->isTransparent())1920ILE = dyn_cast<InitListExpr>(ILE->getInit(0));1921if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))1922return CGF.getContext().getTypeSizeInChars(E->getType());19231924// InitListExprs for structs have to be handled carefully. If there are1925// reference members, we need to consider the size of the reference, not the1926// referencee. InitListExprs for unions and arrays can't have references.1927if (const RecordType *RT = E->getType()->getAs<RecordType>()) {1928if (!RT->isUnionType()) {1929RecordDecl *SD = RT->getDecl();1930CharUnits NumNonZeroBytes = CharUnits::Zero();19311932unsigned ILEElement = 0;1933if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))1934while (ILEElement != CXXRD->getNumBases())1935NumNonZeroBytes +=1936GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);1937for (const auto *Field : SD->fields()) {1938// We're done once we hit the flexible array member or run out of1939// InitListExpr elements.1940if (Field->getType()->isIncompleteArrayType() ||1941ILEElement == ILE->getNumInits())1942break;1943if (Field->isUnnamedBitField())1944continue;19451946const Expr *E = ILE->getInit(ILEElement++);19471948// Reference values are always non-null and have the width of a pointer.1949if (Field->getType()->isReferenceType())1950NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(1951CGF.getTarget().getPointerWidth(LangAS::Default));1952else1953NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);1954}19551956return NumNonZeroBytes;1957}1958}19591960// FIXME: This overestimates the number of non-zero bytes for bit-fields.1961CharUnits NumNonZeroBytes = CharUnits::Zero();1962for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)1963NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);1964return NumNonZeroBytes;1965}19661967/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of1968/// zeros in it, emit a memset and avoid storing the individual zeros.1969///1970static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,1971CodeGenFunction &CGF) {1972// If the slot is already known to be zeroed, nothing to do. Don't mess with1973// volatile stores.1974if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid())1975return;19761977// C++ objects with a user-declared constructor don't need zero'ing.1978if (CGF.getLangOpts().CPlusPlus)1979if (const RecordType *RT = CGF.getContext()1980.getBaseElementType(E->getType())->getAs<RecordType>()) {1981const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());1982if (RD->hasUserDeclaredConstructor())1983return;1984}19851986// If the type is 16-bytes or smaller, prefer individual stores over memset.1987CharUnits Size = Slot.getPreferredSize(CGF.getContext(), E->getType());1988if (Size <= CharUnits::fromQuantity(16))1989return;19901991// Check to see if over 3/4 of the initializer are known to be zero. If so,1992// we prefer to emit memset + individual stores for the rest.1993CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);1994if (NumNonZeroBytes*4 > Size)1995return;19961997// Okay, it seems like a good idea to use an initial memset, emit the call.1998llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());19992000Address Loc = Slot.getAddress().withElementType(CGF.Int8Ty);2001CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);20022003// Tell the AggExprEmitter that the slot is known zero.2004Slot.setZeroed();2005}20062007200820092010/// EmitAggExpr - Emit the computation of the specified expression of aggregate2011/// type. The result is computed into DestPtr. Note that if DestPtr is null,2012/// the value of the aggregate expression is not needed. If VolatileDest is2013/// true, DestPtr cannot be 0.2014void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {2015assert(E && hasAggregateEvaluationKind(E->getType()) &&2016"Invalid aggregate expression to emit");2017assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&2018"slot has bits but no address");20192020// Optimize the slot if possible.2021CheckAggExprForMemSetUse(Slot, E, *this);20222023AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));2024}20252026LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {2027assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");2028Address Temp = CreateMemTemp(E->getType());2029LValue LV = MakeAddrLValue(Temp, E->getType());2030EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,2031AggValueSlot::DoesNotNeedGCBarriers,2032AggValueSlot::IsNotAliased,2033AggValueSlot::DoesNotOverlap));2034return LV;2035}20362037void CodeGenFunction::EmitAggFinalDestCopy(QualType Type, AggValueSlot Dest,2038const LValue &Src,2039ExprValueKind SrcKind) {2040return AggExprEmitter(*this, Dest, Dest.isIgnored())2041.EmitFinalDestCopy(Type, Src, SrcKind);2042}20432044AggValueSlot::Overlap_t2045CodeGenFunction::getOverlapForFieldInit(const FieldDecl *FD) {2046if (!FD->hasAttr<NoUniqueAddressAttr>() || !FD->getType()->isRecordType())2047return AggValueSlot::DoesNotOverlap;20482049// Empty fields can overlap earlier fields.2050if (FD->getType()->getAsCXXRecordDecl()->isEmpty())2051return AggValueSlot::MayOverlap;20522053// If the field lies entirely within the enclosing class's nvsize, its tail2054// padding cannot overlap any already-initialized object. (The only subobjects2055// with greater addresses that might already be initialized are vbases.)2056const RecordDecl *ClassRD = FD->getParent();2057const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassRD);2058if (Layout.getFieldOffset(FD->getFieldIndex()) +2059getContext().getTypeSize(FD->getType()) <=2060(uint64_t)getContext().toBits(Layout.getNonVirtualSize()))2061return AggValueSlot::DoesNotOverlap;20622063// The tail padding may contain values we need to preserve.2064return AggValueSlot::MayOverlap;2065}20662067AggValueSlot::Overlap_t CodeGenFunction::getOverlapForBaseInit(2068const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual) {2069// If the most-derived object is a field declared with [[no_unique_address]],2070// the tail padding of any virtual base could be reused for other subobjects2071// of that field's class.2072if (IsVirtual)2073return AggValueSlot::MayOverlap;20742075// Empty bases can overlap earlier bases.2076if (BaseRD->isEmpty())2077return AggValueSlot::MayOverlap;20782079// If the base class is laid out entirely within the nvsize of the derived2080// class, its tail padding cannot yet be initialized, so we can issue2081// stores at the full width of the base class.2082const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);2083if (Layout.getBaseClassOffset(BaseRD) +2084getContext().getASTRecordLayout(BaseRD).getSize() <=2085Layout.getNonVirtualSize())2086return AggValueSlot::DoesNotOverlap;20872088// The tail padding may contain values we need to preserve.2089return AggValueSlot::MayOverlap;2090}20912092void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty,2093AggValueSlot::Overlap_t MayOverlap,2094bool isVolatile) {2095assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");20962097Address DestPtr = Dest.getAddress();2098Address SrcPtr = Src.getAddress();20992100if (getLangOpts().CPlusPlus) {2101if (const RecordType *RT = Ty->getAs<RecordType>()) {2102CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());2103assert((Record->hasTrivialCopyConstructor() ||2104Record->hasTrivialCopyAssignment() ||2105Record->hasTrivialMoveConstructor() ||2106Record->hasTrivialMoveAssignment() ||2107Record->hasAttr<TrivialABIAttr>() || Record->isUnion()) &&2108"Trying to aggregate-copy a type without a trivial copy/move "2109"constructor or assignment operator");2110// Ignore empty classes in C++.2111if (Record->isEmpty())2112return;2113}2114}21152116if (getLangOpts().CUDAIsDevice) {2117if (Ty->isCUDADeviceBuiltinSurfaceType()) {2118if (getTargetHooks().emitCUDADeviceBuiltinSurfaceDeviceCopy(*this, Dest,2119Src))2120return;2121} else if (Ty->isCUDADeviceBuiltinTextureType()) {2122if (getTargetHooks().emitCUDADeviceBuiltinTextureDeviceCopy(*this, Dest,2123Src))2124return;2125}2126}21272128// Aggregate assignment turns into llvm.memcpy. This is almost valid per2129// C99 6.5.16.1p3, which states "If the value being stored in an object is2130// read from another object that overlaps in anyway the storage of the first2131// object, then the overlap shall be exact and the two objects shall have2132// qualified or unqualified versions of a compatible type."2133//2134// memcpy is not defined if the source and destination pointers are exactly2135// equal, but other compilers do this optimization, and almost every memcpy2136// implementation handles this case safely. If there is a libc that does not2137// safely handle this, we can add a target hook.21382139// Get data size info for this aggregate. Don't copy the tail padding if this2140// might be a potentially-overlapping subobject, since the tail padding might2141// be occupied by a different object. Otherwise, copying it is fine.2142TypeInfoChars TypeInfo;2143if (MayOverlap)2144TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);2145else2146TypeInfo = getContext().getTypeInfoInChars(Ty);21472148llvm::Value *SizeVal = nullptr;2149if (TypeInfo.Width.isZero()) {2150// But note that getTypeInfo returns 0 for a VLA.2151if (auto *VAT = dyn_cast_or_null<VariableArrayType>(2152getContext().getAsArrayType(Ty))) {2153QualType BaseEltTy;2154SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);2155TypeInfo = getContext().getTypeInfoInChars(BaseEltTy);2156assert(!TypeInfo.Width.isZero());2157SizeVal = Builder.CreateNUWMul(2158SizeVal,2159llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity()));2160}2161}2162if (!SizeVal) {2163SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity());2164}21652166// FIXME: If we have a volatile struct, the optimizer can remove what might2167// appear to be `extra' memory ops:2168//2169// volatile struct { int i; } a, b;2170//2171// int main() {2172// a = b;2173// a = b;2174// }2175//2176// we need to use a different call here. We use isVolatile to indicate when2177// either the source or the destination is volatile.21782179DestPtr = DestPtr.withElementType(Int8Ty);2180SrcPtr = SrcPtr.withElementType(Int8Ty);21812182// Don't do any of the memmove_collectable tests if GC isn't set.2183if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {2184// fall through2185} else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {2186RecordDecl *Record = RecordTy->getDecl();2187if (Record->hasObjectMember()) {2188CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,2189SizeVal);2190return;2191}2192} else if (Ty->isArrayType()) {2193QualType BaseType = getContext().getBaseElementType(Ty);2194if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {2195if (RecordTy->getDecl()->hasObjectMember()) {2196CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,2197SizeVal);2198return;2199}2200}2201}22022203auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);22042205// Determine the metadata to describe the position of any padding in this2206// memcpy, as well as the TBAA tags for the members of the struct, in case2207// the optimizer wishes to expand it in to scalar memory operations.2208if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))2209Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);22102211if (CGM.getCodeGenOpts().NewStructPathTBAA) {2212TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer(2213Dest.getTBAAInfo(), Src.getTBAAInfo());2214CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo);2215}2216}221722182219