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