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