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   ReturnValueSlot getReturnValueSlot() const {
39     // If the destination slot requires garbage collection, we can't
40     // use the real return value slot, because we have to use the GC
41     // API.
42     if (Dest.requiresGCollection()) return ReturnValueSlot();
43 
44     return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
45   }
46 
47   AggValueSlot EnsureSlot(QualType T) {
48     if (!Dest.isIgnored()) return Dest;
49     return CGF.CreateAggTemp(T, "agg.tmp.ensured");
50   }
51 
52 public:
53   AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest,
54                  bool ignore)
55     : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
56       IgnoreResult(ignore) {
57   }
58 
59   //===--------------------------------------------------------------------===//
60   //                               Utilities
61   //===--------------------------------------------------------------------===//
62 
63   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
64   /// represents a value lvalue, this method emits the address of the lvalue,
65   /// then loads the result into DestPtr.
66   void EmitAggLoadOfLValue(const Expr *E);
67 
68   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
69   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
70   void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
71 
72   void EmitGCMove(const Expr *E, RValue Src);
73 
74   bool TypeRequiresGCollection(QualType T);
75 
76   //===--------------------------------------------------------------------===//
77   //                            Visitor Methods
78   //===--------------------------------------------------------------------===//
79 
80   void VisitStmt(Stmt *S) {
81     CGF.ErrorUnsupported(S, "aggregate expression");
82   }
83   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
84   void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
85     Visit(GE->getResultExpr());
86   }
87   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
88 
89   // l-values.
90   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
91   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
92   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
93   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
94   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
95     EmitAggLoadOfLValue(E);
96   }
97   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
98     EmitAggLoadOfLValue(E);
99   }
100   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
101     EmitAggLoadOfLValue(E);
102   }
103   void VisitPredefinedExpr(const PredefinedExpr *E) {
104     EmitAggLoadOfLValue(E);
105   }
106 
107   // Operators.
108   void VisitCastExpr(CastExpr *E);
109   void VisitCallExpr(const CallExpr *E);
110   void VisitStmtExpr(const StmtExpr *E);
111   void VisitBinaryOperator(const BinaryOperator *BO);
112   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
113   void VisitBinAssign(const BinaryOperator *E);
114   void VisitBinComma(const BinaryOperator *E);
115 
116   void VisitObjCMessageExpr(ObjCMessageExpr *E);
117   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
118     EmitAggLoadOfLValue(E);
119   }
120   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
121 
122   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
123   void VisitChooseExpr(const ChooseExpr *CE);
124   void VisitInitListExpr(InitListExpr *E);
125   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
126   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
127     Visit(DAE->getExpr());
128   }
129   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
130   void VisitCXXConstructExpr(const CXXConstructExpr *E);
131   void VisitExprWithCleanups(ExprWithCleanups *E);
132   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
133   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
134 
135   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
136 
137   void VisitVAArgExpr(VAArgExpr *E);
138 
139   void EmitInitializationToLValue(Expr *E, LValue Address, QualType T);
140   void EmitNullInitializationToLValue(LValue Address, QualType T);
141   //  case Expr::ChooseExprClass:
142   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
143 };
144 }  // end anonymous namespace.
145 
146 //===----------------------------------------------------------------------===//
147 //                                Utilities
148 //===----------------------------------------------------------------------===//
149 
150 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
151 /// represents a value lvalue, this method emits the address of the lvalue,
152 /// then loads the result into DestPtr.
153 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
154   LValue LV = CGF.EmitLValue(E);
155   EmitFinalDestCopy(E, LV);
156 }
157 
158 /// \brief True if the given aggregate type requires special GC API calls.
159 bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
160   // Only record types have members that might require garbage collection.
161   const RecordType *RecordTy = T->getAs<RecordType>();
162   if (!RecordTy) return false;
163 
164   // Don't mess with non-trivial C++ types.
165   RecordDecl *Record = RecordTy->getDecl();
166   if (isa<CXXRecordDecl>(Record) &&
167       (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
168        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
169     return false;
170 
171   // Check whether the type has an object member.
172   return Record->hasObjectMember();
173 }
174 
175 /// \brief Perform the final move to DestPtr if RequiresGCollection is set.
176 ///
177 /// The idea is that you do something like this:
178 ///   RValue Result = EmitSomething(..., getReturnValueSlot());
179 ///   EmitGCMove(E, Result);
180 /// If GC doesn't interfere, this will cause the result to be emitted
181 /// directly into the return value slot.  If GC does interfere, a final
182 /// move will be performed.
183 void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) {
184   if (Dest.requiresGCollection()) {
185     uint64_t size = CGF.getContext().getTypeSize(E->getType())/8;
186     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
187     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
188     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, Dest.getAddr(),
189                                                     Src.getAggregateAddr(),
190                                                     SizeVal);
191   }
192 }
193 
194 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
195 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
196   assert(Src.isAggregate() && "value must be aggregate value!");
197 
198   // If Dest is ignored, then we're evaluating an aggregate expression
199   // in a context (like an expression statement) that doesn't care
200   // about the result.  C says that an lvalue-to-rvalue conversion is
201   // performed in these cases; C++ says that it is not.  In either
202   // case, we don't actually need to do anything unless the value is
203   // volatile.
204   if (Dest.isIgnored()) {
205     if (!Src.isVolatileQualified() ||
206         CGF.CGM.getLangOptions().CPlusPlus ||
207         (IgnoreResult && Ignore))
208       return;
209 
210     // If the source is volatile, we must read from it; to do that, we need
211     // some place to put it.
212     Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
213   }
214 
215   if (Dest.requiresGCollection()) {
216     uint64_t size = CGF.getContext().getTypeSize(E->getType())/8;
217     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
218     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
219     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
220                                                       Dest.getAddr(),
221                                                       Src.getAggregateAddr(),
222                                                       SizeVal);
223     return;
224   }
225   // If the result of the assignment is used, copy the LHS there also.
226   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
227   // from the source as well, as we can't eliminate it if either operand
228   // is volatile, unless copy has volatile for both source and destination..
229   CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
230                         Dest.isVolatile()|Src.isVolatileQualified());
231 }
232 
233 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
234 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
235   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
236 
237   EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
238                                             Src.isVolatileQualified()),
239                     Ignore);
240 }
241 
242 //===----------------------------------------------------------------------===//
243 //                            Visitor Methods
244 //===----------------------------------------------------------------------===//
245 
246 void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
247   EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e));
248 }
249 
250 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
251   switch (E->getCastKind()) {
252   case CK_Dynamic: {
253     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
254     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
255     // FIXME: Do we also need to handle property references here?
256     if (LV.isSimple())
257       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
258     else
259       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
260 
261     if (!Dest.isIgnored())
262       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
263     break;
264   }
265 
266   case CK_ToUnion: {
267     if (Dest.isIgnored()) break;
268 
269     // GCC union extension
270     QualType Ty = E->getSubExpr()->getType();
271     QualType PtrTy = CGF.getContext().getPointerType(Ty);
272     llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
273                                                  CGF.ConvertType(PtrTy));
274     EmitInitializationToLValue(E->getSubExpr(), CGF.MakeAddrLValue(CastPtr, Ty),
275                                Ty);
276     break;
277   }
278 
279   case CK_DerivedToBase:
280   case CK_BaseToDerived:
281   case CK_UncheckedDerivedToBase: {
282     assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: "
283                 "should have been unpacked before we got here");
284     break;
285   }
286 
287   case CK_GetObjCProperty: {
288     LValue LV = CGF.EmitLValue(E->getSubExpr());
289     assert(LV.isPropertyRef());
290     RValue RV = CGF.EmitLoadOfPropertyRefLValue(LV, getReturnValueSlot());
291     EmitGCMove(E, RV);
292     break;
293   }
294 
295   case CK_LValueToRValue: // hope for downstream optimization
296   case CK_NoOp:
297   case CK_UserDefinedConversion:
298   case CK_ConstructorConversion:
299     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
300                                                    E->getType()) &&
301            "Implicit cast types must be compatible");
302     Visit(E->getSubExpr());
303     break;
304 
305   case CK_LValueBitCast:
306     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
307     break;
308 
309   case CK_Dependent:
310   case CK_BitCast:
311   case CK_ArrayToPointerDecay:
312   case CK_FunctionToPointerDecay:
313   case CK_NullToPointer:
314   case CK_NullToMemberPointer:
315   case CK_BaseToDerivedMemberPointer:
316   case CK_DerivedToBaseMemberPointer:
317   case CK_MemberPointerToBoolean:
318   case CK_IntegralToPointer:
319   case CK_PointerToIntegral:
320   case CK_PointerToBoolean:
321   case CK_ToVoid:
322   case CK_VectorSplat:
323   case CK_IntegralCast:
324   case CK_IntegralToBoolean:
325   case CK_IntegralToFloating:
326   case CK_FloatingToIntegral:
327   case CK_FloatingToBoolean:
328   case CK_FloatingCast:
329   case CK_AnyPointerToObjCPointerCast:
330   case CK_AnyPointerToBlockPointerCast:
331   case CK_ObjCObjectLValueCast:
332   case CK_FloatingRealToComplex:
333   case CK_FloatingComplexToReal:
334   case CK_FloatingComplexToBoolean:
335   case CK_FloatingComplexCast:
336   case CK_FloatingComplexToIntegralComplex:
337   case CK_IntegralRealToComplex:
338   case CK_IntegralComplexToReal:
339   case CK_IntegralComplexToBoolean:
340   case CK_IntegralComplexCast:
341   case CK_IntegralComplexToFloatingComplex:
342     llvm_unreachable("cast kind invalid for aggregate types");
343   }
344 }
345 
346 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
347   if (E->getCallReturnType()->isReferenceType()) {
348     EmitAggLoadOfLValue(E);
349     return;
350   }
351 
352   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
353   EmitGCMove(E, RV);
354 }
355 
356 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
357   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
358   EmitGCMove(E, RV);
359 }
360 
361 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
362   llvm_unreachable("direct property access not surrounded by "
363                    "lvalue-to-rvalue cast");
364 }
365 
366 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
367   CGF.EmitIgnoredExpr(E->getLHS());
368   Visit(E->getRHS());
369 }
370 
371 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
372   CodeGenFunction::StmtExprEvaluation eval(CGF);
373   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
374 }
375 
376 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
377   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
378     VisitPointerToDataMemberBinaryOperator(E);
379   else
380     CGF.ErrorUnsupported(E, "aggregate binary expression");
381 }
382 
383 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
384                                                     const BinaryOperator *E) {
385   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
386   EmitFinalDestCopy(E, LV);
387 }
388 
389 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
390   // For an assignment to work, the value on the right has
391   // to be compatible with the value on the left.
392   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
393                                                  E->getRHS()->getType())
394          && "Invalid assignment");
395 
396   // FIXME:  __block variables need the RHS evaluated first!
397   LValue LHS = CGF.EmitLValue(E->getLHS());
398 
399   // We have to special case property setters, otherwise we must have
400   // a simple lvalue (no aggregates inside vectors, bitfields).
401   if (LHS.isPropertyRef()) {
402     const ObjCPropertyRefExpr *RE = LHS.getPropertyRefExpr();
403     QualType ArgType = RE->getSetterArgType();
404     RValue Src;
405     if (ArgType->isReferenceType())
406       Src = CGF.EmitReferenceBindingToExpr(E->getRHS(), 0);
407     else {
408       AggValueSlot Slot = EnsureSlot(E->getRHS()->getType());
409       CGF.EmitAggExpr(E->getRHS(), Slot);
410       Src = Slot.asRValue();
411     }
412     CGF.EmitStoreThroughPropertyRefLValue(Src, LHS);
413   } else {
414     bool GCollection = false;
415     if (CGF.getContext().getLangOptions().getGCMode())
416       GCollection = TypeRequiresGCollection(E->getLHS()->getType());
417 
418     // Codegen the RHS so that it stores directly into the LHS.
419     AggValueSlot LHSSlot = AggValueSlot::forLValue(LHS, true,
420                                                    GCollection);
421     CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
422     EmitFinalDestCopy(E, LHS, true);
423   }
424 }
425 
426 void AggExprEmitter::
427 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
428   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
429   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
430   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
431 
432   // Bind the common expression if necessary.
433   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
434 
435   CodeGenFunction::ConditionalEvaluation eval(CGF);
436   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
437 
438   // Save whether the destination's lifetime is externally managed.
439   bool DestLifetimeManaged = Dest.isLifetimeExternallyManaged();
440 
441   eval.begin(CGF);
442   CGF.EmitBlock(LHSBlock);
443   Visit(E->getTrueExpr());
444   eval.end(CGF);
445 
446   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
447   CGF.Builder.CreateBr(ContBlock);
448 
449   // If the result of an agg expression is unused, then the emission
450   // of the LHS might need to create a destination slot.  That's fine
451   // with us, and we can safely emit the RHS into the same slot, but
452   // we shouldn't claim that its lifetime is externally managed.
453   Dest.setLifetimeExternallyManaged(DestLifetimeManaged);
454 
455   eval.begin(CGF);
456   CGF.EmitBlock(RHSBlock);
457   Visit(E->getFalseExpr());
458   eval.end(CGF);
459 
460   CGF.EmitBlock(ContBlock);
461 }
462 
463 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
464   Visit(CE->getChosenSubExpr(CGF.getContext()));
465 }
466 
467 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
468   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
469   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
470 
471   if (!ArgPtr) {
472     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
473     return;
474   }
475 
476   EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
477 }
478 
479 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
480   // Ensure that we have a slot, but if we already do, remember
481   // whether its lifetime was externally managed.
482   bool WasManaged = Dest.isLifetimeExternallyManaged();
483   Dest = EnsureSlot(E->getType());
484   Dest.setLifetimeExternallyManaged();
485 
486   Visit(E->getSubExpr());
487 
488   // Set up the temporary's destructor if its lifetime wasn't already
489   // being managed.
490   if (!WasManaged)
491     CGF.EmitCXXTemporary(E->getTemporary(), Dest.getAddr());
492 }
493 
494 void
495 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
496   AggValueSlot Slot = EnsureSlot(E->getType());
497   CGF.EmitCXXConstructExpr(E, Slot);
498 }
499 
500 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
501   CGF.EmitExprWithCleanups(E, Dest);
502 }
503 
504 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
505   QualType T = E->getType();
506   AggValueSlot Slot = EnsureSlot(T);
507   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T), T);
508 }
509 
510 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
511   QualType T = E->getType();
512   AggValueSlot Slot = EnsureSlot(T);
513   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T), T);
514 }
515 
516 /// isSimpleZero - If emitting this value will obviously just cause a store of
517 /// zero to memory, return true.  This can return false if uncertain, so it just
518 /// handles simple cases.
519 static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
520   E = E->IgnoreParens();
521 
522   // 0
523   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
524     return IL->getValue() == 0;
525   // +0.0
526   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
527     return FL->getValue().isPosZero();
528   // int()
529   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
530       CGF.getTypes().isZeroInitializable(E->getType()))
531     return true;
532   // (int*)0 - Null pointer expressions.
533   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
534     return ICE->getCastKind() == CK_NullToPointer;
535   // '\0'
536   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
537     return CL->getValue() == 0;
538 
539   // Otherwise, hard case: conservatively return false.
540   return false;
541 }
542 
543 
544 void
545 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
546   // FIXME: Ignore result?
547   // FIXME: Are initializers affected by volatile?
548   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
549     // Storing "i32 0" to a zero'd memory location is a noop.
550   } else if (isa<ImplicitValueInitExpr>(E)) {
551     EmitNullInitializationToLValue(LV, T);
552   } else if (T->isReferenceType()) {
553     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
554     CGF.EmitStoreThroughLValue(RV, LV, T);
555   } else if (T->isAnyComplexType()) {
556     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
557   } else if (CGF.hasAggregateLLVMType(T)) {
558     CGF.EmitAggExpr(E, AggValueSlot::forAddr(LV.getAddress(), false, true,
559                                              false, Dest.isZeroed()));
560   } else {
561     CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV, T);
562   }
563 }
564 
565 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
566   // If the destination slot is already zeroed out before the aggregate is
567   // copied into it, we don't have to emit any zeros here.
568   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(T))
569     return;
570 
571   if (!CGF.hasAggregateLLVMType(T)) {
572     // For non-aggregates, we can store zero
573     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
574     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
575   } else {
576     // There's a potential optimization opportunity in combining
577     // memsets; that would be easy for arrays, but relatively
578     // difficult for structures with the current code.
579     CGF.EmitNullInitialization(LV.getAddress(), T);
580   }
581 }
582 
583 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
584 #if 0
585   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
586   // (Length of globals? Chunks of zeroed-out space?).
587   //
588   // If we can, prefer a copy from a global; this is a lot less code for long
589   // globals, and it's easier for the current optimizers to analyze.
590   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
591     llvm::GlobalVariable* GV =
592     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
593                              llvm::GlobalValue::InternalLinkage, C, "");
594     EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
595     return;
596   }
597 #endif
598   if (E->hadArrayRangeDesignator())
599     CGF.ErrorUnsupported(E, "GNU array range designator extension");
600 
601   llvm::Value *DestPtr = Dest.getAddr();
602 
603   // Handle initialization of an array.
604   if (E->getType()->isArrayType()) {
605     const llvm::PointerType *APType =
606       cast<llvm::PointerType>(DestPtr->getType());
607     const llvm::ArrayType *AType =
608       cast<llvm::ArrayType>(APType->getElementType());
609 
610     uint64_t NumInitElements = E->getNumInits();
611 
612     if (E->getNumInits() > 0) {
613       QualType T1 = E->getType();
614       QualType T2 = E->getInit(0)->getType();
615       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
616         EmitAggLoadOfLValue(E->getInit(0));
617         return;
618       }
619     }
620 
621     uint64_t NumArrayElements = AType->getNumElements();
622     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
623     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
624 
625     // FIXME: were we intentionally ignoring address spaces and GC attributes?
626 
627     for (uint64_t i = 0; i != NumArrayElements; ++i) {
628       // If we're done emitting initializers and the destination is known-zeroed
629       // then we're done.
630       if (i == NumInitElements &&
631           Dest.isZeroed() &&
632           CGF.getTypes().isZeroInitializable(ElementType))
633         break;
634 
635       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
636       LValue LV = CGF.MakeAddrLValue(NextVal, ElementType);
637 
638       if (i < NumInitElements)
639         EmitInitializationToLValue(E->getInit(i), LV, ElementType);
640       else if (Expr *filler = E->getArrayFiller())
641         EmitInitializationToLValue(filler, LV, ElementType);
642       else
643         EmitNullInitializationToLValue(LV, ElementType);
644 
645       // If the GEP didn't get used because of a dead zero init or something
646       // else, clean it up for -O0 builds and general tidiness.
647       if (llvm::GetElementPtrInst *GEP =
648             dyn_cast<llvm::GetElementPtrInst>(NextVal))
649         if (GEP->use_empty())
650           GEP->eraseFromParent();
651     }
652     return;
653   }
654 
655   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
656 
657   // Do struct initialization; this code just sets each individual member
658   // to the approprate value.  This makes bitfield support automatic;
659   // the disadvantage is that the generated code is more difficult for
660   // the optimizer, especially with bitfields.
661   unsigned NumInitElements = E->getNumInits();
662   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
663 
664   if (E->getType()->isUnionType()) {
665     // Only initialize one field of a union. The field itself is
666     // specified by the initializer list.
667     if (!E->getInitializedFieldInUnion()) {
668       // Empty union; we have nothing to do.
669 
670 #ifndef NDEBUG
671       // Make sure that it's really an empty and not a failure of
672       // semantic analysis.
673       for (RecordDecl::field_iterator Field = SD->field_begin(),
674                                    FieldEnd = SD->field_end();
675            Field != FieldEnd; ++Field)
676         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
677 #endif
678       return;
679     }
680 
681     // FIXME: volatility
682     FieldDecl *Field = E->getInitializedFieldInUnion();
683 
684     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
685     if (NumInitElements) {
686       // Store the initializer into the field
687       EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
688     } else {
689       // Default-initialize to null.
690       EmitNullInitializationToLValue(FieldLoc, Field->getType());
691     }
692 
693     return;
694   }
695 
696   // Here we iterate over the fields; this makes it simpler to both
697   // default-initialize fields and skip over unnamed fields.
698   unsigned CurInitVal = 0;
699   for (RecordDecl::field_iterator Field = SD->field_begin(),
700                                FieldEnd = SD->field_end();
701        Field != FieldEnd; ++Field) {
702     // We're done once we hit the flexible array member
703     if (Field->getType()->isIncompleteArrayType())
704       break;
705 
706     if (Field->isUnnamedBitfield())
707       continue;
708 
709     // Don't emit GEP before a noop store of zero.
710     if (CurInitVal == NumInitElements && Dest.isZeroed() &&
711         CGF.getTypes().isZeroInitializable(E->getType()))
712       break;
713 
714     // FIXME: volatility
715     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
716     // We never generate write-barries for initialized fields.
717     FieldLoc.setNonGC(true);
718 
719     if (CurInitVal < NumInitElements) {
720       // Store the initializer into the field.
721       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
722                                  Field->getType());
723     } else {
724       // We're out of initalizers; default-initialize to null
725       EmitNullInitializationToLValue(FieldLoc, Field->getType());
726     }
727 
728     // If the GEP didn't get used because of a dead zero init or something
729     // else, clean it up for -O0 builds and general tidiness.
730     if (FieldLoc.isSimple())
731       if (llvm::GetElementPtrInst *GEP =
732             dyn_cast<llvm::GetElementPtrInst>(FieldLoc.getAddress()))
733         if (GEP->use_empty())
734           GEP->eraseFromParent();
735   }
736 }
737 
738 //===----------------------------------------------------------------------===//
739 //                        Entry Points into this File
740 //===----------------------------------------------------------------------===//
741 
742 /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
743 /// non-zero bytes that will be stored when outputting the initializer for the
744 /// specified initializer expression.
745 static uint64_t GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
746   E = E->IgnoreParens();
747 
748   // 0 and 0.0 won't require any non-zero stores!
749   if (isSimpleZero(E, CGF)) return 0;
750 
751   // If this is an initlist expr, sum up the size of sizes of the (present)
752   // elements.  If this is something weird, assume the whole thing is non-zero.
753   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
754   if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
755     return CGF.getContext().getTypeSize(E->getType())/8;
756 
757   // InitListExprs for structs have to be handled carefully.  If there are
758   // reference members, we need to consider the size of the reference, not the
759   // referencee.  InitListExprs for unions and arrays can't have references.
760   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
761     if (!RT->isUnionType()) {
762       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
763       uint64_t NumNonZeroBytes = 0;
764 
765       unsigned ILEElement = 0;
766       for (RecordDecl::field_iterator Field = SD->field_begin(),
767            FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
768         // We're done once we hit the flexible array member or run out of
769         // InitListExpr elements.
770         if (Field->getType()->isIncompleteArrayType() ||
771             ILEElement == ILE->getNumInits())
772           break;
773         if (Field->isUnnamedBitfield())
774           continue;
775 
776         const Expr *E = ILE->getInit(ILEElement++);
777 
778         // Reference values are always non-null and have the width of a pointer.
779         if (Field->getType()->isReferenceType())
780           NumNonZeroBytes += CGF.getContext().Target.getPointerWidth(0);
781         else
782           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
783       }
784 
785       return NumNonZeroBytes;
786     }
787   }
788 
789 
790   uint64_t NumNonZeroBytes = 0;
791   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
792     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
793   return NumNonZeroBytes;
794 }
795 
796 /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
797 /// zeros in it, emit a memset and avoid storing the individual zeros.
798 ///
799 static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
800                                      CodeGenFunction &CGF) {
801   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
802   // volatile stores.
803   if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
804 
805   // If the type is 16-bytes or smaller, prefer individual stores over memset.
806   std::pair<uint64_t, unsigned> TypeInfo =
807     CGF.getContext().getTypeInfo(E->getType());
808   if (TypeInfo.first/8 <= 16)
809     return;
810 
811   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
812   // we prefer to emit memset + individual stores for the rest.
813   uint64_t NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
814   if (NumNonZeroBytes*4 > TypeInfo.first/8)
815     return;
816 
817   // Okay, it seems like a good idea to use an initial memset, emit the call.
818   llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first/8);
819   unsigned Align = TypeInfo.second/8;
820 
821   llvm::Value *Loc = Slot.getAddr();
822   const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
823 
824   Loc = CGF.Builder.CreateBitCast(Loc, BP);
825   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, Align, false);
826 
827   // Tell the AggExprEmitter that the slot is known zero.
828   Slot.setZeroed();
829 }
830 
831 
832 
833 
834 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
835 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
836 /// the value of the aggregate expression is not needed.  If VolatileDest is
837 /// true, DestPtr cannot be 0.
838 ///
839 /// \param IsInitializer - true if this evaluation is initializing an
840 /// object whose lifetime is already being managed.
841 //
842 // FIXME: Take Qualifiers object.
843 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
844                                   bool IgnoreResult) {
845   assert(E && hasAggregateLLVMType(E->getType()) &&
846          "Invalid aggregate expression to emit");
847   assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
848          "slot has bits but no address");
849 
850   // Optimize the slot if possible.
851   CheckAggExprForMemSetUse(Slot, E, *this);
852 
853   AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E));
854 }
855 
856 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
857   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
858   llvm::Value *Temp = CreateMemTemp(E->getType());
859   LValue LV = MakeAddrLValue(Temp, E->getType());
860   EmitAggExpr(E, AggValueSlot::forAddr(Temp, LV.isVolatileQualified(), false));
861   return LV;
862 }
863 
864 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
865                                         llvm::Value *SrcPtr, QualType Ty,
866                                         bool isVolatile) {
867   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
868 
869   if (getContext().getLangOptions().CPlusPlus) {
870     if (const RecordType *RT = Ty->getAs<RecordType>()) {
871       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
872       assert((Record->hasTrivialCopyConstructor() ||
873               Record->hasTrivialCopyAssignment()) &&
874              "Trying to aggregate-copy a type without a trivial copy "
875              "constructor or assignment operator");
876       // Ignore empty classes in C++.
877       if (Record->isEmpty())
878         return;
879     }
880   }
881 
882   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
883   // C99 6.5.16.1p3, which states "If the value being stored in an object is
884   // read from another object that overlaps in anyway the storage of the first
885   // object, then the overlap shall be exact and the two objects shall have
886   // qualified or unqualified versions of a compatible type."
887   //
888   // memcpy is not defined if the source and destination pointers are exactly
889   // equal, but other compilers do this optimization, and almost every memcpy
890   // implementation handles this case safely.  If there is a libc that does not
891   // safely handle this, we can add a target hook.
892 
893   // Get size and alignment info for this aggregate.
894   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
895 
896   // FIXME: Handle variable sized types.
897 
898   // FIXME: If we have a volatile struct, the optimizer can remove what might
899   // appear to be `extra' memory ops:
900   //
901   // volatile struct { int i; } a, b;
902   //
903   // int main() {
904   //   a = b;
905   //   a = b;
906   // }
907   //
908   // we need to use a different call here.  We use isVolatile to indicate when
909   // either the source or the destination is volatile.
910 
911   const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
912   const llvm::Type *DBP =
913     llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
914   DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp");
915 
916   const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
917   const llvm::Type *SBP =
918     llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
919   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp");
920 
921   if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
922     RecordDecl *Record = RecordTy->getDecl();
923     if (Record->hasObjectMember()) {
924       unsigned long size = TypeInfo.first/8;
925       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
926       llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
927       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
928                                                     SizeVal);
929       return;
930     }
931   } else if (getContext().getAsArrayType(Ty)) {
932     QualType BaseType = getContext().getBaseElementType(Ty);
933     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
934       if (RecordTy->getDecl()->hasObjectMember()) {
935         unsigned long size = TypeInfo.first/8;
936         const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
937         llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
938         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
939                                                       SizeVal);
940         return;
941       }
942     }
943   }
944 
945   Builder.CreateMemCpy(DestPtr, SrcPtr,
946                        llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8),
947                        TypeInfo.second/8, isVolatile);
948 }
949