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()); }
8491147596SPeter Collingbourne   void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
8591147596SPeter Collingbourne     Visit(GE->getResultExpr());
8691147596SPeter Collingbourne   }
873f66b84cSEli Friedman   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
887a51313dSChris Lattner 
897a51313dSChris Lattner   // l-values.
907a51313dSChris Lattner   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
917a51313dSChris Lattner   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
927a51313dSChris Lattner   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
93d443c0a0SDaniel Dunbar   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
949b71f0cfSDouglas Gregor   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
957a51313dSChris Lattner   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
967a51313dSChris Lattner     EmitAggLoadOfLValue(E);
977a51313dSChris Lattner   }
982f343dd5SChris Lattner   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
992f343dd5SChris Lattner     EmitAggLoadOfLValue(E);
1002f343dd5SChris Lattner   }
1012f343dd5SChris Lattner   void VisitPredefinedExpr(const PredefinedExpr *E) {
1022f343dd5SChris Lattner     EmitAggLoadOfLValue(E);
1032f343dd5SChris Lattner   }
104bc7d67ceSMike Stump 
1057a51313dSChris Lattner   // Operators.
106ec143777SAnders Carlsson   void VisitCastExpr(CastExpr *E);
1077a51313dSChris Lattner   void VisitCallExpr(const CallExpr *E);
1087a51313dSChris Lattner   void VisitStmtExpr(const StmtExpr *E);
1097a51313dSChris Lattner   void VisitBinaryOperator(const BinaryOperator *BO);
110ffba662dSFariborz Jahanian   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
1117a51313dSChris Lattner   void VisitBinAssign(const BinaryOperator *E);
1124b0e2a30SEli Friedman   void VisitBinComma(const BinaryOperator *E);
1137a51313dSChris Lattner 
114b1d329daSChris Lattner   void VisitObjCMessageExpr(ObjCMessageExpr *E);
115c8317a44SDaniel Dunbar   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
116c8317a44SDaniel Dunbar     EmitAggLoadOfLValue(E);
117c8317a44SDaniel Dunbar   }
11855310df7SDaniel Dunbar   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
1197a51313dSChris Lattner 
120c07a0c7eSJohn McCall   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
1215b2095ceSAnders Carlsson   void VisitChooseExpr(const ChooseExpr *CE);
1227a51313dSChris Lattner   void VisitInitListExpr(InitListExpr *E);
12318ada985SAnders Carlsson   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
124aa9c7aedSChris Lattner   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
125aa9c7aedSChris Lattner     Visit(DAE->getExpr());
126aa9c7aedSChris Lattner   }
1273be22e27SAnders Carlsson   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
1281619a504SAnders Carlsson   void VisitCXXConstructExpr(const CXXConstructExpr *E);
1295d413781SJohn McCall   void VisitExprWithCleanups(ExprWithCleanups *E);
130747eb784SDouglas Gregor   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1315bbbb137SMike Stump   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
132*fe31481fSDouglas Gregor   void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
1331bf5846aSJohn McCall   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1341bf5846aSJohn McCall 
13521911e89SEli Friedman   void VisitVAArgExpr(VAArgExpr *E);
136579a05d7SChris Lattner 
1371553b190SJohn McCall   void EmitInitializationToLValue(Expr *E, LValue Address);
1381553b190SJohn McCall   void EmitNullInitializationToLValue(LValue Address);
1397a51313dSChris Lattner   //  case Expr::ChooseExprClass:
140f16b8c30SMike Stump   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
1417a51313dSChris Lattner };
1427a51313dSChris Lattner }  // end anonymous namespace.
1437a51313dSChris Lattner 
1447a51313dSChris Lattner //===----------------------------------------------------------------------===//
1457a51313dSChris Lattner //                                Utilities
1467a51313dSChris Lattner //===----------------------------------------------------------------------===//
1477a51313dSChris Lattner 
1487a51313dSChris Lattner /// EmitAggLoadOfLValue - Given an expression with aggregate type that
1497a51313dSChris Lattner /// represents a value lvalue, this method emits the address of the lvalue,
1507a51313dSChris Lattner /// then loads the result into DestPtr.
1517a51313dSChris Lattner void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
1527a51313dSChris Lattner   LValue LV = CGF.EmitLValue(E);
153ca9fc09cSMike Stump   EmitFinalDestCopy(E, LV);
154ca9fc09cSMike Stump }
155ca9fc09cSMike Stump 
156cc04e9f6SJohn McCall /// \brief True if the given aggregate type requires special GC API calls.
157cc04e9f6SJohn McCall bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
158cc04e9f6SJohn McCall   // Only record types have members that might require garbage collection.
159cc04e9f6SJohn McCall   const RecordType *RecordTy = T->getAs<RecordType>();
160cc04e9f6SJohn McCall   if (!RecordTy) return false;
161cc04e9f6SJohn McCall 
162cc04e9f6SJohn McCall   // Don't mess with non-trivial C++ types.
163cc04e9f6SJohn McCall   RecordDecl *Record = RecordTy->getDecl();
164cc04e9f6SJohn McCall   if (isa<CXXRecordDecl>(Record) &&
165cc04e9f6SJohn McCall       (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
166cc04e9f6SJohn McCall        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
167cc04e9f6SJohn McCall     return false;
168cc04e9f6SJohn McCall 
169cc04e9f6SJohn McCall   // Check whether the type has an object member.
170cc04e9f6SJohn McCall   return Record->hasObjectMember();
171cc04e9f6SJohn McCall }
172cc04e9f6SJohn McCall 
173cc04e9f6SJohn McCall /// \brief Perform the final move to DestPtr if RequiresGCollection is set.
174cc04e9f6SJohn McCall ///
175cc04e9f6SJohn McCall /// The idea is that you do something like this:
176cc04e9f6SJohn McCall ///   RValue Result = EmitSomething(..., getReturnValueSlot());
177cc04e9f6SJohn McCall ///   EmitGCMove(E, Result);
178cc04e9f6SJohn McCall /// If GC doesn't interfere, this will cause the result to be emitted
179cc04e9f6SJohn McCall /// directly into the return value slot.  If GC does interfere, a final
180cc04e9f6SJohn McCall /// move will be performed.
181cc04e9f6SJohn McCall void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) {
18258649dc6SJohn McCall   if (Dest.requiresGCollection()) {
1833b4bd9a1SKen Dyck     CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
184021510e9SFariborz Jahanian     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
1853b4bd9a1SKen Dyck     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
1867a626f63SJohn McCall     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, Dest.getAddr(),
187cc04e9f6SJohn McCall                                                     Src.getAggregateAddr(),
188021510e9SFariborz Jahanian                                                     SizeVal);
189021510e9SFariborz Jahanian   }
190cc04e9f6SJohn McCall }
191cc04e9f6SJohn McCall 
192ca9fc09cSMike Stump /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
193ec3cbfe8SMike Stump void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
194ca9fc09cSMike Stump   assert(Src.isAggregate() && "value must be aggregate value!");
1957a51313dSChris Lattner 
1967a626f63SJohn McCall   // If Dest is ignored, then we're evaluating an aggregate expression
1978d752430SJohn McCall   // in a context (like an expression statement) that doesn't care
1988d752430SJohn McCall   // about the result.  C says that an lvalue-to-rvalue conversion is
1998d752430SJohn McCall   // performed in these cases; C++ says that it is not.  In either
2008d752430SJohn McCall   // case, we don't actually need to do anything unless the value is
2018d752430SJohn McCall   // volatile.
2027a626f63SJohn McCall   if (Dest.isIgnored()) {
2038d752430SJohn McCall     if (!Src.isVolatileQualified() ||
2048d752430SJohn McCall         CGF.CGM.getLangOptions().CPlusPlus ||
2058d752430SJohn McCall         (IgnoreResult && Ignore))
206ec3cbfe8SMike Stump       return;
207c123623dSFariborz Jahanian 
208332ec2ceSMike Stump     // If the source is volatile, we must read from it; to do that, we need
209332ec2ceSMike Stump     // some place to put it.
2107a626f63SJohn McCall     Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
211332ec2ceSMike Stump   }
2127a51313dSChris Lattner 
21358649dc6SJohn McCall   if (Dest.requiresGCollection()) {
2143b4bd9a1SKen Dyck     CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
215021510e9SFariborz Jahanian     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
2163b4bd9a1SKen Dyck     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
217879d7266SFariborz Jahanian     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
2187a626f63SJohn McCall                                                       Dest.getAddr(),
2197a626f63SJohn McCall                                                       Src.getAggregateAddr(),
220021510e9SFariborz Jahanian                                                       SizeVal);
221879d7266SFariborz Jahanian     return;
222879d7266SFariborz Jahanian   }
223ca9fc09cSMike Stump   // If the result of the assignment is used, copy the LHS there also.
224ca9fc09cSMike Stump   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
225ca9fc09cSMike Stump   // from the source as well, as we can't eliminate it if either operand
226ca9fc09cSMike Stump   // is volatile, unless copy has volatile for both source and destination..
2277a626f63SJohn McCall   CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
2287a626f63SJohn McCall                         Dest.isVolatile()|Src.isVolatileQualified());
229ca9fc09cSMike Stump }
230ca9fc09cSMike Stump 
231ca9fc09cSMike Stump /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
232ec3cbfe8SMike Stump void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
233ca9fc09cSMike Stump   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
234ca9fc09cSMike Stump 
235ca9fc09cSMike Stump   EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
236ec3cbfe8SMike Stump                                             Src.isVolatileQualified()),
237ec3cbfe8SMike Stump                     Ignore);
2387a51313dSChris Lattner }
2397a51313dSChris Lattner 
2407a51313dSChris Lattner //===----------------------------------------------------------------------===//
2417a51313dSChris Lattner //                            Visitor Methods
2427a51313dSChris Lattner //===----------------------------------------------------------------------===//
2437a51313dSChris Lattner 
244*fe31481fSDouglas Gregor void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
245*fe31481fSDouglas Gregor   Visit(E->GetTemporaryExpr());
246*fe31481fSDouglas Gregor }
247*fe31481fSDouglas Gregor 
2481bf5846aSJohn McCall void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
249c07a0c7eSJohn McCall   EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e));
2501bf5846aSJohn McCall }
2511bf5846aSJohn McCall 
2529b71f0cfSDouglas Gregor void
2539b71f0cfSDouglas Gregor AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
2546c9d31ebSDouglas Gregor   if (E->getType().isPODType(CGF.getContext())) {
2556c9d31ebSDouglas Gregor     // For a POD type, just emit a load of the lvalue + a copy, because our
2566c9d31ebSDouglas Gregor     // compound literal might alias the destination.
2576c9d31ebSDouglas Gregor     // FIXME: This is a band-aid; the real problem appears to be in our handling
2586c9d31ebSDouglas Gregor     // of assignments, where we store directly into the LHS without checking
2596c9d31ebSDouglas Gregor     // whether anything in the RHS aliases.
2606c9d31ebSDouglas Gregor     EmitAggLoadOfLValue(E);
2616c9d31ebSDouglas Gregor     return;
2626c9d31ebSDouglas Gregor   }
2636c9d31ebSDouglas Gregor 
2649b71f0cfSDouglas Gregor   AggValueSlot Slot = EnsureSlot(E->getType());
2659b71f0cfSDouglas Gregor   CGF.EmitAggExpr(E->getInitializer(), Slot);
2669b71f0cfSDouglas Gregor }
2679b71f0cfSDouglas Gregor 
2689b71f0cfSDouglas Gregor 
269ec143777SAnders Carlsson void AggExprEmitter::VisitCastExpr(CastExpr *E) {
2701fb7ae9eSAnders Carlsson   switch (E->getCastKind()) {
2718a01a751SAnders Carlsson   case CK_Dynamic: {
2721c073f47SDouglas Gregor     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
2731c073f47SDouglas Gregor     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
2741c073f47SDouglas Gregor     // FIXME: Do we also need to handle property references here?
2751c073f47SDouglas Gregor     if (LV.isSimple())
2761c073f47SDouglas Gregor       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
2771c073f47SDouglas Gregor     else
2781c073f47SDouglas Gregor       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
2791c073f47SDouglas Gregor 
2807a626f63SJohn McCall     if (!Dest.isIgnored())
2811c073f47SDouglas Gregor       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
2821c073f47SDouglas Gregor     break;
2831c073f47SDouglas Gregor   }
2841c073f47SDouglas Gregor 
285e302792bSJohn McCall   case CK_ToUnion: {
28658989b71SJohn McCall     if (Dest.isIgnored()) break;
28758989b71SJohn McCall 
2887ffcf93bSNuno Lopes     // GCC union extension
2892e442a00SDaniel Dunbar     QualType Ty = E->getSubExpr()->getType();
2902e442a00SDaniel Dunbar     QualType PtrTy = CGF.getContext().getPointerType(Ty);
2917a626f63SJohn McCall     llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
292dd274848SEli Friedman                                                  CGF.ConvertType(PtrTy));
2931553b190SJohn McCall     EmitInitializationToLValue(E->getSubExpr(),
2941553b190SJohn McCall                                CGF.MakeAddrLValue(CastPtr, Ty));
2951fb7ae9eSAnders Carlsson     break;
2967ffcf93bSNuno Lopes   }
2977ffcf93bSNuno Lopes 
298e302792bSJohn McCall   case CK_DerivedToBase:
299e302792bSJohn McCall   case CK_BaseToDerived:
300e302792bSJohn McCall   case CK_UncheckedDerivedToBase: {
301aae38d66SDouglas Gregor     assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: "
302aae38d66SDouglas Gregor                 "should have been unpacked before we got here");
303aae38d66SDouglas Gregor     break;
304aae38d66SDouglas Gregor   }
305aae38d66SDouglas Gregor 
30634376a68SJohn McCall   case CK_GetObjCProperty: {
30734376a68SJohn McCall     LValue LV = CGF.EmitLValue(E->getSubExpr());
30834376a68SJohn McCall     assert(LV.isPropertyRef());
30934376a68SJohn McCall     RValue RV = CGF.EmitLoadOfPropertyRefLValue(LV, getReturnValueSlot());
31034376a68SJohn McCall     EmitGCMove(E, RV);
31134376a68SJohn McCall     break;
31234376a68SJohn McCall   }
31334376a68SJohn McCall 
31434376a68SJohn McCall   case CK_LValueToRValue: // hope for downstream optimization
315e302792bSJohn McCall   case CK_NoOp:
316e302792bSJohn McCall   case CK_UserDefinedConversion:
317e302792bSJohn McCall   case CK_ConstructorConversion:
3182a69547fSEli Friedman     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
3192a69547fSEli Friedman                                                    E->getType()) &&
3200f398c44SChris Lattner            "Implicit cast types must be compatible");
3217a51313dSChris Lattner     Visit(E->getSubExpr());
3221fb7ae9eSAnders Carlsson     break;
323b05a3e55SAnders Carlsson 
324e302792bSJohn McCall   case CK_LValueBitCast:
325f3735e01SJohn McCall     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
32651954276SDouglas Gregor     break;
32731996343SJohn McCall 
328f3735e01SJohn McCall   case CK_Dependent:
329f3735e01SJohn McCall   case CK_BitCast:
330f3735e01SJohn McCall   case CK_ArrayToPointerDecay:
331f3735e01SJohn McCall   case CK_FunctionToPointerDecay:
332f3735e01SJohn McCall   case CK_NullToPointer:
333f3735e01SJohn McCall   case CK_NullToMemberPointer:
334f3735e01SJohn McCall   case CK_BaseToDerivedMemberPointer:
335f3735e01SJohn McCall   case CK_DerivedToBaseMemberPointer:
336f3735e01SJohn McCall   case CK_MemberPointerToBoolean:
337f3735e01SJohn McCall   case CK_IntegralToPointer:
338f3735e01SJohn McCall   case CK_PointerToIntegral:
339f3735e01SJohn McCall   case CK_PointerToBoolean:
340f3735e01SJohn McCall   case CK_ToVoid:
341f3735e01SJohn McCall   case CK_VectorSplat:
342f3735e01SJohn McCall   case CK_IntegralCast:
343f3735e01SJohn McCall   case CK_IntegralToBoolean:
344f3735e01SJohn McCall   case CK_IntegralToFloating:
345f3735e01SJohn McCall   case CK_FloatingToIntegral:
346f3735e01SJohn McCall   case CK_FloatingToBoolean:
347f3735e01SJohn McCall   case CK_FloatingCast:
348f3735e01SJohn McCall   case CK_AnyPointerToObjCPointerCast:
349f3735e01SJohn McCall   case CK_AnyPointerToBlockPointerCast:
350f3735e01SJohn McCall   case CK_ObjCObjectLValueCast:
351f3735e01SJohn McCall   case CK_FloatingRealToComplex:
352f3735e01SJohn McCall   case CK_FloatingComplexToReal:
353f3735e01SJohn McCall   case CK_FloatingComplexToBoolean:
354f3735e01SJohn McCall   case CK_FloatingComplexCast:
355f3735e01SJohn McCall   case CK_FloatingComplexToIntegralComplex:
356f3735e01SJohn McCall   case CK_IntegralRealToComplex:
357f3735e01SJohn McCall   case CK_IntegralComplexToReal:
358f3735e01SJohn McCall   case CK_IntegralComplexToBoolean:
359f3735e01SJohn McCall   case CK_IntegralComplexCast:
360f3735e01SJohn McCall   case CK_IntegralComplexToFloatingComplex:
36131168b07SJohn McCall   case CK_ObjCProduceObject:
36231168b07SJohn McCall   case CK_ObjCConsumeObject:
363f3735e01SJohn McCall     llvm_unreachable("cast kind invalid for aggregate types");
3641fb7ae9eSAnders Carlsson   }
3657a51313dSChris Lattner }
3667a51313dSChris Lattner 
3670f398c44SChris Lattner void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
368ddcbfe7bSAnders Carlsson   if (E->getCallReturnType()->isReferenceType()) {
369ddcbfe7bSAnders Carlsson     EmitAggLoadOfLValue(E);
370ddcbfe7bSAnders Carlsson     return;
371ddcbfe7bSAnders Carlsson   }
372ddcbfe7bSAnders Carlsson 
373cc04e9f6SJohn McCall   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
374cc04e9f6SJohn McCall   EmitGCMove(E, RV);
3757a51313dSChris Lattner }
3760f398c44SChris Lattner 
3770f398c44SChris Lattner void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
378cc04e9f6SJohn McCall   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
379cc04e9f6SJohn McCall   EmitGCMove(E, RV);
380b1d329daSChris Lattner }
3817a51313dSChris Lattner 
38255310df7SDaniel Dunbar void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
38334376a68SJohn McCall   llvm_unreachable("direct property access not surrounded by "
38434376a68SJohn McCall                    "lvalue-to-rvalue cast");
38555310df7SDaniel Dunbar }
38655310df7SDaniel Dunbar 
3870f398c44SChris Lattner void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
388a2342eb8SJohn McCall   CGF.EmitIgnoredExpr(E->getLHS());
3897a626f63SJohn McCall   Visit(E->getRHS());
3904b0e2a30SEli Friedman }
3914b0e2a30SEli Friedman 
3927a51313dSChris Lattner void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
393ce1de617SJohn McCall   CodeGenFunction::StmtExprEvaluation eval(CGF);
3947a626f63SJohn McCall   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
3957a51313dSChris Lattner }
3967a51313dSChris Lattner 
3977a51313dSChris Lattner void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
398e302792bSJohn McCall   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
399ffba662dSFariborz Jahanian     VisitPointerToDataMemberBinaryOperator(E);
400ffba662dSFariborz Jahanian   else
401a7c8cf62SDaniel Dunbar     CGF.ErrorUnsupported(E, "aggregate binary expression");
4027a51313dSChris Lattner }
4037a51313dSChris Lattner 
404ffba662dSFariborz Jahanian void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
405ffba662dSFariborz Jahanian                                                     const BinaryOperator *E) {
406ffba662dSFariborz Jahanian   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
407ffba662dSFariborz Jahanian   EmitFinalDestCopy(E, LV);
408ffba662dSFariborz Jahanian }
409ffba662dSFariborz Jahanian 
4107a51313dSChris Lattner void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
4117a51313dSChris Lattner   // For an assignment to work, the value on the right has
4127a51313dSChris Lattner   // to be compatible with the value on the left.
4132a69547fSEli Friedman   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
4142a69547fSEli Friedman                                                  E->getRHS()->getType())
4157a51313dSChris Lattner          && "Invalid assignment");
416d0a30016SJohn McCall 
41799514b91SFariborz Jahanian   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getLHS()))
41852a8cca5SFariborz Jahanian     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
41999514b91SFariborz Jahanian       if (VD->hasAttr<BlocksAttr>() &&
42099514b91SFariborz Jahanian           E->getRHS()->HasSideEffects(CGF.getContext())) {
42199514b91SFariborz Jahanian         // When __block variable on LHS, the RHS must be evaluated first
42299514b91SFariborz Jahanian         // as it may change the 'forwarding' field via call to Block_copy.
42399514b91SFariborz Jahanian         LValue RHS = CGF.EmitLValue(E->getRHS());
42499514b91SFariborz Jahanian         LValue LHS = CGF.EmitLValue(E->getLHS());
42599514b91SFariborz Jahanian         bool GCollection = false;
42699514b91SFariborz Jahanian         if (CGF.getContext().getLangOptions().getGCMode())
42799514b91SFariborz Jahanian           GCollection = TypeRequiresGCollection(E->getLHS()->getType());
42899514b91SFariborz Jahanian         Dest = AggValueSlot::forLValue(LHS, true, GCollection);
42999514b91SFariborz Jahanian         EmitFinalDestCopy(E, RHS, true);
43099514b91SFariborz Jahanian         return;
43199514b91SFariborz Jahanian       }
43299514b91SFariborz Jahanian 
4337a51313dSChris Lattner   LValue LHS = CGF.EmitLValue(E->getLHS());
4347a51313dSChris Lattner 
4354b8c6db9SDaniel Dunbar   // We have to special case property setters, otherwise we must have
4364b8c6db9SDaniel Dunbar   // a simple lvalue (no aggregates inside vectors, bitfields).
4374b8c6db9SDaniel Dunbar   if (LHS.isPropertyRef()) {
4387a26ba4dSFariborz Jahanian     const ObjCPropertyRefExpr *RE = LHS.getPropertyRefExpr();
4397a26ba4dSFariborz Jahanian     QualType ArgType = RE->getSetterArgType();
4407a26ba4dSFariborz Jahanian     RValue Src;
4417a26ba4dSFariborz Jahanian     if (ArgType->isReferenceType())
4427a26ba4dSFariborz Jahanian       Src = CGF.EmitReferenceBindingToExpr(E->getRHS(), 0);
4437a26ba4dSFariborz Jahanian     else {
4447a626f63SJohn McCall       AggValueSlot Slot = EnsureSlot(E->getRHS()->getType());
4457a626f63SJohn McCall       CGF.EmitAggExpr(E->getRHS(), Slot);
4467a26ba4dSFariborz Jahanian       Src = Slot.asRValue();
4477a26ba4dSFariborz Jahanian     }
4487a26ba4dSFariborz Jahanian     CGF.EmitStoreThroughPropertyRefLValue(Src, LHS);
4494b8c6db9SDaniel Dunbar   } else {
450b60e70f9SFariborz Jahanian     bool GCollection = false;
451cc04e9f6SJohn McCall     if (CGF.getContext().getLangOptions().getGCMode())
452b60e70f9SFariborz Jahanian       GCollection = TypeRequiresGCollection(E->getLHS()->getType());
453cc04e9f6SJohn McCall 
4547a51313dSChris Lattner     // Codegen the RHS so that it stores directly into the LHS.
455b60e70f9SFariborz Jahanian     AggValueSlot LHSSlot = AggValueSlot::forLValue(LHS, true,
456b60e70f9SFariborz Jahanian                                                    GCollection);
457b60e70f9SFariborz Jahanian     CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
458ec3cbfe8SMike Stump     EmitFinalDestCopy(E, LHS, true);
4597a51313dSChris Lattner   }
4604b8c6db9SDaniel Dunbar }
4617a51313dSChris Lattner 
462c07a0c7eSJohn McCall void AggExprEmitter::
463c07a0c7eSJohn McCall VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
464a612e79bSDaniel Dunbar   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
465a612e79bSDaniel Dunbar   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
466a612e79bSDaniel Dunbar   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
4677a51313dSChris Lattner 
468c07a0c7eSJohn McCall   // Bind the common expression if necessary.
469c07a0c7eSJohn McCall   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
470c07a0c7eSJohn McCall 
471ce1de617SJohn McCall   CodeGenFunction::ConditionalEvaluation eval(CGF);
472b8841af8SEli Friedman   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
4737a51313dSChris Lattner 
4745b26f65bSJohn McCall   // Save whether the destination's lifetime is externally managed.
4755b26f65bSJohn McCall   bool DestLifetimeManaged = Dest.isLifetimeExternallyManaged();
4767a51313dSChris Lattner 
477ce1de617SJohn McCall   eval.begin(CGF);
478ce1de617SJohn McCall   CGF.EmitBlock(LHSBlock);
479c07a0c7eSJohn McCall   Visit(E->getTrueExpr());
480ce1de617SJohn McCall   eval.end(CGF);
4817a51313dSChris Lattner 
482ce1de617SJohn McCall   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
483ce1de617SJohn McCall   CGF.Builder.CreateBr(ContBlock);
4847a51313dSChris Lattner 
4855b26f65bSJohn McCall   // If the result of an agg expression is unused, then the emission
4865b26f65bSJohn McCall   // of the LHS might need to create a destination slot.  That's fine
4875b26f65bSJohn McCall   // with us, and we can safely emit the RHS into the same slot, but
4885b26f65bSJohn McCall   // we shouldn't claim that its lifetime is externally managed.
4895b26f65bSJohn McCall   Dest.setLifetimeExternallyManaged(DestLifetimeManaged);
4905b26f65bSJohn McCall 
491ce1de617SJohn McCall   eval.begin(CGF);
492ce1de617SJohn McCall   CGF.EmitBlock(RHSBlock);
493c07a0c7eSJohn McCall   Visit(E->getFalseExpr());
494ce1de617SJohn McCall   eval.end(CGF);
4957a51313dSChris Lattner 
4967a51313dSChris Lattner   CGF.EmitBlock(ContBlock);
4977a51313dSChris Lattner }
4987a51313dSChris Lattner 
4995b2095ceSAnders Carlsson void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
5005b2095ceSAnders Carlsson   Visit(CE->getChosenSubExpr(CGF.getContext()));
5015b2095ceSAnders Carlsson }
5025b2095ceSAnders Carlsson 
50321911e89SEli Friedman void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
504e9fcadd2SDaniel Dunbar   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
50513abd7e9SAnders Carlsson   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
50613abd7e9SAnders Carlsson 
507020cddcfSSebastian Redl   if (!ArgPtr) {
50813abd7e9SAnders Carlsson     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
509020cddcfSSebastian Redl     return;
510020cddcfSSebastian Redl   }
51113abd7e9SAnders Carlsson 
5122e442a00SDaniel Dunbar   EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
51321911e89SEli Friedman }
51421911e89SEli Friedman 
5153be22e27SAnders Carlsson void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
5167a626f63SJohn McCall   // Ensure that we have a slot, but if we already do, remember
5177a626f63SJohn McCall   // whether its lifetime was externally managed.
5187a626f63SJohn McCall   bool WasManaged = Dest.isLifetimeExternallyManaged();
5197a626f63SJohn McCall   Dest = EnsureSlot(E->getType());
5207a626f63SJohn McCall   Dest.setLifetimeExternallyManaged();
5213be22e27SAnders Carlsson 
5223be22e27SAnders Carlsson   Visit(E->getSubExpr());
5233be22e27SAnders Carlsson 
5247a626f63SJohn McCall   // Set up the temporary's destructor if its lifetime wasn't already
5257a626f63SJohn McCall   // being managed.
5267a626f63SJohn McCall   if (!WasManaged)
5277a626f63SJohn McCall     CGF.EmitCXXTemporary(E->getTemporary(), Dest.getAddr());
5283be22e27SAnders Carlsson }
5293be22e27SAnders Carlsson 
530b7f8f594SAnders Carlsson void
5311619a504SAnders Carlsson AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5327a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(E->getType());
5337a626f63SJohn McCall   CGF.EmitCXXConstructExpr(E, Slot);
534c82b86dfSAnders Carlsson }
535c82b86dfSAnders Carlsson 
5365d413781SJohn McCall void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
5375d413781SJohn McCall   CGF.EmitExprWithCleanups(E, Dest);
538b7f8f594SAnders Carlsson }
539b7f8f594SAnders Carlsson 
540747eb784SDouglas Gregor void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
5417a626f63SJohn McCall   QualType T = E->getType();
5427a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(T);
5431553b190SJohn McCall   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
54418ada985SAnders Carlsson }
54518ada985SAnders Carlsson 
54618ada985SAnders Carlsson void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
5477a626f63SJohn McCall   QualType T = E->getType();
5487a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(T);
5491553b190SJohn McCall   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
550ff3507b9SNuno Lopes }
551ff3507b9SNuno Lopes 
55227a3631bSChris Lattner /// isSimpleZero - If emitting this value will obviously just cause a store of
55327a3631bSChris Lattner /// zero to memory, return true.  This can return false if uncertain, so it just
55427a3631bSChris Lattner /// handles simple cases.
55527a3631bSChris Lattner static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
55691147596SPeter Collingbourne   E = E->IgnoreParens();
55791147596SPeter Collingbourne 
55827a3631bSChris Lattner   // 0
55927a3631bSChris Lattner   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
56027a3631bSChris Lattner     return IL->getValue() == 0;
56127a3631bSChris Lattner   // +0.0
56227a3631bSChris Lattner   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
56327a3631bSChris Lattner     return FL->getValue().isPosZero();
56427a3631bSChris Lattner   // int()
56527a3631bSChris Lattner   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
56627a3631bSChris Lattner       CGF.getTypes().isZeroInitializable(E->getType()))
56727a3631bSChris Lattner     return true;
56827a3631bSChris Lattner   // (int*)0 - Null pointer expressions.
56927a3631bSChris Lattner   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
57027a3631bSChris Lattner     return ICE->getCastKind() == CK_NullToPointer;
57127a3631bSChris Lattner   // '\0'
57227a3631bSChris Lattner   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
57327a3631bSChris Lattner     return CL->getValue() == 0;
57427a3631bSChris Lattner 
57527a3631bSChris Lattner   // Otherwise, hard case: conservatively return false.
57627a3631bSChris Lattner   return false;
57727a3631bSChris Lattner }
57827a3631bSChris Lattner 
57927a3631bSChris Lattner 
580b247350eSAnders Carlsson void
5811553b190SJohn McCall AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
5821553b190SJohn McCall   QualType type = LV.getType();
583df0fe27bSMike Stump   // FIXME: Ignore result?
584579a05d7SChris Lattner   // FIXME: Are initializers affected by volatile?
58527a3631bSChris Lattner   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
58627a3631bSChris Lattner     // Storing "i32 0" to a zero'd memory location is a noop.
58727a3631bSChris Lattner   } else if (isa<ImplicitValueInitExpr>(E)) {
5881553b190SJohn McCall     EmitNullInitializationToLValue(LV);
5891553b190SJohn McCall   } else if (type->isReferenceType()) {
59004775f84SAnders Carlsson     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
5911553b190SJohn McCall     CGF.EmitStoreThroughLValue(RV, LV, type);
5921553b190SJohn McCall   } else if (type->isAnyComplexType()) {
5930202cb40SDouglas Gregor     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
5941553b190SJohn McCall   } else if (CGF.hasAggregateLLVMType(type)) {
5951553b190SJohn McCall     CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV, true, false,
5961553b190SJohn McCall                                                Dest.isZeroed()));
59731168b07SJohn McCall   } else if (LV.isSimple()) {
5981553b190SJohn McCall     CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
5996e313210SEli Friedman   } else {
6001553b190SJohn McCall     CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV, type);
6017a51313dSChris Lattner   }
602579a05d7SChris Lattner }
603579a05d7SChris Lattner 
6041553b190SJohn McCall void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
6051553b190SJohn McCall   QualType type = lv.getType();
6061553b190SJohn McCall 
60727a3631bSChris Lattner   // If the destination slot is already zeroed out before the aggregate is
60827a3631bSChris Lattner   // copied into it, we don't have to emit any zeros here.
6091553b190SJohn McCall   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
61027a3631bSChris Lattner     return;
61127a3631bSChris Lattner 
6121553b190SJohn McCall   if (!CGF.hasAggregateLLVMType(type)) {
613579a05d7SChris Lattner     // For non-aggregates, we can store zero
6141553b190SJohn McCall     llvm::Value *null = llvm::Constant::getNullValue(CGF.ConvertType(type));
6151553b190SJohn McCall     CGF.EmitStoreThroughLValue(RValue::get(null), lv, type);
616579a05d7SChris Lattner   } else {
617579a05d7SChris Lattner     // There's a potential optimization opportunity in combining
618579a05d7SChris Lattner     // memsets; that would be easy for arrays, but relatively
619579a05d7SChris Lattner     // difficult for structures with the current code.
6201553b190SJohn McCall     CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
621579a05d7SChris Lattner   }
622579a05d7SChris Lattner }
623579a05d7SChris Lattner 
624579a05d7SChris Lattner void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
625f5d08c9eSEli Friedman #if 0
6266d11ec8cSEli Friedman   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
6276d11ec8cSEli Friedman   // (Length of globals? Chunks of zeroed-out space?).
628f5d08c9eSEli Friedman   //
62918bb9284SMike Stump   // If we can, prefer a copy from a global; this is a lot less code for long
63018bb9284SMike Stump   // globals, and it's easier for the current optimizers to analyze.
6316d11ec8cSEli Friedman   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
632c59bb48eSEli Friedman     llvm::GlobalVariable* GV =
6336d11ec8cSEli Friedman     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
6346d11ec8cSEli Friedman                              llvm::GlobalValue::InternalLinkage, C, "");
6352e442a00SDaniel Dunbar     EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
636c59bb48eSEli Friedman     return;
637c59bb48eSEli Friedman   }
638f5d08c9eSEli Friedman #endif
639f53c0968SChris Lattner   if (E->hadArrayRangeDesignator())
640bf7207a1SDouglas Gregor     CGF.ErrorUnsupported(E, "GNU array range designator extension");
641bf7207a1SDouglas Gregor 
6427a626f63SJohn McCall   llvm::Value *DestPtr = Dest.getAddr();
6437a626f63SJohn McCall 
644579a05d7SChris Lattner   // Handle initialization of an array.
645579a05d7SChris Lattner   if (E->getType()->isArrayType()) {
646579a05d7SChris Lattner     const llvm::PointerType *APType =
647579a05d7SChris Lattner       cast<llvm::PointerType>(DestPtr->getType());
648579a05d7SChris Lattner     const llvm::ArrayType *AType =
649579a05d7SChris Lattner       cast<llvm::ArrayType>(APType->getElementType());
650579a05d7SChris Lattner 
651579a05d7SChris Lattner     uint64_t NumInitElements = E->getNumInits();
652f23b6fa4SEli Friedman 
6530f398c44SChris Lattner     if (E->getNumInits() > 0) {
6540f398c44SChris Lattner       QualType T1 = E->getType();
6550f398c44SChris Lattner       QualType T2 = E->getInit(0)->getType();
6562a69547fSEli Friedman       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
657f23b6fa4SEli Friedman         EmitAggLoadOfLValue(E->getInit(0));
658f23b6fa4SEli Friedman         return;
659f23b6fa4SEli Friedman       }
6600f398c44SChris Lattner     }
661f23b6fa4SEli Friedman 
662579a05d7SChris Lattner     uint64_t NumArrayElements = AType->getNumElements();
6637adf0760SChris Lattner     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
6647adf0760SChris Lattner     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
66531168b07SJohn McCall     ElementType = CGF.getContext().getQualifiedType(ElementType,
66631168b07SJohn McCall                                                     Dest.getQualifiers());
667579a05d7SChris Lattner 
668e07425a5SArgyrios Kyrtzidis     bool hasNonTrivialCXXConstructor = false;
669e07425a5SArgyrios Kyrtzidis     if (CGF.getContext().getLangOptions().CPlusPlus)
6709d3c5040SArgyrios Kyrtzidis       if (const RecordType *RT = CGF.getContext()
6719d3c5040SArgyrios Kyrtzidis                         .getBaseElementType(ElementType)->getAs<RecordType>()) {
672e07425a5SArgyrios Kyrtzidis         const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
673f479f1b7SAlexis Hunt         hasNonTrivialCXXConstructor = !RD->hasTrivialDefaultConstructor();
674e07425a5SArgyrios Kyrtzidis       }
675e07425a5SArgyrios Kyrtzidis 
676579a05d7SChris Lattner     for (uint64_t i = 0; i != NumArrayElements; ++i) {
67727a3631bSChris Lattner       // If we're done emitting initializers and the destination is known-zeroed
67827a3631bSChris Lattner       // then we're done.
67927a3631bSChris Lattner       if (i == NumInitElements &&
68027a3631bSChris Lattner           Dest.isZeroed() &&
681e07425a5SArgyrios Kyrtzidis           CGF.getTypes().isZeroInitializable(ElementType) &&
682e07425a5SArgyrios Kyrtzidis           !hasNonTrivialCXXConstructor)
68327a3631bSChris Lattner         break;
68427a3631bSChris Lattner 
685579a05d7SChris Lattner       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
686f6fb7e2bSDaniel Dunbar       LValue LV = CGF.MakeAddrLValue(NextVal, ElementType);
68727a3631bSChris Lattner 
688579a05d7SChris Lattner       if (i < NumInitElements)
6891553b190SJohn McCall         EmitInitializationToLValue(E->getInit(i), LV);
690b2ed28eaSArgyrios Kyrtzidis       else if (Expr *filler = E->getArrayFiller())
6911553b190SJohn McCall         EmitInitializationToLValue(filler, LV);
692579a05d7SChris Lattner       else
6931553b190SJohn McCall         EmitNullInitializationToLValue(LV);
69427a3631bSChris Lattner 
69527a3631bSChris Lattner       // If the GEP didn't get used because of a dead zero init or something
69627a3631bSChris Lattner       // else, clean it up for -O0 builds and general tidiness.
69727a3631bSChris Lattner       if (llvm::GetElementPtrInst *GEP =
69827a3631bSChris Lattner             dyn_cast<llvm::GetElementPtrInst>(NextVal))
69927a3631bSChris Lattner         if (GEP->use_empty())
70027a3631bSChris Lattner           GEP->eraseFromParent();
701579a05d7SChris Lattner     }
702579a05d7SChris Lattner     return;
703579a05d7SChris Lattner   }
704579a05d7SChris Lattner 
705579a05d7SChris Lattner   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
706579a05d7SChris Lattner 
707579a05d7SChris Lattner   // Do struct initialization; this code just sets each individual member
708579a05d7SChris Lattner   // to the approprate value.  This makes bitfield support automatic;
709579a05d7SChris Lattner   // the disadvantage is that the generated code is more difficult for
710579a05d7SChris Lattner   // the optimizer, especially with bitfields.
711579a05d7SChris Lattner   unsigned NumInitElements = E->getNumInits();
712c23c7e6aSTed Kremenek   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
71352bcf963SChris Lattner 
7145169570eSDouglas Gregor   if (E->getType()->isUnionType()) {
7155169570eSDouglas Gregor     // Only initialize one field of a union. The field itself is
7165169570eSDouglas Gregor     // specified by the initializer list.
7175169570eSDouglas Gregor     if (!E->getInitializedFieldInUnion()) {
7185169570eSDouglas Gregor       // Empty union; we have nothing to do.
7195169570eSDouglas Gregor 
7205169570eSDouglas Gregor #ifndef NDEBUG
7215169570eSDouglas Gregor       // Make sure that it's really an empty and not a failure of
7225169570eSDouglas Gregor       // semantic analysis.
723cfbfe78eSArgyrios Kyrtzidis       for (RecordDecl::field_iterator Field = SD->field_begin(),
724cfbfe78eSArgyrios Kyrtzidis                                    FieldEnd = SD->field_end();
7255169570eSDouglas Gregor            Field != FieldEnd; ++Field)
7265169570eSDouglas Gregor         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
7275169570eSDouglas Gregor #endif
7285169570eSDouglas Gregor       return;
7295169570eSDouglas Gregor     }
7305169570eSDouglas Gregor 
7315169570eSDouglas Gregor     // FIXME: volatility
7325169570eSDouglas Gregor     FieldDecl *Field = E->getInitializedFieldInUnion();
7335169570eSDouglas Gregor 
73427a3631bSChris Lattner     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
7355169570eSDouglas Gregor     if (NumInitElements) {
7365169570eSDouglas Gregor       // Store the initializer into the field
7371553b190SJohn McCall       EmitInitializationToLValue(E->getInit(0), FieldLoc);
7385169570eSDouglas Gregor     } else {
73927a3631bSChris Lattner       // Default-initialize to null.
7401553b190SJohn McCall       EmitNullInitializationToLValue(FieldLoc);
7415169570eSDouglas Gregor     }
7425169570eSDouglas Gregor 
7435169570eSDouglas Gregor     return;
7445169570eSDouglas Gregor   }
745579a05d7SChris Lattner 
746579a05d7SChris Lattner   // Here we iterate over the fields; this makes it simpler to both
747579a05d7SChris Lattner   // default-initialize fields and skip over unnamed fields.
74852bcf963SChris Lattner   unsigned CurInitVal = 0;
749cfbfe78eSArgyrios Kyrtzidis   for (RecordDecl::field_iterator Field = SD->field_begin(),
750cfbfe78eSArgyrios Kyrtzidis                                FieldEnd = SD->field_end();
75191f84216SDouglas Gregor        Field != FieldEnd; ++Field) {
75291f84216SDouglas Gregor     // We're done once we hit the flexible array member
75391f84216SDouglas Gregor     if (Field->getType()->isIncompleteArrayType())
75491f84216SDouglas Gregor       break;
75591f84216SDouglas Gregor 
75617bd094aSDouglas Gregor     if (Field->isUnnamedBitfield())
757579a05d7SChris Lattner       continue;
75817bd094aSDouglas Gregor 
75927a3631bSChris Lattner     // Don't emit GEP before a noop store of zero.
76027a3631bSChris Lattner     if (CurInitVal == NumInitElements && Dest.isZeroed() &&
76127a3631bSChris Lattner         CGF.getTypes().isZeroInitializable(E->getType()))
76227a3631bSChris Lattner       break;
76327a3631bSChris Lattner 
764327944b3SEli Friedman     // FIXME: volatility
76566498388SAnders Carlsson     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
7667c1baf46SFariborz Jahanian     // We never generate write-barries for initialized fields.
767e50dda95SDaniel Dunbar     FieldLoc.setNonGC(true);
76827a3631bSChris Lattner 
769579a05d7SChris Lattner     if (CurInitVal < NumInitElements) {
770e18aaf2cSChris Lattner       // Store the initializer into the field.
7711553b190SJohn McCall       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc);
772579a05d7SChris Lattner     } else {
773579a05d7SChris Lattner       // We're out of initalizers; default-initialize to null
7741553b190SJohn McCall       EmitNullInitializationToLValue(FieldLoc);
775579a05d7SChris Lattner     }
77627a3631bSChris Lattner 
77727a3631bSChris Lattner     // If the GEP didn't get used because of a dead zero init or something
77827a3631bSChris Lattner     // else, clean it up for -O0 builds and general tidiness.
77927a3631bSChris Lattner     if (FieldLoc.isSimple())
78027a3631bSChris Lattner       if (llvm::GetElementPtrInst *GEP =
78127a3631bSChris Lattner             dyn_cast<llvm::GetElementPtrInst>(FieldLoc.getAddress()))
78227a3631bSChris Lattner         if (GEP->use_empty())
78327a3631bSChris Lattner           GEP->eraseFromParent();
7847a51313dSChris Lattner   }
7857a51313dSChris Lattner }
7867a51313dSChris Lattner 
7877a51313dSChris Lattner //===----------------------------------------------------------------------===//
7887a51313dSChris Lattner //                        Entry Points into this File
7897a51313dSChris Lattner //===----------------------------------------------------------------------===//
7907a51313dSChris Lattner 
79127a3631bSChris Lattner /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
79227a3631bSChris Lattner /// non-zero bytes that will be stored when outputting the initializer for the
79327a3631bSChris Lattner /// specified initializer expression.
794df94cb7dSKen Dyck static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
79591147596SPeter Collingbourne   E = E->IgnoreParens();
79627a3631bSChris Lattner 
79727a3631bSChris Lattner   // 0 and 0.0 won't require any non-zero stores!
798df94cb7dSKen Dyck   if (isSimpleZero(E, CGF)) return CharUnits::Zero();
79927a3631bSChris Lattner 
80027a3631bSChris Lattner   // If this is an initlist expr, sum up the size of sizes of the (present)
80127a3631bSChris Lattner   // elements.  If this is something weird, assume the whole thing is non-zero.
80227a3631bSChris Lattner   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
80327a3631bSChris Lattner   if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
804df94cb7dSKen Dyck     return CGF.getContext().getTypeSizeInChars(E->getType());
80527a3631bSChris Lattner 
806c5cc2fb9SChris Lattner   // InitListExprs for structs have to be handled carefully.  If there are
807c5cc2fb9SChris Lattner   // reference members, we need to consider the size of the reference, not the
808c5cc2fb9SChris Lattner   // referencee.  InitListExprs for unions and arrays can't have references.
8095cd84755SChris Lattner   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
8105cd84755SChris Lattner     if (!RT->isUnionType()) {
811c5cc2fb9SChris Lattner       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
812df94cb7dSKen Dyck       CharUnits NumNonZeroBytes = CharUnits::Zero();
813c5cc2fb9SChris Lattner 
814c5cc2fb9SChris Lattner       unsigned ILEElement = 0;
815c5cc2fb9SChris Lattner       for (RecordDecl::field_iterator Field = SD->field_begin(),
816c5cc2fb9SChris Lattner            FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
817c5cc2fb9SChris Lattner         // We're done once we hit the flexible array member or run out of
818c5cc2fb9SChris Lattner         // InitListExpr elements.
819c5cc2fb9SChris Lattner         if (Field->getType()->isIncompleteArrayType() ||
820c5cc2fb9SChris Lattner             ILEElement == ILE->getNumInits())
821c5cc2fb9SChris Lattner           break;
822c5cc2fb9SChris Lattner         if (Field->isUnnamedBitfield())
823c5cc2fb9SChris Lattner           continue;
824c5cc2fb9SChris Lattner 
825c5cc2fb9SChris Lattner         const Expr *E = ILE->getInit(ILEElement++);
826c5cc2fb9SChris Lattner 
827c5cc2fb9SChris Lattner         // Reference values are always non-null and have the width of a pointer.
8285cd84755SChris Lattner         if (Field->getType()->isReferenceType())
829df94cb7dSKen Dyck           NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
830df94cb7dSKen Dyck               CGF.getContext().Target.getPointerWidth(0));
8315cd84755SChris Lattner         else
832c5cc2fb9SChris Lattner           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
833c5cc2fb9SChris Lattner       }
834c5cc2fb9SChris Lattner 
835c5cc2fb9SChris Lattner       return NumNonZeroBytes;
836c5cc2fb9SChris Lattner     }
8375cd84755SChris Lattner   }
838c5cc2fb9SChris Lattner 
839c5cc2fb9SChris Lattner 
840df94cb7dSKen Dyck   CharUnits NumNonZeroBytes = CharUnits::Zero();
84127a3631bSChris Lattner   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
84227a3631bSChris Lattner     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
84327a3631bSChris Lattner   return NumNonZeroBytes;
84427a3631bSChris Lattner }
84527a3631bSChris Lattner 
84627a3631bSChris Lattner /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
84727a3631bSChris Lattner /// zeros in it, emit a memset and avoid storing the individual zeros.
84827a3631bSChris Lattner ///
84927a3631bSChris Lattner static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
85027a3631bSChris Lattner                                      CodeGenFunction &CGF) {
85127a3631bSChris Lattner   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
85227a3631bSChris Lattner   // volatile stores.
85327a3631bSChris Lattner   if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
85427a3631bSChris Lattner 
85503535265SArgyrios Kyrtzidis   // C++ objects with a user-declared constructor don't need zero'ing.
85603535265SArgyrios Kyrtzidis   if (CGF.getContext().getLangOptions().CPlusPlus)
85703535265SArgyrios Kyrtzidis     if (const RecordType *RT = CGF.getContext()
85803535265SArgyrios Kyrtzidis                        .getBaseElementType(E->getType())->getAs<RecordType>()) {
85903535265SArgyrios Kyrtzidis       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
86003535265SArgyrios Kyrtzidis       if (RD->hasUserDeclaredConstructor())
86103535265SArgyrios Kyrtzidis         return;
86203535265SArgyrios Kyrtzidis     }
86303535265SArgyrios Kyrtzidis 
86427a3631bSChris Lattner   // If the type is 16-bytes or smaller, prefer individual stores over memset.
865239a3357SKen Dyck   std::pair<CharUnits, CharUnits> TypeInfo =
866239a3357SKen Dyck     CGF.getContext().getTypeInfoInChars(E->getType());
867239a3357SKen Dyck   if (TypeInfo.first <= CharUnits::fromQuantity(16))
86827a3631bSChris Lattner     return;
86927a3631bSChris Lattner 
87027a3631bSChris Lattner   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
87127a3631bSChris Lattner   // we prefer to emit memset + individual stores for the rest.
872239a3357SKen Dyck   CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
873239a3357SKen Dyck   if (NumNonZeroBytes*4 > TypeInfo.first)
87427a3631bSChris Lattner     return;
87527a3631bSChris Lattner 
87627a3631bSChris Lattner   // Okay, it seems like a good idea to use an initial memset, emit the call.
877239a3357SKen Dyck   llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
878239a3357SKen Dyck   CharUnits Align = TypeInfo.second;
87927a3631bSChris Lattner 
88027a3631bSChris Lattner   llvm::Value *Loc = Slot.getAddr();
88127a3631bSChris Lattner   const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
88227a3631bSChris Lattner 
88327a3631bSChris Lattner   Loc = CGF.Builder.CreateBitCast(Loc, BP);
884239a3357SKen Dyck   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
885239a3357SKen Dyck                            Align.getQuantity(), false);
88627a3631bSChris Lattner 
88727a3631bSChris Lattner   // Tell the AggExprEmitter that the slot is known zero.
88827a3631bSChris Lattner   Slot.setZeroed();
88927a3631bSChris Lattner }
89027a3631bSChris Lattner 
89127a3631bSChris Lattner 
89227a3631bSChris Lattner 
89327a3631bSChris Lattner 
89425306cacSMike Stump /// EmitAggExpr - Emit the computation of the specified expression of aggregate
89525306cacSMike Stump /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
89625306cacSMike Stump /// the value of the aggregate expression is not needed.  If VolatileDest is
89725306cacSMike Stump /// true, DestPtr cannot be 0.
8987a626f63SJohn McCall ///
8997a626f63SJohn McCall /// \param IsInitializer - true if this evaluation is initializing an
9007a626f63SJohn McCall /// object whose lifetime is already being managed.
9017a626f63SJohn McCall void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
902b60e70f9SFariborz Jahanian                                   bool IgnoreResult) {
9037a51313dSChris Lattner   assert(E && hasAggregateLLVMType(E->getType()) &&
9047a51313dSChris Lattner          "Invalid aggregate expression to emit");
90527a3631bSChris Lattner   assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
90627a3631bSChris Lattner          "slot has bits but no address");
9077a51313dSChris Lattner 
90827a3631bSChris Lattner   // Optimize the slot if possible.
90927a3631bSChris Lattner   CheckAggExprForMemSetUse(Slot, E, *this);
91027a3631bSChris Lattner 
91127a3631bSChris Lattner   AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E));
9127a51313dSChris Lattner }
9130bc8e86dSDaniel Dunbar 
914d0bc7b9dSDaniel Dunbar LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
915d0bc7b9dSDaniel Dunbar   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
916a7566f16SDaniel Dunbar   llvm::Value *Temp = CreateMemTemp(E->getType());
9172e442a00SDaniel Dunbar   LValue LV = MakeAddrLValue(Temp, E->getType());
91831168b07SJohn McCall   EmitAggExpr(E, AggValueSlot::forLValue(LV, false));
9192e442a00SDaniel Dunbar   return LV;
920d0bc7b9dSDaniel Dunbar }
921d0bc7b9dSDaniel Dunbar 
9220bc8e86dSDaniel Dunbar void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
9235e9e61b8SMike Stump                                         llvm::Value *SrcPtr, QualType Ty,
9245e9e61b8SMike Stump                                         bool isVolatile) {
9250bc8e86dSDaniel Dunbar   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
9260bc8e86dSDaniel Dunbar 
92716e94af6SAnders Carlsson   if (getContext().getLangOptions().CPlusPlus) {
92816e94af6SAnders Carlsson     if (const RecordType *RT = Ty->getAs<RecordType>()) {
929f22101a0SDouglas Gregor       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
930f22101a0SDouglas Gregor       assert((Record->hasTrivialCopyConstructor() ||
9316855ba2cSFariborz Jahanian               Record->hasTrivialCopyAssignment()) &&
932f22101a0SDouglas Gregor              "Trying to aggregate-copy a type without a trivial copy "
933f22101a0SDouglas Gregor              "constructor or assignment operator");
934265b8b8dSDouglas Gregor       // Ignore empty classes in C++.
935f22101a0SDouglas Gregor       if (Record->isEmpty())
93616e94af6SAnders Carlsson         return;
93716e94af6SAnders Carlsson     }
93816e94af6SAnders Carlsson   }
93916e94af6SAnders Carlsson 
940ca05dfefSChris Lattner   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
9413ef668c2SChris Lattner   // C99 6.5.16.1p3, which states "If the value being stored in an object is
9423ef668c2SChris Lattner   // read from another object that overlaps in anyway the storage of the first
9433ef668c2SChris Lattner   // object, then the overlap shall be exact and the two objects shall have
9443ef668c2SChris Lattner   // qualified or unqualified versions of a compatible type."
9453ef668c2SChris Lattner   //
946ca05dfefSChris Lattner   // memcpy is not defined if the source and destination pointers are exactly
9473ef668c2SChris Lattner   // equal, but other compilers do this optimization, and almost every memcpy
9483ef668c2SChris Lattner   // implementation handles this case safely.  If there is a libc that does not
9493ef668c2SChris Lattner   // safely handle this, we can add a target hook.
9500bc8e86dSDaniel Dunbar 
9510bc8e86dSDaniel Dunbar   // Get size and alignment info for this aggregate.
952bb2c2400SKen Dyck   std::pair<CharUnits, CharUnits> TypeInfo =
953bb2c2400SKen Dyck     getContext().getTypeInfoInChars(Ty);
9540bc8e86dSDaniel Dunbar 
9550bc8e86dSDaniel Dunbar   // FIXME: Handle variable sized types.
9560bc8e86dSDaniel Dunbar 
95786736572SMike Stump   // FIXME: If we have a volatile struct, the optimizer can remove what might
95886736572SMike Stump   // appear to be `extra' memory ops:
95986736572SMike Stump   //
96086736572SMike Stump   // volatile struct { int i; } a, b;
96186736572SMike Stump   //
96286736572SMike Stump   // int main() {
96386736572SMike Stump   //   a = b;
96486736572SMike Stump   //   a = b;
96586736572SMike Stump   // }
96686736572SMike Stump   //
967cc2ab0cdSMon P Wang   // we need to use a different call here.  We use isVolatile to indicate when
968ec3cbfe8SMike Stump   // either the source or the destination is volatile.
969cc2ab0cdSMon P Wang 
970cc2ab0cdSMon P Wang   const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
971cb7696cfSChris Lattner   const llvm::Type *DBP =
972ad7c5c16SJohn McCall     llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
973cc2ab0cdSMon P Wang   DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp");
974cc2ab0cdSMon P Wang 
975cc2ab0cdSMon P Wang   const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
976cb7696cfSChris Lattner   const llvm::Type *SBP =
977ad7c5c16SJohn McCall     llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
978cc2ab0cdSMon P Wang   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp");
979cc2ab0cdSMon P Wang 
98031168b07SJohn McCall   // Don't do any of the memmove_collectable tests if GC isn't set.
98131168b07SJohn McCall   if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC) {
98231168b07SJohn McCall     // fall through
98331168b07SJohn McCall   } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
984021510e9SFariborz Jahanian     RecordDecl *Record = RecordTy->getDecl();
985021510e9SFariborz Jahanian     if (Record->hasObjectMember()) {
986bb2c2400SKen Dyck       CharUnits size = TypeInfo.first;
987021510e9SFariborz Jahanian       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
988bb2c2400SKen Dyck       llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
989021510e9SFariborz Jahanian       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
990021510e9SFariborz Jahanian                                                     SizeVal);
991021510e9SFariborz Jahanian       return;
992021510e9SFariborz Jahanian     }
99331168b07SJohn McCall   } else if (Ty->isArrayType()) {
994021510e9SFariborz Jahanian     QualType BaseType = getContext().getBaseElementType(Ty);
995021510e9SFariborz Jahanian     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
996021510e9SFariborz Jahanian       if (RecordTy->getDecl()->hasObjectMember()) {
997bb2c2400SKen Dyck         CharUnits size = TypeInfo.first;
998021510e9SFariborz Jahanian         const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
999bb2c2400SKen Dyck         llvm::Value *SizeVal =
1000bb2c2400SKen Dyck           llvm::ConstantInt::get(SizeTy, size.getQuantity());
1001021510e9SFariborz Jahanian         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1002021510e9SFariborz Jahanian                                                       SizeVal);
1003021510e9SFariborz Jahanian         return;
1004021510e9SFariborz Jahanian       }
1005021510e9SFariborz Jahanian     }
1006021510e9SFariborz Jahanian   }
1007021510e9SFariborz Jahanian 
1008acc6b4e2SBenjamin Kramer   Builder.CreateMemCpy(DestPtr, SrcPtr,
1009bb2c2400SKen Dyck                        llvm::ConstantInt::get(IntPtrTy,
1010bb2c2400SKen Dyck                                               TypeInfo.first.getQuantity()),
1011bb2c2400SKen Dyck                        TypeInfo.second.getQuantity(), isVolatile);
10120bc8e86dSDaniel Dunbar }
1013