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