17a51313dSChris Lattner //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
27a51313dSChris Lattner //
37a51313dSChris Lattner //                     The LLVM Compiler Infrastructure
47a51313dSChris Lattner //
57a51313dSChris Lattner // This file is distributed under the University of Illinois Open Source
67a51313dSChris Lattner // License. See LICENSE.TXT for details.
77a51313dSChris Lattner //
87a51313dSChris Lattner //===----------------------------------------------------------------------===//
97a51313dSChris Lattner //
107a51313dSChris Lattner // This contains code to emit Aggregate Expr nodes as LLVM code.
117a51313dSChris Lattner //
127a51313dSChris Lattner //===----------------------------------------------------------------------===//
137a51313dSChris Lattner 
147a51313dSChris Lattner #include "CodeGenFunction.h"
155f21d2f6SFariborz Jahanian #include "CGObjCRuntime.h"
163a02247dSChandler Carruth #include "CodeGenModule.h"
17ad319a73SDaniel Dunbar #include "clang/AST/ASTContext.h"
18b7f8f594SAnders Carlsson #include "clang/AST/DeclCXX.h"
19c83ed824SSebastian Redl #include "clang/AST/DeclTemplate.h"
20ad319a73SDaniel Dunbar #include "clang/AST/StmtVisitor.h"
21ffd5551bSChandler Carruth #include "llvm/IR/Constants.h"
22ffd5551bSChandler Carruth #include "llvm/IR/Function.h"
23ffd5551bSChandler Carruth #include "llvm/IR/GlobalVariable.h"
24ffd5551bSChandler Carruth #include "llvm/IR/Intrinsics.h"
257a51313dSChris Lattner using namespace clang;
267a51313dSChris Lattner using namespace CodeGen;
277a51313dSChris Lattner 
287a51313dSChris Lattner //===----------------------------------------------------------------------===//
297a51313dSChris Lattner //                        Aggregate Expression Emitter
307a51313dSChris Lattner //===----------------------------------------------------------------------===//
317a51313dSChris Lattner 
32a8ec7eb9SJohn McCall llvm::Value *AggValueSlot::getPaddedAtomicAddr() const {
33a8ec7eb9SJohn McCall   assert(isValueOfAtomic());
34a8ec7eb9SJohn McCall   llvm::GEPOperator *op = cast<llvm::GEPOperator>(getAddr());
35a8ec7eb9SJohn McCall   assert(op->getNumIndices() == 2);
36a8ec7eb9SJohn McCall   assert(op->hasAllZeroIndices());
37a8ec7eb9SJohn McCall   return op->getPointerOperand();
38a8ec7eb9SJohn McCall }
39a8ec7eb9SJohn McCall 
407a51313dSChris Lattner namespace  {
41337e3a5fSBenjamin Kramer class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
427a51313dSChris Lattner   CodeGenFunction &CGF;
43cb463859SDaniel Dunbar   CGBuilderTy &Builder;
447a626f63SJohn McCall   AggValueSlot Dest;
4578a15113SJohn McCall 
46a5efa738SJohn McCall   /// We want to use 'dest' as the return slot except under two
47a5efa738SJohn McCall   /// conditions:
48a5efa738SJohn McCall   ///   - The destination slot requires garbage collection, so we
49a5efa738SJohn McCall   ///     need to use the GC API.
50a5efa738SJohn McCall   ///   - The destination slot is potentially aliased.
51a5efa738SJohn McCall   bool shouldUseDestForReturnSlot() const {
52a5efa738SJohn McCall     return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
53a5efa738SJohn McCall   }
54a5efa738SJohn McCall 
5578a15113SJohn McCall   ReturnValueSlot getReturnValueSlot() const {
56a5efa738SJohn McCall     if (!shouldUseDestForReturnSlot())
57a5efa738SJohn McCall       return ReturnValueSlot();
58cc04e9f6SJohn McCall 
597a626f63SJohn McCall     return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
607a626f63SJohn McCall   }
617a626f63SJohn McCall 
627a626f63SJohn McCall   AggValueSlot EnsureSlot(QualType T) {
637a626f63SJohn McCall     if (!Dest.isIgnored()) return Dest;
647a626f63SJohn McCall     return CGF.CreateAggTemp(T, "agg.tmp.ensured");
6578a15113SJohn McCall   }
664e8ca4faSJohn McCall   void EnsureDest(QualType T) {
674e8ca4faSJohn McCall     if (!Dest.isIgnored()) return;
684e8ca4faSJohn McCall     Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
694e8ca4faSJohn McCall   }
70cc04e9f6SJohn McCall 
717a51313dSChris Lattner public:
724e8ca4faSJohn McCall   AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest)
734e8ca4faSJohn McCall     : CGF(cgf), Builder(CGF.Builder), Dest(Dest) {
747a51313dSChris Lattner   }
757a51313dSChris Lattner 
767a51313dSChris Lattner   //===--------------------------------------------------------------------===//
777a51313dSChris Lattner   //                               Utilities
787a51313dSChris Lattner   //===--------------------------------------------------------------------===//
797a51313dSChris Lattner 
807a51313dSChris Lattner   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
817a51313dSChris Lattner   /// represents a value lvalue, this method emits the address of the lvalue,
827a51313dSChris Lattner   /// then loads the result into DestPtr.
837a51313dSChris Lattner   void EmitAggLoadOfLValue(const Expr *E);
847a51313dSChris Lattner 
85ca9fc09cSMike Stump   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
864e8ca4faSJohn McCall   void EmitFinalDestCopy(QualType type, const LValue &src);
874e8ca4faSJohn McCall   void EmitFinalDestCopy(QualType type, RValue src,
884e8ca4faSJohn McCall                          CharUnits srcAlignment = CharUnits::Zero());
894e8ca4faSJohn McCall   void EmitCopy(QualType type, const AggValueSlot &dest,
904e8ca4faSJohn McCall                 const AggValueSlot &src);
91ca9fc09cSMike Stump 
92a5efa738SJohn McCall   void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
93cc04e9f6SJohn McCall 
948eb351d7SSebastian Redl   void EmitStdInitializerList(llvm::Value *DestPtr, InitListExpr *InitList);
95c83ed824SSebastian Redl   void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
96c83ed824SSebastian Redl                      QualType elementType, InitListExpr *E);
97c83ed824SSebastian Redl 
988d6fc958SJohn McCall   AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
99bbafb8a7SDavid Blaikie     if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
1008d6fc958SJohn McCall       return AggValueSlot::NeedsGCBarriers;
1018d6fc958SJohn McCall     return AggValueSlot::DoesNotNeedGCBarriers;
1028d6fc958SJohn McCall   }
1038d6fc958SJohn McCall 
104cc04e9f6SJohn McCall   bool TypeRequiresGCollection(QualType T);
105cc04e9f6SJohn McCall 
1067a51313dSChris Lattner   //===--------------------------------------------------------------------===//
1077a51313dSChris Lattner   //                            Visitor Methods
1087a51313dSChris Lattner   //===--------------------------------------------------------------------===//
1097a51313dSChris Lattner 
1107a51313dSChris Lattner   void VisitStmt(Stmt *S) {
111a7c8cf62SDaniel Dunbar     CGF.ErrorUnsupported(S, "aggregate expression");
1127a51313dSChris Lattner   }
1137a51313dSChris Lattner   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
11491147596SPeter Collingbourne   void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
11591147596SPeter Collingbourne     Visit(GE->getResultExpr());
11691147596SPeter Collingbourne   }
1173f66b84cSEli Friedman   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
1187c454bb8SJohn McCall   void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
1197c454bb8SJohn McCall     return Visit(E->getReplacement());
1207c454bb8SJohn McCall   }
1217a51313dSChris Lattner 
1227a51313dSChris Lattner   // l-values.
123113bee05SJohn McCall   void VisitDeclRefExpr(DeclRefExpr *E) {
12471335059SJohn McCall     // For aggregates, we should always be able to emit the variable
12571335059SJohn McCall     // as an l-value unless it's a reference.  This is due to the fact
12671335059SJohn McCall     // that we can't actually ever see a normal l2r conversion on an
12771335059SJohn McCall     // aggregate in C++, and in C there's no language standard
12871335059SJohn McCall     // actively preventing us from listing variables in the captures
12971335059SJohn McCall     // list of a block.
130113bee05SJohn McCall     if (E->getDecl()->getType()->isReferenceType()) {
13171335059SJohn McCall       if (CodeGenFunction::ConstantEmission result
132113bee05SJohn McCall             = CGF.tryEmitAsConstant(E)) {
1334e8ca4faSJohn McCall         EmitFinalDestCopy(E->getType(), result.getReferenceLValue(CGF, E));
13471335059SJohn McCall         return;
13571335059SJohn McCall       }
13671335059SJohn McCall     }
13771335059SJohn McCall 
138113bee05SJohn McCall     EmitAggLoadOfLValue(E);
13971335059SJohn McCall   }
14071335059SJohn McCall 
1417a51313dSChris Lattner   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
1427a51313dSChris Lattner   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
143d443c0a0SDaniel Dunbar   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
1449b71f0cfSDouglas Gregor   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1457a51313dSChris Lattner   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
1467a51313dSChris Lattner     EmitAggLoadOfLValue(E);
1477a51313dSChris Lattner   }
1482f343dd5SChris Lattner   void VisitPredefinedExpr(const PredefinedExpr *E) {
1492f343dd5SChris Lattner     EmitAggLoadOfLValue(E);
1502f343dd5SChris Lattner   }
151bc7d67ceSMike Stump 
1527a51313dSChris Lattner   // Operators.
153ec143777SAnders Carlsson   void VisitCastExpr(CastExpr *E);
1547a51313dSChris Lattner   void VisitCallExpr(const CallExpr *E);
1557a51313dSChris Lattner   void VisitStmtExpr(const StmtExpr *E);
1567a51313dSChris Lattner   void VisitBinaryOperator(const BinaryOperator *BO);
157ffba662dSFariborz Jahanian   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
1587a51313dSChris Lattner   void VisitBinAssign(const BinaryOperator *E);
1594b0e2a30SEli Friedman   void VisitBinComma(const BinaryOperator *E);
1607a51313dSChris Lattner 
161b1d329daSChris Lattner   void VisitObjCMessageExpr(ObjCMessageExpr *E);
162c8317a44SDaniel Dunbar   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
163c8317a44SDaniel Dunbar     EmitAggLoadOfLValue(E);
164c8317a44SDaniel Dunbar   }
1657a51313dSChris Lattner 
166c07a0c7eSJohn McCall   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
1675b2095ceSAnders Carlsson   void VisitChooseExpr(const ChooseExpr *CE);
1687a51313dSChris Lattner   void VisitInitListExpr(InitListExpr *E);
16918ada985SAnders Carlsson   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
170aa9c7aedSChris Lattner   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
171aa9c7aedSChris Lattner     Visit(DAE->getExpr());
172aa9c7aedSChris Lattner   }
173852c9db7SRichard Smith   void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
174852c9db7SRichard Smith     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
175852c9db7SRichard Smith     Visit(DIE->getExpr());
176852c9db7SRichard Smith   }
1773be22e27SAnders Carlsson   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
1781619a504SAnders Carlsson   void VisitCXXConstructExpr(const CXXConstructExpr *E);
179c370a7eeSEli Friedman   void VisitLambdaExpr(LambdaExpr *E);
1805d413781SJohn McCall   void VisitExprWithCleanups(ExprWithCleanups *E);
181747eb784SDouglas Gregor   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1825bbbb137SMike Stump   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
183fe31481fSDouglas Gregor   void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
1841bf5846aSJohn McCall   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1851bf5846aSJohn McCall 
186fe96e0b6SJohn McCall   void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
187fe96e0b6SJohn McCall     if (E->isGLValue()) {
188fe96e0b6SJohn McCall       LValue LV = CGF.EmitPseudoObjectLValue(E);
1894e8ca4faSJohn McCall       return EmitFinalDestCopy(E->getType(), LV);
190fe96e0b6SJohn McCall     }
191fe96e0b6SJohn McCall 
192fe96e0b6SJohn McCall     CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
193fe96e0b6SJohn McCall   }
194fe96e0b6SJohn McCall 
19521911e89SEli Friedman   void VisitVAArgExpr(VAArgExpr *E);
196579a05d7SChris Lattner 
197615ed1a3SChad Rosier   void EmitInitializationToLValue(Expr *E, LValue Address);
1981553b190SJohn McCall   void EmitNullInitializationToLValue(LValue Address);
1997a51313dSChris Lattner   //  case Expr::ChooseExprClass:
200f16b8c30SMike Stump   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
201df14b3a8SEli Friedman   void VisitAtomicExpr(AtomicExpr *E) {
202df14b3a8SEli Friedman     CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
203df14b3a8SEli Friedman   }
2047a51313dSChris Lattner };
205a8ec7eb9SJohn McCall 
206a8ec7eb9SJohn McCall /// A helper class for emitting expressions into the value sub-object
207a8ec7eb9SJohn McCall /// of a padded atomic type.
208a8ec7eb9SJohn McCall class ValueDestForAtomic {
209a8ec7eb9SJohn McCall   AggValueSlot Dest;
210a8ec7eb9SJohn McCall public:
211a8ec7eb9SJohn McCall   ValueDestForAtomic(CodeGenFunction &CGF, AggValueSlot dest, QualType type)
212a8ec7eb9SJohn McCall     : Dest(dest) {
213a8ec7eb9SJohn McCall     assert(!Dest.isValueOfAtomic());
214a8ec7eb9SJohn McCall     if (!Dest.isIgnored() && CGF.CGM.isPaddedAtomicType(type)) {
215a8ec7eb9SJohn McCall       llvm::Value *valueAddr = CGF.Builder.CreateStructGEP(Dest.getAddr(), 0);
216a8ec7eb9SJohn McCall       Dest = AggValueSlot::forAddr(valueAddr,
217a8ec7eb9SJohn McCall                                    Dest.getAlignment(),
218a8ec7eb9SJohn McCall                                    Dest.getQualifiers(),
219a8ec7eb9SJohn McCall                                    Dest.isExternallyDestructed(),
220a8ec7eb9SJohn McCall                                    Dest.requiresGCollection(),
221a8ec7eb9SJohn McCall                                    Dest.isPotentiallyAliased(),
222a8ec7eb9SJohn McCall                                    Dest.isZeroed(),
223a8ec7eb9SJohn McCall                                    AggValueSlot::IsValueOfAtomic);
224a8ec7eb9SJohn McCall     }
225a8ec7eb9SJohn McCall   }
226a8ec7eb9SJohn McCall 
227a8ec7eb9SJohn McCall   const AggValueSlot &getDest() const { return Dest; }
228a8ec7eb9SJohn McCall 
229a8ec7eb9SJohn McCall   ~ValueDestForAtomic() {
230a8ec7eb9SJohn McCall     // Kill the GEP if we made one and it didn't end up used.
231a8ec7eb9SJohn McCall     if (Dest.isValueOfAtomic()) {
232a8ec7eb9SJohn McCall       llvm::Instruction *addr = cast<llvm::GetElementPtrInst>(Dest.getAddr());
233a8ec7eb9SJohn McCall       if (addr->use_empty()) addr->eraseFromParent();
234a8ec7eb9SJohn McCall     }
235a8ec7eb9SJohn McCall   }
236a8ec7eb9SJohn McCall };
2377a51313dSChris Lattner }  // end anonymous namespace.
2387a51313dSChris Lattner 
2397a51313dSChris Lattner //===----------------------------------------------------------------------===//
2407a51313dSChris Lattner //                                Utilities
2417a51313dSChris Lattner //===----------------------------------------------------------------------===//
2427a51313dSChris Lattner 
2437a51313dSChris Lattner /// EmitAggLoadOfLValue - Given an expression with aggregate type that
2447a51313dSChris Lattner /// represents a value lvalue, this method emits the address of the lvalue,
2457a51313dSChris Lattner /// then loads the result into DestPtr.
2467a51313dSChris Lattner void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
2477a51313dSChris Lattner   LValue LV = CGF.EmitLValue(E);
248a8ec7eb9SJohn McCall 
249a8ec7eb9SJohn McCall   // If the type of the l-value is atomic, then do an atomic load.
250a8ec7eb9SJohn McCall   if (LV.getType()->isAtomicType()) {
251a8ec7eb9SJohn McCall     ValueDestForAtomic valueDest(CGF, Dest, LV.getType());
252a8ec7eb9SJohn McCall     CGF.EmitAtomicLoad(LV, valueDest.getDest());
253a8ec7eb9SJohn McCall     return;
254a8ec7eb9SJohn McCall   }
255a8ec7eb9SJohn McCall 
2564e8ca4faSJohn McCall   EmitFinalDestCopy(E->getType(), LV);
257ca9fc09cSMike Stump }
258ca9fc09cSMike Stump 
259cc04e9f6SJohn McCall /// \brief True if the given aggregate type requires special GC API calls.
260cc04e9f6SJohn McCall bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
261cc04e9f6SJohn McCall   // Only record types have members that might require garbage collection.
262cc04e9f6SJohn McCall   const RecordType *RecordTy = T->getAs<RecordType>();
263cc04e9f6SJohn McCall   if (!RecordTy) return false;
264cc04e9f6SJohn McCall 
265cc04e9f6SJohn McCall   // Don't mess with non-trivial C++ types.
266cc04e9f6SJohn McCall   RecordDecl *Record = RecordTy->getDecl();
267cc04e9f6SJohn McCall   if (isa<CXXRecordDecl>(Record) &&
26816488472SRichard Smith       (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
269cc04e9f6SJohn McCall        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
270cc04e9f6SJohn McCall     return false;
271cc04e9f6SJohn McCall 
272cc04e9f6SJohn McCall   // Check whether the type has an object member.
273cc04e9f6SJohn McCall   return Record->hasObjectMember();
274cc04e9f6SJohn McCall }
275cc04e9f6SJohn McCall 
276a5efa738SJohn McCall /// \brief Perform the final move to DestPtr if for some reason
277a5efa738SJohn McCall /// getReturnValueSlot() didn't use it directly.
278cc04e9f6SJohn McCall ///
279cc04e9f6SJohn McCall /// The idea is that you do something like this:
280cc04e9f6SJohn McCall ///   RValue Result = EmitSomething(..., getReturnValueSlot());
281a5efa738SJohn McCall ///   EmitMoveFromReturnSlot(E, Result);
282a5efa738SJohn McCall ///
283a5efa738SJohn McCall /// If nothing interferes, this will cause the result to be emitted
284a5efa738SJohn McCall /// directly into the return value slot.  Otherwise, a final move
285a5efa738SJohn McCall /// will be performed.
2864e8ca4faSJohn McCall void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
287a5efa738SJohn McCall   if (shouldUseDestForReturnSlot()) {
288a5efa738SJohn McCall     // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
289a5efa738SJohn McCall     // The possibility of undef rvalues complicates that a lot,
290a5efa738SJohn McCall     // though, so we can't really assert.
291a5efa738SJohn McCall     return;
292021510e9SFariborz Jahanian   }
293a5efa738SJohn McCall 
2944e8ca4faSJohn McCall   // Otherwise, copy from there to the destination.
2954e8ca4faSJohn McCall   assert(Dest.getAddr() != src.getAggregateAddr());
2964e8ca4faSJohn McCall   std::pair<CharUnits, CharUnits> typeInfo =
2971e303eefSChad Rosier     CGF.getContext().getTypeInfoInChars(E->getType());
2984e8ca4faSJohn McCall   EmitFinalDestCopy(E->getType(), src, typeInfo.second);
299cc04e9f6SJohn McCall }
300cc04e9f6SJohn McCall 
301ca9fc09cSMike Stump /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
3024e8ca4faSJohn McCall void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src,
3034e8ca4faSJohn McCall                                        CharUnits srcAlign) {
3044e8ca4faSJohn McCall   assert(src.isAggregate() && "value must be aggregate value!");
3054e8ca4faSJohn McCall   LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddr(), type, srcAlign);
3064e8ca4faSJohn McCall   EmitFinalDestCopy(type, srcLV);
3074e8ca4faSJohn McCall }
3087a51313dSChris Lattner 
3094e8ca4faSJohn McCall /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
3104e8ca4faSJohn McCall void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src) {
3117a626f63SJohn McCall   // If Dest is ignored, then we're evaluating an aggregate expression
3124e8ca4faSJohn McCall   // in a context that doesn't care about the result.  Note that loads
3134e8ca4faSJohn McCall   // from volatile l-values force the existence of a non-ignored
3144e8ca4faSJohn McCall   // destination.
3154e8ca4faSJohn McCall   if (Dest.isIgnored())
316ec3cbfe8SMike Stump     return;
317c123623dSFariborz Jahanian 
3184e8ca4faSJohn McCall   AggValueSlot srcAgg =
3194e8ca4faSJohn McCall     AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
3204e8ca4faSJohn McCall                             needsGC(type), AggValueSlot::IsAliased);
3214e8ca4faSJohn McCall   EmitCopy(type, Dest, srcAgg);
322332ec2ceSMike Stump }
3237a51313dSChris Lattner 
3244e8ca4faSJohn McCall /// Perform a copy from the source into the destination.
3254e8ca4faSJohn McCall ///
3264e8ca4faSJohn McCall /// \param type - the type of the aggregate being copied; qualifiers are
3274e8ca4faSJohn McCall ///   ignored
3284e8ca4faSJohn McCall void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
3294e8ca4faSJohn McCall                               const AggValueSlot &src) {
3304e8ca4faSJohn McCall   if (dest.requiresGCollection()) {
3314e8ca4faSJohn McCall     CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
3324e8ca4faSJohn McCall     llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
333879d7266SFariborz Jahanian     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
3344e8ca4faSJohn McCall                                                       dest.getAddr(),
3354e8ca4faSJohn McCall                                                       src.getAddr(),
3364e8ca4faSJohn McCall                                                       size);
337879d7266SFariborz Jahanian     return;
338879d7266SFariborz Jahanian   }
3394e8ca4faSJohn McCall 
340ca9fc09cSMike Stump   // If the result of the assignment is used, copy the LHS there also.
3414e8ca4faSJohn McCall   // It's volatile if either side is.  Use the minimum alignment of
3424e8ca4faSJohn McCall   // the two sides.
3434e8ca4faSJohn McCall   CGF.EmitAggregateCopy(dest.getAddr(), src.getAddr(), type,
3444e8ca4faSJohn McCall                         dest.isVolatile() || src.isVolatile(),
3454e8ca4faSJohn McCall                         std::min(dest.getAlignment(), src.getAlignment()));
3467a51313dSChris Lattner }
3477a51313dSChris Lattner 
348c83ed824SSebastian Redl static QualType GetStdInitializerListElementType(QualType T) {
349c83ed824SSebastian Redl   // Just assume that this is really std::initializer_list.
350c83ed824SSebastian Redl   ClassTemplateSpecializationDecl *specialization =
351c83ed824SSebastian Redl       cast<ClassTemplateSpecializationDecl>(T->castAs<RecordType>()->getDecl());
352c83ed824SSebastian Redl   return specialization->getTemplateArgs()[0].getAsType();
353c83ed824SSebastian Redl }
354c83ed824SSebastian Redl 
355c83ed824SSebastian Redl /// \brief Prepare cleanup for the temporary array.
356c83ed824SSebastian Redl static void EmitStdInitializerListCleanup(CodeGenFunction &CGF,
357c83ed824SSebastian Redl                                           QualType arrayType,
358c83ed824SSebastian Redl                                           llvm::Value *addr,
359c83ed824SSebastian Redl                                           const InitListExpr *initList) {
360c83ed824SSebastian Redl   QualType::DestructionKind dtorKind = arrayType.isDestructedType();
361c83ed824SSebastian Redl   if (!dtorKind)
362c83ed824SSebastian Redl     return; // Type doesn't need destroying.
363c83ed824SSebastian Redl   if (dtorKind != QualType::DK_cxx_destructor) {
364c83ed824SSebastian Redl     CGF.ErrorUnsupported(initList, "ObjC ARC type in initializer_list");
365c83ed824SSebastian Redl     return;
366c83ed824SSebastian Redl   }
367c83ed824SSebastian Redl 
368c83ed824SSebastian Redl   CodeGenFunction::Destroyer *destroyer = CGF.getDestroyer(dtorKind);
369c83ed824SSebastian Redl   CGF.pushDestroy(NormalAndEHCleanup, addr, arrayType, destroyer,
370c83ed824SSebastian Redl                   /*EHCleanup=*/true);
371c83ed824SSebastian Redl }
372c83ed824SSebastian Redl 
373c83ed824SSebastian Redl /// \brief Emit the initializer for a std::initializer_list initialized with a
374c83ed824SSebastian Redl /// real initializer list.
3758eb351d7SSebastian Redl void AggExprEmitter::EmitStdInitializerList(llvm::Value *destPtr,
3768eb351d7SSebastian Redl                                             InitListExpr *initList) {
377c83ed824SSebastian Redl   // We emit an array containing the elements, then have the init list point
378c83ed824SSebastian Redl   // at the array.
379c83ed824SSebastian Redl   ASTContext &ctx = CGF.getContext();
380c83ed824SSebastian Redl   unsigned numInits = initList->getNumInits();
381c83ed824SSebastian Redl   QualType element = GetStdInitializerListElementType(initList->getType());
382c83ed824SSebastian Redl   llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
383c83ed824SSebastian Redl   QualType array = ctx.getConstantArrayType(element, size, ArrayType::Normal,0);
384c83ed824SSebastian Redl   llvm::Type *LTy = CGF.ConvertTypeForMem(array);
385c83ed824SSebastian Redl   llvm::AllocaInst *alloc = CGF.CreateTempAlloca(LTy);
386c83ed824SSebastian Redl   alloc->setAlignment(ctx.getTypeAlignInChars(array).getQuantity());
387c83ed824SSebastian Redl   alloc->setName(".initlist.");
388c83ed824SSebastian Redl 
389c83ed824SSebastian Redl   EmitArrayInit(alloc, cast<llvm::ArrayType>(LTy), element, initList);
390c83ed824SSebastian Redl 
391c83ed824SSebastian Redl   // FIXME: The diagnostics are somewhat out of place here.
392c83ed824SSebastian Redl   RecordDecl *record = initList->getType()->castAs<RecordType>()->getDecl();
393c83ed824SSebastian Redl   RecordDecl::field_iterator field = record->field_begin();
394c83ed824SSebastian Redl   if (field == record->field_end()) {
395c83ed824SSebastian Redl     CGF.ErrorUnsupported(initList, "weird std::initializer_list");
396f2e0a307SSebastian Redl     return;
397c83ed824SSebastian Redl   }
398c83ed824SSebastian Redl 
399c83ed824SSebastian Redl   QualType elementPtr = ctx.getPointerType(element.withConst());
400c83ed824SSebastian Redl 
401c83ed824SSebastian Redl   // Start pointer.
402c83ed824SSebastian Redl   if (!ctx.hasSameType(field->getType(), elementPtr)) {
403c83ed824SSebastian Redl     CGF.ErrorUnsupported(initList, "weird std::initializer_list");
404f2e0a307SSebastian Redl     return;
405c83ed824SSebastian Redl   }
4067f1ff600SEli Friedman   LValue DestLV = CGF.MakeNaturalAlignAddrLValue(destPtr, initList->getType());
40740ed2973SDavid Blaikie   LValue start = CGF.EmitLValueForFieldInitialization(DestLV, *field);
408c83ed824SSebastian Redl   llvm::Value *arrayStart = Builder.CreateStructGEP(alloc, 0, "arraystart");
409c83ed824SSebastian Redl   CGF.EmitStoreThroughLValue(RValue::get(arrayStart), start);
410c83ed824SSebastian Redl   ++field;
411c83ed824SSebastian Redl 
412c83ed824SSebastian Redl   if (field == record->field_end()) {
413c83ed824SSebastian Redl     CGF.ErrorUnsupported(initList, "weird std::initializer_list");
414f2e0a307SSebastian Redl     return;
415c83ed824SSebastian Redl   }
41640ed2973SDavid Blaikie   LValue endOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *field);
417c83ed824SSebastian Redl   if (ctx.hasSameType(field->getType(), elementPtr)) {
418c83ed824SSebastian Redl     // End pointer.
419c83ed824SSebastian Redl     llvm::Value *arrayEnd = Builder.CreateStructGEP(alloc,numInits, "arrayend");
420c83ed824SSebastian Redl     CGF.EmitStoreThroughLValue(RValue::get(arrayEnd), endOrLength);
421c83ed824SSebastian Redl   } else if(ctx.hasSameType(field->getType(), ctx.getSizeType())) {
422c83ed824SSebastian Redl     // Length.
423c83ed824SSebastian Redl     CGF.EmitStoreThroughLValue(RValue::get(Builder.getInt(size)), endOrLength);
424c83ed824SSebastian Redl   } else {
425c83ed824SSebastian Redl     CGF.ErrorUnsupported(initList, "weird std::initializer_list");
426f2e0a307SSebastian Redl     return;
427c83ed824SSebastian Redl   }
428c83ed824SSebastian Redl 
429c83ed824SSebastian Redl   if (!Dest.isExternallyDestructed())
430c83ed824SSebastian Redl     EmitStdInitializerListCleanup(CGF, array, alloc, initList);
431c83ed824SSebastian Redl }
432c83ed824SSebastian Redl 
433c83ed824SSebastian Redl /// \brief Emit initialization of an array from an initializer list.
434c83ed824SSebastian Redl void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
435c83ed824SSebastian Redl                                    QualType elementType, InitListExpr *E) {
436c83ed824SSebastian Redl   uint64_t NumInitElements = E->getNumInits();
437c83ed824SSebastian Redl 
438c83ed824SSebastian Redl   uint64_t NumArrayElements = AType->getNumElements();
439c83ed824SSebastian Redl   assert(NumInitElements <= NumArrayElements);
440c83ed824SSebastian Redl 
441c83ed824SSebastian Redl   // DestPtr is an array*.  Construct an elementType* by drilling
442c83ed824SSebastian Redl   // down a level.
443c83ed824SSebastian Redl   llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
444c83ed824SSebastian Redl   llvm::Value *indices[] = { zero, zero };
445c83ed824SSebastian Redl   llvm::Value *begin =
446c83ed824SSebastian Redl     Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
447c83ed824SSebastian Redl 
448c83ed824SSebastian Redl   // Exception safety requires us to destroy all the
449c83ed824SSebastian Redl   // already-constructed members if an initializer throws.
450c83ed824SSebastian Redl   // For that, we'll need an EH cleanup.
451c83ed824SSebastian Redl   QualType::DestructionKind dtorKind = elementType.isDestructedType();
452c83ed824SSebastian Redl   llvm::AllocaInst *endOfInit = 0;
453c83ed824SSebastian Redl   EHScopeStack::stable_iterator cleanup;
454c83ed824SSebastian Redl   llvm::Instruction *cleanupDominator = 0;
455c83ed824SSebastian Redl   if (CGF.needsEHCleanup(dtorKind)) {
456c83ed824SSebastian Redl     // In principle we could tell the cleanup where we are more
457c83ed824SSebastian Redl     // directly, but the control flow can get so varied here that it
458c83ed824SSebastian Redl     // would actually be quite complex.  Therefore we go through an
459c83ed824SSebastian Redl     // alloca.
460c83ed824SSebastian Redl     endOfInit = CGF.CreateTempAlloca(begin->getType(),
461c83ed824SSebastian Redl                                      "arrayinit.endOfInit");
462c83ed824SSebastian Redl     cleanupDominator = Builder.CreateStore(begin, endOfInit);
463c83ed824SSebastian Redl     CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
464c83ed824SSebastian Redl                                          CGF.getDestroyer(dtorKind));
465c83ed824SSebastian Redl     cleanup = CGF.EHStack.stable_begin();
466c83ed824SSebastian Redl 
467c83ed824SSebastian Redl   // Otherwise, remember that we didn't need a cleanup.
468c83ed824SSebastian Redl   } else {
469c83ed824SSebastian Redl     dtorKind = QualType::DK_none;
470c83ed824SSebastian Redl   }
471c83ed824SSebastian Redl 
472c83ed824SSebastian Redl   llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
473c83ed824SSebastian Redl 
474c83ed824SSebastian Redl   // The 'current element to initialize'.  The invariants on this
475c83ed824SSebastian Redl   // variable are complicated.  Essentially, after each iteration of
476c83ed824SSebastian Redl   // the loop, it points to the last initialized element, except
477c83ed824SSebastian Redl   // that it points to the beginning of the array before any
478c83ed824SSebastian Redl   // elements have been initialized.
479c83ed824SSebastian Redl   llvm::Value *element = begin;
480c83ed824SSebastian Redl 
481c83ed824SSebastian Redl   // Emit the explicit initializers.
482c83ed824SSebastian Redl   for (uint64_t i = 0; i != NumInitElements; ++i) {
483c83ed824SSebastian Redl     // Advance to the next element.
484c83ed824SSebastian Redl     if (i > 0) {
485c83ed824SSebastian Redl       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
486c83ed824SSebastian Redl 
487c83ed824SSebastian Redl       // Tell the cleanup that it needs to destroy up to this
488c83ed824SSebastian Redl       // element.  TODO: some of these stores can be trivially
489c83ed824SSebastian Redl       // observed to be unnecessary.
490c83ed824SSebastian Redl       if (endOfInit) Builder.CreateStore(element, endOfInit);
491c83ed824SSebastian Redl     }
492c83ed824SSebastian Redl 
4938eb351d7SSebastian Redl     // If these are nested std::initializer_list inits, do them directly,
4948eb351d7SSebastian Redl     // because they are conceptually the same "location".
4958eb351d7SSebastian Redl     InitListExpr *initList = dyn_cast<InitListExpr>(E->getInit(i));
4968eb351d7SSebastian Redl     if (initList && initList->initializesStdInitializerList()) {
4978eb351d7SSebastian Redl       EmitStdInitializerList(element, initList);
4988eb351d7SSebastian Redl     } else {
499c83ed824SSebastian Redl       LValue elementLV = CGF.MakeAddrLValue(element, elementType);
500615ed1a3SChad Rosier       EmitInitializationToLValue(E->getInit(i), elementLV);
501c83ed824SSebastian Redl     }
5028eb351d7SSebastian Redl   }
503c83ed824SSebastian Redl 
504c83ed824SSebastian Redl   // Check whether there's a non-trivial array-fill expression.
505c83ed824SSebastian Redl   // Note that this will be a CXXConstructExpr even if the element
506c83ed824SSebastian Redl   // type is an array (or array of array, etc.) of class type.
507c83ed824SSebastian Redl   Expr *filler = E->getArrayFiller();
508c83ed824SSebastian Redl   bool hasTrivialFiller = true;
509c83ed824SSebastian Redl   if (CXXConstructExpr *cons = dyn_cast_or_null<CXXConstructExpr>(filler)) {
510c83ed824SSebastian Redl     assert(cons->getConstructor()->isDefaultConstructor());
511c83ed824SSebastian Redl     hasTrivialFiller = cons->getConstructor()->isTrivial();
512c83ed824SSebastian Redl   }
513c83ed824SSebastian Redl 
514c83ed824SSebastian Redl   // Any remaining elements need to be zero-initialized, possibly
515c83ed824SSebastian Redl   // using the filler expression.  We can skip this if the we're
516c83ed824SSebastian Redl   // emitting to zeroed memory.
517c83ed824SSebastian Redl   if (NumInitElements != NumArrayElements &&
518c83ed824SSebastian Redl       !(Dest.isZeroed() && hasTrivialFiller &&
519c83ed824SSebastian Redl         CGF.getTypes().isZeroInitializable(elementType))) {
520c83ed824SSebastian Redl 
521c83ed824SSebastian Redl     // Use an actual loop.  This is basically
522c83ed824SSebastian Redl     //   do { *array++ = filler; } while (array != end);
523c83ed824SSebastian Redl 
524c83ed824SSebastian Redl     // Advance to the start of the rest of the array.
525c83ed824SSebastian Redl     if (NumInitElements) {
526c83ed824SSebastian Redl       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
527c83ed824SSebastian Redl       if (endOfInit) Builder.CreateStore(element, endOfInit);
528c83ed824SSebastian Redl     }
529c83ed824SSebastian Redl 
530c83ed824SSebastian Redl     // Compute the end of the array.
531c83ed824SSebastian Redl     llvm::Value *end = Builder.CreateInBoundsGEP(begin,
532c83ed824SSebastian Redl                       llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
533c83ed824SSebastian Redl                                                  "arrayinit.end");
534c83ed824SSebastian Redl 
535c83ed824SSebastian Redl     llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
536c83ed824SSebastian Redl     llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
537c83ed824SSebastian Redl 
538c83ed824SSebastian Redl     // Jump into the body.
539c83ed824SSebastian Redl     CGF.EmitBlock(bodyBB);
540c83ed824SSebastian Redl     llvm::PHINode *currentElement =
541c83ed824SSebastian Redl       Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
542c83ed824SSebastian Redl     currentElement->addIncoming(element, entryBB);
543c83ed824SSebastian Redl 
544c83ed824SSebastian Redl     // Emit the actual filler expression.
545c83ed824SSebastian Redl     LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
546c83ed824SSebastian Redl     if (filler)
547615ed1a3SChad Rosier       EmitInitializationToLValue(filler, elementLV);
548c83ed824SSebastian Redl     else
549c83ed824SSebastian Redl       EmitNullInitializationToLValue(elementLV);
550c83ed824SSebastian Redl 
551c83ed824SSebastian Redl     // Move on to the next element.
552c83ed824SSebastian Redl     llvm::Value *nextElement =
553c83ed824SSebastian Redl       Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
554c83ed824SSebastian Redl 
555c83ed824SSebastian Redl     // Tell the EH cleanup that we finished with the last element.
556c83ed824SSebastian Redl     if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
557c83ed824SSebastian Redl 
558c83ed824SSebastian Redl     // Leave the loop if we're done.
559c83ed824SSebastian Redl     llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
560c83ed824SSebastian Redl                                              "arrayinit.done");
561c83ed824SSebastian Redl     llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
562c83ed824SSebastian Redl     Builder.CreateCondBr(done, endBB, bodyBB);
563c83ed824SSebastian Redl     currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
564c83ed824SSebastian Redl 
565c83ed824SSebastian Redl     CGF.EmitBlock(endBB);
566c83ed824SSebastian Redl   }
567c83ed824SSebastian Redl 
568c83ed824SSebastian Redl   // Leave the partial-array cleanup if we entered one.
569c83ed824SSebastian Redl   if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
570c83ed824SSebastian Redl }
571c83ed824SSebastian Redl 
5727a51313dSChris Lattner //===----------------------------------------------------------------------===//
5737a51313dSChris Lattner //                            Visitor Methods
5747a51313dSChris Lattner //===----------------------------------------------------------------------===//
5757a51313dSChris Lattner 
576fe31481fSDouglas Gregor void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
577fe31481fSDouglas Gregor   Visit(E->GetTemporaryExpr());
578fe31481fSDouglas Gregor }
579fe31481fSDouglas Gregor 
5801bf5846aSJohn McCall void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
5814e8ca4faSJohn McCall   EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e));
5821bf5846aSJohn McCall }
5831bf5846aSJohn McCall 
5849b71f0cfSDouglas Gregor void
5859b71f0cfSDouglas Gregor AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
586bea4c3d8SJohn McCall   if (Dest.isPotentiallyAliased() &&
587bea4c3d8SJohn McCall       E->getType().isPODType(CGF.getContext())) {
5886c9d31ebSDouglas Gregor     // For a POD type, just emit a load of the lvalue + a copy, because our
5896c9d31ebSDouglas Gregor     // compound literal might alias the destination.
5906c9d31ebSDouglas Gregor     EmitAggLoadOfLValue(E);
5916c9d31ebSDouglas Gregor     return;
5926c9d31ebSDouglas Gregor   }
5936c9d31ebSDouglas Gregor 
5949b71f0cfSDouglas Gregor   AggValueSlot Slot = EnsureSlot(E->getType());
5959b71f0cfSDouglas Gregor   CGF.EmitAggExpr(E->getInitializer(), Slot);
5969b71f0cfSDouglas Gregor }
5979b71f0cfSDouglas Gregor 
598a8ec7eb9SJohn McCall /// Attempt to look through various unimportant expressions to find a
599a8ec7eb9SJohn McCall /// cast of the given kind.
600a8ec7eb9SJohn McCall static Expr *findPeephole(Expr *op, CastKind kind) {
601a8ec7eb9SJohn McCall   while (true) {
602a8ec7eb9SJohn McCall     op = op->IgnoreParens();
603a8ec7eb9SJohn McCall     if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
604a8ec7eb9SJohn McCall       if (castE->getCastKind() == kind)
605a8ec7eb9SJohn McCall         return castE->getSubExpr();
606a8ec7eb9SJohn McCall       if (castE->getCastKind() == CK_NoOp)
607a8ec7eb9SJohn McCall         continue;
608a8ec7eb9SJohn McCall     }
609a8ec7eb9SJohn McCall     return 0;
610a8ec7eb9SJohn McCall   }
611a8ec7eb9SJohn McCall }
6129b71f0cfSDouglas Gregor 
613ec143777SAnders Carlsson void AggExprEmitter::VisitCastExpr(CastExpr *E) {
6141fb7ae9eSAnders Carlsson   switch (E->getCastKind()) {
6158a01a751SAnders Carlsson   case CK_Dynamic: {
61669d0d262SRichard Smith     // FIXME: Can this actually happen? We have no test coverage for it.
6171c073f47SDouglas Gregor     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
61869d0d262SRichard Smith     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
6194d1458edSRichard Smith                                       CodeGenFunction::TCK_Load);
6201c073f47SDouglas Gregor     // FIXME: Do we also need to handle property references here?
6211c073f47SDouglas Gregor     if (LV.isSimple())
6221c073f47SDouglas Gregor       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
6231c073f47SDouglas Gregor     else
6241c073f47SDouglas Gregor       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
6251c073f47SDouglas Gregor 
6267a626f63SJohn McCall     if (!Dest.isIgnored())
6271c073f47SDouglas Gregor       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
6281c073f47SDouglas Gregor     break;
6291c073f47SDouglas Gregor   }
6301c073f47SDouglas Gregor 
631e302792bSJohn McCall   case CK_ToUnion: {
63258989b71SJohn McCall     if (Dest.isIgnored()) break;
63358989b71SJohn McCall 
6347ffcf93bSNuno Lopes     // GCC union extension
6352e442a00SDaniel Dunbar     QualType Ty = E->getSubExpr()->getType();
6362e442a00SDaniel Dunbar     QualType PtrTy = CGF.getContext().getPointerType(Ty);
6377a626f63SJohn McCall     llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
638dd274848SEli Friedman                                                  CGF.ConvertType(PtrTy));
6391553b190SJohn McCall     EmitInitializationToLValue(E->getSubExpr(),
640615ed1a3SChad Rosier                                CGF.MakeAddrLValue(CastPtr, Ty));
6411fb7ae9eSAnders Carlsson     break;
6427ffcf93bSNuno Lopes   }
6437ffcf93bSNuno Lopes 
644e302792bSJohn McCall   case CK_DerivedToBase:
645e302792bSJohn McCall   case CK_BaseToDerived:
646e302792bSJohn McCall   case CK_UncheckedDerivedToBase: {
64783d382b1SDavid Blaikie     llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
648aae38d66SDouglas Gregor                 "should have been unpacked before we got here");
649aae38d66SDouglas Gregor   }
650aae38d66SDouglas Gregor 
651a8ec7eb9SJohn McCall   case CK_NonAtomicToAtomic:
652a8ec7eb9SJohn McCall   case CK_AtomicToNonAtomic: {
653a8ec7eb9SJohn McCall     bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
654a8ec7eb9SJohn McCall 
655a8ec7eb9SJohn McCall     // Determine the atomic and value types.
656a8ec7eb9SJohn McCall     QualType atomicType = E->getSubExpr()->getType();
657a8ec7eb9SJohn McCall     QualType valueType = E->getType();
658a8ec7eb9SJohn McCall     if (isToAtomic) std::swap(atomicType, valueType);
659a8ec7eb9SJohn McCall 
660a8ec7eb9SJohn McCall     assert(atomicType->isAtomicType());
661a8ec7eb9SJohn McCall     assert(CGF.getContext().hasSameUnqualifiedType(valueType,
662a8ec7eb9SJohn McCall                           atomicType->castAs<AtomicType>()->getValueType()));
663a8ec7eb9SJohn McCall 
664a8ec7eb9SJohn McCall     // Just recurse normally if we're ignoring the result or the
665a8ec7eb9SJohn McCall     // atomic type doesn't change representation.
666a8ec7eb9SJohn McCall     if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
667a8ec7eb9SJohn McCall       return Visit(E->getSubExpr());
668a8ec7eb9SJohn McCall     }
669a8ec7eb9SJohn McCall 
670a8ec7eb9SJohn McCall     CastKind peepholeTarget =
671a8ec7eb9SJohn McCall       (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
672a8ec7eb9SJohn McCall 
673a8ec7eb9SJohn McCall     // These two cases are reverses of each other; try to peephole them.
674a8ec7eb9SJohn McCall     if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
675a8ec7eb9SJohn McCall       assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
676a8ec7eb9SJohn McCall                                                      E->getType()) &&
677a8ec7eb9SJohn McCall            "peephole significantly changed types?");
678a8ec7eb9SJohn McCall       return Visit(op);
679a8ec7eb9SJohn McCall     }
680a8ec7eb9SJohn McCall 
681a8ec7eb9SJohn McCall     // If we're converting an r-value of non-atomic type to an r-value
682a8ec7eb9SJohn McCall     // of atomic type, just make an atomic temporary, emit into that,
683a8ec7eb9SJohn McCall     // and then copy the value out.  (FIXME: do we need to
684a8ec7eb9SJohn McCall     // zero-initialize it first?)
685a8ec7eb9SJohn McCall     if (isToAtomic) {
686a8ec7eb9SJohn McCall       ValueDestForAtomic valueDest(CGF, Dest, atomicType);
687a8ec7eb9SJohn McCall       CGF.EmitAggExpr(E->getSubExpr(), valueDest.getDest());
688a8ec7eb9SJohn McCall       return;
689a8ec7eb9SJohn McCall     }
690a8ec7eb9SJohn McCall 
691a8ec7eb9SJohn McCall     // Otherwise, we're converting an atomic type to a non-atomic type.
692a8ec7eb9SJohn McCall 
693a8ec7eb9SJohn McCall     // If the dest is a value-of-atomic subobject, drill back out.
694a8ec7eb9SJohn McCall     if (Dest.isValueOfAtomic()) {
695a8ec7eb9SJohn McCall       AggValueSlot atomicSlot =
696a8ec7eb9SJohn McCall         AggValueSlot::forAddr(Dest.getPaddedAtomicAddr(),
697a8ec7eb9SJohn McCall                               Dest.getAlignment(),
698a8ec7eb9SJohn McCall                               Dest.getQualifiers(),
699a8ec7eb9SJohn McCall                               Dest.isExternallyDestructed(),
700a8ec7eb9SJohn McCall                               Dest.requiresGCollection(),
701a8ec7eb9SJohn McCall                               Dest.isPotentiallyAliased(),
702a8ec7eb9SJohn McCall                               Dest.isZeroed(),
703a8ec7eb9SJohn McCall                               AggValueSlot::IsNotValueOfAtomic);
704a8ec7eb9SJohn McCall       CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
705a8ec7eb9SJohn McCall       return;
706a8ec7eb9SJohn McCall     }
707a8ec7eb9SJohn McCall 
708a8ec7eb9SJohn McCall     // Otherwise, make an atomic temporary, emit into that, and then
709a8ec7eb9SJohn McCall     // copy the value out.
710a8ec7eb9SJohn McCall     AggValueSlot atomicSlot =
711a8ec7eb9SJohn McCall       CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
712a8ec7eb9SJohn McCall     CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
713a8ec7eb9SJohn McCall 
714a8ec7eb9SJohn McCall     llvm::Value *valueAddr =
715a8ec7eb9SJohn McCall       Builder.CreateStructGEP(atomicSlot.getAddr(), 0);
716a8ec7eb9SJohn McCall     RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
717a8ec7eb9SJohn McCall     return EmitFinalDestCopy(valueType, rvalue);
718a8ec7eb9SJohn McCall   }
719a8ec7eb9SJohn McCall 
7204e8ca4faSJohn McCall   case CK_LValueToRValue:
7214e8ca4faSJohn McCall     // If we're loading from a volatile type, force the destination
7224e8ca4faSJohn McCall     // into existence.
7234e8ca4faSJohn McCall     if (E->getSubExpr()->getType().isVolatileQualified()) {
7244e8ca4faSJohn McCall       EnsureDest(E->getType());
7254e8ca4faSJohn McCall       return Visit(E->getSubExpr());
7264e8ca4faSJohn McCall     }
727a8ec7eb9SJohn McCall 
7284e8ca4faSJohn McCall     // fallthrough
7294e8ca4faSJohn McCall 
730e302792bSJohn McCall   case CK_NoOp:
731e302792bSJohn McCall   case CK_UserDefinedConversion:
732e302792bSJohn McCall   case CK_ConstructorConversion:
7332a69547fSEli Friedman     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
7342a69547fSEli Friedman                                                    E->getType()) &&
7350f398c44SChris Lattner            "Implicit cast types must be compatible");
7367a51313dSChris Lattner     Visit(E->getSubExpr());
7371fb7ae9eSAnders Carlsson     break;
738b05a3e55SAnders Carlsson 
739e302792bSJohn McCall   case CK_LValueBitCast:
740f3735e01SJohn McCall     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
74131996343SJohn McCall 
742f3735e01SJohn McCall   case CK_Dependent:
743f3735e01SJohn McCall   case CK_BitCast:
744f3735e01SJohn McCall   case CK_ArrayToPointerDecay:
745f3735e01SJohn McCall   case CK_FunctionToPointerDecay:
746f3735e01SJohn McCall   case CK_NullToPointer:
747f3735e01SJohn McCall   case CK_NullToMemberPointer:
748f3735e01SJohn McCall   case CK_BaseToDerivedMemberPointer:
749f3735e01SJohn McCall   case CK_DerivedToBaseMemberPointer:
750f3735e01SJohn McCall   case CK_MemberPointerToBoolean:
751c62bb391SJohn McCall   case CK_ReinterpretMemberPointer:
752f3735e01SJohn McCall   case CK_IntegralToPointer:
753f3735e01SJohn McCall   case CK_PointerToIntegral:
754f3735e01SJohn McCall   case CK_PointerToBoolean:
755f3735e01SJohn McCall   case CK_ToVoid:
756f3735e01SJohn McCall   case CK_VectorSplat:
757f3735e01SJohn McCall   case CK_IntegralCast:
758f3735e01SJohn McCall   case CK_IntegralToBoolean:
759f3735e01SJohn McCall   case CK_IntegralToFloating:
760f3735e01SJohn McCall   case CK_FloatingToIntegral:
761f3735e01SJohn McCall   case CK_FloatingToBoolean:
762f3735e01SJohn McCall   case CK_FloatingCast:
7639320b87cSJohn McCall   case CK_CPointerToObjCPointerCast:
7649320b87cSJohn McCall   case CK_BlockPointerToObjCPointerCast:
765f3735e01SJohn McCall   case CK_AnyPointerToBlockPointerCast:
766f3735e01SJohn McCall   case CK_ObjCObjectLValueCast:
767f3735e01SJohn McCall   case CK_FloatingRealToComplex:
768f3735e01SJohn McCall   case CK_FloatingComplexToReal:
769f3735e01SJohn McCall   case CK_FloatingComplexToBoolean:
770f3735e01SJohn McCall   case CK_FloatingComplexCast:
771f3735e01SJohn McCall   case CK_FloatingComplexToIntegralComplex:
772f3735e01SJohn McCall   case CK_IntegralRealToComplex:
773f3735e01SJohn McCall   case CK_IntegralComplexToReal:
774f3735e01SJohn McCall   case CK_IntegralComplexToBoolean:
775f3735e01SJohn McCall   case CK_IntegralComplexCast:
776f3735e01SJohn McCall   case CK_IntegralComplexToFloatingComplex:
7772d637d2eSJohn McCall   case CK_ARCProduceObject:
7782d637d2eSJohn McCall   case CK_ARCConsumeObject:
7792d637d2eSJohn McCall   case CK_ARCReclaimReturnedObject:
7802d637d2eSJohn McCall   case CK_ARCExtendBlockObject:
781ed90df38SDouglas Gregor   case CK_CopyAndAutoreleaseBlockObject:
78234866c77SEli Friedman   case CK_BuiltinFnToFnPtr:
7831b4fb3e0SGuy Benyei   case CK_ZeroToOCLEvent:
784f3735e01SJohn McCall     llvm_unreachable("cast kind invalid for aggregate types");
7851fb7ae9eSAnders Carlsson   }
7867a51313dSChris Lattner }
7877a51313dSChris Lattner 
7880f398c44SChris Lattner void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
789ddcbfe7bSAnders Carlsson   if (E->getCallReturnType()->isReferenceType()) {
790ddcbfe7bSAnders Carlsson     EmitAggLoadOfLValue(E);
791ddcbfe7bSAnders Carlsson     return;
792ddcbfe7bSAnders Carlsson   }
793ddcbfe7bSAnders Carlsson 
794cc04e9f6SJohn McCall   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
795a5efa738SJohn McCall   EmitMoveFromReturnSlot(E, RV);
7967a51313dSChris Lattner }
7970f398c44SChris Lattner 
7980f398c44SChris Lattner void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
799cc04e9f6SJohn McCall   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
800a5efa738SJohn McCall   EmitMoveFromReturnSlot(E, RV);
801b1d329daSChris Lattner }
8027a51313dSChris Lattner 
8030f398c44SChris Lattner void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
804a2342eb8SJohn McCall   CGF.EmitIgnoredExpr(E->getLHS());
8057a626f63SJohn McCall   Visit(E->getRHS());
8064b0e2a30SEli Friedman }
8074b0e2a30SEli Friedman 
8087a51313dSChris Lattner void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
809ce1de617SJohn McCall   CodeGenFunction::StmtExprEvaluation eval(CGF);
8107a626f63SJohn McCall   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
8117a51313dSChris Lattner }
8127a51313dSChris Lattner 
8137a51313dSChris Lattner void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
814e302792bSJohn McCall   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
815ffba662dSFariborz Jahanian     VisitPointerToDataMemberBinaryOperator(E);
816ffba662dSFariborz Jahanian   else
817a7c8cf62SDaniel Dunbar     CGF.ErrorUnsupported(E, "aggregate binary expression");
8187a51313dSChris Lattner }
8197a51313dSChris Lattner 
820ffba662dSFariborz Jahanian void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
821ffba662dSFariborz Jahanian                                                     const BinaryOperator *E) {
822ffba662dSFariborz Jahanian   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
8234e8ca4faSJohn McCall   EmitFinalDestCopy(E->getType(), LV);
8244e8ca4faSJohn McCall }
8254e8ca4faSJohn McCall 
8264e8ca4faSJohn McCall /// Is the value of the given expression possibly a reference to or
8274e8ca4faSJohn McCall /// into a __block variable?
8284e8ca4faSJohn McCall static bool isBlockVarRef(const Expr *E) {
8294e8ca4faSJohn McCall   // Make sure we look through parens.
8304e8ca4faSJohn McCall   E = E->IgnoreParens();
8314e8ca4faSJohn McCall 
8324e8ca4faSJohn McCall   // Check for a direct reference to a __block variable.
8334e8ca4faSJohn McCall   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8344e8ca4faSJohn McCall     const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8354e8ca4faSJohn McCall     return (var && var->hasAttr<BlocksAttr>());
8364e8ca4faSJohn McCall   }
8374e8ca4faSJohn McCall 
8384e8ca4faSJohn McCall   // More complicated stuff.
8394e8ca4faSJohn McCall 
8404e8ca4faSJohn McCall   // Binary operators.
8414e8ca4faSJohn McCall   if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
8424e8ca4faSJohn McCall     // For an assignment or pointer-to-member operation, just care
8434e8ca4faSJohn McCall     // about the LHS.
8444e8ca4faSJohn McCall     if (op->isAssignmentOp() || op->isPtrMemOp())
8454e8ca4faSJohn McCall       return isBlockVarRef(op->getLHS());
8464e8ca4faSJohn McCall 
8474e8ca4faSJohn McCall     // For a comma, just care about the RHS.
8484e8ca4faSJohn McCall     if (op->getOpcode() == BO_Comma)
8494e8ca4faSJohn McCall       return isBlockVarRef(op->getRHS());
8504e8ca4faSJohn McCall 
8514e8ca4faSJohn McCall     // FIXME: pointer arithmetic?
8524e8ca4faSJohn McCall     return false;
8534e8ca4faSJohn McCall 
8544e8ca4faSJohn McCall   // Check both sides of a conditional operator.
8554e8ca4faSJohn McCall   } else if (const AbstractConditionalOperator *op
8564e8ca4faSJohn McCall                = dyn_cast<AbstractConditionalOperator>(E)) {
8574e8ca4faSJohn McCall     return isBlockVarRef(op->getTrueExpr())
8584e8ca4faSJohn McCall         || isBlockVarRef(op->getFalseExpr());
8594e8ca4faSJohn McCall 
8604e8ca4faSJohn McCall   // OVEs are required to support BinaryConditionalOperators.
8614e8ca4faSJohn McCall   } else if (const OpaqueValueExpr *op
8624e8ca4faSJohn McCall                = dyn_cast<OpaqueValueExpr>(E)) {
8634e8ca4faSJohn McCall     if (const Expr *src = op->getSourceExpr())
8644e8ca4faSJohn McCall       return isBlockVarRef(src);
8654e8ca4faSJohn McCall 
8664e8ca4faSJohn McCall   // Casts are necessary to get things like (*(int*)&var) = foo().
8674e8ca4faSJohn McCall   // We don't really care about the kind of cast here, except
8684e8ca4faSJohn McCall   // we don't want to look through l2r casts, because it's okay
8694e8ca4faSJohn McCall   // to get the *value* in a __block variable.
8704e8ca4faSJohn McCall   } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
8714e8ca4faSJohn McCall     if (cast->getCastKind() == CK_LValueToRValue)
8724e8ca4faSJohn McCall       return false;
8734e8ca4faSJohn McCall     return isBlockVarRef(cast->getSubExpr());
8744e8ca4faSJohn McCall 
8754e8ca4faSJohn McCall   // Handle unary operators.  Again, just aggressively look through
8764e8ca4faSJohn McCall   // it, ignoring the operation.
8774e8ca4faSJohn McCall   } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
8784e8ca4faSJohn McCall     return isBlockVarRef(uop->getSubExpr());
8794e8ca4faSJohn McCall 
8804e8ca4faSJohn McCall   // Look into the base of a field access.
8814e8ca4faSJohn McCall   } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
8824e8ca4faSJohn McCall     return isBlockVarRef(mem->getBase());
8834e8ca4faSJohn McCall 
8844e8ca4faSJohn McCall   // Look into the base of a subscript.
8854e8ca4faSJohn McCall   } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
8864e8ca4faSJohn McCall     return isBlockVarRef(sub->getBase());
8874e8ca4faSJohn McCall   }
8884e8ca4faSJohn McCall 
8894e8ca4faSJohn McCall   return false;
890ffba662dSFariborz Jahanian }
891ffba662dSFariborz Jahanian 
8927a51313dSChris Lattner void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
8937a51313dSChris Lattner   // For an assignment to work, the value on the right has
8947a51313dSChris Lattner   // to be compatible with the value on the left.
8952a69547fSEli Friedman   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
8962a69547fSEli Friedman                                                  E->getRHS()->getType())
8977a51313dSChris Lattner          && "Invalid assignment");
898d0a30016SJohn McCall 
8994e8ca4faSJohn McCall   // If the LHS might be a __block variable, and the RHS can
9004e8ca4faSJohn McCall   // potentially cause a block copy, we need to evaluate the RHS first
9014e8ca4faSJohn McCall   // so that the assignment goes the right place.
9024e8ca4faSJohn McCall   // This is pretty semantically fragile.
9034e8ca4faSJohn McCall   if (isBlockVarRef(E->getLHS()) &&
90499514b91SFariborz Jahanian       E->getRHS()->HasSideEffects(CGF.getContext())) {
9054e8ca4faSJohn McCall     // Ensure that we have a destination, and evaluate the RHS into that.
9064e8ca4faSJohn McCall     EnsureDest(E->getRHS()->getType());
9074e8ca4faSJohn McCall     Visit(E->getRHS());
9084e8ca4faSJohn McCall 
9094e8ca4faSJohn McCall     // Now emit the LHS and copy into it.
910e30752c9SRichard Smith     LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
9114e8ca4faSJohn McCall 
912a8ec7eb9SJohn McCall     // That copy is an atomic copy if the LHS is atomic.
913a8ec7eb9SJohn McCall     if (LHS.getType()->isAtomicType()) {
914a8ec7eb9SJohn McCall       CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
915a8ec7eb9SJohn McCall       return;
916a8ec7eb9SJohn McCall     }
917a8ec7eb9SJohn McCall 
9184e8ca4faSJohn McCall     EmitCopy(E->getLHS()->getType(),
9194e8ca4faSJohn McCall              AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
92046759f4fSJohn McCall                                      needsGC(E->getLHS()->getType()),
9214e8ca4faSJohn McCall                                      AggValueSlot::IsAliased),
9224e8ca4faSJohn McCall              Dest);
92399514b91SFariborz Jahanian     return;
92499514b91SFariborz Jahanian   }
92599514b91SFariborz Jahanian 
9267a51313dSChris Lattner   LValue LHS = CGF.EmitLValue(E->getLHS());
9277a51313dSChris Lattner 
928a8ec7eb9SJohn McCall   // If we have an atomic type, evaluate into the destination and then
929a8ec7eb9SJohn McCall   // do an atomic copy.
930a8ec7eb9SJohn McCall   if (LHS.getType()->isAtomicType()) {
931a8ec7eb9SJohn McCall     EnsureDest(E->getRHS()->getType());
932a8ec7eb9SJohn McCall     Visit(E->getRHS());
933a8ec7eb9SJohn McCall     CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
934a8ec7eb9SJohn McCall     return;
935a8ec7eb9SJohn McCall   }
936a8ec7eb9SJohn McCall 
9377a51313dSChris Lattner   // Codegen the RHS so that it stores directly into the LHS.
9388d6fc958SJohn McCall   AggValueSlot LHSSlot =
9398d6fc958SJohn McCall     AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
94046759f4fSJohn McCall                             needsGC(E->getLHS()->getType()),
941615ed1a3SChad Rosier                             AggValueSlot::IsAliased);
9427865220dSFariborz Jahanian   // A non-volatile aggregate destination might have volatile member.
9437865220dSFariborz Jahanian   if (!LHSSlot.isVolatile() &&
9447865220dSFariborz Jahanian       CGF.hasVolatileMember(E->getLHS()->getType()))
9457865220dSFariborz Jahanian     LHSSlot.setVolatile(true);
9467865220dSFariborz Jahanian 
9474e8ca4faSJohn McCall   CGF.EmitAggExpr(E->getRHS(), LHSSlot);
9484e8ca4faSJohn McCall 
9494e8ca4faSJohn McCall   // Copy into the destination if the assignment isn't ignored.
9504e8ca4faSJohn McCall   EmitFinalDestCopy(E->getType(), LHS);
9517a51313dSChris Lattner }
9527a51313dSChris Lattner 
953c07a0c7eSJohn McCall void AggExprEmitter::
954c07a0c7eSJohn McCall VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
955a612e79bSDaniel Dunbar   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
956a612e79bSDaniel Dunbar   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
957a612e79bSDaniel Dunbar   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
9587a51313dSChris Lattner 
959c07a0c7eSJohn McCall   // Bind the common expression if necessary.
96048fd89adSEli Friedman   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
961c07a0c7eSJohn McCall 
962ce1de617SJohn McCall   CodeGenFunction::ConditionalEvaluation eval(CGF);
963b8841af8SEli Friedman   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
9647a51313dSChris Lattner 
9655b26f65bSJohn McCall   // Save whether the destination's lifetime is externally managed.
966cac93853SJohn McCall   bool isExternallyDestructed = Dest.isExternallyDestructed();
9677a51313dSChris Lattner 
968ce1de617SJohn McCall   eval.begin(CGF);
969ce1de617SJohn McCall   CGF.EmitBlock(LHSBlock);
970c07a0c7eSJohn McCall   Visit(E->getTrueExpr());
971ce1de617SJohn McCall   eval.end(CGF);
9727a51313dSChris Lattner 
973ce1de617SJohn McCall   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
974ce1de617SJohn McCall   CGF.Builder.CreateBr(ContBlock);
9757a51313dSChris Lattner 
9765b26f65bSJohn McCall   // If the result of an agg expression is unused, then the emission
9775b26f65bSJohn McCall   // of the LHS might need to create a destination slot.  That's fine
9785b26f65bSJohn McCall   // with us, and we can safely emit the RHS into the same slot, but
979cac93853SJohn McCall   // we shouldn't claim that it's already being destructed.
980cac93853SJohn McCall   Dest.setExternallyDestructed(isExternallyDestructed);
9815b26f65bSJohn McCall 
982ce1de617SJohn McCall   eval.begin(CGF);
983ce1de617SJohn McCall   CGF.EmitBlock(RHSBlock);
984c07a0c7eSJohn McCall   Visit(E->getFalseExpr());
985ce1de617SJohn McCall   eval.end(CGF);
9867a51313dSChris Lattner 
9877a51313dSChris Lattner   CGF.EmitBlock(ContBlock);
9887a51313dSChris Lattner }
9897a51313dSChris Lattner 
9905b2095ceSAnders Carlsson void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
9915b2095ceSAnders Carlsson   Visit(CE->getChosenSubExpr(CGF.getContext()));
9925b2095ceSAnders Carlsson }
9935b2095ceSAnders Carlsson 
99421911e89SEli Friedman void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
995e9fcadd2SDaniel Dunbar   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
99613abd7e9SAnders Carlsson   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
99713abd7e9SAnders Carlsson 
998020cddcfSSebastian Redl   if (!ArgPtr) {
99913abd7e9SAnders Carlsson     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
1000020cddcfSSebastian Redl     return;
1001020cddcfSSebastian Redl   }
100213abd7e9SAnders Carlsson 
10034e8ca4faSJohn McCall   EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
100421911e89SEli Friedman }
100521911e89SEli Friedman 
10063be22e27SAnders Carlsson void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
10077a626f63SJohn McCall   // Ensure that we have a slot, but if we already do, remember
1008cac93853SJohn McCall   // whether it was externally destructed.
1009cac93853SJohn McCall   bool wasExternallyDestructed = Dest.isExternallyDestructed();
10104e8ca4faSJohn McCall   EnsureDest(E->getType());
1011cac93853SJohn McCall 
1012cac93853SJohn McCall   // We're going to push a destructor if there isn't already one.
1013cac93853SJohn McCall   Dest.setExternallyDestructed();
10143be22e27SAnders Carlsson 
10153be22e27SAnders Carlsson   Visit(E->getSubExpr());
10163be22e27SAnders Carlsson 
1017cac93853SJohn McCall   // Push that destructor we promised.
1018cac93853SJohn McCall   if (!wasExternallyDestructed)
1019702b2841SPeter Collingbourne     CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
10203be22e27SAnders Carlsson }
10213be22e27SAnders Carlsson 
1022b7f8f594SAnders Carlsson void
10231619a504SAnders Carlsson AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10247a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(E->getType());
10257a626f63SJohn McCall   CGF.EmitCXXConstructExpr(E, Slot);
1026c82b86dfSAnders Carlsson }
1027c82b86dfSAnders Carlsson 
1028c370a7eeSEli Friedman void
1029c370a7eeSEli Friedman AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1030c370a7eeSEli Friedman   AggValueSlot Slot = EnsureSlot(E->getType());
1031c370a7eeSEli Friedman   CGF.EmitLambdaExpr(E, Slot);
1032c370a7eeSEli Friedman }
1033c370a7eeSEli Friedman 
10345d413781SJohn McCall void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
103508ef4660SJohn McCall   CGF.enterFullExpression(E);
103608ef4660SJohn McCall   CodeGenFunction::RunCleanupsScope cleanups(CGF);
103708ef4660SJohn McCall   Visit(E->getSubExpr());
1038b7f8f594SAnders Carlsson }
1039b7f8f594SAnders Carlsson 
1040747eb784SDouglas Gregor void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
10417a626f63SJohn McCall   QualType T = E->getType();
10427a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(T);
10431553b190SJohn McCall   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
104418ada985SAnders Carlsson }
104518ada985SAnders Carlsson 
104618ada985SAnders Carlsson void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
10477a626f63SJohn McCall   QualType T = E->getType();
10487a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(T);
10491553b190SJohn McCall   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
1050ff3507b9SNuno Lopes }
1051ff3507b9SNuno Lopes 
105227a3631bSChris Lattner /// isSimpleZero - If emitting this value will obviously just cause a store of
105327a3631bSChris Lattner /// zero to memory, return true.  This can return false if uncertain, so it just
105427a3631bSChris Lattner /// handles simple cases.
105527a3631bSChris Lattner static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
105691147596SPeter Collingbourne   E = E->IgnoreParens();
105791147596SPeter Collingbourne 
105827a3631bSChris Lattner   // 0
105927a3631bSChris Lattner   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
106027a3631bSChris Lattner     return IL->getValue() == 0;
106127a3631bSChris Lattner   // +0.0
106227a3631bSChris Lattner   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
106327a3631bSChris Lattner     return FL->getValue().isPosZero();
106427a3631bSChris Lattner   // int()
106527a3631bSChris Lattner   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
106627a3631bSChris Lattner       CGF.getTypes().isZeroInitializable(E->getType()))
106727a3631bSChris Lattner     return true;
106827a3631bSChris Lattner   // (int*)0 - Null pointer expressions.
106927a3631bSChris Lattner   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
107027a3631bSChris Lattner     return ICE->getCastKind() == CK_NullToPointer;
107127a3631bSChris Lattner   // '\0'
107227a3631bSChris Lattner   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
107327a3631bSChris Lattner     return CL->getValue() == 0;
107427a3631bSChris Lattner 
107527a3631bSChris Lattner   // Otherwise, hard case: conservatively return false.
107627a3631bSChris Lattner   return false;
107727a3631bSChris Lattner }
107827a3631bSChris Lattner 
107927a3631bSChris Lattner 
1080b247350eSAnders Carlsson void
1081615ed1a3SChad Rosier AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
10821553b190SJohn McCall   QualType type = LV.getType();
1083df0fe27bSMike Stump   // FIXME: Ignore result?
1084579a05d7SChris Lattner   // FIXME: Are initializers affected by volatile?
108527a3631bSChris Lattner   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
108627a3631bSChris Lattner     // Storing "i32 0" to a zero'd memory location is a noop.
108747fb9508SJohn McCall     return;
1088d82a2ce3SRichard Smith   } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
108947fb9508SJohn McCall     return EmitNullInitializationToLValue(LV);
10901553b190SJohn McCall   } else if (type->isReferenceType()) {
109104775f84SAnders Carlsson     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
109247fb9508SJohn McCall     return CGF.EmitStoreThroughLValue(RV, LV);
109347fb9508SJohn McCall   }
109447fb9508SJohn McCall 
109547fb9508SJohn McCall   switch (CGF.getEvaluationKind(type)) {
109647fb9508SJohn McCall   case TEK_Complex:
109747fb9508SJohn McCall     CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
109847fb9508SJohn McCall     return;
109947fb9508SJohn McCall   case TEK_Aggregate:
11008d6fc958SJohn McCall     CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
11018d6fc958SJohn McCall                                                AggValueSlot::IsDestructed,
11028d6fc958SJohn McCall                                       AggValueSlot::DoesNotNeedGCBarriers,
1103a5efa738SJohn McCall                                                AggValueSlot::IsNotAliased,
11041553b190SJohn McCall                                                Dest.isZeroed()));
110547fb9508SJohn McCall     return;
110647fb9508SJohn McCall   case TEK_Scalar:
110747fb9508SJohn McCall     if (LV.isSimple()) {
11081553b190SJohn McCall       CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
11096e313210SEli Friedman     } else {
111055e1fbc8SJohn McCall       CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
11117a51313dSChris Lattner     }
111247fb9508SJohn McCall     return;
111347fb9508SJohn McCall   }
111447fb9508SJohn McCall   llvm_unreachable("bad evaluation kind");
1115579a05d7SChris Lattner }
1116579a05d7SChris Lattner 
11171553b190SJohn McCall void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
11181553b190SJohn McCall   QualType type = lv.getType();
11191553b190SJohn McCall 
112027a3631bSChris Lattner   // If the destination slot is already zeroed out before the aggregate is
112127a3631bSChris Lattner   // copied into it, we don't have to emit any zeros here.
11221553b190SJohn McCall   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
112327a3631bSChris Lattner     return;
112427a3631bSChris Lattner 
112547fb9508SJohn McCall   if (CGF.hasScalarEvaluationKind(type)) {
1126d82a2ce3SRichard Smith     // For non-aggregates, we can store the appropriate null constant.
1127d82a2ce3SRichard Smith     llvm::Value *null = CGF.CGM.EmitNullConstant(type);
112891d5bb1eSEli Friedman     // Note that the following is not equivalent to
112991d5bb1eSEli Friedman     // EmitStoreThroughBitfieldLValue for ARC types.
1130cb3785e4SEli Friedman     if (lv.isBitField()) {
113191d5bb1eSEli Friedman       CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
1132cb3785e4SEli Friedman     } else {
113391d5bb1eSEli Friedman       assert(lv.isSimple());
113491d5bb1eSEli Friedman       CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1135cb3785e4SEli Friedman     }
1136579a05d7SChris Lattner   } else {
1137579a05d7SChris Lattner     // There's a potential optimization opportunity in combining
1138579a05d7SChris Lattner     // memsets; that would be easy for arrays, but relatively
1139579a05d7SChris Lattner     // difficult for structures with the current code.
11401553b190SJohn McCall     CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
1141579a05d7SChris Lattner   }
1142579a05d7SChris Lattner }
1143579a05d7SChris Lattner 
1144579a05d7SChris Lattner void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1145f5d08c9eSEli Friedman #if 0
11466d11ec8cSEli Friedman   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
11476d11ec8cSEli Friedman   // (Length of globals? Chunks of zeroed-out space?).
1148f5d08c9eSEli Friedman   //
114918bb9284SMike Stump   // If we can, prefer a copy from a global; this is a lot less code for long
115018bb9284SMike Stump   // globals, and it's easier for the current optimizers to analyze.
11516d11ec8cSEli Friedman   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
1152c59bb48eSEli Friedman     llvm::GlobalVariable* GV =
11536d11ec8cSEli Friedman     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
11546d11ec8cSEli Friedman                              llvm::GlobalValue::InternalLinkage, C, "");
11554e8ca4faSJohn McCall     EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
1156c59bb48eSEli Friedman     return;
1157c59bb48eSEli Friedman   }
1158f5d08c9eSEli Friedman #endif
1159f53c0968SChris Lattner   if (E->hadArrayRangeDesignator())
1160bf7207a1SDouglas Gregor     CGF.ErrorUnsupported(E, "GNU array range designator extension");
1161bf7207a1SDouglas Gregor 
1162*be93c00aSRichard Smith   AggValueSlot Dest = EnsureSlot(E->getType());
1163*be93c00aSRichard Smith 
1164c83ed824SSebastian Redl   if (E->initializesStdInitializerList()) {
11658eb351d7SSebastian Redl     EmitStdInitializerList(Dest.getAddr(), E);
1166c83ed824SSebastian Redl     return;
1167c83ed824SSebastian Redl   }
1168c83ed824SSebastian Redl 
11697f1ff600SEli Friedman   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
11707f1ff600SEli Friedman                                      Dest.getAlignment());
11717a626f63SJohn McCall 
1172579a05d7SChris Lattner   // Handle initialization of an array.
1173579a05d7SChris Lattner   if (E->getType()->isArrayType()) {
11749ec1e48bSRichard Smith     if (E->isStringLiteralInit())
11759ec1e48bSRichard Smith       return Visit(E->getInit(0));
1176f23b6fa4SEli Friedman 
117791f5ae50SEli Friedman     QualType elementType =
117891f5ae50SEli Friedman         CGF.getContext().getAsArrayType(E->getType())->getElementType();
117982fe67bbSJohn McCall 
1180c83ed824SSebastian Redl     llvm::PointerType *APType =
11817f1ff600SEli Friedman       cast<llvm::PointerType>(Dest.getAddr()->getType());
1182c83ed824SSebastian Redl     llvm::ArrayType *AType =
1183c83ed824SSebastian Redl       cast<llvm::ArrayType>(APType->getElementType());
118482fe67bbSJohn McCall 
11857f1ff600SEli Friedman     EmitArrayInit(Dest.getAddr(), AType, elementType, E);
1186579a05d7SChris Lattner     return;
1187579a05d7SChris Lattner   }
1188579a05d7SChris Lattner 
1189579a05d7SChris Lattner   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
1190579a05d7SChris Lattner 
1191579a05d7SChris Lattner   // Do struct initialization; this code just sets each individual member
1192579a05d7SChris Lattner   // to the approprate value.  This makes bitfield support automatic;
1193579a05d7SChris Lattner   // the disadvantage is that the generated code is more difficult for
1194579a05d7SChris Lattner   // the optimizer, especially with bitfields.
1195579a05d7SChris Lattner   unsigned NumInitElements = E->getNumInits();
11963b935d33SJohn McCall   RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
119752bcf963SChris Lattner 
1198852c9db7SRichard Smith   // Prepare a 'this' for CXXDefaultInitExprs.
1199852c9db7SRichard Smith   CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddr());
1200852c9db7SRichard Smith 
12013b935d33SJohn McCall   if (record->isUnion()) {
12025169570eSDouglas Gregor     // Only initialize one field of a union. The field itself is
12035169570eSDouglas Gregor     // specified by the initializer list.
12045169570eSDouglas Gregor     if (!E->getInitializedFieldInUnion()) {
12055169570eSDouglas Gregor       // Empty union; we have nothing to do.
12065169570eSDouglas Gregor 
12075169570eSDouglas Gregor #ifndef NDEBUG
12085169570eSDouglas Gregor       // Make sure that it's really an empty and not a failure of
12095169570eSDouglas Gregor       // semantic analysis.
12103b935d33SJohn McCall       for (RecordDecl::field_iterator Field = record->field_begin(),
12113b935d33SJohn McCall                                    FieldEnd = record->field_end();
12125169570eSDouglas Gregor            Field != FieldEnd; ++Field)
12135169570eSDouglas Gregor         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
12145169570eSDouglas Gregor #endif
12155169570eSDouglas Gregor       return;
12165169570eSDouglas Gregor     }
12175169570eSDouglas Gregor 
12185169570eSDouglas Gregor     // FIXME: volatility
12195169570eSDouglas Gregor     FieldDecl *Field = E->getInitializedFieldInUnion();
12205169570eSDouglas Gregor 
12217f1ff600SEli Friedman     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
12225169570eSDouglas Gregor     if (NumInitElements) {
12235169570eSDouglas Gregor       // Store the initializer into the field
1224615ed1a3SChad Rosier       EmitInitializationToLValue(E->getInit(0), FieldLoc);
12255169570eSDouglas Gregor     } else {
122627a3631bSChris Lattner       // Default-initialize to null.
12271553b190SJohn McCall       EmitNullInitializationToLValue(FieldLoc);
12285169570eSDouglas Gregor     }
12295169570eSDouglas Gregor 
12305169570eSDouglas Gregor     return;
12315169570eSDouglas Gregor   }
1232579a05d7SChris Lattner 
12333b935d33SJohn McCall   // We'll need to enter cleanup scopes in case any of the member
12343b935d33SJohn McCall   // initializers throw an exception.
12350e62c1ccSChris Lattner   SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
1236f4beacd0SJohn McCall   llvm::Instruction *cleanupDominator = 0;
12373b935d33SJohn McCall 
1238579a05d7SChris Lattner   // Here we iterate over the fields; this makes it simpler to both
1239579a05d7SChris Lattner   // default-initialize fields and skip over unnamed fields.
12403b935d33SJohn McCall   unsigned curInitIndex = 0;
12413b935d33SJohn McCall   for (RecordDecl::field_iterator field = record->field_begin(),
12423b935d33SJohn McCall                                fieldEnd = record->field_end();
12433b935d33SJohn McCall        field != fieldEnd; ++field) {
12443b935d33SJohn McCall     // We're done once we hit the flexible array member.
12453b935d33SJohn McCall     if (field->getType()->isIncompleteArrayType())
124691f84216SDouglas Gregor       break;
124791f84216SDouglas Gregor 
12483b935d33SJohn McCall     // Always skip anonymous bitfields.
12493b935d33SJohn McCall     if (field->isUnnamedBitfield())
1250579a05d7SChris Lattner       continue;
125117bd094aSDouglas Gregor 
12523b935d33SJohn McCall     // We're done if we reach the end of the explicit initializers, we
12533b935d33SJohn McCall     // have a zeroed object, and the rest of the fields are
12543b935d33SJohn McCall     // zero-initializable.
12553b935d33SJohn McCall     if (curInitIndex == NumInitElements && Dest.isZeroed() &&
125627a3631bSChris Lattner         CGF.getTypes().isZeroInitializable(E->getType()))
125727a3631bSChris Lattner       break;
125827a3631bSChris Lattner 
12597f1ff600SEli Friedman 
126040ed2973SDavid Blaikie     LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, *field);
12617c1baf46SFariborz Jahanian     // We never generate write-barries for initialized fields.
12623b935d33SJohn McCall     LV.setNonGC(true);
126327a3631bSChris Lattner 
12643b935d33SJohn McCall     if (curInitIndex < NumInitElements) {
1265e18aaf2cSChris Lattner       // Store the initializer into the field.
1266615ed1a3SChad Rosier       EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
1267579a05d7SChris Lattner     } else {
1268579a05d7SChris Lattner       // We're out of initalizers; default-initialize to null
12693b935d33SJohn McCall       EmitNullInitializationToLValue(LV);
12703b935d33SJohn McCall     }
12713b935d33SJohn McCall 
12723b935d33SJohn McCall     // Push a destructor if necessary.
12733b935d33SJohn McCall     // FIXME: if we have an array of structures, all explicitly
12743b935d33SJohn McCall     // initialized, we can end up pushing a linear number of cleanups.
12753b935d33SJohn McCall     bool pushedCleanup = false;
12763b935d33SJohn McCall     if (QualType::DestructionKind dtorKind
12773b935d33SJohn McCall           = field->getType().isDestructedType()) {
12783b935d33SJohn McCall       assert(LV.isSimple());
12793b935d33SJohn McCall       if (CGF.needsEHCleanup(dtorKind)) {
1280f4beacd0SJohn McCall         if (!cleanupDominator)
1281f4beacd0SJohn McCall           cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1282f4beacd0SJohn McCall 
12833b935d33SJohn McCall         CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
12843b935d33SJohn McCall                         CGF.getDestroyer(dtorKind), false);
12853b935d33SJohn McCall         cleanups.push_back(CGF.EHStack.stable_begin());
12863b935d33SJohn McCall         pushedCleanup = true;
12873b935d33SJohn McCall       }
1288579a05d7SChris Lattner     }
128927a3631bSChris Lattner 
129027a3631bSChris Lattner     // If the GEP didn't get used because of a dead zero init or something
129127a3631bSChris Lattner     // else, clean it up for -O0 builds and general tidiness.
12923b935d33SJohn McCall     if (!pushedCleanup && LV.isSimple())
129327a3631bSChris Lattner       if (llvm::GetElementPtrInst *GEP =
12943b935d33SJohn McCall             dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
129527a3631bSChris Lattner         if (GEP->use_empty())
129627a3631bSChris Lattner           GEP->eraseFromParent();
12977a51313dSChris Lattner   }
12983b935d33SJohn McCall 
12993b935d33SJohn McCall   // Deactivate all the partial cleanups in reverse order, which
13003b935d33SJohn McCall   // generally means popping them.
13013b935d33SJohn McCall   for (unsigned i = cleanups.size(); i != 0; --i)
1302f4beacd0SJohn McCall     CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1303f4beacd0SJohn McCall 
1304f4beacd0SJohn McCall   // Destroy the placeholder if we made one.
1305f4beacd0SJohn McCall   if (cleanupDominator)
1306f4beacd0SJohn McCall     cleanupDominator->eraseFromParent();
13077a51313dSChris Lattner }
13087a51313dSChris Lattner 
13097a51313dSChris Lattner //===----------------------------------------------------------------------===//
13107a51313dSChris Lattner //                        Entry Points into this File
13117a51313dSChris Lattner //===----------------------------------------------------------------------===//
13127a51313dSChris Lattner 
131327a3631bSChris Lattner /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
131427a3631bSChris Lattner /// non-zero bytes that will be stored when outputting the initializer for the
131527a3631bSChris Lattner /// specified initializer expression.
1316df94cb7dSKen Dyck static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
131791147596SPeter Collingbourne   E = E->IgnoreParens();
131827a3631bSChris Lattner 
131927a3631bSChris Lattner   // 0 and 0.0 won't require any non-zero stores!
1320df94cb7dSKen Dyck   if (isSimpleZero(E, CGF)) return CharUnits::Zero();
132127a3631bSChris Lattner 
132227a3631bSChris Lattner   // If this is an initlist expr, sum up the size of sizes of the (present)
132327a3631bSChris Lattner   // elements.  If this is something weird, assume the whole thing is non-zero.
132427a3631bSChris Lattner   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
132527a3631bSChris Lattner   if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
1326df94cb7dSKen Dyck     return CGF.getContext().getTypeSizeInChars(E->getType());
132727a3631bSChris Lattner 
1328c5cc2fb9SChris Lattner   // InitListExprs for structs have to be handled carefully.  If there are
1329c5cc2fb9SChris Lattner   // reference members, we need to consider the size of the reference, not the
1330c5cc2fb9SChris Lattner   // referencee.  InitListExprs for unions and arrays can't have references.
13315cd84755SChris Lattner   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
13325cd84755SChris Lattner     if (!RT->isUnionType()) {
1333c5cc2fb9SChris Lattner       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
1334df94cb7dSKen Dyck       CharUnits NumNonZeroBytes = CharUnits::Zero();
1335c5cc2fb9SChris Lattner 
1336c5cc2fb9SChris Lattner       unsigned ILEElement = 0;
1337c5cc2fb9SChris Lattner       for (RecordDecl::field_iterator Field = SD->field_begin(),
1338c5cc2fb9SChris Lattner            FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
1339c5cc2fb9SChris Lattner         // We're done once we hit the flexible array member or run out of
1340c5cc2fb9SChris Lattner         // InitListExpr elements.
1341c5cc2fb9SChris Lattner         if (Field->getType()->isIncompleteArrayType() ||
1342c5cc2fb9SChris Lattner             ILEElement == ILE->getNumInits())
1343c5cc2fb9SChris Lattner           break;
1344c5cc2fb9SChris Lattner         if (Field->isUnnamedBitfield())
1345c5cc2fb9SChris Lattner           continue;
1346c5cc2fb9SChris Lattner 
1347c5cc2fb9SChris Lattner         const Expr *E = ILE->getInit(ILEElement++);
1348c5cc2fb9SChris Lattner 
1349c5cc2fb9SChris Lattner         // Reference values are always non-null and have the width of a pointer.
13505cd84755SChris Lattner         if (Field->getType()->isReferenceType())
1351df94cb7dSKen Dyck           NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1352c8e01705SJohn McCall               CGF.getTarget().getPointerWidth(0));
13535cd84755SChris Lattner         else
1354c5cc2fb9SChris Lattner           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1355c5cc2fb9SChris Lattner       }
1356c5cc2fb9SChris Lattner 
1357c5cc2fb9SChris Lattner       return NumNonZeroBytes;
1358c5cc2fb9SChris Lattner     }
13595cd84755SChris Lattner   }
1360c5cc2fb9SChris Lattner 
1361c5cc2fb9SChris Lattner 
1362df94cb7dSKen Dyck   CharUnits NumNonZeroBytes = CharUnits::Zero();
136327a3631bSChris Lattner   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
136427a3631bSChris Lattner     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
136527a3631bSChris Lattner   return NumNonZeroBytes;
136627a3631bSChris Lattner }
136727a3631bSChris Lattner 
136827a3631bSChris Lattner /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
136927a3631bSChris Lattner /// zeros in it, emit a memset and avoid storing the individual zeros.
137027a3631bSChris Lattner ///
137127a3631bSChris Lattner static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
137227a3631bSChris Lattner                                      CodeGenFunction &CGF) {
137327a3631bSChris Lattner   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
137427a3631bSChris Lattner   // volatile stores.
137527a3631bSChris Lattner   if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
137627a3631bSChris Lattner 
137703535265SArgyrios Kyrtzidis   // C++ objects with a user-declared constructor don't need zero'ing.
13789c6890a7SRichard Smith   if (CGF.getLangOpts().CPlusPlus)
137903535265SArgyrios Kyrtzidis     if (const RecordType *RT = CGF.getContext()
138003535265SArgyrios Kyrtzidis                        .getBaseElementType(E->getType())->getAs<RecordType>()) {
138103535265SArgyrios Kyrtzidis       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
138203535265SArgyrios Kyrtzidis       if (RD->hasUserDeclaredConstructor())
138303535265SArgyrios Kyrtzidis         return;
138403535265SArgyrios Kyrtzidis     }
138503535265SArgyrios Kyrtzidis 
138627a3631bSChris Lattner   // If the type is 16-bytes or smaller, prefer individual stores over memset.
1387239a3357SKen Dyck   std::pair<CharUnits, CharUnits> TypeInfo =
1388239a3357SKen Dyck     CGF.getContext().getTypeInfoInChars(E->getType());
1389239a3357SKen Dyck   if (TypeInfo.first <= CharUnits::fromQuantity(16))
139027a3631bSChris Lattner     return;
139127a3631bSChris Lattner 
139227a3631bSChris Lattner   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
139327a3631bSChris Lattner   // we prefer to emit memset + individual stores for the rest.
1394239a3357SKen Dyck   CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1395239a3357SKen Dyck   if (NumNonZeroBytes*4 > TypeInfo.first)
139627a3631bSChris Lattner     return;
139727a3631bSChris Lattner 
139827a3631bSChris Lattner   // Okay, it seems like a good idea to use an initial memset, emit the call.
1399239a3357SKen Dyck   llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1400239a3357SKen Dyck   CharUnits Align = TypeInfo.second;
140127a3631bSChris Lattner 
140227a3631bSChris Lattner   llvm::Value *Loc = Slot.getAddr();
140327a3631bSChris Lattner 
1404ece0409aSChris Lattner   Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
1405239a3357SKen Dyck   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1406239a3357SKen Dyck                            Align.getQuantity(), false);
140727a3631bSChris Lattner 
140827a3631bSChris Lattner   // Tell the AggExprEmitter that the slot is known zero.
140927a3631bSChris Lattner   Slot.setZeroed();
141027a3631bSChris Lattner }
141127a3631bSChris Lattner 
141227a3631bSChris Lattner 
141327a3631bSChris Lattner 
141427a3631bSChris Lattner 
141525306cacSMike Stump /// EmitAggExpr - Emit the computation of the specified expression of aggregate
141625306cacSMike Stump /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
141725306cacSMike Stump /// the value of the aggregate expression is not needed.  If VolatileDest is
141825306cacSMike Stump /// true, DestPtr cannot be 0.
14194e8ca4faSJohn McCall void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
142047fb9508SJohn McCall   assert(E && hasAggregateEvaluationKind(E->getType()) &&
14217a51313dSChris Lattner          "Invalid aggregate expression to emit");
142227a3631bSChris Lattner   assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
142327a3631bSChris Lattner          "slot has bits but no address");
14247a51313dSChris Lattner 
142527a3631bSChris Lattner   // Optimize the slot if possible.
142627a3631bSChris Lattner   CheckAggExprForMemSetUse(Slot, E, *this);
142727a3631bSChris Lattner 
14284e8ca4faSJohn McCall   AggExprEmitter(*this, Slot).Visit(const_cast<Expr*>(E));
14297a51313dSChris Lattner }
14300bc8e86dSDaniel Dunbar 
1431d0bc7b9dSDaniel Dunbar LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
143247fb9508SJohn McCall   assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
1433a7566f16SDaniel Dunbar   llvm::Value *Temp = CreateMemTemp(E->getType());
14342e442a00SDaniel Dunbar   LValue LV = MakeAddrLValue(Temp, E->getType());
14358d6fc958SJohn McCall   EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
143646759f4fSJohn McCall                                          AggValueSlot::DoesNotNeedGCBarriers,
1437615ed1a3SChad Rosier                                          AggValueSlot::IsNotAliased));
14382e442a00SDaniel Dunbar   return LV;
1439d0bc7b9dSDaniel Dunbar }
1440d0bc7b9dSDaniel Dunbar 
1441615ed1a3SChad Rosier void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1442615ed1a3SChad Rosier                                         llvm::Value *SrcPtr, QualType Ty,
14434e8ca4faSJohn McCall                                         bool isVolatile,
14441ca66919SBenjamin Kramer                                         CharUnits alignment,
14451ca66919SBenjamin Kramer                                         bool isAssignment) {
1446615ed1a3SChad Rosier   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
14470bc8e86dSDaniel Dunbar 
14489c6890a7SRichard Smith   if (getLangOpts().CPlusPlus) {
1449615ed1a3SChad Rosier     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1450615ed1a3SChad Rosier       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1451615ed1a3SChad Rosier       assert((Record->hasTrivialCopyConstructor() ||
1452615ed1a3SChad Rosier               Record->hasTrivialCopyAssignment() ||
1453615ed1a3SChad Rosier               Record->hasTrivialMoveConstructor() ||
1454615ed1a3SChad Rosier               Record->hasTrivialMoveAssignment()) &&
145516488472SRichard Smith              "Trying to aggregate-copy a type without a trivial copy/move "
1456f22101a0SDouglas Gregor              "constructor or assignment operator");
1457615ed1a3SChad Rosier       // Ignore empty classes in C++.
1458615ed1a3SChad Rosier       if (Record->isEmpty())
145916e94af6SAnders Carlsson         return;
146016e94af6SAnders Carlsson     }
146116e94af6SAnders Carlsson   }
146216e94af6SAnders Carlsson 
1463ca05dfefSChris Lattner   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
14643ef668c2SChris Lattner   // C99 6.5.16.1p3, which states "If the value being stored in an object is
14653ef668c2SChris Lattner   // read from another object that overlaps in anyway the storage of the first
14663ef668c2SChris Lattner   // object, then the overlap shall be exact and the two objects shall have
14673ef668c2SChris Lattner   // qualified or unqualified versions of a compatible type."
14683ef668c2SChris Lattner   //
1469ca05dfefSChris Lattner   // memcpy is not defined if the source and destination pointers are exactly
14703ef668c2SChris Lattner   // equal, but other compilers do this optimization, and almost every memcpy
14713ef668c2SChris Lattner   // implementation handles this case safely.  If there is a libc that does not
14723ef668c2SChris Lattner   // safely handle this, we can add a target hook.
14730bc8e86dSDaniel Dunbar 
14741ca66919SBenjamin Kramer   // Get data size and alignment info for this aggregate. If this is an
14751ca66919SBenjamin Kramer   // assignment don't copy the tail padding. Otherwise copying it is fine.
14761ca66919SBenjamin Kramer   std::pair<CharUnits, CharUnits> TypeInfo;
14771ca66919SBenjamin Kramer   if (isAssignment)
14781ca66919SBenjamin Kramer     TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
14791ca66919SBenjamin Kramer   else
14801ca66919SBenjamin Kramer     TypeInfo = getContext().getTypeInfoInChars(Ty);
1481615ed1a3SChad Rosier 
14824e8ca4faSJohn McCall   if (alignment.isZero())
14834e8ca4faSJohn McCall     alignment = TypeInfo.second;
1484615ed1a3SChad Rosier 
1485615ed1a3SChad Rosier   // FIXME: Handle variable sized types.
1486615ed1a3SChad Rosier 
1487615ed1a3SChad Rosier   // FIXME: If we have a volatile struct, the optimizer can remove what might
1488615ed1a3SChad Rosier   // appear to be `extra' memory ops:
1489615ed1a3SChad Rosier   //
1490615ed1a3SChad Rosier   // volatile struct { int i; } a, b;
1491615ed1a3SChad Rosier   //
1492615ed1a3SChad Rosier   // int main() {
1493615ed1a3SChad Rosier   //   a = b;
1494615ed1a3SChad Rosier   //   a = b;
1495615ed1a3SChad Rosier   // }
1496615ed1a3SChad Rosier   //
1497615ed1a3SChad Rosier   // we need to use a different call here.  We use isVolatile to indicate when
1498615ed1a3SChad Rosier   // either the source or the destination is volatile.
1499615ed1a3SChad Rosier 
1500615ed1a3SChad Rosier   llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1501615ed1a3SChad Rosier   llvm::Type *DBP =
1502615ed1a3SChad Rosier     llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1503615ed1a3SChad Rosier   DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1504615ed1a3SChad Rosier 
1505615ed1a3SChad Rosier   llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1506615ed1a3SChad Rosier   llvm::Type *SBP =
1507615ed1a3SChad Rosier     llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1508615ed1a3SChad Rosier   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1509615ed1a3SChad Rosier 
1510615ed1a3SChad Rosier   // Don't do any of the memmove_collectable tests if GC isn't set.
1511615ed1a3SChad Rosier   if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1512615ed1a3SChad Rosier     // fall through
1513615ed1a3SChad Rosier   } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1514615ed1a3SChad Rosier     RecordDecl *Record = RecordTy->getDecl();
1515615ed1a3SChad Rosier     if (Record->hasObjectMember()) {
1516615ed1a3SChad Rosier       CharUnits size = TypeInfo.first;
1517615ed1a3SChad Rosier       llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1518615ed1a3SChad Rosier       llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
1519615ed1a3SChad Rosier       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1520615ed1a3SChad Rosier                                                     SizeVal);
1521615ed1a3SChad Rosier       return;
1522615ed1a3SChad Rosier     }
1523615ed1a3SChad Rosier   } else if (Ty->isArrayType()) {
1524615ed1a3SChad Rosier     QualType BaseType = getContext().getBaseElementType(Ty);
1525615ed1a3SChad Rosier     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1526615ed1a3SChad Rosier       if (RecordTy->getDecl()->hasObjectMember()) {
1527615ed1a3SChad Rosier         CharUnits size = TypeInfo.first;
1528615ed1a3SChad Rosier         llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1529615ed1a3SChad Rosier         llvm::Value *SizeVal =
1530615ed1a3SChad Rosier           llvm::ConstantInt::get(SizeTy, size.getQuantity());
1531615ed1a3SChad Rosier         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1532615ed1a3SChad Rosier                                                       SizeVal);
1533615ed1a3SChad Rosier         return;
1534615ed1a3SChad Rosier       }
1535615ed1a3SChad Rosier     }
1536615ed1a3SChad Rosier   }
1537615ed1a3SChad Rosier 
153822695fceSDan Gohman   // Determine the metadata to describe the position of any padding in this
153922695fceSDan Gohman   // memcpy, as well as the TBAA tags for the members of the struct, in case
154022695fceSDan Gohman   // the optimizer wishes to expand it in to scalar memory operations.
154122695fceSDan Gohman   llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty);
154222695fceSDan Gohman 
1543615ed1a3SChad Rosier   Builder.CreateMemCpy(DestPtr, SrcPtr,
1544615ed1a3SChad Rosier                        llvm::ConstantInt::get(IntPtrTy,
1545615ed1a3SChad Rosier                                               TypeInfo.first.getQuantity()),
154622695fceSDan Gohman                        alignment.getQuantity(), isVolatile,
154722695fceSDan Gohman                        /*TBAATag=*/0, TBAAStructTag);
15480bc8e86dSDaniel Dunbar }
1549c83ed824SSebastian Redl 
1550d026dc49SSebastian Redl void CodeGenFunction::MaybeEmitStdInitializerListCleanup(llvm::Value *loc,
1551c83ed824SSebastian Redl                                                          const Expr *init) {
1552c83ed824SSebastian Redl   const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(init);
1553d026dc49SSebastian Redl   if (cleanups)
1554c83ed824SSebastian Redl     init = cleanups->getSubExpr();
1555c83ed824SSebastian Redl 
1556c83ed824SSebastian Redl   if (isa<InitListExpr>(init) &&
1557c83ed824SSebastian Redl       cast<InitListExpr>(init)->initializesStdInitializerList()) {
1558c83ed824SSebastian Redl     // We initialized this std::initializer_list with an initializer list.
1559c83ed824SSebastian Redl     // A backing array was created. Push a cleanup for it.
1560d026dc49SSebastian Redl     EmitStdInitializerListCleanup(loc, cast<InitListExpr>(init));
1561c83ed824SSebastian Redl   }
1562c83ed824SSebastian Redl }
1563c83ed824SSebastian Redl 
15648eb351d7SSebastian Redl static void EmitRecursiveStdInitializerListCleanup(CodeGenFunction &CGF,
15658eb351d7SSebastian Redl                                                    llvm::Value *arrayStart,
15668eb351d7SSebastian Redl                                                    const InitListExpr *init) {
15678eb351d7SSebastian Redl   // Check if there are any recursive cleanups to do, i.e. if we have
15688eb351d7SSebastian Redl   //   std::initializer_list<std::initializer_list<obj>> list = {{obj()}};
15698eb351d7SSebastian Redl   // then we need to destroy the inner array as well.
15708eb351d7SSebastian Redl   for (unsigned i = 0, e = init->getNumInits(); i != e; ++i) {
15718eb351d7SSebastian Redl     const InitListExpr *subInit = dyn_cast<InitListExpr>(init->getInit(i));
15728eb351d7SSebastian Redl     if (!subInit || !subInit->initializesStdInitializerList())
15738eb351d7SSebastian Redl       continue;
15748eb351d7SSebastian Redl 
15758eb351d7SSebastian Redl     // This one needs to be destroyed. Get the address of the std::init_list.
15768eb351d7SSebastian Redl     llvm::Value *offset = llvm::ConstantInt::get(CGF.SizeTy, i);
15778eb351d7SSebastian Redl     llvm::Value *loc = CGF.Builder.CreateInBoundsGEP(arrayStart, offset,
15788eb351d7SSebastian Redl                                                  "std.initlist");
15798eb351d7SSebastian Redl     CGF.EmitStdInitializerListCleanup(loc, subInit);
15808eb351d7SSebastian Redl   }
15818eb351d7SSebastian Redl }
15828eb351d7SSebastian Redl 
15838eb351d7SSebastian Redl void CodeGenFunction::EmitStdInitializerListCleanup(llvm::Value *loc,
1584c83ed824SSebastian Redl                                                     const InitListExpr *init) {
1585c83ed824SSebastian Redl   ASTContext &ctx = getContext();
1586c83ed824SSebastian Redl   QualType element = GetStdInitializerListElementType(init->getType());
1587c83ed824SSebastian Redl   unsigned numInits = init->getNumInits();
1588c83ed824SSebastian Redl   llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
1589c83ed824SSebastian Redl   QualType array =ctx.getConstantArrayType(element, size, ArrayType::Normal, 0);
1590c83ed824SSebastian Redl   QualType arrayPtr = ctx.getPointerType(array);
1591c83ed824SSebastian Redl   llvm::Type *arrayPtrType = ConvertType(arrayPtr);
1592c83ed824SSebastian Redl 
1593c83ed824SSebastian Redl   // lvalue is the location of a std::initializer_list, which as its first
1594c83ed824SSebastian Redl   // element has a pointer to the array we want to destroy.
15958eb351d7SSebastian Redl   llvm::Value *startPointer = Builder.CreateStructGEP(loc, 0, "startPointer");
15968eb351d7SSebastian Redl   llvm::Value *startAddress = Builder.CreateLoad(startPointer, "startAddress");
1597c83ed824SSebastian Redl 
15988eb351d7SSebastian Redl   ::EmitRecursiveStdInitializerListCleanup(*this, startAddress, init);
15998eb351d7SSebastian Redl 
16008eb351d7SSebastian Redl   llvm::Value *arrayAddress =
16018eb351d7SSebastian Redl       Builder.CreateBitCast(startAddress, arrayPtrType, "arrayAddress");
1602c83ed824SSebastian Redl   ::EmitStdInitializerListCleanup(*this, array, arrayAddress, init);
1603c83ed824SSebastian Redl }
1604