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);
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     break;
193   }
194 
195   // FIXME: Remove the CK_Unknown check here.
196   case CastExpr::CK_Unknown:
197   case CastExpr::CK_NoOp:
198   case CastExpr::CK_UserDefinedConversion:
199   case CastExpr::CK_ConstructorConversion:
200     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
201                                                    E->getType()) &&
202            "Implicit cast types must be compatible");
203     Visit(E->getSubExpr());
204     break;
205 
206   case CastExpr::CK_NullToMemberPointer: {
207     const llvm::Type *PtrDiffTy =
208       CGF.ConvertType(CGF.getContext().getPointerDiffType());
209 
210     llvm::Value *NullValue = llvm::Constant::getNullValue(PtrDiffTy);
211     llvm::Value *Ptr = Builder.CreateStructGEP(DestPtr, 0, "ptr");
212     Builder.CreateStore(NullValue, Ptr, VolatileDest);
213 
214     llvm::Value *Adj = Builder.CreateStructGEP(DestPtr, 1, "adj");
215     Builder.CreateStore(NullValue, Adj, VolatileDest);
216 
217     break;
218   }
219 
220   case CastExpr::CK_BitCast: {
221     // This must be a member function pointer cast.
222     Visit(E->getSubExpr());
223     break;
224   }
225 
226   case CastExpr::CK_DerivedToBaseMemberPointer:
227   case CastExpr::CK_BaseToDerivedMemberPointer: {
228     QualType SrcType = E->getSubExpr()->getType();
229 
230     llvm::Value *Src = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(SrcType),
231                                             "tmp");
232     CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified());
233 
234     llvm::Value *SrcPtr = Builder.CreateStructGEP(Src, 0, "src.ptr");
235     SrcPtr = Builder.CreateLoad(SrcPtr);
236 
237     llvm::Value *SrcAdj = Builder.CreateStructGEP(Src, 1, "src.adj");
238     SrcAdj = Builder.CreateLoad(SrcAdj);
239 
240     llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
241     Builder.CreateStore(SrcPtr, DstPtr, VolatileDest);
242 
243     llvm::Value *DstAdj = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
244 
245     // Now See if we need to update the adjustment.
246     const CXXRecordDecl *BaseDecl =
247       cast<CXXRecordDecl>(SrcType->getAs<MemberPointerType>()->
248                           getClass()->getAs<RecordType>()->getDecl());
249     const CXXRecordDecl *DerivedDecl =
250       cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()->
251                           getClass()->getAs<RecordType>()->getDecl());
252     if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
253       std::swap(DerivedDecl, BaseDecl);
254 
255     llvm::Constant *Adj = CGF.CGM.GetCXXBaseClassOffset(DerivedDecl, BaseDecl);
256     if (Adj) {
257       if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
258         SrcAdj = Builder.CreateSub(SrcAdj, Adj, "adj");
259       else
260         SrcAdj = Builder.CreateAdd(SrcAdj, Adj, "adj");
261     }
262 
263     Builder.CreateStore(SrcAdj, DstAdj, VolatileDest);
264     break;
265   }
266   }
267 }
268 
269 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
270   if (E->getCallReturnType()->isReferenceType()) {
271     EmitAggLoadOfLValue(E);
272     return;
273   }
274 
275   RValue RV = CGF.EmitCallExpr(E);
276   EmitFinalDestCopy(E, RV);
277 }
278 
279 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
280   RValue RV = CGF.EmitObjCMessageExpr(E);
281   EmitFinalDestCopy(E, RV);
282 }
283 
284 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
285   RValue RV = CGF.EmitObjCPropertyGet(E);
286   EmitFinalDestCopy(E, RV);
287 }
288 
289 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr(
290                                    ObjCImplicitSetterGetterRefExpr *E) {
291   RValue RV = CGF.EmitObjCPropertyGet(E);
292   EmitFinalDestCopy(E, RV);
293 }
294 
295 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
296   CGF.EmitAnyExpr(E->getLHS(), 0, false, true);
297   CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest,
298                   /*IgnoreResult=*/false, IsInitializer);
299 }
300 
301 void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) {
302   // We have a member function pointer.
303   const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
304   (void) MPT;
305   assert(MPT->getPointeeType()->isFunctionProtoType() &&
306          "Unexpected member pointer type!");
307 
308   const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr());
309   const CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
310 
311   const llvm::Type *PtrDiffTy =
312     CGF.ConvertType(CGF.getContext().getPointerDiffType());
313 
314   llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
315   llvm::Value *FuncPtr;
316 
317   if (MD->isVirtual()) {
318     int64_t Index =
319       CGF.CGM.getVtableInfo().getMethodVtableIndex(MD);
320 
321     FuncPtr = llvm::ConstantInt::get(PtrDiffTy, Index + 1);
322   } else {
323     FuncPtr = llvm::ConstantExpr::getPtrToInt(CGF.CGM.GetAddrOfFunction(MD),
324                                               PtrDiffTy);
325   }
326   Builder.CreateStore(FuncPtr, DstPtr, VolatileDest);
327 
328   llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
329 
330   // The adjustment will always be 0.
331   Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr,
332                       VolatileDest);
333 }
334 
335 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
336   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
337 }
338 
339 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
340   if (E->getOpcode() == BinaryOperator::PtrMemD ||
341       E->getOpcode() == BinaryOperator::PtrMemI)
342     VisitPointerToDataMemberBinaryOperator(E);
343   else
344     CGF.ErrorUnsupported(E, "aggregate binary expression");
345 }
346 
347 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
348                                                     const BinaryOperator *E) {
349   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
350   EmitFinalDestCopy(E, LV);
351 }
352 
353 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
354   // For an assignment to work, the value on the right has
355   // to be compatible with the value on the left.
356   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
357                                                  E->getRHS()->getType())
358          && "Invalid assignment");
359   LValue LHS = CGF.EmitLValue(E->getLHS());
360 
361   // We have to special case property setters, otherwise we must have
362   // a simple lvalue (no aggregates inside vectors, bitfields).
363   if (LHS.isPropertyRef()) {
364     llvm::Value *AggLoc = DestPtr;
365     if (!AggLoc)
366       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
367     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
368     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
369                             RValue::getAggregate(AggLoc, VolatileDest));
370   } else if (LHS.isKVCRef()) {
371     llvm::Value *AggLoc = DestPtr;
372     if (!AggLoc)
373       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
374     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
375     CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
376                             RValue::getAggregate(AggLoc, VolatileDest));
377   } else {
378     bool RequiresGCollection = false;
379     if (CGF.getContext().getLangOptions().NeXTRuntime) {
380       QualType LHSTy = E->getLHS()->getType();
381       if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>())
382         RequiresGCollection = FDTTy->getDecl()->hasObjectMember();
383     }
384     // Codegen the RHS so that it stores directly into the LHS.
385     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(),
386                     false, false, RequiresGCollection);
387     EmitFinalDestCopy(E, LHS, true);
388   }
389 }
390 
391 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
392   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
393   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
394   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
395 
396   llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
397   Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
398 
399   CGF.StartConditionalBranch();
400   CGF.EmitBlock(LHSBlock);
401 
402   // Handle the GNU extension for missing LHS.
403   assert(E->getLHS() && "Must have LHS for aggregate value");
404 
405   Visit(E->getLHS());
406   CGF.FinishConditionalBranch();
407   CGF.EmitBranch(ContBlock);
408 
409   CGF.StartConditionalBranch();
410   CGF.EmitBlock(RHSBlock);
411 
412   Visit(E->getRHS());
413   CGF.FinishConditionalBranch();
414   CGF.EmitBranch(ContBlock);
415 
416   CGF.EmitBlock(ContBlock);
417 }
418 
419 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
420   Visit(CE->getChosenSubExpr(CGF.getContext()));
421 }
422 
423 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
424   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
425   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
426 
427   if (!ArgPtr) {
428     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
429     return;
430   }
431 
432   EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers()));
433 }
434 
435 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
436   llvm::Value *Val = DestPtr;
437 
438   if (!Val) {
439     // Create a temporary variable.
440     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
441 
442     // FIXME: volatile
443     CGF.EmitAggExpr(E->getSubExpr(), Val, false);
444   } else
445     Visit(E->getSubExpr());
446 
447   // Don't make this a live temporary if we're emitting an initializer expr.
448   if (!IsInitializer)
449     CGF.PushCXXTemporary(E->getTemporary(), Val);
450 }
451 
452 void
453 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
454   llvm::Value *Val = DestPtr;
455 
456   if (!Val) {
457     // Create a temporary variable.
458     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
459   }
460 
461   if (E->requiresZeroInitialization())
462     EmitNullInitializationToLValue(LValue::MakeAddr(Val,
463                                                  E->getType().getQualifiers()),
464                                    E->getType());
465 
466   CGF.EmitCXXConstructExpr(Val, E);
467 }
468 
469 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
470   CGF.EmitCXXExprWithTemporaries(E, DestPtr, VolatileDest, IsInitializer);
471 }
472 
473 void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
474   LValue LV = LValue::MakeAddr(DestPtr, Qualifiers());
475   EmitNullInitializationToLValue(LV, E->getType());
476 }
477 
478 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
479   LValue LV = LValue::MakeAddr(DestPtr, Qualifiers());
480   EmitNullInitializationToLValue(LV, E->getType());
481 }
482 
483 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
484   // FIXME: Ignore result?
485   // FIXME: Are initializers affected by volatile?
486   if (isa<ImplicitValueInitExpr>(E)) {
487     EmitNullInitializationToLValue(LV, E->getType());
488   } else if (E->getType()->isComplexType()) {
489     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
490   } else if (CGF.hasAggregateLLVMType(E->getType())) {
491     CGF.EmitAnyExpr(E, LV.getAddress(), false);
492   } else {
493     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType());
494   }
495 }
496 
497 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
498   if (!CGF.hasAggregateLLVMType(T)) {
499     // For non-aggregates, we can store zero
500     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
501     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
502   } else {
503     // Otherwise, just memset the whole thing to zero.  This is legal
504     // because in LLVM, all default initializers are guaranteed to have a
505     // bit pattern of all zeros.
506     // FIXME: That isn't true for member pointers!
507     // There's a potential optimization opportunity in combining
508     // memsets; that would be easy for arrays, but relatively
509     // difficult for structures with the current code.
510     CGF.EmitMemSetToZero(LV.getAddress(), T);
511   }
512 }
513 
514 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
515 #if 0
516   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
517   // (Length of globals? Chunks of zeroed-out space?).
518   //
519   // If we can, prefer a copy from a global; this is a lot less code for long
520   // globals, and it's easier for the current optimizers to analyze.
521   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
522     llvm::GlobalVariable* GV =
523     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
524                              llvm::GlobalValue::InternalLinkage, C, "");
525     EmitFinalDestCopy(E, LValue::MakeAddr(GV, Qualifiers()));
526     return;
527   }
528 #endif
529   if (E->hadArrayRangeDesignator()) {
530     CGF.ErrorUnsupported(E, "GNU array range designator extension");
531   }
532 
533   // Handle initialization of an array.
534   if (E->getType()->isArrayType()) {
535     const llvm::PointerType *APType =
536       cast<llvm::PointerType>(DestPtr->getType());
537     const llvm::ArrayType *AType =
538       cast<llvm::ArrayType>(APType->getElementType());
539 
540     uint64_t NumInitElements = E->getNumInits();
541 
542     if (E->getNumInits() > 0) {
543       QualType T1 = E->getType();
544       QualType T2 = E->getInit(0)->getType();
545       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
546         EmitAggLoadOfLValue(E->getInit(0));
547         return;
548       }
549     }
550 
551     uint64_t NumArrayElements = AType->getNumElements();
552     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
553     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
554 
555     // FIXME: were we intentionally ignoring address spaces and GC attributes?
556     Qualifiers Quals = CGF.MakeQualifiers(ElementType);
557 
558     for (uint64_t i = 0; i != NumArrayElements; ++i) {
559       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
560       if (i < NumInitElements)
561         EmitInitializationToLValue(E->getInit(i),
562                                    LValue::MakeAddr(NextVal, Quals));
563       else
564         EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals),
565                                        ElementType);
566     }
567     return;
568   }
569 
570   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
571 
572   // Do struct initialization; this code just sets each individual member
573   // to the approprate value.  This makes bitfield support automatic;
574   // the disadvantage is that the generated code is more difficult for
575   // the optimizer, especially with bitfields.
576   unsigned NumInitElements = E->getNumInits();
577   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
578   unsigned CurInitVal = 0;
579 
580   if (E->getType()->isUnionType()) {
581     // Only initialize one field of a union. The field itself is
582     // specified by the initializer list.
583     if (!E->getInitializedFieldInUnion()) {
584       // Empty union; we have nothing to do.
585 
586 #ifndef NDEBUG
587       // Make sure that it's really an empty and not a failure of
588       // semantic analysis.
589       for (RecordDecl::field_iterator Field = SD->field_begin(),
590                                    FieldEnd = SD->field_end();
591            Field != FieldEnd; ++Field)
592         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
593 #endif
594       return;
595     }
596 
597     // FIXME: volatility
598     FieldDecl *Field = E->getInitializedFieldInUnion();
599     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, Field, true, 0);
600 
601     if (NumInitElements) {
602       // Store the initializer into the field
603       EmitInitializationToLValue(E->getInit(0), FieldLoc);
604     } else {
605       // Default-initialize to null
606       EmitNullInitializationToLValue(FieldLoc, Field->getType());
607     }
608 
609     return;
610   }
611 
612   // Here we iterate over the fields; this makes it simpler to both
613   // default-initialize fields and skip over unnamed fields.
614   for (RecordDecl::field_iterator Field = SD->field_begin(),
615                                FieldEnd = SD->field_end();
616        Field != FieldEnd; ++Field) {
617     // We're done once we hit the flexible array member
618     if (Field->getType()->isIncompleteArrayType())
619       break;
620 
621     if (Field->isUnnamedBitfield())
622       continue;
623 
624     // FIXME: volatility
625     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, false, 0);
626     // We never generate write-barries for initialized fields.
627     LValue::SetObjCNonGC(FieldLoc, true);
628     if (CurInitVal < NumInitElements) {
629       // Store the initializer into the field
630       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc);
631     } else {
632       // We're out of initalizers; default-initialize to null
633       EmitNullInitializationToLValue(FieldLoc, Field->getType());
634     }
635   }
636 }
637 
638 //===----------------------------------------------------------------------===//
639 //                        Entry Points into this File
640 //===----------------------------------------------------------------------===//
641 
642 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
643 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
644 /// the value of the aggregate expression is not needed.  If VolatileDest is
645 /// true, DestPtr cannot be 0.
646 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
647                                   bool VolatileDest, bool IgnoreResult,
648                                   bool IsInitializer,
649                                   bool RequiresGCollection) {
650   assert(E && hasAggregateLLVMType(E->getType()) &&
651          "Invalid aggregate expression to emit");
652   assert ((DestPtr != 0 || VolatileDest == false)
653           && "volatile aggregate can't be 0");
654 
655   AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer,
656                  RequiresGCollection)
657     .Visit(const_cast<Expr*>(E));
658 }
659 
660 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
661   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
662 
663   EmitMemSetToZero(DestPtr, Ty);
664 }
665 
666 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
667                                         llvm::Value *SrcPtr, QualType Ty,
668                                         bool isVolatile) {
669   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
670 
671   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
672   // C99 6.5.16.1p3, which states "If the value being stored in an object is
673   // read from another object that overlaps in anyway the storage of the first
674   // object, then the overlap shall be exact and the two objects shall have
675   // qualified or unqualified versions of a compatible type."
676   //
677   // memcpy is not defined if the source and destination pointers are exactly
678   // equal, but other compilers do this optimization, and almost every memcpy
679   // implementation handles this case safely.  If there is a libc that does not
680   // safely handle this, we can add a target hook.
681   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
682   if (DestPtr->getType() != BP)
683     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
684   if (SrcPtr->getType() != BP)
685     SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
686 
687   // Get size and alignment info for this aggregate.
688   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
689 
690   // FIXME: Handle variable sized types.
691   const llvm::Type *IntPtr =
692           llvm::IntegerType::get(VMContext, LLVMPointerWidth);
693 
694   // FIXME: If we have a volatile struct, the optimizer can remove what might
695   // appear to be `extra' memory ops:
696   //
697   // volatile struct { int i; } a, b;
698   //
699   // int main() {
700   //   a = b;
701   //   a = b;
702   // }
703   //
704   // we need to use a differnt call here.  We use isVolatile to indicate when
705   // either the source or the destination is volatile.
706   Builder.CreateCall4(CGM.getMemCpyFn(),
707                       DestPtr, SrcPtr,
708                       // TypeInfo.first describes size in bits.
709                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
710                       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
711                                              TypeInfo.second/8));
712 }
713