1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Aggregate Expr nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "CGObjCRuntime.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 using namespace clang;
26 using namespace CodeGen;
27 
28 //===----------------------------------------------------------------------===//
29 //                        Aggregate Expression Emitter
30 //===----------------------------------------------------------------------===//
31 
32 namespace  {
33 class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
34   CodeGenFunction &CGF;
35   CGBuilderTy &Builder;
36   AggValueSlot Dest;
37   bool IgnoreResult;
38 
39   /// We want to use 'dest' as the return slot except under two
40   /// conditions:
41   ///   - The destination slot requires garbage collection, so we
42   ///     need to use the GC API.
43   ///   - The destination slot is potentially aliased.
44   bool shouldUseDestForReturnSlot() const {
45     return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
46   }
47 
48   ReturnValueSlot getReturnValueSlot() const {
49     if (!shouldUseDestForReturnSlot())
50       return ReturnValueSlot();
51 
52     return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
53   }
54 
55   AggValueSlot EnsureSlot(QualType T) {
56     if (!Dest.isIgnored()) return Dest;
57     return CGF.CreateAggTemp(T, "agg.tmp.ensured");
58   }
59 
60 public:
61   AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest,
62                  bool ignore)
63     : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
64       IgnoreResult(ignore) {
65   }
66 
67   //===--------------------------------------------------------------------===//
68   //                               Utilities
69   //===--------------------------------------------------------------------===//
70 
71   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
72   /// represents a value lvalue, this method emits the address of the lvalue,
73   /// then loads the result into DestPtr.
74   void EmitAggLoadOfLValue(const Expr *E);
75 
76   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
77   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
78   void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false,
79                          unsigned Alignment = 0);
80 
81   void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
82 
83   void EmitStdInitializerList(llvm::Value *DestPtr, InitListExpr *InitList);
84   void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
85                      QualType elementType, InitListExpr *E);
86 
87   AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
88     if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
89       return AggValueSlot::NeedsGCBarriers;
90     return AggValueSlot::DoesNotNeedGCBarriers;
91   }
92 
93   bool TypeRequiresGCollection(QualType T);
94 
95   //===--------------------------------------------------------------------===//
96   //                            Visitor Methods
97   //===--------------------------------------------------------------------===//
98 
99   void VisitStmt(Stmt *S) {
100     CGF.ErrorUnsupported(S, "aggregate expression");
101   }
102   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
103   void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
104     Visit(GE->getResultExpr());
105   }
106   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
107   void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
108     return Visit(E->getReplacement());
109   }
110 
111   // l-values.
112   void VisitDeclRefExpr(DeclRefExpr *E) {
113     // For aggregates, we should always be able to emit the variable
114     // as an l-value unless it's a reference.  This is due to the fact
115     // that we can't actually ever see a normal l2r conversion on an
116     // aggregate in C++, and in C there's no language standard
117     // actively preventing us from listing variables in the captures
118     // list of a block.
119     if (E->getDecl()->getType()->isReferenceType()) {
120       if (CodeGenFunction::ConstantEmission result
121             = CGF.tryEmitAsConstant(E)) {
122         EmitFinalDestCopy(E, result.getReferenceLValue(CGF, E));
123         return;
124       }
125     }
126 
127     EmitAggLoadOfLValue(E);
128   }
129 
130   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
131   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
132   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
133   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
134   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
135     EmitAggLoadOfLValue(E);
136   }
137   void VisitPredefinedExpr(const PredefinedExpr *E) {
138     EmitAggLoadOfLValue(E);
139   }
140 
141   // Operators.
142   void VisitCastExpr(CastExpr *E);
143   void VisitCallExpr(const CallExpr *E);
144   void VisitStmtExpr(const StmtExpr *E);
145   void VisitBinaryOperator(const BinaryOperator *BO);
146   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
147   void VisitBinAssign(const BinaryOperator *E);
148   void VisitBinComma(const BinaryOperator *E);
149 
150   void VisitObjCMessageExpr(ObjCMessageExpr *E);
151   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
152     EmitAggLoadOfLValue(E);
153   }
154 
155   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
156   void VisitChooseExpr(const ChooseExpr *CE);
157   void VisitInitListExpr(InitListExpr *E);
158   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
159   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
160     Visit(DAE->getExpr());
161   }
162   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
163   void VisitCXXConstructExpr(const CXXConstructExpr *E);
164   void VisitLambdaExpr(LambdaExpr *E);
165   void VisitExprWithCleanups(ExprWithCleanups *E);
166   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
167   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
168   void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
169   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
170 
171   void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
172     if (E->isGLValue()) {
173       LValue LV = CGF.EmitPseudoObjectLValue(E);
174       return EmitFinalDestCopy(E, LV);
175     }
176 
177     CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
178   }
179 
180   void VisitVAArgExpr(VAArgExpr *E);
181 
182   void EmitInitializationToLValue(Expr *E, LValue Address);
183   void EmitNullInitializationToLValue(LValue Address);
184   //  case Expr::ChooseExprClass:
185   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
186   void VisitAtomicExpr(AtomicExpr *E) {
187     CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
188   }
189 };
190 }  // end anonymous namespace.
191 
192 //===----------------------------------------------------------------------===//
193 //                                Utilities
194 //===----------------------------------------------------------------------===//
195 
196 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
197 /// represents a value lvalue, this method emits the address of the lvalue,
198 /// then loads the result into DestPtr.
199 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
200   LValue LV = CGF.EmitLValue(E);
201   EmitFinalDestCopy(E, LV);
202 }
203 
204 /// \brief True if the given aggregate type requires special GC API calls.
205 bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
206   // Only record types have members that might require garbage collection.
207   const RecordType *RecordTy = T->getAs<RecordType>();
208   if (!RecordTy) return false;
209 
210   // Don't mess with non-trivial C++ types.
211   RecordDecl *Record = RecordTy->getDecl();
212   if (isa<CXXRecordDecl>(Record) &&
213       (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
214        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
215     return false;
216 
217   // Check whether the type has an object member.
218   return Record->hasObjectMember();
219 }
220 
221 /// \brief Perform the final move to DestPtr if for some reason
222 /// getReturnValueSlot() didn't use it directly.
223 ///
224 /// The idea is that you do something like this:
225 ///   RValue Result = EmitSomething(..., getReturnValueSlot());
226 ///   EmitMoveFromReturnSlot(E, Result);
227 ///
228 /// If nothing interferes, this will cause the result to be emitted
229 /// directly into the return value slot.  Otherwise, a final move
230 /// will be performed.
231 void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue Src) {
232   if (shouldUseDestForReturnSlot()) {
233     // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
234     // The possibility of undef rvalues complicates that a lot,
235     // though, so we can't really assert.
236     return;
237   }
238 
239   // Otherwise, do a final copy,
240   assert(Dest.getAddr() != Src.getAggregateAddr());
241   EmitFinalDestCopy(E, Src, /*Ignore*/ true);
242 }
243 
244 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
245 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore,
246                                        unsigned Alignment) {
247   assert(Src.isAggregate() && "value must be aggregate value!");
248 
249   // If Dest is ignored, then we're evaluating an aggregate expression
250   // in a context (like an expression statement) that doesn't care
251   // about the result.  C says that an lvalue-to-rvalue conversion is
252   // performed in these cases; C++ says that it is not.  In either
253   // case, we don't actually need to do anything unless the value is
254   // volatile.
255   if (Dest.isIgnored()) {
256     if (!Src.isVolatileQualified() ||
257         CGF.CGM.getLangOpts().CPlusPlus ||
258         (IgnoreResult && Ignore))
259       return;
260 
261     // If the source is volatile, we must read from it; to do that, we need
262     // some place to put it.
263     Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
264   }
265 
266   if (Dest.requiresGCollection()) {
267     CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
268     llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
269     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
270     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
271                                                       Dest.getAddr(),
272                                                       Src.getAggregateAddr(),
273                                                       SizeVal);
274     return;
275   }
276   // If the result of the assignment is used, copy the LHS there also.
277   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
278   // from the source as well, as we can't eliminate it if either operand
279   // is volatile, unless copy has volatile for both source and destination..
280   CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
281                         Dest.isVolatile()|Src.isVolatileQualified(),
282                         Alignment);
283 }
284 
285 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
286 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
287   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
288 
289   CharUnits Alignment = std::min(Src.getAlignment(), Dest.getAlignment());
290   EmitFinalDestCopy(E, Src.asAggregateRValue(), Ignore, Alignment.getQuantity());
291 }
292 
293 static QualType GetStdInitializerListElementType(QualType T) {
294   // Just assume that this is really std::initializer_list.
295   ClassTemplateSpecializationDecl *specialization =
296       cast<ClassTemplateSpecializationDecl>(T->castAs<RecordType>()->getDecl());
297   return specialization->getTemplateArgs()[0].getAsType();
298 }
299 
300 /// \brief Prepare cleanup for the temporary array.
301 static void EmitStdInitializerListCleanup(CodeGenFunction &CGF,
302                                           QualType arrayType,
303                                           llvm::Value *addr,
304                                           const InitListExpr *initList) {
305   QualType::DestructionKind dtorKind = arrayType.isDestructedType();
306   if (!dtorKind)
307     return; // Type doesn't need destroying.
308   if (dtorKind != QualType::DK_cxx_destructor) {
309     CGF.ErrorUnsupported(initList, "ObjC ARC type in initializer_list");
310     return;
311   }
312 
313   CodeGenFunction::Destroyer *destroyer = CGF.getDestroyer(dtorKind);
314   CGF.pushDestroy(NormalAndEHCleanup, addr, arrayType, destroyer,
315                   /*EHCleanup=*/true);
316 }
317 
318 /// \brief Emit the initializer for a std::initializer_list initialized with a
319 /// real initializer list.
320 void AggExprEmitter::EmitStdInitializerList(llvm::Value *destPtr,
321                                             InitListExpr *initList) {
322   // We emit an array containing the elements, then have the init list point
323   // at the array.
324   ASTContext &ctx = CGF.getContext();
325   unsigned numInits = initList->getNumInits();
326   QualType element = GetStdInitializerListElementType(initList->getType());
327   llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
328   QualType array = ctx.getConstantArrayType(element, size, ArrayType::Normal,0);
329   llvm::Type *LTy = CGF.ConvertTypeForMem(array);
330   llvm::AllocaInst *alloc = CGF.CreateTempAlloca(LTy);
331   alloc->setAlignment(ctx.getTypeAlignInChars(array).getQuantity());
332   alloc->setName(".initlist.");
333 
334   EmitArrayInit(alloc, cast<llvm::ArrayType>(LTy), element, initList);
335 
336   // FIXME: The diagnostics are somewhat out of place here.
337   RecordDecl *record = initList->getType()->castAs<RecordType>()->getDecl();
338   RecordDecl::field_iterator field = record->field_begin();
339   if (field == record->field_end()) {
340     CGF.ErrorUnsupported(initList, "weird std::initializer_list");
341     return;
342   }
343 
344   QualType elementPtr = ctx.getPointerType(element.withConst());
345 
346   // Start pointer.
347   if (!ctx.hasSameType(field->getType(), elementPtr)) {
348     CGF.ErrorUnsupported(initList, "weird std::initializer_list");
349     return;
350   }
351   LValue start = CGF.EmitLValueForFieldInitialization(destPtr, *field, 0);
352   llvm::Value *arrayStart = Builder.CreateStructGEP(alloc, 0, "arraystart");
353   CGF.EmitStoreThroughLValue(RValue::get(arrayStart), start);
354   ++field;
355 
356   if (field == record->field_end()) {
357     CGF.ErrorUnsupported(initList, "weird std::initializer_list");
358     return;
359   }
360   LValue endOrLength = CGF.EmitLValueForFieldInitialization(destPtr, *field, 0);
361   if (ctx.hasSameType(field->getType(), elementPtr)) {
362     // End pointer.
363     llvm::Value *arrayEnd = Builder.CreateStructGEP(alloc,numInits, "arrayend");
364     CGF.EmitStoreThroughLValue(RValue::get(arrayEnd), endOrLength);
365   } else if(ctx.hasSameType(field->getType(), ctx.getSizeType())) {
366     // Length.
367     CGF.EmitStoreThroughLValue(RValue::get(Builder.getInt(size)), endOrLength);
368   } else {
369     CGF.ErrorUnsupported(initList, "weird std::initializer_list");
370     return;
371   }
372 
373   if (!Dest.isExternallyDestructed())
374     EmitStdInitializerListCleanup(CGF, array, alloc, initList);
375 }
376 
377 /// \brief Emit initialization of an array from an initializer list.
378 void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
379                                    QualType elementType, InitListExpr *E) {
380   uint64_t NumInitElements = E->getNumInits();
381 
382   uint64_t NumArrayElements = AType->getNumElements();
383   assert(NumInitElements <= NumArrayElements);
384 
385   // DestPtr is an array*.  Construct an elementType* by drilling
386   // down a level.
387   llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
388   llvm::Value *indices[] = { zero, zero };
389   llvm::Value *begin =
390     Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
391 
392   // Exception safety requires us to destroy all the
393   // already-constructed members if an initializer throws.
394   // For that, we'll need an EH cleanup.
395   QualType::DestructionKind dtorKind = elementType.isDestructedType();
396   llvm::AllocaInst *endOfInit = 0;
397   EHScopeStack::stable_iterator cleanup;
398   llvm::Instruction *cleanupDominator = 0;
399   if (CGF.needsEHCleanup(dtorKind)) {
400     // In principle we could tell the cleanup where we are more
401     // directly, but the control flow can get so varied here that it
402     // would actually be quite complex.  Therefore we go through an
403     // alloca.
404     endOfInit = CGF.CreateTempAlloca(begin->getType(),
405                                      "arrayinit.endOfInit");
406     cleanupDominator = Builder.CreateStore(begin, endOfInit);
407     CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
408                                          CGF.getDestroyer(dtorKind));
409     cleanup = CGF.EHStack.stable_begin();
410 
411   // Otherwise, remember that we didn't need a cleanup.
412   } else {
413     dtorKind = QualType::DK_none;
414   }
415 
416   llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
417 
418   // The 'current element to initialize'.  The invariants on this
419   // variable are complicated.  Essentially, after each iteration of
420   // the loop, it points to the last initialized element, except
421   // that it points to the beginning of the array before any
422   // elements have been initialized.
423   llvm::Value *element = begin;
424 
425   // Emit the explicit initializers.
426   for (uint64_t i = 0; i != NumInitElements; ++i) {
427     // Advance to the next element.
428     if (i > 0) {
429       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
430 
431       // Tell the cleanup that it needs to destroy up to this
432       // element.  TODO: some of these stores can be trivially
433       // observed to be unnecessary.
434       if (endOfInit) Builder.CreateStore(element, endOfInit);
435     }
436 
437     // If these are nested std::initializer_list inits, do them directly,
438     // because they are conceptually the same "location".
439     InitListExpr *initList = dyn_cast<InitListExpr>(E->getInit(i));
440     if (initList && initList->initializesStdInitializerList()) {
441       EmitStdInitializerList(element, initList);
442     } else {
443       LValue elementLV = CGF.MakeAddrLValue(element, elementType);
444       EmitInitializationToLValue(E->getInit(i), elementLV);
445     }
446   }
447 
448   // Check whether there's a non-trivial array-fill expression.
449   // Note that this will be a CXXConstructExpr even if the element
450   // type is an array (or array of array, etc.) of class type.
451   Expr *filler = E->getArrayFiller();
452   bool hasTrivialFiller = true;
453   if (CXXConstructExpr *cons = dyn_cast_or_null<CXXConstructExpr>(filler)) {
454     assert(cons->getConstructor()->isDefaultConstructor());
455     hasTrivialFiller = cons->getConstructor()->isTrivial();
456   }
457 
458   // Any remaining elements need to be zero-initialized, possibly
459   // using the filler expression.  We can skip this if the we're
460   // emitting to zeroed memory.
461   if (NumInitElements != NumArrayElements &&
462       !(Dest.isZeroed() && hasTrivialFiller &&
463         CGF.getTypes().isZeroInitializable(elementType))) {
464 
465     // Use an actual loop.  This is basically
466     //   do { *array++ = filler; } while (array != end);
467 
468     // Advance to the start of the rest of the array.
469     if (NumInitElements) {
470       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
471       if (endOfInit) Builder.CreateStore(element, endOfInit);
472     }
473 
474     // Compute the end of the array.
475     llvm::Value *end = Builder.CreateInBoundsGEP(begin,
476                       llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
477                                                  "arrayinit.end");
478 
479     llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
480     llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
481 
482     // Jump into the body.
483     CGF.EmitBlock(bodyBB);
484     llvm::PHINode *currentElement =
485       Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
486     currentElement->addIncoming(element, entryBB);
487 
488     // Emit the actual filler expression.
489     LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
490     if (filler)
491       EmitInitializationToLValue(filler, elementLV);
492     else
493       EmitNullInitializationToLValue(elementLV);
494 
495     // Move on to the next element.
496     llvm::Value *nextElement =
497       Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
498 
499     // Tell the EH cleanup that we finished with the last element.
500     if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
501 
502     // Leave the loop if we're done.
503     llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
504                                              "arrayinit.done");
505     llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
506     Builder.CreateCondBr(done, endBB, bodyBB);
507     currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
508 
509     CGF.EmitBlock(endBB);
510   }
511 
512   // Leave the partial-array cleanup if we entered one.
513   if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
514 }
515 
516 //===----------------------------------------------------------------------===//
517 //                            Visitor Methods
518 //===----------------------------------------------------------------------===//
519 
520 void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
521   Visit(E->GetTemporaryExpr());
522 }
523 
524 void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
525   EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e));
526 }
527 
528 void
529 AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
530   if (E->getType().isPODType(CGF.getContext())) {
531     // For a POD type, just emit a load of the lvalue + a copy, because our
532     // compound literal might alias the destination.
533     // FIXME: This is a band-aid; the real problem appears to be in our handling
534     // of assignments, where we store directly into the LHS without checking
535     // whether anything in the RHS aliases.
536     EmitAggLoadOfLValue(E);
537     return;
538   }
539 
540   AggValueSlot Slot = EnsureSlot(E->getType());
541   CGF.EmitAggExpr(E->getInitializer(), Slot);
542 }
543 
544 
545 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
546   switch (E->getCastKind()) {
547   case CK_Dynamic: {
548     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
549     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
550     // FIXME: Do we also need to handle property references here?
551     if (LV.isSimple())
552       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
553     else
554       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
555 
556     if (!Dest.isIgnored())
557       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
558     break;
559   }
560 
561   case CK_ToUnion: {
562     if (Dest.isIgnored()) break;
563 
564     // GCC union extension
565     QualType Ty = E->getSubExpr()->getType();
566     QualType PtrTy = CGF.getContext().getPointerType(Ty);
567     llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
568                                                  CGF.ConvertType(PtrTy));
569     EmitInitializationToLValue(E->getSubExpr(),
570                                CGF.MakeAddrLValue(CastPtr, Ty));
571     break;
572   }
573 
574   case CK_DerivedToBase:
575   case CK_BaseToDerived:
576   case CK_UncheckedDerivedToBase: {
577     llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
578                 "should have been unpacked before we got here");
579   }
580 
581   case CK_LValueToRValue: // hope for downstream optimization
582   case CK_NoOp:
583   case CK_AtomicToNonAtomic:
584   case CK_NonAtomicToAtomic:
585   case CK_UserDefinedConversion:
586   case CK_ConstructorConversion:
587     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
588                                                    E->getType()) &&
589            "Implicit cast types must be compatible");
590     Visit(E->getSubExpr());
591     break;
592 
593   case CK_LValueBitCast:
594     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
595 
596   case CK_Dependent:
597   case CK_BitCast:
598   case CK_ArrayToPointerDecay:
599   case CK_FunctionToPointerDecay:
600   case CK_NullToPointer:
601   case CK_NullToMemberPointer:
602   case CK_BaseToDerivedMemberPointer:
603   case CK_DerivedToBaseMemberPointer:
604   case CK_MemberPointerToBoolean:
605   case CK_ReinterpretMemberPointer:
606   case CK_IntegralToPointer:
607   case CK_PointerToIntegral:
608   case CK_PointerToBoolean:
609   case CK_ToVoid:
610   case CK_VectorSplat:
611   case CK_IntegralCast:
612   case CK_IntegralToBoolean:
613   case CK_IntegralToFloating:
614   case CK_FloatingToIntegral:
615   case CK_FloatingToBoolean:
616   case CK_FloatingCast:
617   case CK_CPointerToObjCPointerCast:
618   case CK_BlockPointerToObjCPointerCast:
619   case CK_AnyPointerToBlockPointerCast:
620   case CK_ObjCObjectLValueCast:
621   case CK_FloatingRealToComplex:
622   case CK_FloatingComplexToReal:
623   case CK_FloatingComplexToBoolean:
624   case CK_FloatingComplexCast:
625   case CK_FloatingComplexToIntegralComplex:
626   case CK_IntegralRealToComplex:
627   case CK_IntegralComplexToReal:
628   case CK_IntegralComplexToBoolean:
629   case CK_IntegralComplexCast:
630   case CK_IntegralComplexToFloatingComplex:
631   case CK_ARCProduceObject:
632   case CK_ARCConsumeObject:
633   case CK_ARCReclaimReturnedObject:
634   case CK_ARCExtendBlockObject:
635   case CK_CopyAndAutoreleaseBlockObject:
636     llvm_unreachable("cast kind invalid for aggregate types");
637   }
638 }
639 
640 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
641   if (E->getCallReturnType()->isReferenceType()) {
642     EmitAggLoadOfLValue(E);
643     return;
644   }
645 
646   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
647   EmitMoveFromReturnSlot(E, RV);
648 }
649 
650 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
651   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
652   EmitMoveFromReturnSlot(E, RV);
653 }
654 
655 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
656   CGF.EmitIgnoredExpr(E->getLHS());
657   Visit(E->getRHS());
658 }
659 
660 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
661   CodeGenFunction::StmtExprEvaluation eval(CGF);
662   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
663 }
664 
665 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
666   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
667     VisitPointerToDataMemberBinaryOperator(E);
668   else
669     CGF.ErrorUnsupported(E, "aggregate binary expression");
670 }
671 
672 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
673                                                     const BinaryOperator *E) {
674   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
675   EmitFinalDestCopy(E, LV);
676 }
677 
678 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
679   // For an assignment to work, the value on the right has
680   // to be compatible with the value on the left.
681   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
682                                                  E->getRHS()->getType())
683          && "Invalid assignment");
684 
685   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getLHS()))
686     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
687       if (VD->hasAttr<BlocksAttr>() &&
688           E->getRHS()->HasSideEffects(CGF.getContext())) {
689         // When __block variable on LHS, the RHS must be evaluated first
690         // as it may change the 'forwarding' field via call to Block_copy.
691         LValue RHS = CGF.EmitLValue(E->getRHS());
692         LValue LHS = CGF.EmitLValue(E->getLHS());
693         Dest = AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
694                                        needsGC(E->getLHS()->getType()),
695                                        AggValueSlot::IsAliased);
696         EmitFinalDestCopy(E, RHS, true);
697         return;
698       }
699 
700   LValue LHS = CGF.EmitLValue(E->getLHS());
701 
702   // Codegen the RHS so that it stores directly into the LHS.
703   AggValueSlot LHSSlot =
704     AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
705                             needsGC(E->getLHS()->getType()),
706                             AggValueSlot::IsAliased);
707   CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
708   EmitFinalDestCopy(E, LHS, true);
709 }
710 
711 void AggExprEmitter::
712 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
713   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
714   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
715   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
716 
717   // Bind the common expression if necessary.
718   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
719 
720   CodeGenFunction::ConditionalEvaluation eval(CGF);
721   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
722 
723   // Save whether the destination's lifetime is externally managed.
724   bool isExternallyDestructed = Dest.isExternallyDestructed();
725 
726   eval.begin(CGF);
727   CGF.EmitBlock(LHSBlock);
728   Visit(E->getTrueExpr());
729   eval.end(CGF);
730 
731   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
732   CGF.Builder.CreateBr(ContBlock);
733 
734   // If the result of an agg expression is unused, then the emission
735   // of the LHS might need to create a destination slot.  That's fine
736   // with us, and we can safely emit the RHS into the same slot, but
737   // we shouldn't claim that it's already being destructed.
738   Dest.setExternallyDestructed(isExternallyDestructed);
739 
740   eval.begin(CGF);
741   CGF.EmitBlock(RHSBlock);
742   Visit(E->getFalseExpr());
743   eval.end(CGF);
744 
745   CGF.EmitBlock(ContBlock);
746 }
747 
748 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
749   Visit(CE->getChosenSubExpr(CGF.getContext()));
750 }
751 
752 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
753   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
754   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
755 
756   if (!ArgPtr) {
757     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
758     return;
759   }
760 
761   EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
762 }
763 
764 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
765   // Ensure that we have a slot, but if we already do, remember
766   // whether it was externally destructed.
767   bool wasExternallyDestructed = Dest.isExternallyDestructed();
768   Dest = EnsureSlot(E->getType());
769 
770   // We're going to push a destructor if there isn't already one.
771   Dest.setExternallyDestructed();
772 
773   Visit(E->getSubExpr());
774 
775   // Push that destructor we promised.
776   if (!wasExternallyDestructed)
777     CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
778 }
779 
780 void
781 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
782   AggValueSlot Slot = EnsureSlot(E->getType());
783   CGF.EmitCXXConstructExpr(E, Slot);
784 }
785 
786 void
787 AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
788   AggValueSlot Slot = EnsureSlot(E->getType());
789   CGF.EmitLambdaExpr(E, Slot);
790 }
791 
792 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
793   CGF.enterFullExpression(E);
794   CodeGenFunction::RunCleanupsScope cleanups(CGF);
795   Visit(E->getSubExpr());
796 }
797 
798 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
799   QualType T = E->getType();
800   AggValueSlot Slot = EnsureSlot(T);
801   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
802 }
803 
804 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
805   QualType T = E->getType();
806   AggValueSlot Slot = EnsureSlot(T);
807   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
808 }
809 
810 /// isSimpleZero - If emitting this value will obviously just cause a store of
811 /// zero to memory, return true.  This can return false if uncertain, so it just
812 /// handles simple cases.
813 static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
814   E = E->IgnoreParens();
815 
816   // 0
817   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
818     return IL->getValue() == 0;
819   // +0.0
820   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
821     return FL->getValue().isPosZero();
822   // int()
823   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
824       CGF.getTypes().isZeroInitializable(E->getType()))
825     return true;
826   // (int*)0 - Null pointer expressions.
827   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
828     return ICE->getCastKind() == CK_NullToPointer;
829   // '\0'
830   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
831     return CL->getValue() == 0;
832 
833   // Otherwise, hard case: conservatively return false.
834   return false;
835 }
836 
837 
838 void
839 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
840   QualType type = LV.getType();
841   // FIXME: Ignore result?
842   // FIXME: Are initializers affected by volatile?
843   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
844     // Storing "i32 0" to a zero'd memory location is a noop.
845   } else if (isa<ImplicitValueInitExpr>(E)) {
846     EmitNullInitializationToLValue(LV);
847   } else if (type->isReferenceType()) {
848     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
849     CGF.EmitStoreThroughLValue(RV, LV);
850   } else if (type->isAnyComplexType()) {
851     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
852   } else if (CGF.hasAggregateLLVMType(type)) {
853     CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
854                                                AggValueSlot::IsDestructed,
855                                       AggValueSlot::DoesNotNeedGCBarriers,
856                                                AggValueSlot::IsNotAliased,
857                                                Dest.isZeroed()));
858   } else if (LV.isSimple()) {
859     CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
860   } else {
861     CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
862   }
863 }
864 
865 void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
866   QualType type = lv.getType();
867 
868   // If the destination slot is already zeroed out before the aggregate is
869   // copied into it, we don't have to emit any zeros here.
870   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
871     return;
872 
873   if (!CGF.hasAggregateLLVMType(type)) {
874     // For non-aggregates, we can store zero.
875     llvm::Value *null = llvm::Constant::getNullValue(CGF.ConvertType(type));
876     // Note that the following is not equivalent to
877     // EmitStoreThroughBitfieldLValue for ARC types.
878     if (lv.isBitField()) {
879       CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
880     } else {
881       assert(lv.isSimple());
882       CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
883     }
884   } else {
885     // There's a potential optimization opportunity in combining
886     // memsets; that would be easy for arrays, but relatively
887     // difficult for structures with the current code.
888     CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
889   }
890 }
891 
892 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
893 #if 0
894   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
895   // (Length of globals? Chunks of zeroed-out space?).
896   //
897   // If we can, prefer a copy from a global; this is a lot less code for long
898   // globals, and it's easier for the current optimizers to analyze.
899   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
900     llvm::GlobalVariable* GV =
901     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
902                              llvm::GlobalValue::InternalLinkage, C, "");
903     EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
904     return;
905   }
906 #endif
907   if (E->hadArrayRangeDesignator())
908     CGF.ErrorUnsupported(E, "GNU array range designator extension");
909 
910   if (E->initializesStdInitializerList()) {
911     EmitStdInitializerList(Dest.getAddr(), E);
912     return;
913   }
914 
915   llvm::Value *DestPtr = EnsureSlot(E->getType()).getAddr();
916 
917   // Handle initialization of an array.
918   if (E->getType()->isArrayType()) {
919     if (E->getNumInits() > 0) {
920       QualType T1 = E->getType();
921       QualType T2 = E->getInit(0)->getType();
922       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
923         EmitAggLoadOfLValue(E->getInit(0));
924         return;
925       }
926     }
927 
928     QualType elementType =
929         CGF.getContext().getAsArrayType(E->getType())->getElementType();
930 
931     llvm::PointerType *APType =
932       cast<llvm::PointerType>(DestPtr->getType());
933     llvm::ArrayType *AType =
934       cast<llvm::ArrayType>(APType->getElementType());
935 
936     EmitArrayInit(DestPtr, AType, elementType, E);
937     return;
938   }
939 
940   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
941 
942   // Do struct initialization; this code just sets each individual member
943   // to the approprate value.  This makes bitfield support automatic;
944   // the disadvantage is that the generated code is more difficult for
945   // the optimizer, especially with bitfields.
946   unsigned NumInitElements = E->getNumInits();
947   RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
948 
949   if (record->isUnion()) {
950     // Only initialize one field of a union. The field itself is
951     // specified by the initializer list.
952     if (!E->getInitializedFieldInUnion()) {
953       // Empty union; we have nothing to do.
954 
955 #ifndef NDEBUG
956       // Make sure that it's really an empty and not a failure of
957       // semantic analysis.
958       for (RecordDecl::field_iterator Field = record->field_begin(),
959                                    FieldEnd = record->field_end();
960            Field != FieldEnd; ++Field)
961         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
962 #endif
963       return;
964     }
965 
966     // FIXME: volatility
967     FieldDecl *Field = E->getInitializedFieldInUnion();
968 
969     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
970     if (NumInitElements) {
971       // Store the initializer into the field
972       EmitInitializationToLValue(E->getInit(0), FieldLoc);
973     } else {
974       // Default-initialize to null.
975       EmitNullInitializationToLValue(FieldLoc);
976     }
977 
978     return;
979   }
980 
981   // We'll need to enter cleanup scopes in case any of the member
982   // initializers throw an exception.
983   SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
984   llvm::Instruction *cleanupDominator = 0;
985 
986   // Here we iterate over the fields; this makes it simpler to both
987   // default-initialize fields and skip over unnamed fields.
988   unsigned curInitIndex = 0;
989   for (RecordDecl::field_iterator field = record->field_begin(),
990                                fieldEnd = record->field_end();
991        field != fieldEnd; ++field) {
992     // We're done once we hit the flexible array member.
993     if (field->getType()->isIncompleteArrayType())
994       break;
995 
996     // Always skip anonymous bitfields.
997     if (field->isUnnamedBitfield())
998       continue;
999 
1000     // We're done if we reach the end of the explicit initializers, we
1001     // have a zeroed object, and the rest of the fields are
1002     // zero-initializable.
1003     if (curInitIndex == NumInitElements && Dest.isZeroed() &&
1004         CGF.getTypes().isZeroInitializable(E->getType()))
1005       break;
1006 
1007     // FIXME: volatility
1008     LValue LV = CGF.EmitLValueForFieldInitialization(DestPtr, *field, 0);
1009     // We never generate write-barries for initialized fields.
1010     LV.setNonGC(true);
1011 
1012     if (curInitIndex < NumInitElements) {
1013       // Store the initializer into the field.
1014       EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
1015     } else {
1016       // We're out of initalizers; default-initialize to null
1017       EmitNullInitializationToLValue(LV);
1018     }
1019 
1020     // Push a destructor if necessary.
1021     // FIXME: if we have an array of structures, all explicitly
1022     // initialized, we can end up pushing a linear number of cleanups.
1023     bool pushedCleanup = false;
1024     if (QualType::DestructionKind dtorKind
1025           = field->getType().isDestructedType()) {
1026       assert(LV.isSimple());
1027       if (CGF.needsEHCleanup(dtorKind)) {
1028         if (!cleanupDominator)
1029           cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1030 
1031         CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1032                         CGF.getDestroyer(dtorKind), false);
1033         cleanups.push_back(CGF.EHStack.stable_begin());
1034         pushedCleanup = true;
1035       }
1036     }
1037 
1038     // If the GEP didn't get used because of a dead zero init or something
1039     // else, clean it up for -O0 builds and general tidiness.
1040     if (!pushedCleanup && LV.isSimple())
1041       if (llvm::GetElementPtrInst *GEP =
1042             dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
1043         if (GEP->use_empty())
1044           GEP->eraseFromParent();
1045   }
1046 
1047   // Deactivate all the partial cleanups in reverse order, which
1048   // generally means popping them.
1049   for (unsigned i = cleanups.size(); i != 0; --i)
1050     CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1051 
1052   // Destroy the placeholder if we made one.
1053   if (cleanupDominator)
1054     cleanupDominator->eraseFromParent();
1055 }
1056 
1057 //===----------------------------------------------------------------------===//
1058 //                        Entry Points into this File
1059 //===----------------------------------------------------------------------===//
1060 
1061 /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1062 /// non-zero bytes that will be stored when outputting the initializer for the
1063 /// specified initializer expression.
1064 static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
1065   E = E->IgnoreParens();
1066 
1067   // 0 and 0.0 won't require any non-zero stores!
1068   if (isSimpleZero(E, CGF)) return CharUnits::Zero();
1069 
1070   // If this is an initlist expr, sum up the size of sizes of the (present)
1071   // elements.  If this is something weird, assume the whole thing is non-zero.
1072   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
1073   if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
1074     return CGF.getContext().getTypeSizeInChars(E->getType());
1075 
1076   // InitListExprs for structs have to be handled carefully.  If there are
1077   // reference members, we need to consider the size of the reference, not the
1078   // referencee.  InitListExprs for unions and arrays can't have references.
1079   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1080     if (!RT->isUnionType()) {
1081       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
1082       CharUnits NumNonZeroBytes = CharUnits::Zero();
1083 
1084       unsigned ILEElement = 0;
1085       for (RecordDecl::field_iterator Field = SD->field_begin(),
1086            FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
1087         // We're done once we hit the flexible array member or run out of
1088         // InitListExpr elements.
1089         if (Field->getType()->isIncompleteArrayType() ||
1090             ILEElement == ILE->getNumInits())
1091           break;
1092         if (Field->isUnnamedBitfield())
1093           continue;
1094 
1095         const Expr *E = ILE->getInit(ILEElement++);
1096 
1097         // Reference values are always non-null and have the width of a pointer.
1098         if (Field->getType()->isReferenceType())
1099           NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1100               CGF.getContext().getTargetInfo().getPointerWidth(0));
1101         else
1102           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1103       }
1104 
1105       return NumNonZeroBytes;
1106     }
1107   }
1108 
1109 
1110   CharUnits NumNonZeroBytes = CharUnits::Zero();
1111   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1112     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1113   return NumNonZeroBytes;
1114 }
1115 
1116 /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1117 /// zeros in it, emit a memset and avoid storing the individual zeros.
1118 ///
1119 static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1120                                      CodeGenFunction &CGF) {
1121   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
1122   // volatile stores.
1123   if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
1124 
1125   // C++ objects with a user-declared constructor don't need zero'ing.
1126   if (CGF.getContext().getLangOpts().CPlusPlus)
1127     if (const RecordType *RT = CGF.getContext()
1128                        .getBaseElementType(E->getType())->getAs<RecordType>()) {
1129       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1130       if (RD->hasUserDeclaredConstructor())
1131         return;
1132     }
1133 
1134   // If the type is 16-bytes or smaller, prefer individual stores over memset.
1135   std::pair<CharUnits, CharUnits> TypeInfo =
1136     CGF.getContext().getTypeInfoInChars(E->getType());
1137   if (TypeInfo.first <= CharUnits::fromQuantity(16))
1138     return;
1139 
1140   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
1141   // we prefer to emit memset + individual stores for the rest.
1142   CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1143   if (NumNonZeroBytes*4 > TypeInfo.first)
1144     return;
1145 
1146   // Okay, it seems like a good idea to use an initial memset, emit the call.
1147   llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1148   CharUnits Align = TypeInfo.second;
1149 
1150   llvm::Value *Loc = Slot.getAddr();
1151 
1152   Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
1153   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1154                            Align.getQuantity(), false);
1155 
1156   // Tell the AggExprEmitter that the slot is known zero.
1157   Slot.setZeroed();
1158 }
1159 
1160 
1161 
1162 
1163 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
1164 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
1165 /// the value of the aggregate expression is not needed.  If VolatileDest is
1166 /// true, DestPtr cannot be 0.
1167 ///
1168 /// \param IsInitializer - true if this evaluation is initializing an
1169 /// object whose lifetime is already being managed.
1170 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
1171                                   bool IgnoreResult) {
1172   assert(E && hasAggregateLLVMType(E->getType()) &&
1173          "Invalid aggregate expression to emit");
1174   assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
1175          "slot has bits but no address");
1176 
1177   // Optimize the slot if possible.
1178   CheckAggExprForMemSetUse(Slot, E, *this);
1179 
1180   AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E));
1181 }
1182 
1183 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1184   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
1185   llvm::Value *Temp = CreateMemTemp(E->getType());
1186   LValue LV = MakeAddrLValue(Temp, E->getType());
1187   EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
1188                                          AggValueSlot::DoesNotNeedGCBarriers,
1189                                          AggValueSlot::IsNotAliased));
1190   return LV;
1191 }
1192 
1193 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1194                                         llvm::Value *SrcPtr, QualType Ty,
1195                                         bool isVolatile, unsigned Alignment) {
1196   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
1197 
1198   if (getContext().getLangOpts().CPlusPlus) {
1199     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1200       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1201       assert((Record->hasTrivialCopyConstructor() ||
1202               Record->hasTrivialCopyAssignment() ||
1203               Record->hasTrivialMoveConstructor() ||
1204               Record->hasTrivialMoveAssignment()) &&
1205              "Trying to aggregate-copy a type without a trivial copy "
1206              "constructor or assignment operator");
1207       // Ignore empty classes in C++.
1208       if (Record->isEmpty())
1209         return;
1210     }
1211   }
1212 
1213   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
1214   // C99 6.5.16.1p3, which states "If the value being stored in an object is
1215   // read from another object that overlaps in anyway the storage of the first
1216   // object, then the overlap shall be exact and the two objects shall have
1217   // qualified or unqualified versions of a compatible type."
1218   //
1219   // memcpy is not defined if the source and destination pointers are exactly
1220   // equal, but other compilers do this optimization, and almost every memcpy
1221   // implementation handles this case safely.  If there is a libc that does not
1222   // safely handle this, we can add a target hook.
1223 
1224   // Get size and alignment info for this aggregate.
1225   std::pair<CharUnits, CharUnits> TypeInfo =
1226     getContext().getTypeInfoInChars(Ty);
1227 
1228   if (!Alignment)
1229     Alignment = TypeInfo.second.getQuantity();
1230 
1231   // FIXME: Handle variable sized types.
1232 
1233   // FIXME: If we have a volatile struct, the optimizer can remove what might
1234   // appear to be `extra' memory ops:
1235   //
1236   // volatile struct { int i; } a, b;
1237   //
1238   // int main() {
1239   //   a = b;
1240   //   a = b;
1241   // }
1242   //
1243   // we need to use a different call here.  We use isVolatile to indicate when
1244   // either the source or the destination is volatile.
1245 
1246   llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1247   llvm::Type *DBP =
1248     llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1249   DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1250 
1251   llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1252   llvm::Type *SBP =
1253     llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1254   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1255 
1256   // Don't do any of the memmove_collectable tests if GC isn't set.
1257   if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1258     // fall through
1259   } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1260     RecordDecl *Record = RecordTy->getDecl();
1261     if (Record->hasObjectMember()) {
1262       CharUnits size = TypeInfo.first;
1263       llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1264       llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
1265       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1266                                                     SizeVal);
1267       return;
1268     }
1269   } else if (Ty->isArrayType()) {
1270     QualType BaseType = getContext().getBaseElementType(Ty);
1271     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1272       if (RecordTy->getDecl()->hasObjectMember()) {
1273         CharUnits size = TypeInfo.first;
1274         llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1275         llvm::Value *SizeVal =
1276           llvm::ConstantInt::get(SizeTy, size.getQuantity());
1277         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1278                                                       SizeVal);
1279         return;
1280       }
1281     }
1282   }
1283 
1284   Builder.CreateMemCpy(DestPtr, SrcPtr,
1285                        llvm::ConstantInt::get(IntPtrTy,
1286                                               TypeInfo.first.getQuantity()),
1287                        Alignment, isVolatile);
1288 }
1289 
1290 void CodeGenFunction::MaybeEmitStdInitializerListCleanup(llvm::Value *loc,
1291                                                          const Expr *init) {
1292   const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(init);
1293   if (cleanups)
1294     init = cleanups->getSubExpr();
1295 
1296   if (isa<InitListExpr>(init) &&
1297       cast<InitListExpr>(init)->initializesStdInitializerList()) {
1298     // We initialized this std::initializer_list with an initializer list.
1299     // A backing array was created. Push a cleanup for it.
1300     EmitStdInitializerListCleanup(loc, cast<InitListExpr>(init));
1301   }
1302 }
1303 
1304 static void EmitRecursiveStdInitializerListCleanup(CodeGenFunction &CGF,
1305                                                    llvm::Value *arrayStart,
1306                                                    const InitListExpr *init) {
1307   // Check if there are any recursive cleanups to do, i.e. if we have
1308   //   std::initializer_list<std::initializer_list<obj>> list = {{obj()}};
1309   // then we need to destroy the inner array as well.
1310   for (unsigned i = 0, e = init->getNumInits(); i != e; ++i) {
1311     const InitListExpr *subInit = dyn_cast<InitListExpr>(init->getInit(i));
1312     if (!subInit || !subInit->initializesStdInitializerList())
1313       continue;
1314 
1315     // This one needs to be destroyed. Get the address of the std::init_list.
1316     llvm::Value *offset = llvm::ConstantInt::get(CGF.SizeTy, i);
1317     llvm::Value *loc = CGF.Builder.CreateInBoundsGEP(arrayStart, offset,
1318                                                  "std.initlist");
1319     CGF.EmitStdInitializerListCleanup(loc, subInit);
1320   }
1321 }
1322 
1323 void CodeGenFunction::EmitStdInitializerListCleanup(llvm::Value *loc,
1324                                                     const InitListExpr *init) {
1325   ASTContext &ctx = getContext();
1326   QualType element = GetStdInitializerListElementType(init->getType());
1327   unsigned numInits = init->getNumInits();
1328   llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
1329   QualType array =ctx.getConstantArrayType(element, size, ArrayType::Normal, 0);
1330   QualType arrayPtr = ctx.getPointerType(array);
1331   llvm::Type *arrayPtrType = ConvertType(arrayPtr);
1332 
1333   // lvalue is the location of a std::initializer_list, which as its first
1334   // element has a pointer to the array we want to destroy.
1335   llvm::Value *startPointer = Builder.CreateStructGEP(loc, 0, "startPointer");
1336   llvm::Value *startAddress = Builder.CreateLoad(startPointer, "startAddress");
1337 
1338   ::EmitRecursiveStdInitializerListCleanup(*this, startAddress, init);
1339 
1340   llvm::Value *arrayAddress =
1341       Builder.CreateBitCast(startAddress, arrayPtrType, "arrayAddress");
1342   ::EmitStdInitializerListCleanup(*this, array, arrayAddress, init);
1343 }
1344