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"
157a51313dSChris Lattner #include "CodeGenModule.h"
165f21d2f6SFariborz Jahanian #include "CGObjCRuntime.h"
17ad319a73SDaniel Dunbar #include "clang/AST/ASTContext.h"
18b7f8f594SAnders Carlsson #include "clang/AST/DeclCXX.h"
19ad319a73SDaniel Dunbar #include "clang/AST/StmtVisitor.h"
207a51313dSChris Lattner #include "llvm/Constants.h"
217a51313dSChris Lattner #include "llvm/Function.h"
227a51313dSChris Lattner #include "llvm/GlobalVariable.h"
23579a05d7SChris Lattner #include "llvm/Intrinsics.h"
247a51313dSChris Lattner using namespace clang;
257a51313dSChris Lattner using namespace CodeGen;
267a51313dSChris Lattner 
277a51313dSChris Lattner //===----------------------------------------------------------------------===//
287a51313dSChris Lattner //                        Aggregate Expression Emitter
297a51313dSChris Lattner //===----------------------------------------------------------------------===//
307a51313dSChris Lattner 
317a51313dSChris Lattner namespace  {
32337e3a5fSBenjamin Kramer class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
337a51313dSChris Lattner   CodeGenFunction &CGF;
34cb463859SDaniel Dunbar   CGBuilderTy &Builder;
357a626f63SJohn McCall   AggValueSlot Dest;
36ec3cbfe8SMike Stump   bool IgnoreResult;
3778a15113SJohn McCall 
3878a15113SJohn McCall   ReturnValueSlot getReturnValueSlot() const {
39cc04e9f6SJohn McCall     // If the destination slot requires garbage collection, we can't
40cc04e9f6SJohn McCall     // use the real return value slot, because we have to use the GC
41cc04e9f6SJohn McCall     // API.
4258649dc6SJohn McCall     if (Dest.requiresGCollection()) return ReturnValueSlot();
43cc04e9f6SJohn McCall 
447a626f63SJohn McCall     return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
457a626f63SJohn McCall   }
467a626f63SJohn McCall 
477a626f63SJohn McCall   AggValueSlot EnsureSlot(QualType T) {
487a626f63SJohn McCall     if (!Dest.isIgnored()) return Dest;
497a626f63SJohn McCall     return CGF.CreateAggTemp(T, "agg.tmp.ensured");
5078a15113SJohn McCall   }
51cc04e9f6SJohn McCall 
527a51313dSChris Lattner public:
537a626f63SJohn McCall   AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest,
54b60e70f9SFariborz Jahanian                  bool ignore)
557a626f63SJohn McCall     : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
56b60e70f9SFariborz Jahanian       IgnoreResult(ignore) {
577a51313dSChris Lattner   }
587a51313dSChris Lattner 
597a51313dSChris Lattner   //===--------------------------------------------------------------------===//
607a51313dSChris Lattner   //                               Utilities
617a51313dSChris Lattner   //===--------------------------------------------------------------------===//
627a51313dSChris Lattner 
637a51313dSChris Lattner   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
647a51313dSChris Lattner   /// represents a value lvalue, this method emits the address of the lvalue,
657a51313dSChris Lattner   /// then loads the result into DestPtr.
667a51313dSChris Lattner   void EmitAggLoadOfLValue(const Expr *E);
677a51313dSChris Lattner 
68ca9fc09cSMike Stump   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
69ec3cbfe8SMike Stump   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
70ec3cbfe8SMike Stump   void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
71ca9fc09cSMike Stump 
72cc04e9f6SJohn McCall   void EmitGCMove(const Expr *E, RValue Src);
73cc04e9f6SJohn McCall 
74cc04e9f6SJohn McCall   bool TypeRequiresGCollection(QualType T);
75cc04e9f6SJohn McCall 
767a51313dSChris Lattner   //===--------------------------------------------------------------------===//
777a51313dSChris Lattner   //                            Visitor Methods
787a51313dSChris Lattner   //===--------------------------------------------------------------------===//
797a51313dSChris Lattner 
807a51313dSChris Lattner   void VisitStmt(Stmt *S) {
81a7c8cf62SDaniel Dunbar     CGF.ErrorUnsupported(S, "aggregate expression");
827a51313dSChris Lattner   }
837a51313dSChris Lattner   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
843f66b84cSEli Friedman   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
857a51313dSChris Lattner 
867a51313dSChris Lattner   // l-values.
877a51313dSChris Lattner   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
887a51313dSChris Lattner   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
897a51313dSChris Lattner   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
90d443c0a0SDaniel Dunbar   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
912f343dd5SChris Lattner   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
922f343dd5SChris Lattner     EmitAggLoadOfLValue(E);
932f343dd5SChris Lattner   }
947a51313dSChris Lattner   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
957a51313dSChris Lattner     EmitAggLoadOfLValue(E);
967a51313dSChris Lattner   }
972f343dd5SChris Lattner   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
982f343dd5SChris Lattner     EmitAggLoadOfLValue(E);
992f343dd5SChris Lattner   }
1002f343dd5SChris Lattner   void VisitPredefinedExpr(const PredefinedExpr *E) {
1012f343dd5SChris Lattner     EmitAggLoadOfLValue(E);
1022f343dd5SChris Lattner   }
103bc7d67ceSMike Stump 
1047a51313dSChris Lattner   // Operators.
105ec143777SAnders Carlsson   void VisitCastExpr(CastExpr *E);
1067a51313dSChris Lattner   void VisitCallExpr(const CallExpr *E);
1077a51313dSChris Lattner   void VisitStmtExpr(const StmtExpr *E);
1087a51313dSChris Lattner   void VisitBinaryOperator(const BinaryOperator *BO);
109ffba662dSFariborz Jahanian   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
1107a51313dSChris Lattner   void VisitBinAssign(const BinaryOperator *E);
1114b0e2a30SEli Friedman   void VisitBinComma(const BinaryOperator *E);
1127a51313dSChris Lattner 
113b1d329daSChris Lattner   void VisitObjCMessageExpr(ObjCMessageExpr *E);
114c8317a44SDaniel Dunbar   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
115c8317a44SDaniel Dunbar     EmitAggLoadOfLValue(E);
116c8317a44SDaniel Dunbar   }
11755310df7SDaniel Dunbar   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
1187a51313dSChris Lattner 
119c07a0c7eSJohn McCall   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
1205b2095ceSAnders Carlsson   void VisitChooseExpr(const ChooseExpr *CE);
1217a51313dSChris Lattner   void VisitInitListExpr(InitListExpr *E);
12218ada985SAnders Carlsson   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
123aa9c7aedSChris Lattner   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
124aa9c7aedSChris Lattner     Visit(DAE->getExpr());
125aa9c7aedSChris Lattner   }
1263be22e27SAnders Carlsson   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
1271619a504SAnders Carlsson   void VisitCXXConstructExpr(const CXXConstructExpr *E);
1285d413781SJohn McCall   void VisitExprWithCleanups(ExprWithCleanups *E);
129747eb784SDouglas Gregor   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1305bbbb137SMike Stump   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
131c82b86dfSAnders Carlsson 
1321bf5846aSJohn McCall   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1331bf5846aSJohn McCall 
13421911e89SEli Friedman   void VisitVAArgExpr(VAArgExpr *E);
135579a05d7SChris Lattner 
136b247350eSAnders Carlsson   void EmitInitializationToLValue(Expr *E, LValue Address, QualType T);
137579a05d7SChris Lattner   void EmitNullInitializationToLValue(LValue Address, QualType T);
1387a51313dSChris Lattner   //  case Expr::ChooseExprClass:
139f16b8c30SMike Stump   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
1407a51313dSChris Lattner };
1417a51313dSChris Lattner }  // end anonymous namespace.
1427a51313dSChris Lattner 
1437a51313dSChris Lattner //===----------------------------------------------------------------------===//
1447a51313dSChris Lattner //                                Utilities
1457a51313dSChris Lattner //===----------------------------------------------------------------------===//
1467a51313dSChris Lattner 
1477a51313dSChris Lattner /// EmitAggLoadOfLValue - Given an expression with aggregate type that
1487a51313dSChris Lattner /// represents a value lvalue, this method emits the address of the lvalue,
1497a51313dSChris Lattner /// then loads the result into DestPtr.
1507a51313dSChris Lattner void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
1517a51313dSChris Lattner   LValue LV = CGF.EmitLValue(E);
152ca9fc09cSMike Stump   EmitFinalDestCopy(E, LV);
153ca9fc09cSMike Stump }
154ca9fc09cSMike Stump 
155cc04e9f6SJohn McCall /// \brief True if the given aggregate type requires special GC API calls.
156cc04e9f6SJohn McCall bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
157cc04e9f6SJohn McCall   // Only record types have members that might require garbage collection.
158cc04e9f6SJohn McCall   const RecordType *RecordTy = T->getAs<RecordType>();
159cc04e9f6SJohn McCall   if (!RecordTy) return false;
160cc04e9f6SJohn McCall 
161cc04e9f6SJohn McCall   // Don't mess with non-trivial C++ types.
162cc04e9f6SJohn McCall   RecordDecl *Record = RecordTy->getDecl();
163cc04e9f6SJohn McCall   if (isa<CXXRecordDecl>(Record) &&
164cc04e9f6SJohn McCall       (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
165cc04e9f6SJohn McCall        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
166cc04e9f6SJohn McCall     return false;
167cc04e9f6SJohn McCall 
168cc04e9f6SJohn McCall   // Check whether the type has an object member.
169cc04e9f6SJohn McCall   return Record->hasObjectMember();
170cc04e9f6SJohn McCall }
171cc04e9f6SJohn McCall 
172cc04e9f6SJohn McCall /// \brief Perform the final move to DestPtr if RequiresGCollection is set.
173cc04e9f6SJohn McCall ///
174cc04e9f6SJohn McCall /// The idea is that you do something like this:
175cc04e9f6SJohn McCall ///   RValue Result = EmitSomething(..., getReturnValueSlot());
176cc04e9f6SJohn McCall ///   EmitGCMove(E, Result);
177cc04e9f6SJohn McCall /// If GC doesn't interfere, this will cause the result to be emitted
178cc04e9f6SJohn McCall /// directly into the return value slot.  If GC does interfere, a final
179cc04e9f6SJohn McCall /// move will be performed.
180cc04e9f6SJohn McCall void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) {
18158649dc6SJohn McCall   if (Dest.requiresGCollection()) {
182021510e9SFariborz Jahanian     std::pair<uint64_t, unsigned> TypeInfo =
183021510e9SFariborz Jahanian       CGF.getContext().getTypeInfo(E->getType());
184021510e9SFariborz Jahanian     unsigned long size = TypeInfo.first/8;
185021510e9SFariborz Jahanian     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
186021510e9SFariborz Jahanian     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
1877a626f63SJohn McCall     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, Dest.getAddr(),
188cc04e9f6SJohn McCall                                                     Src.getAggregateAddr(),
189021510e9SFariborz Jahanian                                                     SizeVal);
190021510e9SFariborz Jahanian   }
191cc04e9f6SJohn McCall }
192cc04e9f6SJohn McCall 
193ca9fc09cSMike Stump /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
194ec3cbfe8SMike Stump void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
195ca9fc09cSMike Stump   assert(Src.isAggregate() && "value must be aggregate value!");
1967a51313dSChris Lattner 
1977a626f63SJohn McCall   // If Dest is ignored, then we're evaluating an aggregate expression
1988d752430SJohn McCall   // in a context (like an expression statement) that doesn't care
1998d752430SJohn McCall   // about the result.  C says that an lvalue-to-rvalue conversion is
2008d752430SJohn McCall   // performed in these cases; C++ says that it is not.  In either
2018d752430SJohn McCall   // case, we don't actually need to do anything unless the value is
2028d752430SJohn McCall   // volatile.
2037a626f63SJohn McCall   if (Dest.isIgnored()) {
2048d752430SJohn McCall     if (!Src.isVolatileQualified() ||
2058d752430SJohn McCall         CGF.CGM.getLangOptions().CPlusPlus ||
2068d752430SJohn McCall         (IgnoreResult && Ignore))
207ec3cbfe8SMike Stump       return;
208c123623dSFariborz Jahanian 
209332ec2ceSMike Stump     // If the source is volatile, we must read from it; to do that, we need
210332ec2ceSMike Stump     // some place to put it.
2117a626f63SJohn McCall     Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
212332ec2ceSMike Stump   }
2137a51313dSChris Lattner 
21458649dc6SJohn McCall   if (Dest.requiresGCollection()) {
215021510e9SFariborz Jahanian     std::pair<uint64_t, unsigned> TypeInfo =
216021510e9SFariborz Jahanian     CGF.getContext().getTypeInfo(E->getType());
217021510e9SFariborz Jahanian     unsigned long size = TypeInfo.first/8;
218021510e9SFariborz Jahanian     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
219021510e9SFariborz Jahanian     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
220879d7266SFariborz Jahanian     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
2217a626f63SJohn McCall                                                       Dest.getAddr(),
2227a626f63SJohn McCall                                                       Src.getAggregateAddr(),
223021510e9SFariborz Jahanian                                                       SizeVal);
224879d7266SFariborz Jahanian     return;
225879d7266SFariborz Jahanian   }
226ca9fc09cSMike Stump   // If the result of the assignment is used, copy the LHS there also.
227ca9fc09cSMike Stump   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
228ca9fc09cSMike Stump   // from the source as well, as we can't eliminate it if either operand
229ca9fc09cSMike Stump   // is volatile, unless copy has volatile for both source and destination..
2307a626f63SJohn McCall   CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
2317a626f63SJohn McCall                         Dest.isVolatile()|Src.isVolatileQualified());
232ca9fc09cSMike Stump }
233ca9fc09cSMike Stump 
234ca9fc09cSMike Stump /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
235ec3cbfe8SMike Stump void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
236ca9fc09cSMike Stump   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
237ca9fc09cSMike Stump 
238ca9fc09cSMike Stump   EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
239ec3cbfe8SMike Stump                                             Src.isVolatileQualified()),
240ec3cbfe8SMike Stump                     Ignore);
2417a51313dSChris Lattner }
2427a51313dSChris Lattner 
2437a51313dSChris Lattner //===----------------------------------------------------------------------===//
2447a51313dSChris Lattner //                            Visitor Methods
2457a51313dSChris Lattner //===----------------------------------------------------------------------===//
2467a51313dSChris Lattner 
2471bf5846aSJohn McCall void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
248c07a0c7eSJohn McCall   EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e));
2491bf5846aSJohn McCall }
2501bf5846aSJohn McCall 
251ec143777SAnders Carlsson void AggExprEmitter::VisitCastExpr(CastExpr *E) {
2527a626f63SJohn McCall   if (Dest.isIgnored() && E->getCastKind() != CK_Dynamic) {
253c934bc84SDouglas Gregor     Visit(E->getSubExpr());
254c934bc84SDouglas Gregor     return;
255c934bc84SDouglas Gregor   }
256c934bc84SDouglas Gregor 
2571fb7ae9eSAnders Carlsson   switch (E->getCastKind()) {
258*8a01a751SAnders Carlsson   case CK_Dynamic: {
2591c073f47SDouglas Gregor     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
2601c073f47SDouglas Gregor     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
2611c073f47SDouglas Gregor     // FIXME: Do we also need to handle property references here?
2621c073f47SDouglas Gregor     if (LV.isSimple())
2631c073f47SDouglas Gregor       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
2641c073f47SDouglas Gregor     else
2651c073f47SDouglas Gregor       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
2661c073f47SDouglas Gregor 
2677a626f63SJohn McCall     if (!Dest.isIgnored())
2681c073f47SDouglas Gregor       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
2691c073f47SDouglas Gregor     break;
2701c073f47SDouglas Gregor   }
2711c073f47SDouglas Gregor 
272e302792bSJohn McCall   case CK_ToUnion: {
2737ffcf93bSNuno Lopes     // GCC union extension
2742e442a00SDaniel Dunbar     QualType Ty = E->getSubExpr()->getType();
2752e442a00SDaniel Dunbar     QualType PtrTy = CGF.getContext().getPointerType(Ty);
2767a626f63SJohn McCall     llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
277dd274848SEli Friedman                                                  CGF.ConvertType(PtrTy));
2782e442a00SDaniel Dunbar     EmitInitializationToLValue(E->getSubExpr(), CGF.MakeAddrLValue(CastPtr, Ty),
2792e442a00SDaniel Dunbar                                Ty);
2801fb7ae9eSAnders Carlsson     break;
2817ffcf93bSNuno Lopes   }
2827ffcf93bSNuno Lopes 
283e302792bSJohn McCall   case CK_DerivedToBase:
284e302792bSJohn McCall   case CK_BaseToDerived:
285e302792bSJohn McCall   case CK_UncheckedDerivedToBase: {
286aae38d66SDouglas Gregor     assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: "
287aae38d66SDouglas Gregor                 "should have been unpacked before we got here");
288aae38d66SDouglas Gregor     break;
289aae38d66SDouglas Gregor   }
290aae38d66SDouglas Gregor 
29134376a68SJohn McCall   case CK_GetObjCProperty: {
29234376a68SJohn McCall     LValue LV = CGF.EmitLValue(E->getSubExpr());
29334376a68SJohn McCall     assert(LV.isPropertyRef());
29434376a68SJohn McCall     RValue RV = CGF.EmitLoadOfPropertyRefLValue(LV, getReturnValueSlot());
29534376a68SJohn McCall     EmitGCMove(E, RV);
29634376a68SJohn McCall     break;
29734376a68SJohn McCall   }
29834376a68SJohn McCall 
29934376a68SJohn McCall   case CK_LValueToRValue: // hope for downstream optimization
300e302792bSJohn McCall   case CK_NoOp:
301e302792bSJohn McCall   case CK_UserDefinedConversion:
302e302792bSJohn McCall   case CK_ConstructorConversion:
3032a69547fSEli Friedman     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
3042a69547fSEli Friedman                                                    E->getType()) &&
3050f398c44SChris Lattner            "Implicit cast types must be compatible");
3067a51313dSChris Lattner     Visit(E->getSubExpr());
3071fb7ae9eSAnders Carlsson     break;
308b05a3e55SAnders Carlsson 
309e302792bSJohn McCall   case CK_LValueBitCast:
310f3735e01SJohn McCall     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
31151954276SDouglas Gregor     break;
31231996343SJohn McCall 
31331996343SJohn McCall   case CK_ResolveUnknownAnyType:
31431996343SJohn McCall     EmitAggLoadOfLValue(E);
31531996343SJohn McCall     break;
316f3735e01SJohn McCall 
317f3735e01SJohn McCall   case CK_Dependent:
318f3735e01SJohn McCall   case CK_BitCast:
319f3735e01SJohn McCall   case CK_ArrayToPointerDecay:
320f3735e01SJohn McCall   case CK_FunctionToPointerDecay:
321f3735e01SJohn McCall   case CK_NullToPointer:
322f3735e01SJohn McCall   case CK_NullToMemberPointer:
323f3735e01SJohn McCall   case CK_BaseToDerivedMemberPointer:
324f3735e01SJohn McCall   case CK_DerivedToBaseMemberPointer:
325f3735e01SJohn McCall   case CK_MemberPointerToBoolean:
326f3735e01SJohn McCall   case CK_IntegralToPointer:
327f3735e01SJohn McCall   case CK_PointerToIntegral:
328f3735e01SJohn McCall   case CK_PointerToBoolean:
329f3735e01SJohn McCall   case CK_ToVoid:
330f3735e01SJohn McCall   case CK_VectorSplat:
331f3735e01SJohn McCall   case CK_IntegralCast:
332f3735e01SJohn McCall   case CK_IntegralToBoolean:
333f3735e01SJohn McCall   case CK_IntegralToFloating:
334f3735e01SJohn McCall   case CK_FloatingToIntegral:
335f3735e01SJohn McCall   case CK_FloatingToBoolean:
336f3735e01SJohn McCall   case CK_FloatingCast:
337f3735e01SJohn McCall   case CK_AnyPointerToObjCPointerCast:
338f3735e01SJohn McCall   case CK_AnyPointerToBlockPointerCast:
339f3735e01SJohn McCall   case CK_ObjCObjectLValueCast:
340f3735e01SJohn McCall   case CK_FloatingRealToComplex:
341f3735e01SJohn McCall   case CK_FloatingComplexToReal:
342f3735e01SJohn McCall   case CK_FloatingComplexToBoolean:
343f3735e01SJohn McCall   case CK_FloatingComplexCast:
344f3735e01SJohn McCall   case CK_FloatingComplexToIntegralComplex:
345f3735e01SJohn McCall   case CK_IntegralRealToComplex:
346f3735e01SJohn McCall   case CK_IntegralComplexToReal:
347f3735e01SJohn McCall   case CK_IntegralComplexToBoolean:
348f3735e01SJohn McCall   case CK_IntegralComplexCast:
349f3735e01SJohn McCall   case CK_IntegralComplexToFloatingComplex:
350f3735e01SJohn McCall     llvm_unreachable("cast kind invalid for aggregate types");
3511fb7ae9eSAnders Carlsson   }
3527a51313dSChris Lattner }
3537a51313dSChris Lattner 
3540f398c44SChris Lattner void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
355ddcbfe7bSAnders Carlsson   if (E->getCallReturnType()->isReferenceType()) {
356ddcbfe7bSAnders Carlsson     EmitAggLoadOfLValue(E);
357ddcbfe7bSAnders Carlsson     return;
358ddcbfe7bSAnders Carlsson   }
359ddcbfe7bSAnders Carlsson 
360cc04e9f6SJohn McCall   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
361cc04e9f6SJohn McCall   EmitGCMove(E, RV);
3627a51313dSChris Lattner }
3630f398c44SChris Lattner 
3640f398c44SChris Lattner void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
365cc04e9f6SJohn McCall   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
366cc04e9f6SJohn McCall   EmitGCMove(E, RV);
367b1d329daSChris Lattner }
3687a51313dSChris Lattner 
36955310df7SDaniel Dunbar void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
37034376a68SJohn McCall   llvm_unreachable("direct property access not surrounded by "
37134376a68SJohn McCall                    "lvalue-to-rvalue cast");
37255310df7SDaniel Dunbar }
37355310df7SDaniel Dunbar 
3740f398c44SChris Lattner void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
375a2342eb8SJohn McCall   CGF.EmitIgnoredExpr(E->getLHS());
3767a626f63SJohn McCall   Visit(E->getRHS());
3774b0e2a30SEli Friedman }
3784b0e2a30SEli Friedman 
3797a51313dSChris Lattner void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
380ce1de617SJohn McCall   CodeGenFunction::StmtExprEvaluation eval(CGF);
3817a626f63SJohn McCall   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
3827a51313dSChris Lattner }
3837a51313dSChris Lattner 
3847a51313dSChris Lattner void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
385e302792bSJohn McCall   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
386ffba662dSFariborz Jahanian     VisitPointerToDataMemberBinaryOperator(E);
387ffba662dSFariborz Jahanian   else
388a7c8cf62SDaniel Dunbar     CGF.ErrorUnsupported(E, "aggregate binary expression");
3897a51313dSChris Lattner }
3907a51313dSChris Lattner 
391ffba662dSFariborz Jahanian void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
392ffba662dSFariborz Jahanian                                                     const BinaryOperator *E) {
393ffba662dSFariborz Jahanian   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
394ffba662dSFariborz Jahanian   EmitFinalDestCopy(E, LV);
395ffba662dSFariborz Jahanian }
396ffba662dSFariborz Jahanian 
3977a51313dSChris Lattner void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
3987a51313dSChris Lattner   // For an assignment to work, the value on the right has
3997a51313dSChris Lattner   // to be compatible with the value on the left.
4002a69547fSEli Friedman   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
4012a69547fSEli Friedman                                                  E->getRHS()->getType())
4027a51313dSChris Lattner          && "Invalid assignment");
403d0a30016SJohn McCall 
404d0a30016SJohn McCall   // FIXME:  __block variables need the RHS evaluated first!
4057a51313dSChris Lattner   LValue LHS = CGF.EmitLValue(E->getLHS());
4067a51313dSChris Lattner 
4074b8c6db9SDaniel Dunbar   // We have to special case property setters, otherwise we must have
4084b8c6db9SDaniel Dunbar   // a simple lvalue (no aggregates inside vectors, bitfields).
4094b8c6db9SDaniel Dunbar   if (LHS.isPropertyRef()) {
4107a26ba4dSFariborz Jahanian     const ObjCPropertyRefExpr *RE = LHS.getPropertyRefExpr();
4117a26ba4dSFariborz Jahanian     QualType ArgType = RE->getSetterArgType();
4127a26ba4dSFariborz Jahanian     RValue Src;
4137a26ba4dSFariborz Jahanian     if (ArgType->isReferenceType())
4147a26ba4dSFariborz Jahanian       Src = CGF.EmitReferenceBindingToExpr(E->getRHS(), 0);
4157a26ba4dSFariborz Jahanian     else {
4167a626f63SJohn McCall       AggValueSlot Slot = EnsureSlot(E->getRHS()->getType());
4177a626f63SJohn McCall       CGF.EmitAggExpr(E->getRHS(), Slot);
4187a26ba4dSFariborz Jahanian       Src = Slot.asRValue();
4197a26ba4dSFariborz Jahanian     }
4207a26ba4dSFariborz Jahanian     CGF.EmitStoreThroughPropertyRefLValue(Src, LHS);
4214b8c6db9SDaniel Dunbar   } else {
422b60e70f9SFariborz Jahanian     bool GCollection = false;
423cc04e9f6SJohn McCall     if (CGF.getContext().getLangOptions().getGCMode())
424b60e70f9SFariborz Jahanian       GCollection = TypeRequiresGCollection(E->getLHS()->getType());
425cc04e9f6SJohn McCall 
4267a51313dSChris Lattner     // Codegen the RHS so that it stores directly into the LHS.
427b60e70f9SFariborz Jahanian     AggValueSlot LHSSlot = AggValueSlot::forLValue(LHS, true,
428b60e70f9SFariborz Jahanian                                                    GCollection);
429b60e70f9SFariborz Jahanian     CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
430ec3cbfe8SMike Stump     EmitFinalDestCopy(E, LHS, true);
4317a51313dSChris Lattner   }
4324b8c6db9SDaniel Dunbar }
4337a51313dSChris Lattner 
434c07a0c7eSJohn McCall void AggExprEmitter::
435c07a0c7eSJohn McCall VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
436a612e79bSDaniel Dunbar   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
437a612e79bSDaniel Dunbar   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
438a612e79bSDaniel Dunbar   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
4397a51313dSChris Lattner 
440c07a0c7eSJohn McCall   // Bind the common expression if necessary.
441c07a0c7eSJohn McCall   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
442c07a0c7eSJohn McCall 
443ce1de617SJohn McCall   CodeGenFunction::ConditionalEvaluation eval(CGF);
444b8841af8SEli Friedman   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
4457a51313dSChris Lattner 
4465b26f65bSJohn McCall   // Save whether the destination's lifetime is externally managed.
4475b26f65bSJohn McCall   bool DestLifetimeManaged = Dest.isLifetimeExternallyManaged();
4487a51313dSChris Lattner 
449ce1de617SJohn McCall   eval.begin(CGF);
450ce1de617SJohn McCall   CGF.EmitBlock(LHSBlock);
451c07a0c7eSJohn McCall   Visit(E->getTrueExpr());
452ce1de617SJohn McCall   eval.end(CGF);
4537a51313dSChris Lattner 
454ce1de617SJohn McCall   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
455ce1de617SJohn McCall   CGF.Builder.CreateBr(ContBlock);
4567a51313dSChris Lattner 
4575b26f65bSJohn McCall   // If the result of an agg expression is unused, then the emission
4585b26f65bSJohn McCall   // of the LHS might need to create a destination slot.  That's fine
4595b26f65bSJohn McCall   // with us, and we can safely emit the RHS into the same slot, but
4605b26f65bSJohn McCall   // we shouldn't claim that its lifetime is externally managed.
4615b26f65bSJohn McCall   Dest.setLifetimeExternallyManaged(DestLifetimeManaged);
4625b26f65bSJohn McCall 
463ce1de617SJohn McCall   eval.begin(CGF);
464ce1de617SJohn McCall   CGF.EmitBlock(RHSBlock);
465c07a0c7eSJohn McCall   Visit(E->getFalseExpr());
466ce1de617SJohn McCall   eval.end(CGF);
4677a51313dSChris Lattner 
4687a51313dSChris Lattner   CGF.EmitBlock(ContBlock);
4697a51313dSChris Lattner }
4707a51313dSChris Lattner 
4715b2095ceSAnders Carlsson void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
4725b2095ceSAnders Carlsson   Visit(CE->getChosenSubExpr(CGF.getContext()));
4735b2095ceSAnders Carlsson }
4745b2095ceSAnders Carlsson 
47521911e89SEli Friedman void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
476e9fcadd2SDaniel Dunbar   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
47713abd7e9SAnders Carlsson   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
47813abd7e9SAnders Carlsson 
479020cddcfSSebastian Redl   if (!ArgPtr) {
48013abd7e9SAnders Carlsson     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
481020cddcfSSebastian Redl     return;
482020cddcfSSebastian Redl   }
48313abd7e9SAnders Carlsson 
4842e442a00SDaniel Dunbar   EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
48521911e89SEli Friedman }
48621911e89SEli Friedman 
4873be22e27SAnders Carlsson void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
4887a626f63SJohn McCall   // Ensure that we have a slot, but if we already do, remember
4897a626f63SJohn McCall   // whether its lifetime was externally managed.
4907a626f63SJohn McCall   bool WasManaged = Dest.isLifetimeExternallyManaged();
4917a626f63SJohn McCall   Dest = EnsureSlot(E->getType());
4927a626f63SJohn McCall   Dest.setLifetimeExternallyManaged();
4933be22e27SAnders Carlsson 
4943be22e27SAnders Carlsson   Visit(E->getSubExpr());
4953be22e27SAnders Carlsson 
4967a626f63SJohn McCall   // Set up the temporary's destructor if its lifetime wasn't already
4977a626f63SJohn McCall   // being managed.
4987a626f63SJohn McCall   if (!WasManaged)
4997a626f63SJohn McCall     CGF.EmitCXXTemporary(E->getTemporary(), Dest.getAddr());
5003be22e27SAnders Carlsson }
5013be22e27SAnders Carlsson 
502b7f8f594SAnders Carlsson void
5031619a504SAnders Carlsson AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5047a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(E->getType());
5057a626f63SJohn McCall   CGF.EmitCXXConstructExpr(E, Slot);
506c82b86dfSAnders Carlsson }
507c82b86dfSAnders Carlsson 
5085d413781SJohn McCall void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
5095d413781SJohn McCall   CGF.EmitExprWithCleanups(E, Dest);
510b7f8f594SAnders Carlsson }
511b7f8f594SAnders Carlsson 
512747eb784SDouglas Gregor void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
5137a626f63SJohn McCall   QualType T = E->getType();
5147a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(T);
5157a626f63SJohn McCall   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T), T);
51618ada985SAnders Carlsson }
51718ada985SAnders Carlsson 
51818ada985SAnders Carlsson void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
5197a626f63SJohn McCall   QualType T = E->getType();
5207a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(T);
5217a626f63SJohn McCall   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T), T);
522ff3507b9SNuno Lopes }
523ff3507b9SNuno Lopes 
52427a3631bSChris Lattner /// isSimpleZero - If emitting this value will obviously just cause a store of
52527a3631bSChris Lattner /// zero to memory, return true.  This can return false if uncertain, so it just
52627a3631bSChris Lattner /// handles simple cases.
52727a3631bSChris Lattner static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
52827a3631bSChris Lattner   // (0)
52927a3631bSChris Lattner   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
53027a3631bSChris Lattner     return isSimpleZero(PE->getSubExpr(), CGF);
53127a3631bSChris Lattner   // 0
53227a3631bSChris Lattner   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
53327a3631bSChris Lattner     return IL->getValue() == 0;
53427a3631bSChris Lattner   // +0.0
53527a3631bSChris Lattner   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
53627a3631bSChris Lattner     return FL->getValue().isPosZero();
53727a3631bSChris Lattner   // int()
53827a3631bSChris Lattner   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
53927a3631bSChris Lattner       CGF.getTypes().isZeroInitializable(E->getType()))
54027a3631bSChris Lattner     return true;
54127a3631bSChris Lattner   // (int*)0 - Null pointer expressions.
54227a3631bSChris Lattner   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
54327a3631bSChris Lattner     return ICE->getCastKind() == CK_NullToPointer;
54427a3631bSChris Lattner   // '\0'
54527a3631bSChris Lattner   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
54627a3631bSChris Lattner     return CL->getValue() == 0;
54727a3631bSChris Lattner 
54827a3631bSChris Lattner   // Otherwise, hard case: conservatively return false.
54927a3631bSChris Lattner   return false;
55027a3631bSChris Lattner }
55127a3631bSChris Lattner 
55227a3631bSChris Lattner 
553b247350eSAnders Carlsson void
554b247350eSAnders Carlsson AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
555df0fe27bSMike Stump   // FIXME: Ignore result?
556579a05d7SChris Lattner   // FIXME: Are initializers affected by volatile?
55727a3631bSChris Lattner   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
55827a3631bSChris Lattner     // Storing "i32 0" to a zero'd memory location is a noop.
55927a3631bSChris Lattner   } else if (isa<ImplicitValueInitExpr>(E)) {
560b247350eSAnders Carlsson     EmitNullInitializationToLValue(LV, T);
56166498388SAnders Carlsson   } else if (T->isReferenceType()) {
56204775f84SAnders Carlsson     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
56366498388SAnders Carlsson     CGF.EmitStoreThroughLValue(RV, LV, T);
564b247350eSAnders Carlsson   } else if (T->isAnyComplexType()) {
5650202cb40SDouglas Gregor     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
566b247350eSAnders Carlsson   } else if (CGF.hasAggregateLLVMType(T)) {
56727a3631bSChris Lattner     CGF.EmitAggExpr(E, AggValueSlot::forAddr(LV.getAddress(), false, true,
56827a3631bSChris Lattner                                              false, Dest.isZeroed()));
5696e313210SEli Friedman   } else {
570a2342eb8SJohn McCall     CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV, T);
5717a51313dSChris Lattner   }
572579a05d7SChris Lattner }
573579a05d7SChris Lattner 
574579a05d7SChris Lattner void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
57527a3631bSChris Lattner   // If the destination slot is already zeroed out before the aggregate is
57627a3631bSChris Lattner   // copied into it, we don't have to emit any zeros here.
57727a3631bSChris Lattner   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(T))
57827a3631bSChris Lattner     return;
57927a3631bSChris Lattner 
580579a05d7SChris Lattner   if (!CGF.hasAggregateLLVMType(T)) {
581579a05d7SChris Lattner     // For non-aggregates, we can store zero
5820b75f23bSOwen Anderson     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
583e8bdce44SDaniel Dunbar     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
584579a05d7SChris Lattner   } else {
585579a05d7SChris Lattner     // There's a potential optimization opportunity in combining
586579a05d7SChris Lattner     // memsets; that would be easy for arrays, but relatively
587579a05d7SChris Lattner     // difficult for structures with the current code.
588c0964b60SAnders Carlsson     CGF.EmitNullInitialization(LV.getAddress(), T);
589579a05d7SChris Lattner   }
590579a05d7SChris Lattner }
591579a05d7SChris Lattner 
592579a05d7SChris Lattner void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
593f5d08c9eSEli Friedman #if 0
5946d11ec8cSEli Friedman   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
5956d11ec8cSEli Friedman   // (Length of globals? Chunks of zeroed-out space?).
596f5d08c9eSEli Friedman   //
59718bb9284SMike Stump   // If we can, prefer a copy from a global; this is a lot less code for long
59818bb9284SMike Stump   // globals, and it's easier for the current optimizers to analyze.
5996d11ec8cSEli Friedman   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
600c59bb48eSEli Friedman     llvm::GlobalVariable* GV =
6016d11ec8cSEli Friedman     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
6026d11ec8cSEli Friedman                              llvm::GlobalValue::InternalLinkage, C, "");
6032e442a00SDaniel Dunbar     EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
604c59bb48eSEli Friedman     return;
605c59bb48eSEli Friedman   }
606f5d08c9eSEli Friedman #endif
607f53c0968SChris Lattner   if (E->hadArrayRangeDesignator())
608bf7207a1SDouglas Gregor     CGF.ErrorUnsupported(E, "GNU array range designator extension");
609bf7207a1SDouglas Gregor 
6107a626f63SJohn McCall   llvm::Value *DestPtr = Dest.getAddr();
6117a626f63SJohn McCall 
612579a05d7SChris Lattner   // Handle initialization of an array.
613579a05d7SChris Lattner   if (E->getType()->isArrayType()) {
614579a05d7SChris Lattner     const llvm::PointerType *APType =
615579a05d7SChris Lattner       cast<llvm::PointerType>(DestPtr->getType());
616579a05d7SChris Lattner     const llvm::ArrayType *AType =
617579a05d7SChris Lattner       cast<llvm::ArrayType>(APType->getElementType());
618579a05d7SChris Lattner 
619579a05d7SChris Lattner     uint64_t NumInitElements = E->getNumInits();
620f23b6fa4SEli Friedman 
6210f398c44SChris Lattner     if (E->getNumInits() > 0) {
6220f398c44SChris Lattner       QualType T1 = E->getType();
6230f398c44SChris Lattner       QualType T2 = E->getInit(0)->getType();
6242a69547fSEli Friedman       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
625f23b6fa4SEli Friedman         EmitAggLoadOfLValue(E->getInit(0));
626f23b6fa4SEli Friedman         return;
627f23b6fa4SEli Friedman       }
6280f398c44SChris Lattner     }
629f23b6fa4SEli Friedman 
630579a05d7SChris Lattner     uint64_t NumArrayElements = AType->getNumElements();
6317adf0760SChris Lattner     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
6327adf0760SChris Lattner     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
633579a05d7SChris Lattner 
6348ccfcb51SJohn McCall     // FIXME: were we intentionally ignoring address spaces and GC attributes?
635327944b3SEli Friedman 
636579a05d7SChris Lattner     for (uint64_t i = 0; i != NumArrayElements; ++i) {
63727a3631bSChris Lattner       // If we're done emitting initializers and the destination is known-zeroed
63827a3631bSChris Lattner       // then we're done.
63927a3631bSChris Lattner       if (i == NumInitElements &&
64027a3631bSChris Lattner           Dest.isZeroed() &&
64127a3631bSChris Lattner           CGF.getTypes().isZeroInitializable(ElementType))
64227a3631bSChris Lattner         break;
64327a3631bSChris Lattner 
644579a05d7SChris Lattner       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
645f6fb7e2bSDaniel Dunbar       LValue LV = CGF.MakeAddrLValue(NextVal, ElementType);
64627a3631bSChris Lattner 
647579a05d7SChris Lattner       if (i < NumInitElements)
648f6fb7e2bSDaniel Dunbar         EmitInitializationToLValue(E->getInit(i), LV, ElementType);
649579a05d7SChris Lattner       else
650f6fb7e2bSDaniel Dunbar         EmitNullInitializationToLValue(LV, ElementType);
65127a3631bSChris Lattner 
65227a3631bSChris Lattner       // If the GEP didn't get used because of a dead zero init or something
65327a3631bSChris Lattner       // else, clean it up for -O0 builds and general tidiness.
65427a3631bSChris Lattner       if (llvm::GetElementPtrInst *GEP =
65527a3631bSChris Lattner             dyn_cast<llvm::GetElementPtrInst>(NextVal))
65627a3631bSChris Lattner         if (GEP->use_empty())
65727a3631bSChris Lattner           GEP->eraseFromParent();
658579a05d7SChris Lattner     }
659579a05d7SChris Lattner     return;
660579a05d7SChris Lattner   }
661579a05d7SChris Lattner 
662579a05d7SChris Lattner   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
663579a05d7SChris Lattner 
664579a05d7SChris Lattner   // Do struct initialization; this code just sets each individual member
665579a05d7SChris Lattner   // to the approprate value.  This makes bitfield support automatic;
666579a05d7SChris Lattner   // the disadvantage is that the generated code is more difficult for
667579a05d7SChris Lattner   // the optimizer, especially with bitfields.
668579a05d7SChris Lattner   unsigned NumInitElements = E->getNumInits();
669c23c7e6aSTed Kremenek   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
67052bcf963SChris Lattner 
6715169570eSDouglas Gregor   if (E->getType()->isUnionType()) {
6725169570eSDouglas Gregor     // Only initialize one field of a union. The field itself is
6735169570eSDouglas Gregor     // specified by the initializer list.
6745169570eSDouglas Gregor     if (!E->getInitializedFieldInUnion()) {
6755169570eSDouglas Gregor       // Empty union; we have nothing to do.
6765169570eSDouglas Gregor 
6775169570eSDouglas Gregor #ifndef NDEBUG
6785169570eSDouglas Gregor       // Make sure that it's really an empty and not a failure of
6795169570eSDouglas Gregor       // semantic analysis.
680cfbfe78eSArgyrios Kyrtzidis       for (RecordDecl::field_iterator Field = SD->field_begin(),
681cfbfe78eSArgyrios Kyrtzidis                                    FieldEnd = SD->field_end();
6825169570eSDouglas Gregor            Field != FieldEnd; ++Field)
6835169570eSDouglas Gregor         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
6845169570eSDouglas Gregor #endif
6855169570eSDouglas Gregor       return;
6865169570eSDouglas Gregor     }
6875169570eSDouglas Gregor 
6885169570eSDouglas Gregor     // FIXME: volatility
6895169570eSDouglas Gregor     FieldDecl *Field = E->getInitializedFieldInUnion();
6905169570eSDouglas Gregor 
69127a3631bSChris Lattner     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
6925169570eSDouglas Gregor     if (NumInitElements) {
6935169570eSDouglas Gregor       // Store the initializer into the field
694b247350eSAnders Carlsson       EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
6955169570eSDouglas Gregor     } else {
69627a3631bSChris Lattner       // Default-initialize to null.
6975169570eSDouglas Gregor       EmitNullInitializationToLValue(FieldLoc, Field->getType());
6985169570eSDouglas Gregor     }
6995169570eSDouglas Gregor 
7005169570eSDouglas Gregor     return;
7015169570eSDouglas Gregor   }
702579a05d7SChris Lattner 
703579a05d7SChris Lattner   // Here we iterate over the fields; this makes it simpler to both
704579a05d7SChris Lattner   // default-initialize fields and skip over unnamed fields.
70552bcf963SChris Lattner   unsigned CurInitVal = 0;
706cfbfe78eSArgyrios Kyrtzidis   for (RecordDecl::field_iterator Field = SD->field_begin(),
707cfbfe78eSArgyrios Kyrtzidis                                FieldEnd = SD->field_end();
70891f84216SDouglas Gregor        Field != FieldEnd; ++Field) {
70991f84216SDouglas Gregor     // We're done once we hit the flexible array member
71091f84216SDouglas Gregor     if (Field->getType()->isIncompleteArrayType())
71191f84216SDouglas Gregor       break;
71291f84216SDouglas Gregor 
71317bd094aSDouglas Gregor     if (Field->isUnnamedBitfield())
714579a05d7SChris Lattner       continue;
71517bd094aSDouglas Gregor 
71627a3631bSChris Lattner     // Don't emit GEP before a noop store of zero.
71727a3631bSChris Lattner     if (CurInitVal == NumInitElements && Dest.isZeroed() &&
71827a3631bSChris Lattner         CGF.getTypes().isZeroInitializable(E->getType()))
71927a3631bSChris Lattner       break;
72027a3631bSChris Lattner 
721327944b3SEli Friedman     // FIXME: volatility
72266498388SAnders Carlsson     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
7237c1baf46SFariborz Jahanian     // We never generate write-barries for initialized fields.
724e50dda95SDaniel Dunbar     FieldLoc.setNonGC(true);
72527a3631bSChris Lattner 
726579a05d7SChris Lattner     if (CurInitVal < NumInitElements) {
727e18aaf2cSChris Lattner       // Store the initializer into the field.
728b247350eSAnders Carlsson       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
729b247350eSAnders Carlsson                                  Field->getType());
730579a05d7SChris Lattner     } else {
731579a05d7SChris Lattner       // We're out of initalizers; default-initialize to null
73291f84216SDouglas Gregor       EmitNullInitializationToLValue(FieldLoc, Field->getType());
733579a05d7SChris Lattner     }
73427a3631bSChris Lattner 
73527a3631bSChris Lattner     // If the GEP didn't get used because of a dead zero init or something
73627a3631bSChris Lattner     // else, clean it up for -O0 builds and general tidiness.
73727a3631bSChris Lattner     if (FieldLoc.isSimple())
73827a3631bSChris Lattner       if (llvm::GetElementPtrInst *GEP =
73927a3631bSChris Lattner             dyn_cast<llvm::GetElementPtrInst>(FieldLoc.getAddress()))
74027a3631bSChris Lattner         if (GEP->use_empty())
74127a3631bSChris Lattner           GEP->eraseFromParent();
7427a51313dSChris Lattner   }
7437a51313dSChris Lattner }
7447a51313dSChris Lattner 
7457a51313dSChris Lattner //===----------------------------------------------------------------------===//
7467a51313dSChris Lattner //                        Entry Points into this File
7477a51313dSChris Lattner //===----------------------------------------------------------------------===//
7487a51313dSChris Lattner 
74927a3631bSChris Lattner /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
75027a3631bSChris Lattner /// non-zero bytes that will be stored when outputting the initializer for the
75127a3631bSChris Lattner /// specified initializer expression.
75227a3631bSChris Lattner static uint64_t GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
75327a3631bSChris Lattner   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
75427a3631bSChris Lattner     return GetNumNonZeroBytesInInit(PE->getSubExpr(), CGF);
75527a3631bSChris Lattner 
75627a3631bSChris Lattner   // 0 and 0.0 won't require any non-zero stores!
75727a3631bSChris Lattner   if (isSimpleZero(E, CGF)) return 0;
75827a3631bSChris Lattner 
75927a3631bSChris Lattner   // If this is an initlist expr, sum up the size of sizes of the (present)
76027a3631bSChris Lattner   // elements.  If this is something weird, assume the whole thing is non-zero.
76127a3631bSChris Lattner   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
76227a3631bSChris Lattner   if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
76327a3631bSChris Lattner     return CGF.getContext().getTypeSize(E->getType())/8;
76427a3631bSChris Lattner 
765c5cc2fb9SChris Lattner   // InitListExprs for structs have to be handled carefully.  If there are
766c5cc2fb9SChris Lattner   // reference members, we need to consider the size of the reference, not the
767c5cc2fb9SChris Lattner   // referencee.  InitListExprs for unions and arrays can't have references.
7685cd84755SChris Lattner   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
7695cd84755SChris Lattner     if (!RT->isUnionType()) {
770c5cc2fb9SChris Lattner       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
771c5cc2fb9SChris Lattner       uint64_t NumNonZeroBytes = 0;
772c5cc2fb9SChris Lattner 
773c5cc2fb9SChris Lattner       unsigned ILEElement = 0;
774c5cc2fb9SChris Lattner       for (RecordDecl::field_iterator Field = SD->field_begin(),
775c5cc2fb9SChris Lattner            FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
776c5cc2fb9SChris Lattner         // We're done once we hit the flexible array member or run out of
777c5cc2fb9SChris Lattner         // InitListExpr elements.
778c5cc2fb9SChris Lattner         if (Field->getType()->isIncompleteArrayType() ||
779c5cc2fb9SChris Lattner             ILEElement == ILE->getNumInits())
780c5cc2fb9SChris Lattner           break;
781c5cc2fb9SChris Lattner         if (Field->isUnnamedBitfield())
782c5cc2fb9SChris Lattner           continue;
783c5cc2fb9SChris Lattner 
784c5cc2fb9SChris Lattner         const Expr *E = ILE->getInit(ILEElement++);
785c5cc2fb9SChris Lattner 
786c5cc2fb9SChris Lattner         // Reference values are always non-null and have the width of a pointer.
7875cd84755SChris Lattner         if (Field->getType()->isReferenceType())
788c5cc2fb9SChris Lattner           NumNonZeroBytes += CGF.getContext().Target.getPointerWidth(0);
7895cd84755SChris Lattner         else
790c5cc2fb9SChris Lattner           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
791c5cc2fb9SChris Lattner       }
792c5cc2fb9SChris Lattner 
793c5cc2fb9SChris Lattner       return NumNonZeroBytes;
794c5cc2fb9SChris Lattner     }
7955cd84755SChris Lattner   }
796c5cc2fb9SChris Lattner 
797c5cc2fb9SChris Lattner 
79827a3631bSChris Lattner   uint64_t NumNonZeroBytes = 0;
79927a3631bSChris Lattner   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
80027a3631bSChris Lattner     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
80127a3631bSChris Lattner   return NumNonZeroBytes;
80227a3631bSChris Lattner }
80327a3631bSChris Lattner 
80427a3631bSChris Lattner /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
80527a3631bSChris Lattner /// zeros in it, emit a memset and avoid storing the individual zeros.
80627a3631bSChris Lattner ///
80727a3631bSChris Lattner static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
80827a3631bSChris Lattner                                      CodeGenFunction &CGF) {
80927a3631bSChris Lattner   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
81027a3631bSChris Lattner   // volatile stores.
81127a3631bSChris Lattner   if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
81227a3631bSChris Lattner 
81327a3631bSChris Lattner   // If the type is 16-bytes or smaller, prefer individual stores over memset.
81427a3631bSChris Lattner   std::pair<uint64_t, unsigned> TypeInfo =
81527a3631bSChris Lattner     CGF.getContext().getTypeInfo(E->getType());
81627a3631bSChris Lattner   if (TypeInfo.first/8 <= 16)
81727a3631bSChris Lattner     return;
81827a3631bSChris Lattner 
81927a3631bSChris Lattner   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
82027a3631bSChris Lattner   // we prefer to emit memset + individual stores for the rest.
82127a3631bSChris Lattner   uint64_t NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
82227a3631bSChris Lattner   if (NumNonZeroBytes*4 > TypeInfo.first/8)
82327a3631bSChris Lattner     return;
82427a3631bSChris Lattner 
82527a3631bSChris Lattner   // Okay, it seems like a good idea to use an initial memset, emit the call.
82627a3631bSChris Lattner   llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first/8);
827acc6b4e2SBenjamin Kramer   unsigned Align = TypeInfo.second/8;
82827a3631bSChris Lattner 
82927a3631bSChris Lattner   llvm::Value *Loc = Slot.getAddr();
83027a3631bSChris Lattner   const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
83127a3631bSChris Lattner 
83227a3631bSChris Lattner   Loc = CGF.Builder.CreateBitCast(Loc, BP);
833acc6b4e2SBenjamin Kramer   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, Align, false);
83427a3631bSChris Lattner 
83527a3631bSChris Lattner   // Tell the AggExprEmitter that the slot is known zero.
83627a3631bSChris Lattner   Slot.setZeroed();
83727a3631bSChris Lattner }
83827a3631bSChris Lattner 
83927a3631bSChris Lattner 
84027a3631bSChris Lattner 
84127a3631bSChris Lattner 
84225306cacSMike Stump /// EmitAggExpr - Emit the computation of the specified expression of aggregate
84325306cacSMike Stump /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
84425306cacSMike Stump /// the value of the aggregate expression is not needed.  If VolatileDest is
84525306cacSMike Stump /// true, DestPtr cannot be 0.
8467a626f63SJohn McCall ///
8477a626f63SJohn McCall /// \param IsInitializer - true if this evaluation is initializing an
8487a626f63SJohn McCall /// object whose lifetime is already being managed.
849d0bc7b9dSDaniel Dunbar //
850d0bc7b9dSDaniel Dunbar // FIXME: Take Qualifiers object.
8517a626f63SJohn McCall void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
852b60e70f9SFariborz Jahanian                                   bool IgnoreResult) {
8537a51313dSChris Lattner   assert(E && hasAggregateLLVMType(E->getType()) &&
8547a51313dSChris Lattner          "Invalid aggregate expression to emit");
85527a3631bSChris Lattner   assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
85627a3631bSChris Lattner          "slot has bits but no address");
8577a51313dSChris Lattner 
85827a3631bSChris Lattner   // Optimize the slot if possible.
85927a3631bSChris Lattner   CheckAggExprForMemSetUse(Slot, E, *this);
86027a3631bSChris Lattner 
86127a3631bSChris Lattner   AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E));
8627a51313dSChris Lattner }
8630bc8e86dSDaniel Dunbar 
864d0bc7b9dSDaniel Dunbar LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
865d0bc7b9dSDaniel Dunbar   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
866a7566f16SDaniel Dunbar   llvm::Value *Temp = CreateMemTemp(E->getType());
8672e442a00SDaniel Dunbar   LValue LV = MakeAddrLValue(Temp, E->getType());
86827a3631bSChris Lattner   EmitAggExpr(E, AggValueSlot::forAddr(Temp, LV.isVolatileQualified(), false));
8692e442a00SDaniel Dunbar   return LV;
870d0bc7b9dSDaniel Dunbar }
871d0bc7b9dSDaniel Dunbar 
8720bc8e86dSDaniel Dunbar void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
8735e9e61b8SMike Stump                                         llvm::Value *SrcPtr, QualType Ty,
8745e9e61b8SMike Stump                                         bool isVolatile) {
8750bc8e86dSDaniel Dunbar   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
8760bc8e86dSDaniel Dunbar 
87716e94af6SAnders Carlsson   if (getContext().getLangOptions().CPlusPlus) {
87816e94af6SAnders Carlsson     if (const RecordType *RT = Ty->getAs<RecordType>()) {
879f22101a0SDouglas Gregor       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
880f22101a0SDouglas Gregor       assert((Record->hasTrivialCopyConstructor() ||
8816855ba2cSFariborz Jahanian               Record->hasTrivialCopyAssignment()) &&
882f22101a0SDouglas Gregor              "Trying to aggregate-copy a type without a trivial copy "
883f22101a0SDouglas Gregor              "constructor or assignment operator");
884265b8b8dSDouglas Gregor       // Ignore empty classes in C++.
885f22101a0SDouglas Gregor       if (Record->isEmpty())
88616e94af6SAnders Carlsson         return;
88716e94af6SAnders Carlsson     }
88816e94af6SAnders Carlsson   }
88916e94af6SAnders Carlsson 
890ca05dfefSChris Lattner   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
8913ef668c2SChris Lattner   // C99 6.5.16.1p3, which states "If the value being stored in an object is
8923ef668c2SChris Lattner   // read from another object that overlaps in anyway the storage of the first
8933ef668c2SChris Lattner   // object, then the overlap shall be exact and the two objects shall have
8943ef668c2SChris Lattner   // qualified or unqualified versions of a compatible type."
8953ef668c2SChris Lattner   //
896ca05dfefSChris Lattner   // memcpy is not defined if the source and destination pointers are exactly
8973ef668c2SChris Lattner   // equal, but other compilers do this optimization, and almost every memcpy
8983ef668c2SChris Lattner   // implementation handles this case safely.  If there is a libc that does not
8993ef668c2SChris Lattner   // safely handle this, we can add a target hook.
9000bc8e86dSDaniel Dunbar 
9010bc8e86dSDaniel Dunbar   // Get size and alignment info for this aggregate.
9020bc8e86dSDaniel Dunbar   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
9030bc8e86dSDaniel Dunbar 
9040bc8e86dSDaniel Dunbar   // FIXME: Handle variable sized types.
9050bc8e86dSDaniel Dunbar 
90686736572SMike Stump   // FIXME: If we have a volatile struct, the optimizer can remove what might
90786736572SMike Stump   // appear to be `extra' memory ops:
90886736572SMike Stump   //
90986736572SMike Stump   // volatile struct { int i; } a, b;
91086736572SMike Stump   //
91186736572SMike Stump   // int main() {
91286736572SMike Stump   //   a = b;
91386736572SMike Stump   //   a = b;
91486736572SMike Stump   // }
91586736572SMike Stump   //
916cc2ab0cdSMon P Wang   // we need to use a different call here.  We use isVolatile to indicate when
917ec3cbfe8SMike Stump   // either the source or the destination is volatile.
918cc2ab0cdSMon P Wang 
919cc2ab0cdSMon P Wang   const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
920cb7696cfSChris Lattner   const llvm::Type *DBP =
921ad7c5c16SJohn McCall     llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
922cc2ab0cdSMon P Wang   DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp");
923cc2ab0cdSMon P Wang 
924cc2ab0cdSMon P Wang   const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
925cb7696cfSChris Lattner   const llvm::Type *SBP =
926ad7c5c16SJohn McCall     llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
927cc2ab0cdSMon P Wang   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp");
928cc2ab0cdSMon P Wang 
929021510e9SFariborz Jahanian   if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
930021510e9SFariborz Jahanian     RecordDecl *Record = RecordTy->getDecl();
931021510e9SFariborz Jahanian     if (Record->hasObjectMember()) {
932021510e9SFariborz Jahanian       unsigned long size = TypeInfo.first/8;
933021510e9SFariborz Jahanian       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
934021510e9SFariborz Jahanian       llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
935021510e9SFariborz Jahanian       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
936021510e9SFariborz Jahanian                                                     SizeVal);
937021510e9SFariborz Jahanian       return;
938021510e9SFariborz Jahanian     }
939021510e9SFariborz Jahanian   } else if (getContext().getAsArrayType(Ty)) {
940021510e9SFariborz Jahanian     QualType BaseType = getContext().getBaseElementType(Ty);
941021510e9SFariborz Jahanian     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
942021510e9SFariborz Jahanian       if (RecordTy->getDecl()->hasObjectMember()) {
943021510e9SFariborz Jahanian         unsigned long size = TypeInfo.first/8;
944021510e9SFariborz Jahanian         const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
945021510e9SFariborz Jahanian         llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
946021510e9SFariborz Jahanian         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
947021510e9SFariborz Jahanian                                                       SizeVal);
948021510e9SFariborz Jahanian         return;
949021510e9SFariborz Jahanian       }
950021510e9SFariborz Jahanian     }
951021510e9SFariborz Jahanian   }
952021510e9SFariborz Jahanian 
953acc6b4e2SBenjamin Kramer   Builder.CreateMemCpy(DestPtr, SrcPtr,
9545e016ae9SChris Lattner                        llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8),
955acc6b4e2SBenjamin Kramer                        TypeInfo.second/8, isVolatile);
9560bc8e86dSDaniel Dunbar }
957