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   const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
368   (void) MPT;
369   assert(MPT->getPointeeType()->isFunctionProtoType() &&
370          "Unexpected member pointer type!");
371 
372   // The creation of member function pointers has no side effects; if
373   // there is no destination pointer, we have nothing to do.
374   if (!DestPtr)
375     return;
376 
377   const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr());
378   const CXXMethodDecl *MD =
379     cast<CXXMethodDecl>(DRE->getDecl())->getCanonicalDecl();
380 
381   const llvm::Type *PtrDiffTy =
382     CGF.ConvertType(CGF.getContext().getPointerDiffType());
383 
384   llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
385   llvm::Value *FuncPtr = CGF.CGM.GetCXXMemberFunctionPointerValue(MD);
386   Builder.CreateStore(FuncPtr, DstPtr, VolatileDest);
387 
388   llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
389   // The adjustment will always be 0.
390   Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr,
391                       VolatileDest);
392 }
393 
394 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
395   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
396 }
397 
398 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
399   if (E->getOpcode() == BinaryOperator::PtrMemD ||
400       E->getOpcode() == BinaryOperator::PtrMemI)
401     VisitPointerToDataMemberBinaryOperator(E);
402   else
403     CGF.ErrorUnsupported(E, "aggregate binary expression");
404 }
405 
406 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
407                                                     const BinaryOperator *E) {
408   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
409   EmitFinalDestCopy(E, LV);
410 }
411 
412 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
413   // For an assignment to work, the value on the right has
414   // to be compatible with the value on the left.
415   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
416                                                  E->getRHS()->getType())
417          && "Invalid assignment");
418   LValue LHS = CGF.EmitLValue(E->getLHS());
419 
420   // We have to special case property setters, otherwise we must have
421   // a simple lvalue (no aggregates inside vectors, bitfields).
422   if (LHS.isPropertyRef()) {
423     llvm::Value *AggLoc = DestPtr;
424     if (!AggLoc)
425       AggLoc = CGF.CreateMemTemp(E->getRHS()->getType());
426     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
427     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
428                             RValue::getAggregate(AggLoc, VolatileDest));
429   } else if (LHS.isKVCRef()) {
430     llvm::Value *AggLoc = DestPtr;
431     if (!AggLoc)
432       AggLoc = CGF.CreateMemTemp(E->getRHS()->getType());
433     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
434     CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
435                             RValue::getAggregate(AggLoc, VolatileDest));
436   } else {
437     bool RequiresGCollection = false;
438     if (CGF.getContext().getLangOptions().getGCMode())
439       RequiresGCollection = TypeRequiresGCollection(E->getLHS()->getType());
440 
441     // Codegen the RHS so that it stores directly into the LHS.
442     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(),
443                     false, false, RequiresGCollection);
444     EmitFinalDestCopy(E, LHS, true);
445   }
446 }
447 
448 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
449   if (!E->getLHS()) {
450     CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
451     return;
452   }
453 
454   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
455   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
456   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
457 
458   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
459 
460   CGF.BeginConditionalBranch();
461   CGF.EmitBlock(LHSBlock);
462 
463   // Handle the GNU extension for missing LHS.
464   assert(E->getLHS() && "Must have LHS for aggregate value");
465 
466   Visit(E->getLHS());
467   CGF.EndConditionalBranch();
468   CGF.EmitBranch(ContBlock);
469 
470   CGF.BeginConditionalBranch();
471   CGF.EmitBlock(RHSBlock);
472 
473   Visit(E->getRHS());
474   CGF.EndConditionalBranch();
475   CGF.EmitBranch(ContBlock);
476 
477   CGF.EmitBlock(ContBlock);
478 }
479 
480 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
481   Visit(CE->getChosenSubExpr(CGF.getContext()));
482 }
483 
484 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
485   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
486   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
487 
488   if (!ArgPtr) {
489     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
490     return;
491   }
492 
493   EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
494 }
495 
496 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
497   llvm::Value *Val = DestPtr;
498 
499   if (!Val) {
500     // Create a temporary variable.
501     Val = CGF.CreateMemTemp(E->getType(), "tmp");
502 
503     // FIXME: volatile
504     CGF.EmitAggExpr(E->getSubExpr(), Val, false);
505   } else
506     Visit(E->getSubExpr());
507 
508   // Don't make this a live temporary if we're emitting an initializer expr.
509   if (!IsInitializer)
510     CGF.EmitCXXTemporary(E->getTemporary(), Val);
511 }
512 
513 void
514 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
515   llvm::Value *Val = DestPtr;
516 
517   if (!Val) // Create a temporary variable.
518     Val = CGF.CreateMemTemp(E->getType(), "tmp");
519 
520   if (E->requiresZeroInitialization())
521     EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()),
522                                    E->getType());
523 
524   CGF.EmitCXXConstructExpr(Val, E);
525 }
526 
527 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
528   llvm::Value *Val = DestPtr;
529 
530   CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer);
531 }
532 
533 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
534   llvm::Value *Val = DestPtr;
535 
536   if (!Val) {
537     // Create a temporary variable.
538     Val = CGF.CreateMemTemp(E->getType(), "tmp");
539   }
540   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()),
541                                  E->getType());
542 }
543 
544 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
545   llvm::Value *Val = DestPtr;
546 
547   if (!Val) {
548     // Create a temporary variable.
549     Val = CGF.CreateMemTemp(E->getType(), "tmp");
550   }
551   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()),
552                                  E->getType());
553 }
554 
555 void
556 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
557   // FIXME: Ignore result?
558   // FIXME: Are initializers affected by volatile?
559   if (isa<ImplicitValueInitExpr>(E)) {
560     EmitNullInitializationToLValue(LV, T);
561   } else if (T->isReferenceType()) {
562     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
563     CGF.EmitStoreThroughLValue(RV, LV, T);
564   } else if (T->isAnyComplexType()) {
565     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
566   } else if (CGF.hasAggregateLLVMType(T)) {
567     CGF.EmitAnyExpr(E, LV.getAddress(), false);
568   } else {
569     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T);
570   }
571 }
572 
573 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
574   if (!CGF.hasAggregateLLVMType(T)) {
575     // For non-aggregates, we can store zero
576     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
577     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
578   } else {
579     // There's a potential optimization opportunity in combining
580     // memsets; that would be easy for arrays, but relatively
581     // difficult for structures with the current code.
582     CGF.EmitNullInitialization(LV.getAddress(), T);
583   }
584 }
585 
586 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
587 #if 0
588   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
589   // (Length of globals? Chunks of zeroed-out space?).
590   //
591   // If we can, prefer a copy from a global; this is a lot less code for long
592   // globals, and it's easier for the current optimizers to analyze.
593   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
594     llvm::GlobalVariable* GV =
595     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
596                              llvm::GlobalValue::InternalLinkage, C, "");
597     EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
598     return;
599   }
600 #endif
601   if (E->hadArrayRangeDesignator()) {
602     CGF.ErrorUnsupported(E, "GNU array range designator extension");
603   }
604 
605   // Handle initialization of an array.
606   if (E->getType()->isArrayType()) {
607     const llvm::PointerType *APType =
608       cast<llvm::PointerType>(DestPtr->getType());
609     const llvm::ArrayType *AType =
610       cast<llvm::ArrayType>(APType->getElementType());
611 
612     uint64_t NumInitElements = E->getNumInits();
613 
614     if (E->getNumInits() > 0) {
615       QualType T1 = E->getType();
616       QualType T2 = E->getInit(0)->getType();
617       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
618         EmitAggLoadOfLValue(E->getInit(0));
619         return;
620       }
621     }
622 
623     uint64_t NumArrayElements = AType->getNumElements();
624     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
625     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
626 
627     // FIXME: were we intentionally ignoring address spaces and GC attributes?
628 
629     for (uint64_t i = 0; i != NumArrayElements; ++i) {
630       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
631       LValue LV = CGF.MakeAddrLValue(NextVal, ElementType);
632       if (i < NumInitElements)
633         EmitInitializationToLValue(E->getInit(i), LV, ElementType);
634 
635       else
636         EmitNullInitializationToLValue(LV, ElementType);
637     }
638     return;
639   }
640 
641   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
642 
643   // Do struct initialization; this code just sets each individual member
644   // to the approprate value.  This makes bitfield support automatic;
645   // the disadvantage is that the generated code is more difficult for
646   // the optimizer, especially with bitfields.
647   unsigned NumInitElements = E->getNumInits();
648   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
649   unsigned CurInitVal = 0;
650 
651   if (E->getType()->isUnionType()) {
652     // Only initialize one field of a union. The field itself is
653     // specified by the initializer list.
654     if (!E->getInitializedFieldInUnion()) {
655       // Empty union; we have nothing to do.
656 
657 #ifndef NDEBUG
658       // Make sure that it's really an empty and not a failure of
659       // semantic analysis.
660       for (RecordDecl::field_iterator Field = SD->field_begin(),
661                                    FieldEnd = SD->field_end();
662            Field != FieldEnd; ++Field)
663         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
664 #endif
665       return;
666     }
667 
668     // FIXME: volatility
669     FieldDecl *Field = E->getInitializedFieldInUnion();
670     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
671 
672     if (NumInitElements) {
673       // Store the initializer into the field
674       EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
675     } else {
676       // Default-initialize to null
677       EmitNullInitializationToLValue(FieldLoc, Field->getType());
678     }
679 
680     return;
681   }
682 
683   // If we're initializing the whole aggregate, just do it in place.
684   // FIXME: This is a hack around an AST bug (PR6537).
685   if (NumInitElements == 1 && E->getType() == E->getInit(0)->getType()) {
686     EmitInitializationToLValue(E->getInit(0),
687                                CGF.MakeAddrLValue(DestPtr, E->getType()),
688                                E->getType());
689     return;
690   }
691 
692 
693   // Here we iterate over the fields; this makes it simpler to both
694   // default-initialize fields and skip over unnamed fields.
695   for (RecordDecl::field_iterator Field = SD->field_begin(),
696                                FieldEnd = SD->field_end();
697        Field != FieldEnd; ++Field) {
698     // We're done once we hit the flexible array member
699     if (Field->getType()->isIncompleteArrayType())
700       break;
701 
702     if (Field->isUnnamedBitfield())
703       continue;
704 
705     // FIXME: volatility
706     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
707     // We never generate write-barries for initialized fields.
708     FieldLoc.setNonGC(true);
709     if (CurInitVal < NumInitElements) {
710       // Store the initializer into the field.
711       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
712                                  Field->getType());
713     } else {
714       // We're out of initalizers; default-initialize to null
715       EmitNullInitializationToLValue(FieldLoc, Field->getType());
716     }
717   }
718 }
719 
720 //===----------------------------------------------------------------------===//
721 //                        Entry Points into this File
722 //===----------------------------------------------------------------------===//
723 
724 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
725 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
726 /// the value of the aggregate expression is not needed.  If VolatileDest is
727 /// true, DestPtr cannot be 0.
728 //
729 // FIXME: Take Qualifiers object.
730 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
731                                   bool VolatileDest, bool IgnoreResult,
732                                   bool IsInitializer,
733                                   bool RequiresGCollection) {
734   assert(E && hasAggregateLLVMType(E->getType()) &&
735          "Invalid aggregate expression to emit");
736   assert ((DestPtr != 0 || VolatileDest == false)
737           && "volatile aggregate can't be 0");
738 
739   AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer,
740                  RequiresGCollection)
741     .Visit(const_cast<Expr*>(E));
742 }
743 
744 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
745   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
746   llvm::Value *Temp = CreateMemTemp(E->getType());
747   LValue LV = MakeAddrLValue(Temp, E->getType());
748   EmitAggExpr(E, Temp, LV.isVolatileQualified());
749   return LV;
750 }
751 
752 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
753                                         llvm::Value *SrcPtr, QualType Ty,
754                                         bool isVolatile) {
755   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
756 
757   if (getContext().getLangOptions().CPlusPlus) {
758     if (const RecordType *RT = Ty->getAs<RecordType>()) {
759       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
760       assert((Record->hasTrivialCopyConstructor() ||
761               Record->hasTrivialCopyAssignment()) &&
762              "Trying to aggregate-copy a type without a trivial copy "
763              "constructor or assignment operator");
764       // Ignore empty classes in C++.
765       if (Record->isEmpty())
766         return;
767     }
768   }
769 
770   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
771   // C99 6.5.16.1p3, which states "If the value being stored in an object is
772   // read from another object that overlaps in anyway the storage of the first
773   // object, then the overlap shall be exact and the two objects shall have
774   // qualified or unqualified versions of a compatible type."
775   //
776   // memcpy is not defined if the source and destination pointers are exactly
777   // equal, but other compilers do this optimization, and almost every memcpy
778   // implementation handles this case safely.  If there is a libc that does not
779   // safely handle this, we can add a target hook.
780 
781   // Get size and alignment info for this aggregate.
782   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
783 
784   // FIXME: Handle variable sized types.
785 
786   // FIXME: If we have a volatile struct, the optimizer can remove what might
787   // appear to be `extra' memory ops:
788   //
789   // volatile struct { int i; } a, b;
790   //
791   // int main() {
792   //   a = b;
793   //   a = b;
794   // }
795   //
796   // we need to use a different call here.  We use isVolatile to indicate when
797   // either the source or the destination is volatile.
798 
799   const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
800   const llvm::Type *DBP =
801     llvm::Type::getInt8PtrTy(VMContext, DPT->getAddressSpace());
802   DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp");
803 
804   const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
805   const llvm::Type *SBP =
806     llvm::Type::getInt8PtrTy(VMContext, SPT->getAddressSpace());
807   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp");
808 
809   if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
810     RecordDecl *Record = RecordTy->getDecl();
811     if (Record->hasObjectMember()) {
812       unsigned long size = TypeInfo.first/8;
813       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
814       llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
815       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
816                                                     SizeVal);
817       return;
818     }
819   } else if (getContext().getAsArrayType(Ty)) {
820     QualType BaseType = getContext().getBaseElementType(Ty);
821     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
822       if (RecordTy->getDecl()->hasObjectMember()) {
823         unsigned long size = TypeInfo.first/8;
824         const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
825         llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
826         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
827                                                       SizeVal);
828         return;
829       }
830     }
831   }
832 
833   Builder.CreateCall5(CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(),
834                                       IntPtrTy),
835                       DestPtr, SrcPtr,
836                       // TypeInfo.first describes size in bits.
837                       llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8),
838                       Builder.getInt32(TypeInfo.second/8),
839                       Builder.getInt1(isVolatile));
840 }
841