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