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/ASTContext.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Function.h"
20 #include "llvm/GlobalVariable.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Intrinsics.h"
23 using namespace clang;
24 using namespace CodeGen;
25 
26 //===----------------------------------------------------------------------===//
27 //                        Aggregate Expression Emitter
28 //===----------------------------------------------------------------------===//
29 
30 namespace  {
31 class VISIBILITY_HIDDEN AggExprEmitter : public StmtVisitor<AggExprEmitter> {
32   CodeGenFunction &CGF;
33   CGBuilderTy &Builder;
34   llvm::Value *DestPtr;
35   bool VolatileDest;
36 public:
37   AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool volatileDest)
38     : CGF(cgf), Builder(CGF.Builder),
39       DestPtr(destPtr), VolatileDest(volatileDest) {
40   }
41 
42   //===--------------------------------------------------------------------===//
43   //                               Utilities
44   //===--------------------------------------------------------------------===//
45 
46   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
47   /// represents a value lvalue, this method emits the address of the lvalue,
48   /// then loads the result into DestPtr.
49   void EmitAggLoadOfLValue(const Expr *E);
50 
51   void EmitNonConstInit(InitListExpr *E);
52 
53   //===--------------------------------------------------------------------===//
54   //                            Visitor Methods
55   //===--------------------------------------------------------------------===//
56 
57   void VisitStmt(Stmt *S) {
58     CGF.ErrorUnsupported(S, "aggregate expression");
59   }
60   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
61 
62   // l-values.
63   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
64   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
65   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
66   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
67   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
68       { EmitAggLoadOfLValue(E); }
69 
70   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
71     EmitAggLoadOfLValue(E);
72   }
73 
74   // Operators.
75   //  case Expr::UnaryOperatorClass:
76   //  case Expr::CastExprClass:
77   void VisitImplicitCastExpr(ImplicitCastExpr *E);
78   void VisitCallExpr(const CallExpr *E);
79   void VisitStmtExpr(const StmtExpr *E);
80   void VisitBinaryOperator(const BinaryOperator *BO);
81   void VisitBinAssign(const BinaryOperator *E);
82   void VisitOverloadExpr(const OverloadExpr *E);
83   void VisitBinComma(const BinaryOperator *E);
84 
85   void VisitObjCMessageExpr(ObjCMessageExpr *E);
86   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
87     EmitAggLoadOfLValue(E);
88   }
89   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
90 
91   void VisitConditionalOperator(const ConditionalOperator *CO);
92   void VisitInitListExpr(InitListExpr *E);
93   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
94     Visit(DAE->getExpr());
95   }
96   void VisitVAArgExpr(VAArgExpr *E);
97 
98   void EmitInitializationToLValue(Expr *E, LValue Address);
99   void EmitNullInitializationToLValue(LValue Address, QualType T);
100   //  case Expr::ChooseExprClass:
101 
102 };
103 }  // end anonymous namespace.
104 
105 //===----------------------------------------------------------------------===//
106 //                                Utilities
107 //===----------------------------------------------------------------------===//
108 
109 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
110 /// represents a value lvalue, this method emits the address of the lvalue,
111 /// then loads the result into DestPtr.
112 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
113   LValue LV = CGF.EmitLValue(E);
114   assert(LV.isSimple() && "Can't have aggregate bitfield, vector, etc");
115   llvm::Value *SrcPtr = LV.getAddress();
116 
117   // If the result is ignored, don't copy from the value.
118   if (DestPtr == 0)
119     // FIXME: If the source is volatile, we must read from it.
120     return;
121 
122   CGF.EmitAggregateCopy(DestPtr, SrcPtr, E->getType());
123 }
124 
125 //===----------------------------------------------------------------------===//
126 //                            Visitor Methods
127 //===----------------------------------------------------------------------===//
128 
129 void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
130   assert(CGF.getContext().typesAreCompatible(
131                           E->getSubExpr()->getType().getUnqualifiedType(),
132                           E->getType().getUnqualifiedType()) &&
133          "Implicit cast types must be compatible");
134   Visit(E->getSubExpr());
135 }
136 
137 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
138   RValue RV = CGF.EmitCallExpr(E);
139   assert(RV.isAggregate() && "Return value must be aggregate value!");
140 
141   // If the result is ignored, don't copy from the value.
142   if (DestPtr == 0)
143     // FIXME: If the source is volatile, we must read from it.
144     return;
145 
146   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
147 }
148 
149 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
150   RValue RV = CGF.EmitObjCMessageExpr(E);
151   assert(RV.isAggregate() && "Return value must be aggregate value!");
152 
153   // If the result is ignored, don't copy from the value.
154   if (DestPtr == 0)
155     // FIXME: If the source is volatile, we must read from it.
156     return;
157 
158   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
159 }
160 
161 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
162   RValue RV = CGF.EmitObjCPropertyGet(E);
163   assert(RV.isAggregate() && "Return value must be aggregate value!");
164 
165   // If the result is ignored, don't copy from the value.
166   if (DestPtr == 0)
167     // FIXME: If the source is volatile, we must read from it.
168     return;
169 
170   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
171 }
172 
173 void AggExprEmitter::VisitOverloadExpr(const OverloadExpr *E) {
174   RValue RV = CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
175                                E->arg_end(CGF.getContext()));
176 
177   assert(RV.isAggregate() && "Return value must be aggregate value!");
178 
179   // If the result is ignored, don't copy from the value.
180   if (DestPtr == 0)
181     // FIXME: If the source is volatile, we must read from it.
182     return;
183 
184   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
185 }
186 
187 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
188   CGF.EmitAnyExpr(E->getLHS());
189   CGF.EmitAggExpr(E->getRHS(), DestPtr, false);
190 }
191 
192 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
193   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
194 }
195 
196 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
197   CGF.ErrorUnsupported(E, "aggregate binary expression");
198 }
199 
200 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
201   // For an assignment to work, the value on the right has
202   // to be compatible with the value on the left.
203   assert(CGF.getContext().typesAreCompatible(
204              E->getLHS()->getType().getUnqualifiedType(),
205              E->getRHS()->getType().getUnqualifiedType())
206          && "Invalid assignment");
207   LValue LHS = CGF.EmitLValue(E->getLHS());
208 
209   // We have to special case property setters, otherwise we must have
210   // a simple lvalue (no aggregates inside vectors, bitfields).
211   if (LHS.isPropertyRef()) {
212     // FIXME: Volatility?
213     llvm::Value *AggLoc = DestPtr;
214     if (!AggLoc)
215       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
216     CGF.EmitAggExpr(E->getRHS(), AggLoc, false);
217     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
218                             RValue::getAggregate(AggLoc));
219   } else {
220     // Codegen the RHS so that it stores directly into the LHS.
221     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), false /*FIXME: VOLATILE LHS*/);
222 
223     if (DestPtr == 0)
224       return;
225 
226     // If the result of the assignment is used, copy the RHS there also.
227     CGF.EmitAggregateCopy(DestPtr, LHS.getAddress(), E->getType());
228   }
229 }
230 
231 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
232   llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?");
233   llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:");
234   llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont");
235 
236   llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
237   Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
238 
239   CGF.EmitBlock(LHSBlock);
240 
241   // Handle the GNU extension for missing LHS.
242   assert(E->getLHS() && "Must have LHS for aggregate value");
243 
244   Visit(E->getLHS());
245   Builder.CreateBr(ContBlock);
246   LHSBlock = Builder.GetInsertBlock();
247 
248   CGF.EmitBlock(RHSBlock);
249 
250   Visit(E->getRHS());
251   Builder.CreateBr(ContBlock);
252   RHSBlock = Builder.GetInsertBlock();
253 
254   CGF.EmitBlock(ContBlock);
255 }
256 
257 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
258   llvm::Value *ArgValue = CGF.EmitLValue(VE->getSubExpr()).getAddress();
259   llvm::Value *V = Builder.CreateVAArg(ArgValue, CGF.ConvertType(VE->getType()));
260   if (DestPtr)
261     // FIXME: volatility
262     Builder.CreateStore(V, DestPtr);
263 }
264 
265 void AggExprEmitter::EmitNonConstInit(InitListExpr *E) {
266   if (E->hadDesignators()) {
267     CGF.ErrorUnsupported(E, "initializer list with designators");
268     return;
269   }
270 
271   const llvm::PointerType *APType =
272     cast<llvm::PointerType>(DestPtr->getType());
273   const llvm::Type *DestType = APType->getElementType();
274 
275   if (const llvm::ArrayType *AType = dyn_cast<llvm::ArrayType>(DestType)) {
276     unsigned NumInitElements = E->getNumInits();
277 
278     unsigned i;
279     for (i = 0; i != NumInitElements; ++i) {
280       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
281       Expr *Init = E->getInit(i);
282       if (isa<InitListExpr>(Init))
283         CGF.EmitAggExpr(Init, NextVal, VolatileDest);
284       else
285         // FIXME: volatility
286         Builder.CreateStore(CGF.EmitScalarExpr(Init), NextVal);
287     }
288 
289     // Emit remaining default initializers
290     unsigned NumArrayElements = AType->getNumElements();
291     QualType QType = E->getInit(0)->getType();
292     const llvm::Type *EType = AType->getElementType();
293     for (/*Do not initialize i*/; i < NumArrayElements; ++i) {
294       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
295       if (EType->isSingleValueType())
296         // FIXME: volatility
297         Builder.CreateStore(llvm::Constant::getNullValue(EType), NextVal);
298       else
299         CGF.EmitAggregateClear(NextVal, QType);
300     }
301   } else
302     assert(false && "Invalid initializer");
303 }
304 
305 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
306   // FIXME: Are initializers affected by volatile?
307   if (E->getType()->isComplexType()) {
308     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
309   } else if (CGF.hasAggregateLLVMType(E->getType())) {
310     CGF.EmitAnyExpr(E, LV.getAddress(), false);
311   } else {
312     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType());
313   }
314 }
315 
316 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
317   if (!CGF.hasAggregateLLVMType(T)) {
318     // For non-aggregates, we can store zero
319     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
320     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
321   } else {
322     // Otherwise, just memset the whole thing to zero.  This is legal
323     // because in LLVM, all default initializers are guaranteed to have a
324     // bit pattern of all zeros.
325     // There's a potential optimization opportunity in combining
326     // memsets; that would be easy for arrays, but relatively
327     // difficult for structures with the current code.
328     llvm::Value *MemSet = CGF.CGM.getIntrinsic(llvm::Intrinsic::memset_i64);
329     uint64_t Size = CGF.getContext().getTypeSize(T);
330 
331     const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
332     llvm::Value* DestPtr = Builder.CreateBitCast(LV.getAddress(), BP, "tmp");
333     Builder.CreateCall4(MemSet, DestPtr,
334                         llvm::ConstantInt::get(llvm::Type::Int8Ty, 0),
335                         llvm::ConstantInt::get(llvm::Type::Int64Ty, Size/8),
336                         llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
337   }
338 }
339 
340 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
341   if (E->hadDesignators()) {
342     CGF.ErrorUnsupported(E, "initializer list with designators");
343     return;
344   }
345 
346   // FIXME: For constant expressions, call into const expr emitter so
347   // that we can emit a memcpy instead of storing the individual
348   // members.  This is purely for perf; both codepaths lead to
349   // equivalent (although not necessarily identical) code.  It's worth
350   // noting that LLVM keeps on getting smarter, though, so it might
351   // not be worth bothering.
352 
353   // Handle initialization of an array.
354   if (E->getType()->isArrayType()) {
355     const llvm::PointerType *APType =
356       cast<llvm::PointerType>(DestPtr->getType());
357     const llvm::ArrayType *AType =
358       cast<llvm::ArrayType>(APType->getElementType());
359 
360     uint64_t NumInitElements = E->getNumInits();
361 
362     if (E->getNumInits() > 0) {
363       QualType T1 = E->getType();
364       QualType T2 = E->getInit(0)->getType();
365       if (CGF.getContext().getCanonicalType(T1).getUnqualifiedType() ==
366           CGF.getContext().getCanonicalType(T2).getUnqualifiedType()) {
367         EmitAggLoadOfLValue(E->getInit(0));
368         return;
369       }
370     }
371 
372     uint64_t NumArrayElements = AType->getNumElements();
373     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
374     ElementType =CGF.getContext().getAsArrayType(ElementType)->getElementType();
375 
376     unsigned CVRqualifier = ElementType.getCVRQualifiers();
377 
378     for (uint64_t i = 0; i != NumArrayElements; ++i) {
379       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
380       if (i < NumInitElements)
381         EmitInitializationToLValue(E->getInit(i),
382                                    LValue::MakeAddr(NextVal, CVRqualifier));
383       else
384         EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, CVRqualifier),
385                                        ElementType);
386     }
387     return;
388   }
389 
390   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
391 
392   // Do struct initialization; this code just sets each individual member
393   // to the approprate value.  This makes bitfield support automatic;
394   // the disadvantage is that the generated code is more difficult for
395   // the optimizer, especially with bitfields.
396   unsigned NumInitElements = E->getNumInits();
397   RecordDecl *SD = E->getType()->getAsRecordType()->getDecl();
398   unsigned NumMembers = SD->getNumMembers() - SD->hasFlexibleArrayMember();
399   unsigned CurInitVal = 0;
400   bool isUnion = E->getType()->isUnionType();
401 
402   // Here we iterate over the fields; this makes it simpler to both
403   // default-initialize fields and skip over unnamed fields.
404   for (unsigned CurFieldNo = 0; CurFieldNo != NumMembers; ++CurFieldNo) {
405     FieldDecl *CurField = SD->getMember(CurFieldNo);
406     if (CurField->getIdentifier() == 0) {
407       // Initializers can't initialize unnamed fields, e.g. "int : 20;"
408       continue;
409     }
410     // FIXME: volatility
411     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, CurField, isUnion,0);
412     if (CurInitVal < NumInitElements) {
413       // Store the initializer into the field
414       // This will probably have to get a bit smarter when we support
415       // designators in initializers
416       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc);
417     } else {
418       // We're out of initalizers; default-initialize to null
419       EmitNullInitializationToLValue(FieldLoc, CurField->getType());
420     }
421 
422     // Unions only initialize one field.
423     // (things can get weird with designators, but they aren't
424     // supported yet.)
425     if (E->getType()->isUnionType())
426       break;
427   }
428 }
429 
430 //===----------------------------------------------------------------------===//
431 //                        Entry Points into this File
432 //===----------------------------------------------------------------------===//
433 
434 /// EmitAggExpr - Emit the computation of the specified expression of
435 /// aggregate type.  The result is computed into DestPtr.  Note that if
436 /// DestPtr is null, the value of the aggregate expression is not needed.
437 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
438                                   bool VolatileDest) {
439   assert(E && hasAggregateLLVMType(E->getType()) &&
440          "Invalid aggregate expression to emit");
441 
442   AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E));
443 }
444 
445 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
446   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
447 
448   EmitMemSetToZero(DestPtr, Ty);
449 }
450 
451 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
452                                         llvm::Value *SrcPtr, QualType Ty) {
453   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
454 
455   // Aggregate assignment turns into llvm.memmove.
456   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
457   if (DestPtr->getType() != BP)
458     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
459   if (SrcPtr->getType() != BP)
460     SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
461 
462   // Get size and alignment info for this aggregate.
463   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
464 
465   // FIXME: Handle variable sized types.
466   const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
467 
468   Builder.CreateCall4(CGM.getMemMoveFn(),
469                       DestPtr, SrcPtr,
470                       // TypeInfo.first describes size in bits.
471                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
472                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
473                                              TypeInfo.second/8));
474 }
475