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