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 public:
41   AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v,
42                  bool ignore, bool isinit, bool requiresGCollection)
43     : CGF(cgf), Builder(CGF.Builder),
44       DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore),
45       IsInitializer(isinit), RequiresGCollection(requiresGCollection) {
46   }
47 
48   //===--------------------------------------------------------------------===//
49   //                               Utilities
50   //===--------------------------------------------------------------------===//
51 
52   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
53   /// represents a value lvalue, this method emits the address of the lvalue,
54   /// then loads the result into DestPtr.
55   void EmitAggLoadOfLValue(const Expr *E);
56 
57   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
58   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
59   void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
60 
61   //===--------------------------------------------------------------------===//
62   //                            Visitor Methods
63   //===--------------------------------------------------------------------===//
64 
65   void VisitStmt(Stmt *S) {
66     CGF.ErrorUnsupported(S, "aggregate expression");
67   }
68   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
69   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
70 
71   // l-values.
72   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
73   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
74   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
75   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
76   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
77     EmitAggLoadOfLValue(E);
78   }
79   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
80     EmitAggLoadOfLValue(E);
81   }
82   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
83     EmitAggLoadOfLValue(E);
84   }
85   void VisitPredefinedExpr(const PredefinedExpr *E) {
86     EmitAggLoadOfLValue(E);
87   }
88 
89   // Operators.
90   void VisitCastExpr(CastExpr *E);
91   void VisitCallExpr(const CallExpr *E);
92   void VisitStmtExpr(const StmtExpr *E);
93   void VisitBinaryOperator(const BinaryOperator *BO);
94   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
95   void VisitBinAssign(const BinaryOperator *E);
96   void VisitBinComma(const BinaryOperator *E);
97   void VisitUnaryAddrOf(const UnaryOperator *E);
98 
99   void VisitObjCMessageExpr(ObjCMessageExpr *E);
100   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
101     EmitAggLoadOfLValue(E);
102   }
103   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
104   void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E);
105 
106   void VisitConditionalOperator(const ConditionalOperator *CO);
107   void VisitChooseExpr(const ChooseExpr *CE);
108   void VisitInitListExpr(InitListExpr *E);
109   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
110   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
111     Visit(DAE->getExpr());
112   }
113   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
114   void VisitCXXConstructExpr(const CXXConstructExpr *E);
115   void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E);
116   void VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
117   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
118 
119   void VisitVAArgExpr(VAArgExpr *E);
120 
121   void EmitInitializationToLValue(Expr *E, LValue Address, QualType T);
122   void EmitNullInitializationToLValue(LValue Address, QualType T);
123   //  case Expr::ChooseExprClass:
124   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
125 };
126 }  // end anonymous namespace.
127 
128 //===----------------------------------------------------------------------===//
129 //                                Utilities
130 //===----------------------------------------------------------------------===//
131 
132 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
133 /// represents a value lvalue, this method emits the address of the lvalue,
134 /// then loads the result into DestPtr.
135 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
136   LValue LV = CGF.EmitLValue(E);
137   EmitFinalDestCopy(E, LV);
138 }
139 
140 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
141 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
142   assert(Src.isAggregate() && "value must be aggregate value!");
143 
144   // If the result is ignored, don't copy from the value.
145   if (DestPtr == 0) {
146     if (!Src.isVolatileQualified() || (IgnoreResult && Ignore))
147       return;
148     // If the source is volatile, we must read from it; to do that, we need
149     // some place to put it.
150     DestPtr = CGF.CreateTempAlloca(CGF.ConvertType(E->getType()), "agg.tmp");
151   }
152 
153   if (RequiresGCollection) {
154     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
155                                               DestPtr, Src.getAggregateAddr(),
156                                               E->getType());
157     return;
158   }
159   // If the result of the assignment is used, copy the LHS there also.
160   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
161   // from the source as well, as we can't eliminate it if either operand
162   // is volatile, unless copy has volatile for both source and destination..
163   CGF.EmitAggregateCopy(DestPtr, Src.getAggregateAddr(), E->getType(),
164                         VolatileDest|Src.isVolatileQualified());
165 }
166 
167 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
168 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
169   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
170 
171   EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
172                                             Src.isVolatileQualified()),
173                     Ignore);
174 }
175 
176 //===----------------------------------------------------------------------===//
177 //                            Visitor Methods
178 //===----------------------------------------------------------------------===//
179 
180 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
181   switch (E->getCastKind()) {
182   default: assert(0 && "Unhandled cast kind!");
183 
184   case CastExpr::CK_ToUnion: {
185     // GCC union extension
186     QualType PtrTy =
187     CGF.getContext().getPointerType(E->getSubExpr()->getType());
188     llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr,
189                                                  CGF.ConvertType(PtrTy));
190     EmitInitializationToLValue(E->getSubExpr(),
191                                LValue::MakeAddr(CastPtr, Qualifiers()),
192                                E->getType());
193     break;
194   }
195 
196   // FIXME: Remove the CK_Unknown check here.
197   case CastExpr::CK_Unknown:
198   case CastExpr::CK_NoOp:
199   case CastExpr::CK_UserDefinedConversion:
200   case CastExpr::CK_ConstructorConversion:
201     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
202                                                    E->getType()) &&
203            "Implicit cast types must be compatible");
204     Visit(E->getSubExpr());
205     break;
206 
207   case CastExpr::CK_NullToMemberPointer: {
208     const llvm::Type *PtrDiffTy =
209       CGF.ConvertType(CGF.getContext().getPointerDiffType());
210 
211     llvm::Value *NullValue = llvm::Constant::getNullValue(PtrDiffTy);
212     llvm::Value *Ptr = Builder.CreateStructGEP(DestPtr, 0, "ptr");
213     Builder.CreateStore(NullValue, Ptr, VolatileDest);
214 
215     llvm::Value *Adj = Builder.CreateStructGEP(DestPtr, 1, "adj");
216     Builder.CreateStore(NullValue, Adj, VolatileDest);
217 
218     break;
219   }
220 
221   case CastExpr::CK_BitCast: {
222     // This must be a member function pointer cast.
223     Visit(E->getSubExpr());
224     break;
225   }
226 
227   case CastExpr::CK_DerivedToBaseMemberPointer:
228   case CastExpr::CK_BaseToDerivedMemberPointer: {
229     QualType SrcType = E->getSubExpr()->getType();
230 
231     llvm::Value *Src = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(SrcType),
232                                             "tmp");
233     CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified());
234 
235     llvm::Value *SrcPtr = Builder.CreateStructGEP(Src, 0, "src.ptr");
236     SrcPtr = Builder.CreateLoad(SrcPtr);
237 
238     llvm::Value *SrcAdj = Builder.CreateStructGEP(Src, 1, "src.adj");
239     SrcAdj = Builder.CreateLoad(SrcAdj);
240 
241     llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
242     Builder.CreateStore(SrcPtr, DstPtr, VolatileDest);
243 
244     llvm::Value *DstAdj = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
245 
246     // Now See if we need to update the adjustment.
247     const CXXRecordDecl *BaseDecl =
248       cast<CXXRecordDecl>(SrcType->getAs<MemberPointerType>()->
249                           getClass()->getAs<RecordType>()->getDecl());
250     const CXXRecordDecl *DerivedDecl =
251       cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()->
252                           getClass()->getAs<RecordType>()->getDecl());
253     if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
254       std::swap(DerivedDecl, BaseDecl);
255 
256     if (llvm::Constant *Adj =
257           CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl, BaseDecl)) {
258       if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
259         SrcAdj = Builder.CreateSub(SrcAdj, Adj, "adj");
260       else
261         SrcAdj = Builder.CreateAdd(SrcAdj, Adj, "adj");
262     }
263 
264     Builder.CreateStore(SrcAdj, DstAdj, VolatileDest);
265     break;
266   }
267   }
268 }
269 
270 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
271   if (E->getCallReturnType()->isReferenceType()) {
272     EmitAggLoadOfLValue(E);
273     return;
274   }
275 
276   // If the struct doesn't require GC, we can just pass the destination
277   // directly to EmitCall.
278   if (!RequiresGCollection) {
279     CGF.EmitCallExpr(E, ReturnValueSlot(DestPtr, VolatileDest));
280     return;
281   }
282 
283   RValue RV = CGF.EmitCallExpr(E);
284   EmitFinalDestCopy(E, RV);
285 }
286 
287 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
288   RValue RV = CGF.EmitObjCMessageExpr(E);
289   EmitFinalDestCopy(E, RV);
290 }
291 
292 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
293   RValue RV = CGF.EmitObjCPropertyGet(E);
294   EmitFinalDestCopy(E, RV);
295 }
296 
297 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr(
298                                    ObjCImplicitSetterGetterRefExpr *E) {
299   RValue RV = CGF.EmitObjCPropertyGet(E);
300   EmitFinalDestCopy(E, RV);
301 }
302 
303 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
304   CGF.EmitAnyExpr(E->getLHS(), 0, false, true);
305   CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest,
306                   /*IgnoreResult=*/false, IsInitializer);
307 }
308 
309 void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) {
310   // We have a member function pointer.
311   const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
312   (void) MPT;
313   assert(MPT->getPointeeType()->isFunctionProtoType() &&
314          "Unexpected member pointer type!");
315 
316   const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr());
317   const CXXMethodDecl *MD =
318     cast<CXXMethodDecl>(DRE->getDecl())->getCanonicalDecl();
319 
320   const llvm::Type *PtrDiffTy =
321     CGF.ConvertType(CGF.getContext().getPointerDiffType());
322 
323   llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
324   llvm::Value *FuncPtr;
325 
326   if (MD->isVirtual()) {
327     int64_t Index =
328       CGF.CGM.getVtableInfo().getMethodVtableIndex(MD);
329 
330     // Itanium C++ ABI 2.3:
331     //   For a non-virtual function, this field is a simple function pointer.
332     //   For a virtual function, it is 1 plus the virtual table offset
333     //   (in bytes) of the function, represented as a ptrdiff_t.
334     FuncPtr = llvm::ConstantInt::get(PtrDiffTy, (Index * 8) + 1);
335   } else {
336     const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
337     const llvm::Type *Ty =
338       CGF.CGM.getTypes().GetFunctionType(CGF.CGM.getTypes().getFunctionInfo(MD),
339                                          FPT->isVariadic());
340     llvm::Constant *Fn = CGF.CGM.GetAddrOfFunction(MD, Ty);
341     FuncPtr = llvm::ConstantExpr::getPtrToInt(Fn, PtrDiffTy);
342   }
343   Builder.CreateStore(FuncPtr, DstPtr, VolatileDest);
344 
345   llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
346 
347   // The adjustment will always be 0.
348   Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr,
349                       VolatileDest);
350 }
351 
352 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
353   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
354 }
355 
356 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
357   if (E->getOpcode() == BinaryOperator::PtrMemD ||
358       E->getOpcode() == BinaryOperator::PtrMemI)
359     VisitPointerToDataMemberBinaryOperator(E);
360   else
361     CGF.ErrorUnsupported(E, "aggregate binary expression");
362 }
363 
364 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
365                                                     const BinaryOperator *E) {
366   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
367   EmitFinalDestCopy(E, LV);
368 }
369 
370 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
371   // For an assignment to work, the value on the right has
372   // to be compatible with the value on the left.
373   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
374                                                  E->getRHS()->getType())
375          && "Invalid assignment");
376   LValue LHS = CGF.EmitLValue(E->getLHS());
377 
378   // We have to special case property setters, otherwise we must have
379   // a simple lvalue (no aggregates inside vectors, bitfields).
380   if (LHS.isPropertyRef()) {
381     llvm::Value *AggLoc = DestPtr;
382     if (!AggLoc)
383       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
384     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
385     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
386                             RValue::getAggregate(AggLoc, VolatileDest));
387   } else if (LHS.isKVCRef()) {
388     llvm::Value *AggLoc = DestPtr;
389     if (!AggLoc)
390       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
391     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
392     CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
393                             RValue::getAggregate(AggLoc, VolatileDest));
394   } else {
395     bool RequiresGCollection = false;
396     if (CGF.getContext().getLangOptions().NeXTRuntime) {
397       QualType LHSTy = E->getLHS()->getType();
398       if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>())
399         RequiresGCollection = FDTTy->getDecl()->hasObjectMember();
400     }
401     // Codegen the RHS so that it stores directly into the LHS.
402     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(),
403                     false, false, RequiresGCollection);
404     EmitFinalDestCopy(E, LHS, true);
405   }
406 }
407 
408 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
409   if (!E->getLHS()) {
410     CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
411     return;
412   }
413 
414   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
415   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
416   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
417 
418   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
419 
420   CGF.BeginConditionalBranch();
421   CGF.EmitBlock(LHSBlock);
422 
423   // Handle the GNU extension for missing LHS.
424   assert(E->getLHS() && "Must have LHS for aggregate value");
425 
426   Visit(E->getLHS());
427   CGF.EndConditionalBranch();
428   CGF.EmitBranch(ContBlock);
429 
430   CGF.BeginConditionalBranch();
431   CGF.EmitBlock(RHSBlock);
432 
433   Visit(E->getRHS());
434   CGF.EndConditionalBranch();
435   CGF.EmitBranch(ContBlock);
436 
437   CGF.EmitBlock(ContBlock);
438 }
439 
440 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
441   Visit(CE->getChosenSubExpr(CGF.getContext()));
442 }
443 
444 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
445   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
446   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
447 
448   if (!ArgPtr) {
449     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
450     return;
451   }
452 
453   EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers()));
454 }
455 
456 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
457   llvm::Value *Val = DestPtr;
458 
459   if (!Val) {
460     // Create a temporary variable.
461     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
462 
463     // FIXME: volatile
464     CGF.EmitAggExpr(E->getSubExpr(), Val, false);
465   } else
466     Visit(E->getSubExpr());
467 
468   // Don't make this a live temporary if we're emitting an initializer expr.
469   if (!IsInitializer)
470     CGF.PushCXXTemporary(E->getTemporary(), Val);
471 }
472 
473 void
474 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
475   llvm::Value *Val = DestPtr;
476 
477   if (!Val) {
478     // Create a temporary variable.
479     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
480   }
481 
482   if (E->requiresZeroInitialization())
483     EmitNullInitializationToLValue(LValue::MakeAddr(Val,
484                                                     // FIXME: Qualifiers()?
485                                                  E->getType().getQualifiers()),
486                                    E->getType());
487 
488   CGF.EmitCXXConstructExpr(Val, E);
489 }
490 
491 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
492   llvm::Value *Val = DestPtr;
493 
494   if (!Val) {
495     // Create a temporary variable.
496     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
497   }
498   CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer);
499 }
500 
501 void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
502   llvm::Value *Val = DestPtr;
503 
504   if (!Val) {
505     // Create a temporary variable.
506     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
507   }
508   LValue LV = LValue::MakeAddr(Val, Qualifiers());
509   EmitNullInitializationToLValue(LV, E->getType());
510 }
511 
512 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
513   llvm::Value *Val = DestPtr;
514 
515   if (!Val) {
516     // Create a temporary variable.
517     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
518   }
519   LValue LV = LValue::MakeAddr(Val, Qualifiers());
520   EmitNullInitializationToLValue(LV, E->getType());
521 }
522 
523 void
524 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
525   // FIXME: Ignore result?
526   // FIXME: Are initializers affected by volatile?
527   if (isa<ImplicitValueInitExpr>(E)) {
528     EmitNullInitializationToLValue(LV, T);
529   } else if (T->isReferenceType()) {
530     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*IsInitializer=*/false);
531     CGF.EmitStoreThroughLValue(RV, LV, T);
532   } else if (T->isAnyComplexType()) {
533     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
534   } else if (CGF.hasAggregateLLVMType(T)) {
535     CGF.EmitAnyExpr(E, LV.getAddress(), false);
536   } else {
537     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T);
538   }
539 }
540 
541 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
542   if (!CGF.hasAggregateLLVMType(T)) {
543     // For non-aggregates, we can store zero
544     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
545     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
546   } else {
547     // Otherwise, just memset the whole thing to zero.  This is legal
548     // because in LLVM, all default initializers are guaranteed to have a
549     // bit pattern of all zeros.
550     // FIXME: That isn't true for member pointers!
551     // There's a potential optimization opportunity in combining
552     // memsets; that would be easy for arrays, but relatively
553     // difficult for structures with the current code.
554     CGF.EmitMemSetToZero(LV.getAddress(), T);
555   }
556 }
557 
558 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
559 #if 0
560   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
561   // (Length of globals? Chunks of zeroed-out space?).
562   //
563   // If we can, prefer a copy from a global; this is a lot less code for long
564   // globals, and it's easier for the current optimizers to analyze.
565   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
566     llvm::GlobalVariable* GV =
567     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
568                              llvm::GlobalValue::InternalLinkage, C, "");
569     EmitFinalDestCopy(E, LValue::MakeAddr(GV, Qualifiers()));
570     return;
571   }
572 #endif
573   if (E->hadArrayRangeDesignator()) {
574     CGF.ErrorUnsupported(E, "GNU array range designator extension");
575   }
576 
577   // Handle initialization of an array.
578   if (E->getType()->isArrayType()) {
579     const llvm::PointerType *APType =
580       cast<llvm::PointerType>(DestPtr->getType());
581     const llvm::ArrayType *AType =
582       cast<llvm::ArrayType>(APType->getElementType());
583 
584     uint64_t NumInitElements = E->getNumInits();
585 
586     if (E->getNumInits() > 0) {
587       QualType T1 = E->getType();
588       QualType T2 = E->getInit(0)->getType();
589       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
590         EmitAggLoadOfLValue(E->getInit(0));
591         return;
592       }
593     }
594 
595     uint64_t NumArrayElements = AType->getNumElements();
596     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
597     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
598 
599     // FIXME: were we intentionally ignoring address spaces and GC attributes?
600     Qualifiers Quals = CGF.MakeQualifiers(ElementType);
601 
602     for (uint64_t i = 0; i != NumArrayElements; ++i) {
603       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
604       if (i < NumInitElements)
605         EmitInitializationToLValue(E->getInit(i),
606                                    LValue::MakeAddr(NextVal, Quals),
607                                    ElementType);
608       else
609         EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals),
610                                        ElementType);
611     }
612     return;
613   }
614 
615   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
616 
617   // Do struct initialization; this code just sets each individual member
618   // to the approprate value.  This makes bitfield support automatic;
619   // the disadvantage is that the generated code is more difficult for
620   // the optimizer, especially with bitfields.
621   unsigned NumInitElements = E->getNumInits();
622   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
623   unsigned CurInitVal = 0;
624 
625   if (E->getType()->isUnionType()) {
626     // Only initialize one field of a union. The field itself is
627     // specified by the initializer list.
628     if (!E->getInitializedFieldInUnion()) {
629       // Empty union; we have nothing to do.
630 
631 #ifndef NDEBUG
632       // Make sure that it's really an empty and not a failure of
633       // semantic analysis.
634       for (RecordDecl::field_iterator Field = SD->field_begin(),
635                                    FieldEnd = SD->field_end();
636            Field != FieldEnd; ++Field)
637         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
638 #endif
639       return;
640     }
641 
642     // FIXME: volatility
643     FieldDecl *Field = E->getInitializedFieldInUnion();
644     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
645 
646     if (NumInitElements) {
647       // Store the initializer into the field
648       EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
649     } else {
650       // Default-initialize to null
651       EmitNullInitializationToLValue(FieldLoc, Field->getType());
652     }
653 
654     return;
655   }
656 
657   // Here we iterate over the fields; this makes it simpler to both
658   // default-initialize fields and skip over unnamed fields.
659   for (RecordDecl::field_iterator Field = SD->field_begin(),
660                                FieldEnd = SD->field_end();
661        Field != FieldEnd; ++Field) {
662     // We're done once we hit the flexible array member
663     if (Field->getType()->isIncompleteArrayType())
664       break;
665 
666     if (Field->isUnnamedBitfield())
667       continue;
668 
669     // FIXME: volatility
670     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
671     // We never generate write-barries for initialized fields.
672     LValue::SetObjCNonGC(FieldLoc, true);
673     if (CurInitVal < NumInitElements) {
674       // Store the initializer into the field
675       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
676                                  Field->getType());
677     } else {
678       // We're out of initalizers; default-initialize to null
679       EmitNullInitializationToLValue(FieldLoc, Field->getType());
680     }
681   }
682 }
683 
684 //===----------------------------------------------------------------------===//
685 //                        Entry Points into this File
686 //===----------------------------------------------------------------------===//
687 
688 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
689 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
690 /// the value of the aggregate expression is not needed.  If VolatileDest is
691 /// true, DestPtr cannot be 0.
692 //
693 // FIXME: Take Qualifiers object.
694 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
695                                   bool VolatileDest, bool IgnoreResult,
696                                   bool IsInitializer,
697                                   bool RequiresGCollection) {
698   assert(E && hasAggregateLLVMType(E->getType()) &&
699          "Invalid aggregate expression to emit");
700   assert ((DestPtr != 0 || VolatileDest == false)
701           && "volatile aggregate can't be 0");
702 
703   AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer,
704                  RequiresGCollection)
705     .Visit(const_cast<Expr*>(E));
706 }
707 
708 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
709   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
710   Qualifiers Q = MakeQualifiers(E->getType());
711   llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(E->getType()));
712   EmitAggExpr(E, Temp, Q.hasVolatile());
713   return LValue::MakeAddr(Temp, Q);
714 }
715 
716 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
717   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
718 
719   EmitMemSetToZero(DestPtr, Ty);
720 }
721 
722 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
723                                         llvm::Value *SrcPtr, QualType Ty,
724                                         bool isVolatile) {
725   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
726 
727   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
728   // C99 6.5.16.1p3, which states "If the value being stored in an object is
729   // read from another object that overlaps in anyway the storage of the first
730   // object, then the overlap shall be exact and the two objects shall have
731   // qualified or unqualified versions of a compatible type."
732   //
733   // memcpy is not defined if the source and destination pointers are exactly
734   // equal, but other compilers do this optimization, and almost every memcpy
735   // implementation handles this case safely.  If there is a libc that does not
736   // safely handle this, we can add a target hook.
737   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
738   if (DestPtr->getType() != BP)
739     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
740   if (SrcPtr->getType() != BP)
741     SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
742 
743   // Get size and alignment info for this aggregate.
744   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
745 
746   // FIXME: Handle variable sized types.
747   const llvm::Type *IntPtr =
748           llvm::IntegerType::get(VMContext, LLVMPointerWidth);
749 
750   // FIXME: If we have a volatile struct, the optimizer can remove what might
751   // appear to be `extra' memory ops:
752   //
753   // volatile struct { int i; } a, b;
754   //
755   // int main() {
756   //   a = b;
757   //   a = b;
758   // }
759   //
760   // we need to use a differnt call here.  We use isVolatile to indicate when
761   // either the source or the destination is volatile.
762   Builder.CreateCall4(CGM.getMemCpyFn(),
763                       DestPtr, SrcPtr,
764                       // TypeInfo.first describes size in bits.
765                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
766                       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
767                                              TypeInfo.second/8));
768 }
769