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