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