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   llvm::Value *DestPtr;
36   bool VolatileDest;
37   bool IgnoreResult;
38   bool IsInitializer;
39   bool RequiresGCollection;
40 
41   ReturnValueSlot getReturnValueSlot() const {
42     // If the destination slot requires garbage collection, we can't
43     // use the real return value slot, because we have to use the GC
44     // API.
45     if (RequiresGCollection) return ReturnValueSlot();
46 
47     return ReturnValueSlot(DestPtr, VolatileDest);
48   }
49 
50 public:
51   AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v,
52                  bool ignore, bool isinit, bool requiresGCollection)
53     : CGF(cgf), Builder(CGF.Builder),
54       DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore),
55       IsInitializer(isinit), RequiresGCollection(requiresGCollection) {
56   }
57 
58   //===--------------------------------------------------------------------===//
59   //                               Utilities
60   //===--------------------------------------------------------------------===//
61 
62   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
63   /// represents a value lvalue, this method emits the address of the lvalue,
64   /// then loads the result into DestPtr.
65   void EmitAggLoadOfLValue(const Expr *E);
66 
67   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
68   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
69   void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
70 
71   void EmitGCMove(const Expr *E, RValue Src);
72 
73   bool TypeRequiresGCollection(QualType T);
74 
75   //===--------------------------------------------------------------------===//
76   //                            Visitor Methods
77   //===--------------------------------------------------------------------===//
78 
79   void VisitStmt(Stmt *S) {
80     CGF.ErrorUnsupported(S, "aggregate expression");
81   }
82   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
83   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
84 
85   // l-values.
86   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
87   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
88   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
89   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
90   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
91     EmitAggLoadOfLValue(E);
92   }
93   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
94     EmitAggLoadOfLValue(E);
95   }
96   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
97     EmitAggLoadOfLValue(E);
98   }
99   void VisitPredefinedExpr(const PredefinedExpr *E) {
100     EmitAggLoadOfLValue(E);
101   }
102 
103   // Operators.
104   void VisitCastExpr(CastExpr *E);
105   void VisitCallExpr(const CallExpr *E);
106   void VisitStmtExpr(const StmtExpr *E);
107   void VisitBinaryOperator(const BinaryOperator *BO);
108   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
109   void VisitBinAssign(const BinaryOperator *E);
110   void VisitBinComma(const BinaryOperator *E);
111   void VisitUnaryAddrOf(const UnaryOperator *E);
112 
113   void VisitObjCMessageExpr(ObjCMessageExpr *E);
114   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
115     EmitAggLoadOfLValue(E);
116   }
117   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
118   void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E);
119 
120   void VisitConditionalOperator(const ConditionalOperator *CO);
121   void VisitChooseExpr(const ChooseExpr *CE);
122   void VisitInitListExpr(InitListExpr *E);
123   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
124   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
125     Visit(DAE->getExpr());
126   }
127   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
128   void VisitCXXConstructExpr(const CXXConstructExpr *E);
129   void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E);
130   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
131   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
132 
133   void VisitVAArgExpr(VAArgExpr *E);
134 
135   void EmitInitializationToLValue(Expr *E, LValue Address, QualType T);
136   void EmitNullInitializationToLValue(LValue Address, QualType T);
137   //  case Expr::ChooseExprClass:
138   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
139 };
140 }  // end anonymous namespace.
141 
142 //===----------------------------------------------------------------------===//
143 //                                Utilities
144 //===----------------------------------------------------------------------===//
145 
146 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
147 /// represents a value lvalue, this method emits the address of the lvalue,
148 /// then loads the result into DestPtr.
149 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
150   LValue LV = CGF.EmitLValue(E);
151   EmitFinalDestCopy(E, LV);
152 }
153 
154 /// \brief True if the given aggregate type requires special GC API calls.
155 bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
156   // Only record types have members that might require garbage collection.
157   const RecordType *RecordTy = T->getAs<RecordType>();
158   if (!RecordTy) return false;
159 
160   // Don't mess with non-trivial C++ types.
161   RecordDecl *Record = RecordTy->getDecl();
162   if (isa<CXXRecordDecl>(Record) &&
163       (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
164        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
165     return false;
166 
167   // Check whether the type has an object member.
168   return Record->hasObjectMember();
169 }
170 
171 /// \brief Perform the final move to DestPtr if RequiresGCollection is set.
172 ///
173 /// The idea is that you do something like this:
174 ///   RValue Result = EmitSomething(..., getReturnValueSlot());
175 ///   EmitGCMove(E, Result);
176 /// If GC doesn't interfere, this will cause the result to be emitted
177 /// directly into the return value slot.  If GC does interfere, a final
178 /// move will be performed.
179 void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) {
180   if (RequiresGCollection) {
181     std::pair<uint64_t, unsigned> TypeInfo =
182       CGF.getContext().getTypeInfo(E->getType());
183     unsigned long size = TypeInfo.first/8;
184     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
185     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
186     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, DestPtr,
187                                                     Src.getAggregateAddr(),
188                                                     SizeVal);
189   }
190 }
191 
192 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
193 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
194   assert(Src.isAggregate() && "value must be aggregate value!");
195 
196   // If the result is ignored, don't copy from the value.
197   if (DestPtr == 0) {
198     if (!Src.isVolatileQualified() || (IgnoreResult && Ignore))
199       return;
200     // If the source is volatile, we must read from it; to do that, we need
201     // some place to put it.
202     DestPtr = CGF.CreateMemTemp(E->getType(), "agg.tmp");
203   }
204 
205   if (RequiresGCollection) {
206     std::pair<uint64_t, unsigned> TypeInfo =
207     CGF.getContext().getTypeInfo(E->getType());
208     unsigned long size = TypeInfo.first/8;
209     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
210     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
211     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
212                                               DestPtr, Src.getAggregateAddr(),
213                                               SizeVal);
214     return;
215   }
216   // If the result of the assignment is used, copy the LHS there also.
217   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
218   // from the source as well, as we can't eliminate it if either operand
219   // is volatile, unless copy has volatile for both source and destination..
220   CGF.EmitAggregateCopy(DestPtr, Src.getAggregateAddr(), E->getType(),
221                         VolatileDest|Src.isVolatileQualified());
222 }
223 
224 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
225 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
226   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
227 
228   EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
229                                             Src.isVolatileQualified()),
230                     Ignore);
231 }
232 
233 //===----------------------------------------------------------------------===//
234 //                            Visitor Methods
235 //===----------------------------------------------------------------------===//
236 
237 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
238   if (!DestPtr && E->getCastKind() != CastExpr::CK_Dynamic) {
239     Visit(E->getSubExpr());
240     return;
241   }
242 
243   switch (E->getCastKind()) {
244   default: assert(0 && "Unhandled cast kind!");
245 
246   case CastExpr::CK_Dynamic: {
247     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
248     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
249     // FIXME: Do we also need to handle property references here?
250     if (LV.isSimple())
251       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
252     else
253       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
254 
255     if (DestPtr)
256       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
257     break;
258   }
259 
260   case CastExpr::CK_ToUnion: {
261     // GCC union extension
262     QualType Ty = E->getSubExpr()->getType();
263     QualType PtrTy = CGF.getContext().getPointerType(Ty);
264     llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr,
265                                                  CGF.ConvertType(PtrTy));
266     EmitInitializationToLValue(E->getSubExpr(), CGF.MakeAddrLValue(CastPtr, Ty),
267                                Ty);
268     break;
269   }
270 
271   case CastExpr::CK_DerivedToBase:
272   case CastExpr::CK_BaseToDerived:
273   case CastExpr::CK_UncheckedDerivedToBase: {
274     assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: "
275                 "should have been unpacked before we got here");
276     break;
277   }
278 
279   // FIXME: Remove the CK_Unknown check here.
280   case CastExpr::CK_Unknown:
281   case CastExpr::CK_NoOp:
282   case CastExpr::CK_UserDefinedConversion:
283   case CastExpr::CK_ConstructorConversion:
284     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
285                                                    E->getType()) &&
286            "Implicit cast types must be compatible");
287     Visit(E->getSubExpr());
288     break;
289 
290   case CastExpr::CK_NullToMemberPointer: {
291     // If the subexpression's type is the C++0x nullptr_t, emit the
292     // subexpression, which may have side effects.
293     if (E->getSubExpr()->getType()->isNullPtrType())
294       Visit(E->getSubExpr());
295 
296     CGF.CGM.getCXXABI().EmitNullMemberFunctionPointer(CGF,
297                                     E->getType()->getAs<MemberPointerType>(),
298                                                       DestPtr, VolatileDest);
299 
300     break;
301   }
302 
303   case CastExpr::CK_LValueBitCast:
304     llvm_unreachable("there are no lvalue bit-casts on aggregates");
305     break;
306 
307   case CastExpr::CK_BitCast: {
308     // This must be a member function pointer cast.
309     Visit(E->getSubExpr());
310     break;
311   }
312 
313   case CastExpr::CK_DerivedToBaseMemberPointer:
314   case CastExpr::CK_BaseToDerivedMemberPointer: {
315     QualType SrcType = E->getSubExpr()->getType();
316 
317     llvm::Value *Src = CGF.CreateMemTemp(SrcType, "tmp");
318     CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified());
319 
320     // Note that the AST doesn't distinguish between checked and
321     // unchecked member pointer conversions, so we always have to
322     // implement checked conversions here.  This is inefficient for
323     // ABIs where an actual null check is thus required; fortunately,
324     // the Itanium and ARM ABIs ignore the adjustment value when
325     // considering null-ness.
326     CGF.CGM.getCXXABI().EmitMemberFunctionPointerConversion(CGF, E, Src,
327                                                    DestPtr, VolatileDest);
328     break;
329   }
330   }
331 }
332 
333 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
334   if (E->getCallReturnType()->isReferenceType()) {
335     EmitAggLoadOfLValue(E);
336     return;
337   }
338 
339   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
340   EmitGCMove(E, RV);
341 }
342 
343 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
344   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
345   EmitGCMove(E, RV);
346 }
347 
348 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
349   RValue RV = CGF.EmitObjCPropertyGet(E, getReturnValueSlot());
350   EmitGCMove(E, RV);
351 }
352 
353 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr(
354                                    ObjCImplicitSetterGetterRefExpr *E) {
355   RValue RV = CGF.EmitObjCPropertyGet(E, getReturnValueSlot());
356   EmitGCMove(E, RV);
357 }
358 
359 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
360   CGF.EmitAnyExpr(E->getLHS(), 0, false, true);
361   CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest,
362                   /*IgnoreResult=*/false, IsInitializer);
363 }
364 
365 void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) {
366   // We have a member function pointer.
367   assert(E->getType()->getAs<MemberPointerType>()
368           ->getPointeeType()->isFunctionProtoType() &&
369          "Unexpected member pointer type!");
370 
371   // The creation of member function pointers has no side effects; if
372   // there is no destination pointer, we have nothing to do.
373   if (!DestPtr)
374     return;
375 
376   const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr());
377   const CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
378 
379   CGF.CGM.getCXXABI().EmitMemberFunctionPointer(CGF, MD, DestPtr, VolatileDest);
380 }
381 
382 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
383   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
384 }
385 
386 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
387   if (E->getOpcode() == BinaryOperator::PtrMemD ||
388       E->getOpcode() == BinaryOperator::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   LValue LHS = CGF.EmitLValue(E->getLHS());
407 
408   // We have to special case property setters, otherwise we must have
409   // a simple lvalue (no aggregates inside vectors, bitfields).
410   if (LHS.isPropertyRef()) {
411     llvm::Value *AggLoc = DestPtr;
412     if (!AggLoc)
413       AggLoc = CGF.CreateMemTemp(E->getRHS()->getType());
414     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
415     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
416                             RValue::getAggregate(AggLoc, VolatileDest));
417   } else if (LHS.isKVCRef()) {
418     llvm::Value *AggLoc = DestPtr;
419     if (!AggLoc)
420       AggLoc = CGF.CreateMemTemp(E->getRHS()->getType());
421     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
422     CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
423                             RValue::getAggregate(AggLoc, VolatileDest));
424   } else {
425     bool RequiresGCollection = false;
426     if (CGF.getContext().getLangOptions().getGCMode())
427       RequiresGCollection = TypeRequiresGCollection(E->getLHS()->getType());
428 
429     // Codegen the RHS so that it stores directly into the LHS.
430     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(),
431                     false, false, RequiresGCollection);
432     EmitFinalDestCopy(E, LHS, true);
433   }
434 }
435 
436 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
437   if (!E->getLHS()) {
438     CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
439     return;
440   }
441 
442   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
443   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
444   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
445 
446   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
447 
448   CGF.BeginConditionalBranch();
449   CGF.EmitBlock(LHSBlock);
450 
451   // Handle the GNU extension for missing LHS.
452   assert(E->getLHS() && "Must have LHS for aggregate value");
453 
454   Visit(E->getLHS());
455   CGF.EndConditionalBranch();
456   CGF.EmitBranch(ContBlock);
457 
458   CGF.BeginConditionalBranch();
459   CGF.EmitBlock(RHSBlock);
460 
461   Visit(E->getRHS());
462   CGF.EndConditionalBranch();
463   CGF.EmitBranch(ContBlock);
464 
465   CGF.EmitBlock(ContBlock);
466 }
467 
468 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
469   Visit(CE->getChosenSubExpr(CGF.getContext()));
470 }
471 
472 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
473   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
474   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
475 
476   if (!ArgPtr) {
477     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
478     return;
479   }
480 
481   EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
482 }
483 
484 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
485   llvm::Value *Val = DestPtr;
486 
487   if (!Val) {
488     // Create a temporary variable.
489     Val = CGF.CreateMemTemp(E->getType(), "tmp");
490 
491     // FIXME: volatile
492     CGF.EmitAggExpr(E->getSubExpr(), Val, false);
493   } else
494     Visit(E->getSubExpr());
495 
496   // Don't make this a live temporary if we're emitting an initializer expr.
497   if (!IsInitializer)
498     CGF.EmitCXXTemporary(E->getTemporary(), Val);
499 }
500 
501 void
502 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
503   llvm::Value *Val = DestPtr;
504 
505   if (!Val) // Create a temporary variable.
506     Val = CGF.CreateMemTemp(E->getType(), "tmp");
507 
508   if (E->requiresZeroInitialization())
509     EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()),
510                                    E->getType());
511 
512   CGF.EmitCXXConstructExpr(Val, E);
513 }
514 
515 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
516   llvm::Value *Val = DestPtr;
517 
518   CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer);
519 }
520 
521 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
522   llvm::Value *Val = DestPtr;
523 
524   if (!Val) {
525     // Create a temporary variable.
526     Val = CGF.CreateMemTemp(E->getType(), "tmp");
527   }
528   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()),
529                                  E->getType());
530 }
531 
532 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
533   llvm::Value *Val = DestPtr;
534 
535   if (!Val) {
536     // Create a temporary variable.
537     Val = CGF.CreateMemTemp(E->getType(), "tmp");
538   }
539   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()),
540                                  E->getType());
541 }
542 
543 void
544 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
545   // FIXME: Ignore result?
546   // FIXME: Are initializers affected by volatile?
547   if (isa<ImplicitValueInitExpr>(E)) {
548     EmitNullInitializationToLValue(LV, T);
549   } else if (T->isReferenceType()) {
550     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
551     CGF.EmitStoreThroughLValue(RV, LV, T);
552   } else if (T->isAnyComplexType()) {
553     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
554   } else if (CGF.hasAggregateLLVMType(T)) {
555     CGF.EmitAnyExpr(E, LV.getAddress(), false);
556   } else {
557     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T);
558   }
559 }
560 
561 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
562   if (!CGF.hasAggregateLLVMType(T)) {
563     // For non-aggregates, we can store zero
564     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
565     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
566   } else {
567     // There's a potential optimization opportunity in combining
568     // memsets; that would be easy for arrays, but relatively
569     // difficult for structures with the current code.
570     CGF.EmitNullInitialization(LV.getAddress(), T);
571   }
572 }
573 
574 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
575 #if 0
576   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
577   // (Length of globals? Chunks of zeroed-out space?).
578   //
579   // If we can, prefer a copy from a global; this is a lot less code for long
580   // globals, and it's easier for the current optimizers to analyze.
581   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
582     llvm::GlobalVariable* GV =
583     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
584                              llvm::GlobalValue::InternalLinkage, C, "");
585     EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
586     return;
587   }
588 #endif
589   if (E->hadArrayRangeDesignator()) {
590     CGF.ErrorUnsupported(E, "GNU array range designator extension");
591   }
592 
593   // Handle initialization of an array.
594   if (E->getType()->isArrayType()) {
595     const llvm::PointerType *APType =
596       cast<llvm::PointerType>(DestPtr->getType());
597     const llvm::ArrayType *AType =
598       cast<llvm::ArrayType>(APType->getElementType());
599 
600     uint64_t NumInitElements = E->getNumInits();
601 
602     if (E->getNumInits() > 0) {
603       QualType T1 = E->getType();
604       QualType T2 = E->getInit(0)->getType();
605       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
606         EmitAggLoadOfLValue(E->getInit(0));
607         return;
608       }
609     }
610 
611     uint64_t NumArrayElements = AType->getNumElements();
612     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
613     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
614 
615     // FIXME: were we intentionally ignoring address spaces and GC attributes?
616 
617     for (uint64_t i = 0; i != NumArrayElements; ++i) {
618       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
619       LValue LV = CGF.MakeAddrLValue(NextVal, ElementType);
620       if (i < NumInitElements)
621         EmitInitializationToLValue(E->getInit(i), LV, ElementType);
622 
623       else
624         EmitNullInitializationToLValue(LV, ElementType);
625     }
626     return;
627   }
628 
629   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
630 
631   // Do struct initialization; this code just sets each individual member
632   // to the approprate value.  This makes bitfield support automatic;
633   // the disadvantage is that the generated code is more difficult for
634   // the optimizer, especially with bitfields.
635   unsigned NumInitElements = E->getNumInits();
636   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
637   unsigned CurInitVal = 0;
638 
639   if (E->getType()->isUnionType()) {
640     // Only initialize one field of a union. The field itself is
641     // specified by the initializer list.
642     if (!E->getInitializedFieldInUnion()) {
643       // Empty union; we have nothing to do.
644 
645 #ifndef NDEBUG
646       // Make sure that it's really an empty and not a failure of
647       // semantic analysis.
648       for (RecordDecl::field_iterator Field = SD->field_begin(),
649                                    FieldEnd = SD->field_end();
650            Field != FieldEnd; ++Field)
651         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
652 #endif
653       return;
654     }
655 
656     // FIXME: volatility
657     FieldDecl *Field = E->getInitializedFieldInUnion();
658     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
659 
660     if (NumInitElements) {
661       // Store the initializer into the field
662       EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
663     } else {
664       // Default-initialize to null
665       EmitNullInitializationToLValue(FieldLoc, Field->getType());
666     }
667 
668     return;
669   }
670 
671   // If we're initializing the whole aggregate, just do it in place.
672   // FIXME: This is a hack around an AST bug (PR6537).
673   if (NumInitElements == 1 && E->getType() == E->getInit(0)->getType()) {
674     EmitInitializationToLValue(E->getInit(0),
675                                CGF.MakeAddrLValue(DestPtr, E->getType()),
676                                E->getType());
677     return;
678   }
679 
680 
681   // Here we iterate over the fields; this makes it simpler to both
682   // default-initialize fields and skip over unnamed fields.
683   for (RecordDecl::field_iterator Field = SD->field_begin(),
684                                FieldEnd = SD->field_end();
685        Field != FieldEnd; ++Field) {
686     // We're done once we hit the flexible array member
687     if (Field->getType()->isIncompleteArrayType())
688       break;
689 
690     if (Field->isUnnamedBitfield())
691       continue;
692 
693     // FIXME: volatility
694     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
695     // We never generate write-barries for initialized fields.
696     FieldLoc.setNonGC(true);
697     if (CurInitVal < NumInitElements) {
698       // Store the initializer into the field.
699       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
700                                  Field->getType());
701     } else {
702       // We're out of initalizers; default-initialize to null
703       EmitNullInitializationToLValue(FieldLoc, Field->getType());
704     }
705   }
706 }
707 
708 //===----------------------------------------------------------------------===//
709 //                        Entry Points into this File
710 //===----------------------------------------------------------------------===//
711 
712 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
713 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
714 /// the value of the aggregate expression is not needed.  If VolatileDest is
715 /// true, DestPtr cannot be 0.
716 //
717 // FIXME: Take Qualifiers object.
718 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
719                                   bool VolatileDest, bool IgnoreResult,
720                                   bool IsInitializer,
721                                   bool RequiresGCollection) {
722   assert(E && hasAggregateLLVMType(E->getType()) &&
723          "Invalid aggregate expression to emit");
724   assert ((DestPtr != 0 || VolatileDest == false)
725           && "volatile aggregate can't be 0");
726 
727   AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer,
728                  RequiresGCollection)
729     .Visit(const_cast<Expr*>(E));
730 }
731 
732 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
733   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
734   llvm::Value *Temp = CreateMemTemp(E->getType());
735   LValue LV = MakeAddrLValue(Temp, E->getType());
736   EmitAggExpr(E, Temp, LV.isVolatileQualified());
737   return LV;
738 }
739 
740 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
741                                         llvm::Value *SrcPtr, QualType Ty,
742                                         bool isVolatile) {
743   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
744 
745   if (getContext().getLangOptions().CPlusPlus) {
746     if (const RecordType *RT = Ty->getAs<RecordType>()) {
747       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
748       assert((Record->hasTrivialCopyConstructor() ||
749               Record->hasTrivialCopyAssignment()) &&
750              "Trying to aggregate-copy a type without a trivial copy "
751              "constructor or assignment operator");
752       // Ignore empty classes in C++.
753       if (Record->isEmpty())
754         return;
755     }
756   }
757 
758   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
759   // C99 6.5.16.1p3, which states "If the value being stored in an object is
760   // read from another object that overlaps in anyway the storage of the first
761   // object, then the overlap shall be exact and the two objects shall have
762   // qualified or unqualified versions of a compatible type."
763   //
764   // memcpy is not defined if the source and destination pointers are exactly
765   // equal, but other compilers do this optimization, and almost every memcpy
766   // implementation handles this case safely.  If there is a libc that does not
767   // safely handle this, we can add a target hook.
768 
769   // Get size and alignment info for this aggregate.
770   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
771 
772   // FIXME: Handle variable sized types.
773 
774   // FIXME: If we have a volatile struct, the optimizer can remove what might
775   // appear to be `extra' memory ops:
776   //
777   // volatile struct { int i; } a, b;
778   //
779   // int main() {
780   //   a = b;
781   //   a = b;
782   // }
783   //
784   // we need to use a different call here.  We use isVolatile to indicate when
785   // either the source or the destination is volatile.
786 
787   const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
788   const llvm::Type *DBP =
789     llvm::Type::getInt8PtrTy(VMContext, DPT->getAddressSpace());
790   DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp");
791 
792   const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
793   const llvm::Type *SBP =
794     llvm::Type::getInt8PtrTy(VMContext, SPT->getAddressSpace());
795   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp");
796 
797   if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
798     RecordDecl *Record = RecordTy->getDecl();
799     if (Record->hasObjectMember()) {
800       unsigned long size = TypeInfo.first/8;
801       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
802       llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
803       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
804                                                     SizeVal);
805       return;
806     }
807   } else if (getContext().getAsArrayType(Ty)) {
808     QualType BaseType = getContext().getBaseElementType(Ty);
809     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
810       if (RecordTy->getDecl()->hasObjectMember()) {
811         unsigned long size = TypeInfo.first/8;
812         const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
813         llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
814         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
815                                                       SizeVal);
816         return;
817       }
818     }
819   }
820 
821   Builder.CreateCall5(CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(),
822                                       IntPtrTy),
823                       DestPtr, SrcPtr,
824                       // TypeInfo.first describes size in bits.
825                       llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8),
826                       Builder.getInt32(TypeInfo.second/8),
827                       Builder.getInt1(isVolatile));
828 }
829