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