CGExprAgg.cpp revision 9b2dc287177394a8f73833e2ad4f7ca8cd6f22bb
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 "clang/AST/AST.h"
17#include "llvm/Constants.h"
18#include "llvm/Function.h"
19#include "llvm/GlobalVariable.h"
20#include "llvm/Support/Compiler.h"
21using namespace clang;
22using namespace CodeGen;
23
24//===----------------------------------------------------------------------===//
25//                        Aggregate Expression Emitter
26//===----------------------------------------------------------------------===//
27
28namespace  {
29class VISIBILITY_HIDDEN AggExprEmitter : public StmtVisitor<AggExprEmitter> {
30  CodeGenFunction &CGF;
31  llvm::LLVMFoldingBuilder &Builder;
32  llvm::Value *DestPtr;
33  bool VolatileDest;
34public:
35  AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool volatileDest)
36    : CGF(cgf), Builder(CGF.Builder),
37      DestPtr(destPtr), VolatileDest(volatileDest) {
38  }
39
40  //===--------------------------------------------------------------------===//
41  //                               Utilities
42  //===--------------------------------------------------------------------===//
43
44  /// EmitAggLoadOfLValue - Given an expression with aggregate type that
45  /// represents a value lvalue, this method emits the address of the lvalue,
46  /// then loads the result into DestPtr.
47  void EmitAggLoadOfLValue(const Expr *E);
48
49  void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
50                         QualType EltTy);
51
52  void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty);
53
54  void EmitNonConstInit(InitListExpr *E);
55
56  //===--------------------------------------------------------------------===//
57  //                            Visitor Methods
58  //===--------------------------------------------------------------------===//
59
60  void VisitStmt(Stmt *S) {
61    CGF.WarnUnsupported(S, "aggregate expression");
62  }
63  void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
64
65  // l-values.
66  void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
67  void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
68  void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
69  void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
70
71  void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
72    EmitAggLoadOfLValue(E);
73  }
74
75  // Operators.
76  //  case Expr::UnaryOperatorClass:
77  //  case Expr::CastExprClass:
78  void VisitImplicitCastExpr(ImplicitCastExpr *E);
79  void VisitCallExpr(const CallExpr *E);
80  void VisitStmtExpr(const StmtExpr *E);
81  void VisitBinaryOperator(const BinaryOperator *BO);
82  void VisitBinAssign(const BinaryOperator *E);
83  void VisitOverloadExpr(const OverloadExpr *E);
84
85
86  void VisitConditionalOperator(const ConditionalOperator *CO);
87  void VisitInitListExpr(InitListExpr *E);
88  //  case Expr::ChooseExprClass:
89
90};
91}  // end anonymous namespace.
92
93//===----------------------------------------------------------------------===//
94//                                Utilities
95//===----------------------------------------------------------------------===//
96
97void AggExprEmitter::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
98  assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
99
100  // Aggregate assignment turns into llvm.memset.
101  const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
102  if (DestPtr->getType() != BP)
103    DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
104
105  // Get size and alignment info for this aggregate.
106  std::pair<uint64_t, unsigned> TypeInfo = CGF.getContext().getTypeInfo(Ty);
107
108  // FIXME: Handle variable sized types.
109  const llvm::Type *IntPtr = llvm::IntegerType::get(CGF.LLVMPointerWidth);
110
111  llvm::Value *MemSetOps[4] = {
112    DestPtr,
113    llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
114    // TypeInfo.first describes size in bits.
115    llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
116    llvm::ConstantInt::get(llvm::Type::Int32Ty, TypeInfo.second/8)
117  };
118
119  Builder.CreateCall(CGF.CGM.getMemSetFn(), MemSetOps, MemSetOps+4);
120}
121
122void AggExprEmitter::EmitAggregateCopy(llvm::Value *DestPtr,
123                                       llvm::Value *SrcPtr, QualType Ty) {
124  assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
125
126  // Aggregate assignment turns into llvm.memcpy.
127  const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
128  if (DestPtr->getType() != BP)
129    DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
130  if (SrcPtr->getType() != BP)
131    SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
132
133  // Get size and alignment info for this aggregate.
134  std::pair<uint64_t, unsigned> TypeInfo = CGF.getContext().getTypeInfo(Ty);
135
136  // FIXME: Handle variable sized types.
137  const llvm::Type *IntPtr = llvm::IntegerType::get(CGF.LLVMPointerWidth);
138
139  llvm::Value *MemCpyOps[4] = {
140    DestPtr, SrcPtr,
141    // TypeInfo.first describes size in bits.
142    llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
143    llvm::ConstantInt::get(llvm::Type::Int32Ty, TypeInfo.second/8)
144  };
145
146  Builder.CreateCall(CGF.CGM.getMemCpyFn(), MemCpyOps, MemCpyOps+4);
147}
148
149
150/// EmitAggLoadOfLValue - Given an expression with aggregate type that
151/// represents a value lvalue, this method emits the address of the lvalue,
152/// then loads the result into DestPtr.
153void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
154  LValue LV = CGF.EmitLValue(E);
155  assert(LV.isSimple() && "Can't have aggregate bitfield, vector, etc");
156  llvm::Value *SrcPtr = LV.getAddress();
157
158  // If the result is ignored, don't copy from the value.
159  if (DestPtr == 0)
160    // FIXME: If the source is volatile, we must read from it.
161    return;
162
163  EmitAggregateCopy(DestPtr, SrcPtr, E->getType());
164}
165
166//===----------------------------------------------------------------------===//
167//                            Visitor Methods
168//===----------------------------------------------------------------------===//
169
170void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E)
171{
172  QualType STy = E->getSubExpr()->getType().getCanonicalType();
173  QualType Ty = E->getType().getCanonicalType();
174
175  assert(CGF.getContext().typesAreCompatible(
176             STy.getUnqualifiedType(), Ty.getUnqualifiedType())
177         && "Implicit cast types must be compatible");
178
179  Visit(E->getSubExpr());
180}
181
182void AggExprEmitter::VisitCallExpr(const CallExpr *E)
183{
184  RValue RV = CGF.EmitCallExpr(E);
185  assert(RV.isAggregate() && "Return value must be aggregate value!");
186
187  // If the result is ignored, don't copy from the value.
188  if (DestPtr == 0)
189    // FIXME: If the source is volatile, we must read from it.
190    return;
191
192  EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
193}
194
195void AggExprEmitter::VisitOverloadExpr(const OverloadExpr *E)
196{
197  RValue RV = CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
198                               E->getNumArgs(CGF.getContext()));
199  assert(RV.isAggregate() && "Return value must be aggregate value!");
200
201  // If the result is ignored, don't copy from the value.
202  if (DestPtr == 0)
203    // FIXME: If the source is volatile, we must read from it.
204    return;
205
206  EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
207}
208
209void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
210  CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
211}
212
213void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
214  CGF.WarnUnsupported(E, "aggregate binary expression");
215}
216
217void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
218  // For an assignment to work, the value on the right has
219  // to be compatible with the value on the left.
220  assert(CGF.getContext().typesAreCompatible(
221             E->getLHS()->getType().getUnqualifiedType(),
222             E->getRHS()->getType().getUnqualifiedType())
223         && "Invalid assignment");
224  LValue LHS = CGF.EmitLValue(E->getLHS());
225
226  // Codegen the RHS so that it stores directly into the LHS.
227  CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), false /*FIXME: VOLATILE LHS*/);
228
229  if (DestPtr == 0)
230    return;
231
232  // If the result of the assignment is used, copy the RHS there also.
233  EmitAggregateCopy(DestPtr, LHS.getAddress(), E->getType());
234}
235
236void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
237  llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
238  llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
239  llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
240
241  llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
242  Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
243
244  CGF.EmitBlock(LHSBlock);
245
246  // Handle the GNU extension for missing LHS.
247  assert(E->getLHS() && "Must have LHS for aggregate value");
248
249  Visit(E->getLHS());
250  Builder.CreateBr(ContBlock);
251  LHSBlock = Builder.GetInsertBlock();
252
253  CGF.EmitBlock(RHSBlock);
254
255  Visit(E->getRHS());
256  Builder.CreateBr(ContBlock);
257  RHSBlock = Builder.GetInsertBlock();
258
259  CGF.EmitBlock(ContBlock);
260}
261
262void AggExprEmitter::EmitNonConstInit(InitListExpr *E) {
263
264  const llvm::PointerType *APType =
265    cast<llvm::PointerType>(DestPtr->getType());
266  const llvm::Type *DestType = APType->getElementType();
267
268  if (const llvm::ArrayType *AType = dyn_cast<llvm::ArrayType>(DestType)) {
269    unsigned NumInitElements = E->getNumInits();
270
271    unsigned i;
272    for (i = 0; i != NumInitElements; ++i) {
273      llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
274      Expr *Init = E->getInit(i);
275      if (isa<InitListExpr>(Init))
276        CGF.EmitAggExpr(Init, NextVal, VolatileDest);
277      else
278        Builder.CreateStore(CGF.EmitScalarExpr(Init), NextVal);
279    }
280
281    // Emit remaining default initializers
282    unsigned NumArrayElements = AType->getNumElements();
283    QualType QType = E->getInit(0)->getType();
284    const llvm::Type *EType = AType->getElementType();
285    for (/*Do not initialize i*/; i < NumArrayElements; ++i) {
286      llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
287      if (EType->isFirstClassType())
288        Builder.CreateStore(llvm::Constant::getNullValue(EType), NextVal);
289      else
290        EmitAggregateClear(NextVal, QType);
291    }
292  } else
293    assert(false && "Invalid initializer");
294}
295
296void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
297
298  if (E->isConstantExpr(CGF.CGM.getContext(), NULL)) {
299    llvm::Constant *V = CGF.CGM.EmitConstantExpr(E);
300    // Create global value to hold this array.
301    V = new llvm::GlobalVariable(V->getType(), true,
302                                 llvm::GlobalValue::InternalLinkage,
303                                 V, ".array",
304                                 &CGF.CGM.getModule());
305
306    EmitAggregateCopy(DestPtr, V , E->getType());
307    return;
308  } else {
309    if (!E->getType()->isArrayType()) {
310      CGF.WarnUnsupported(E, "aggregate init-list expression");
311      return;
312    }
313    EmitNonConstInit(E);
314  }
315}
316
317//===----------------------------------------------------------------------===//
318//                        Entry Points into this File
319//===----------------------------------------------------------------------===//
320
321/// EmitAggExpr - Emit the computation of the specified expression of
322/// aggregate type.  The result is computed into DestPtr.  Note that if
323/// DestPtr is null, the value of the aggregate expression is not needed.
324void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
325                                  bool VolatileDest) {
326  assert(E && hasAggregateLLVMType(E->getType()) &&
327         "Invalid aggregate expression to emit");
328
329  AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E));
330}
331