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