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