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     FuncPtr = llvm::ConstantInt::get(PtrDiffTy, Index + 1);
331   } else {
332     FuncPtr = llvm::ConstantExpr::getPtrToInt(CGF.CGM.GetAddrOfFunction(MD),
333                                               PtrDiffTy);
334   }
335   Builder.CreateStore(FuncPtr, DstPtr, VolatileDest);
336 
337   llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
338 
339   // The adjustment will always be 0.
340   Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr,
341                       VolatileDest);
342 }
343 
344 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
345   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
346 }
347 
348 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
349   if (E->getOpcode() == BinaryOperator::PtrMemD ||
350       E->getOpcode() == BinaryOperator::PtrMemI)
351     VisitPointerToDataMemberBinaryOperator(E);
352   else
353     CGF.ErrorUnsupported(E, "aggregate binary expression");
354 }
355 
356 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
357                                                     const BinaryOperator *E) {
358   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
359   EmitFinalDestCopy(E, LV);
360 }
361 
362 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
363   // For an assignment to work, the value on the right has
364   // to be compatible with the value on the left.
365   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
366                                                  E->getRHS()->getType())
367          && "Invalid assignment");
368   LValue LHS = CGF.EmitLValue(E->getLHS());
369 
370   // We have to special case property setters, otherwise we must have
371   // a simple lvalue (no aggregates inside vectors, bitfields).
372   if (LHS.isPropertyRef()) {
373     llvm::Value *AggLoc = DestPtr;
374     if (!AggLoc)
375       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
376     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
377     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
378                             RValue::getAggregate(AggLoc, VolatileDest));
379   } else if (LHS.isKVCRef()) {
380     llvm::Value *AggLoc = DestPtr;
381     if (!AggLoc)
382       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
383     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
384     CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
385                             RValue::getAggregate(AggLoc, VolatileDest));
386   } else {
387     bool RequiresGCollection = false;
388     if (CGF.getContext().getLangOptions().NeXTRuntime) {
389       QualType LHSTy = E->getLHS()->getType();
390       if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>())
391         RequiresGCollection = FDTTy->getDecl()->hasObjectMember();
392     }
393     // Codegen the RHS so that it stores directly into the LHS.
394     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(),
395                     false, false, RequiresGCollection);
396     EmitFinalDestCopy(E, LHS, true);
397   }
398 }
399 
400 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
401   if (!E->getLHS()) {
402     CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
403     return;
404   }
405 
406   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
407   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
408   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
409 
410   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
411 
412   CGF.StartConditionalBranch();
413   CGF.EmitBlock(LHSBlock);
414 
415   // Handle the GNU extension for missing LHS.
416   assert(E->getLHS() && "Must have LHS for aggregate value");
417 
418   Visit(E->getLHS());
419   CGF.FinishConditionalBranch();
420   CGF.EmitBranch(ContBlock);
421 
422   CGF.StartConditionalBranch();
423   CGF.EmitBlock(RHSBlock);
424 
425   Visit(E->getRHS());
426   CGF.FinishConditionalBranch();
427   CGF.EmitBranch(ContBlock);
428 
429   CGF.EmitBlock(ContBlock);
430 }
431 
432 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
433   Visit(CE->getChosenSubExpr(CGF.getContext()));
434 }
435 
436 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
437   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
438   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
439 
440   if (!ArgPtr) {
441     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
442     return;
443   }
444 
445   EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers()));
446 }
447 
448 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
449   llvm::Value *Val = DestPtr;
450 
451   if (!Val) {
452     // Create a temporary variable.
453     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
454 
455     // FIXME: volatile
456     CGF.EmitAggExpr(E->getSubExpr(), Val, false);
457   } else
458     Visit(E->getSubExpr());
459 
460   // Don't make this a live temporary if we're emitting an initializer expr.
461   if (!IsInitializer)
462     CGF.PushCXXTemporary(E->getTemporary(), Val);
463 }
464 
465 void
466 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
467   llvm::Value *Val = DestPtr;
468 
469   if (!Val) {
470     // Create a temporary variable.
471     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
472   }
473 
474   if (E->requiresZeroInitialization())
475     EmitNullInitializationToLValue(LValue::MakeAddr(Val,
476                                                     // FIXME: Qualifiers()?
477                                                  E->getType().getQualifiers()),
478                                    E->getType());
479 
480   CGF.EmitCXXConstructExpr(Val, E);
481 }
482 
483 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
484   llvm::Value *Val = DestPtr;
485 
486   if (!Val) {
487     // Create a temporary variable.
488     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
489   }
490   CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer);
491 }
492 
493 void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
494   llvm::Value *Val = DestPtr;
495 
496   if (!Val) {
497     // Create a temporary variable.
498     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
499   }
500   LValue LV = LValue::MakeAddr(Val, Qualifiers());
501   EmitNullInitializationToLValue(LV, E->getType());
502 }
503 
504 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
505   llvm::Value *Val = DestPtr;
506 
507   if (!Val) {
508     // Create a temporary variable.
509     Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
510   }
511   LValue LV = LValue::MakeAddr(Val, Qualifiers());
512   EmitNullInitializationToLValue(LV, E->getType());
513 }
514 
515 void
516 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
517   // FIXME: Ignore result?
518   // FIXME: Are initializers affected by volatile?
519   if (isa<ImplicitValueInitExpr>(E)) {
520     EmitNullInitializationToLValue(LV, T);
521   } else if (T->isAnyComplexType()) {
522     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
523   } else if (CGF.hasAggregateLLVMType(T)) {
524     CGF.EmitAnyExpr(E, LV.getAddress(), false);
525   } else {
526     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T);
527   }
528 }
529 
530 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
531   if (!CGF.hasAggregateLLVMType(T)) {
532     // For non-aggregates, we can store zero
533     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
534     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
535   } else {
536     // Otherwise, just memset the whole thing to zero.  This is legal
537     // because in LLVM, all default initializers are guaranteed to have a
538     // bit pattern of all zeros.
539     // FIXME: That isn't true for member pointers!
540     // There's a potential optimization opportunity in combining
541     // memsets; that would be easy for arrays, but relatively
542     // difficult for structures with the current code.
543     CGF.EmitMemSetToZero(LV.getAddress(), T);
544   }
545 }
546 
547 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
548 #if 0
549   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
550   // (Length of globals? Chunks of zeroed-out space?).
551   //
552   // If we can, prefer a copy from a global; this is a lot less code for long
553   // globals, and it's easier for the current optimizers to analyze.
554   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
555     llvm::GlobalVariable* GV =
556     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
557                              llvm::GlobalValue::InternalLinkage, C, "");
558     EmitFinalDestCopy(E, LValue::MakeAddr(GV, Qualifiers()));
559     return;
560   }
561 #endif
562   if (E->hadArrayRangeDesignator()) {
563     CGF.ErrorUnsupported(E, "GNU array range designator extension");
564   }
565 
566   // Handle initialization of an array.
567   if (E->getType()->isArrayType()) {
568     const llvm::PointerType *APType =
569       cast<llvm::PointerType>(DestPtr->getType());
570     const llvm::ArrayType *AType =
571       cast<llvm::ArrayType>(APType->getElementType());
572 
573     uint64_t NumInitElements = E->getNumInits();
574 
575     if (E->getNumInits() > 0) {
576       QualType T1 = E->getType();
577       QualType T2 = E->getInit(0)->getType();
578       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
579         EmitAggLoadOfLValue(E->getInit(0));
580         return;
581       }
582     }
583 
584     uint64_t NumArrayElements = AType->getNumElements();
585     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
586     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
587 
588     // FIXME: were we intentionally ignoring address spaces and GC attributes?
589     Qualifiers Quals = CGF.MakeQualifiers(ElementType);
590 
591     for (uint64_t i = 0; i != NumArrayElements; ++i) {
592       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
593       if (i < NumInitElements)
594         EmitInitializationToLValue(E->getInit(i),
595                                    LValue::MakeAddr(NextVal, Quals),
596                                    ElementType);
597       else
598         EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals),
599                                        ElementType);
600     }
601     return;
602   }
603 
604   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
605 
606   // Do struct initialization; this code just sets each individual member
607   // to the approprate value.  This makes bitfield support automatic;
608   // the disadvantage is that the generated code is more difficult for
609   // the optimizer, especially with bitfields.
610   unsigned NumInitElements = E->getNumInits();
611   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
612   unsigned CurInitVal = 0;
613 
614   if (E->getType()->isUnionType()) {
615     // Only initialize one field of a union. The field itself is
616     // specified by the initializer list.
617     if (!E->getInitializedFieldInUnion()) {
618       // Empty union; we have nothing to do.
619 
620 #ifndef NDEBUG
621       // Make sure that it's really an empty and not a failure of
622       // semantic analysis.
623       for (RecordDecl::field_iterator Field = SD->field_begin(),
624                                    FieldEnd = SD->field_end();
625            Field != FieldEnd; ++Field)
626         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
627 #endif
628       return;
629     }
630 
631     // FIXME: volatility
632     FieldDecl *Field = E->getInitializedFieldInUnion();
633     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, Field, 0);
634 
635     if (NumInitElements) {
636       // Store the initializer into the field
637       EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
638     } else {
639       // Default-initialize to null
640       EmitNullInitializationToLValue(FieldLoc, Field->getType());
641     }
642 
643     return;
644   }
645 
646   // Here we iterate over the fields; this makes it simpler to both
647   // default-initialize fields and skip over unnamed fields.
648   for (RecordDecl::field_iterator Field = SD->field_begin(),
649                                FieldEnd = SD->field_end();
650        Field != FieldEnd; ++Field) {
651     // We're done once we hit the flexible array member
652     if (Field->getType()->isIncompleteArrayType())
653       break;
654 
655     if (Field->isUnnamedBitfield())
656       continue;
657 
658     // FIXME: volatility
659     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, 0);
660     // We never generate write-barries for initialized fields.
661     LValue::SetObjCNonGC(FieldLoc, true);
662     if (CurInitVal < NumInitElements) {
663       // Store the initializer into the field
664       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
665                                  Field->getType());
666     } else {
667       // We're out of initalizers; default-initialize to null
668       EmitNullInitializationToLValue(FieldLoc, Field->getType());
669     }
670   }
671 }
672 
673 //===----------------------------------------------------------------------===//
674 //                        Entry Points into this File
675 //===----------------------------------------------------------------------===//
676 
677 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
678 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
679 /// the value of the aggregate expression is not needed.  If VolatileDest is
680 /// true, DestPtr cannot be 0.
681 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
682                                   bool VolatileDest, bool IgnoreResult,
683                                   bool IsInitializer,
684                                   bool RequiresGCollection) {
685   assert(E && hasAggregateLLVMType(E->getType()) &&
686          "Invalid aggregate expression to emit");
687   assert ((DestPtr != 0 || VolatileDest == false)
688           && "volatile aggregate can't be 0");
689 
690   AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer,
691                  RequiresGCollection)
692     .Visit(const_cast<Expr*>(E));
693 }
694 
695 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
696   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
697 
698   EmitMemSetToZero(DestPtr, Ty);
699 }
700 
701 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
702                                         llvm::Value *SrcPtr, QualType Ty,
703                                         bool isVolatile) {
704   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
705 
706   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
707   // C99 6.5.16.1p3, which states "If the value being stored in an object is
708   // read from another object that overlaps in anyway the storage of the first
709   // object, then the overlap shall be exact and the two objects shall have
710   // qualified or unqualified versions of a compatible type."
711   //
712   // memcpy is not defined if the source and destination pointers are exactly
713   // equal, but other compilers do this optimization, and almost every memcpy
714   // implementation handles this case safely.  If there is a libc that does not
715   // safely handle this, we can add a target hook.
716   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
717   if (DestPtr->getType() != BP)
718     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
719   if (SrcPtr->getType() != BP)
720     SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
721 
722   // Get size and alignment info for this aggregate.
723   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
724 
725   // FIXME: Handle variable sized types.
726   const llvm::Type *IntPtr =
727           llvm::IntegerType::get(VMContext, LLVMPointerWidth);
728 
729   // FIXME: If we have a volatile struct, the optimizer can remove what might
730   // appear to be `extra' memory ops:
731   //
732   // volatile struct { int i; } a, b;
733   //
734   // int main() {
735   //   a = b;
736   //   a = b;
737   // }
738   //
739   // we need to use a differnt call here.  We use isVolatile to indicate when
740   // either the source or the destination is volatile.
741   Builder.CreateCall4(CGM.getMemCpyFn(),
742                       DestPtr, SrcPtr,
743                       // TypeInfo.first describes size in bits.
744                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
745                       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
746                                              TypeInfo.second/8));
747 }
748