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