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