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::IRBuilder &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   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
90     Visit(DAE->getExpr());
91   }
92 
93   void EmitInitializationToLValue(Expr *E, LValue Address);
94   void EmitNullInitializationToLValue(LValue Address, QualType T);
95   //  case Expr::ChooseExprClass:
96 
97 };
98 }  // end anonymous namespace.
99 
100 //===----------------------------------------------------------------------===//
101 //                                Utilities
102 //===----------------------------------------------------------------------===//
103 
104 void AggExprEmitter::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
105   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
106 
107   // Aggregate assignment turns into llvm.memset.
108   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
109   if (DestPtr->getType() != BP)
110     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
111 
112   // Get size and alignment info for this aggregate.
113   std::pair<uint64_t, unsigned> TypeInfo = CGF.getContext().getTypeInfo(Ty);
114 
115   // FIXME: Handle variable sized types.
116   const llvm::Type *IntPtr = llvm::IntegerType::get(CGF.LLVMPointerWidth);
117 
118   llvm::Value *MemSetOps[4] = {
119     DestPtr,
120     llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
121     // TypeInfo.first describes size in bits.
122     llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
123     llvm::ConstantInt::get(llvm::Type::Int32Ty, TypeInfo.second/8)
124   };
125 
126   Builder.CreateCall(CGF.CGM.getMemSetFn(), MemSetOps, MemSetOps+4);
127 }
128 
129 void AggExprEmitter::EmitAggregateCopy(llvm::Value *DestPtr,
130                                        llvm::Value *SrcPtr, QualType Ty) {
131   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
132 
133   // Aggregate assignment turns into llvm.memcpy.
134   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
135   if (DestPtr->getType() != BP)
136     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
137   if (SrcPtr->getType() != BP)
138     SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
139 
140   // Get size and alignment info for this aggregate.
141   std::pair<uint64_t, unsigned> TypeInfo = CGF.getContext().getTypeInfo(Ty);
142 
143   // FIXME: Handle variable sized types.
144   const llvm::Type *IntPtr = llvm::IntegerType::get(CGF.LLVMPointerWidth);
145 
146   llvm::Value *MemCpyOps[4] = {
147     DestPtr, SrcPtr,
148     // TypeInfo.first describes size in bits.
149     llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
150     llvm::ConstantInt::get(llvm::Type::Int32Ty, TypeInfo.second/8)
151   };
152 
153   Builder.CreateCall(CGF.CGM.getMemCpyFn(), MemCpyOps, MemCpyOps+4);
154 }
155 
156 
157 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
158 /// represents a value lvalue, this method emits the address of the lvalue,
159 /// then loads the result into DestPtr.
160 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
161   LValue LV = CGF.EmitLValue(E);
162   assert(LV.isSimple() && "Can't have aggregate bitfield, vector, etc");
163   llvm::Value *SrcPtr = LV.getAddress();
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   EmitAggregateCopy(DestPtr, SrcPtr, E->getType());
171 }
172 
173 //===----------------------------------------------------------------------===//
174 //                            Visitor Methods
175 //===----------------------------------------------------------------------===//
176 
177 void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E)
178 {
179   QualType STy = E->getSubExpr()->getType().getCanonicalType();
180   QualType Ty = E->getType().getCanonicalType();
181 
182   assert(CGF.getContext().typesAreCompatible(
183              STy.getUnqualifiedType(), Ty.getUnqualifiedType())
184          && "Implicit cast types must be compatible");
185 
186   Visit(E->getSubExpr());
187 }
188 
189 void AggExprEmitter::VisitCallExpr(const CallExpr *E)
190 {
191   RValue RV = CGF.EmitCallExpr(E);
192   assert(RV.isAggregate() && "Return value must be aggregate value!");
193 
194   // If the result is ignored, don't copy from the value.
195   if (DestPtr == 0)
196     // FIXME: If the source is volatile, we must read from it.
197     return;
198 
199   EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
200 }
201 
202 void AggExprEmitter::VisitOverloadExpr(const OverloadExpr *E)
203 {
204   RValue RV = CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
205                                E->getNumArgs(CGF.getContext()));
206   assert(RV.isAggregate() && "Return value must be aggregate value!");
207 
208   // If the result is ignored, don't copy from the value.
209   if (DestPtr == 0)
210     // FIXME: If the source is volatile, we must read from it.
211     return;
212 
213   EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
214 }
215 
216 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
217   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
218 }
219 
220 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
221   CGF.WarnUnsupported(E, "aggregate binary expression");
222 }
223 
224 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
225   // For an assignment to work, the value on the right has
226   // to be compatible with the value on the left.
227   assert(CGF.getContext().typesAreCompatible(
228              E->getLHS()->getType().getUnqualifiedType(),
229              E->getRHS()->getType().getUnqualifiedType())
230          && "Invalid assignment");
231   LValue LHS = CGF.EmitLValue(E->getLHS());
232 
233   // Codegen the RHS so that it stores directly into the LHS.
234   CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), false /*FIXME: VOLATILE LHS*/);
235 
236   if (DestPtr == 0)
237     return;
238 
239   // If the result of the assignment is used, copy the RHS there also.
240   EmitAggregateCopy(DestPtr, LHS.getAddress(), E->getType());
241 }
242 
243 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
244   llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?");
245   llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:");
246   llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont");
247 
248   llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
249   Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
250 
251   CGF.EmitBlock(LHSBlock);
252 
253   // Handle the GNU extension for missing LHS.
254   assert(E->getLHS() && "Must have LHS for aggregate value");
255 
256   Visit(E->getLHS());
257   Builder.CreateBr(ContBlock);
258   LHSBlock = Builder.GetInsertBlock();
259 
260   CGF.EmitBlock(RHSBlock);
261 
262   Visit(E->getRHS());
263   Builder.CreateBr(ContBlock);
264   RHSBlock = Builder.GetInsertBlock();
265 
266   CGF.EmitBlock(ContBlock);
267 }
268 
269 void AggExprEmitter::EmitNonConstInit(InitListExpr *E) {
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         Builder.CreateStore(CGF.EmitScalarExpr(Init), NextVal);
286     }
287 
288     // Emit remaining default initializers
289     unsigned NumArrayElements = AType->getNumElements();
290     QualType QType = E->getInit(0)->getType();
291     const llvm::Type *EType = AType->getElementType();
292     for (/*Do not initialize i*/; i < NumArrayElements; ++i) {
293       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
294       if (EType->isFirstClassType())
295         Builder.CreateStore(llvm::Constant::getNullValue(EType), NextVal);
296       else
297         EmitAggregateClear(NextVal, QType);
298     }
299   } else
300     assert(false && "Invalid initializer");
301 }
302 
303 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
304   // FIXME: Are initializers affected by volatile?
305   if (E->getType()->isComplexType()) {
306     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
307     return;
308   }
309   RValue RV = CGF.EmitAnyExpr(E, LV.getAddress(), false);
310   if (CGF.hasAggregateLLVMType(E->getType()))
311     return;
312   CGF.EmitStoreThroughLValue(RV, LV, E->getType());
313 }
314 
315 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
316   if (!CGF.hasAggregateLLVMType(T)) {
317     // For non-aggregates, we can store zero
318     const llvm::Type *T =
319        cast<llvm::PointerType>(LV.getAddress()->getType())->getElementType();
320     Builder.CreateStore(llvm::Constant::getNullValue(T), LV.getAddress());
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 
341 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
342   if (E->isConstantExpr(CGF.getContext(), 0)) {
343     // FIXME: call into const expr emitter so that we can emit
344     // a memcpy instead of storing the individual members.
345     // This is purely for perf; both codepaths lead to equivalent
346     // (although not necessarily identical) code.
347     // It's worth noting that LLVM keeps on getting smarter, though,
348     // so it might not be worth bothering.
349   }
350 
351   // Handle initialization of an array.
352   if (E->getType()->isArrayType()) {
353     const llvm::PointerType *APType =
354       cast<llvm::PointerType>(DestPtr->getType());
355     const llvm::ArrayType *AType =
356       cast<llvm::ArrayType>(APType->getElementType());
357 
358     uint64_t NumInitElements = E->getNumInits();
359     uint64_t NumArrayElements = AType->getNumElements();
360     QualType ElementType = E->getType()->getAsArrayType()->getElementType();
361 
362     for (uint64_t i = 0; i != NumArrayElements; ++i) {
363       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
364       if (i < NumInitElements)
365         EmitInitializationToLValue(E->getInit(i), LValue::MakeAddr(NextVal));
366       else
367         EmitNullInitializationToLValue(LValue::MakeAddr(NextVal),
368                                        ElementType);
369     }
370     return;
371   }
372 
373   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
374 
375   // Do struct initialization; this code just sets each individual member
376   // to the approprate value.  This makes bitfield support automatic;
377   // the disadvantage is that the generated code is more difficult for
378   // the optimizer, especially with bitfields.
379   unsigned NumInitElements = E->getNumInits();
380   RecordDecl *SD = E->getType()->getAsRecordType()->getDecl();
381   unsigned NumMembers = SD->getNumMembers() - SD->hasFlexibleArrayMember();
382   unsigned CurInitVal = 0;
383   bool isUnion = E->getType()->isUnionType();
384 
385   // Here we iterate over the fields; this makes it simpler to both
386   // default-initialize fields and skip over unnamed fields.
387   for (unsigned CurFieldNo = 0; CurFieldNo != NumMembers; ++CurFieldNo) {
388     if (CurInitVal >= NumInitElements) {
389       // No more initializers; we're done.
390       break;
391     }
392 
393     FieldDecl *CurField = SD->getMember(CurFieldNo);
394     if (CurField->getIdentifier() == 0) {
395       // Initializers can't initialize unnamed fields, e.g. "int : 20;"
396       continue;
397     }
398     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, CurField, isUnion);
399     if (CurInitVal < NumInitElements) {
400       // Store the initializer into the field
401       // This will probably have to get a bit smarter when we support
402       // designators in initializers
403       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc);
404     } else {
405       // We're out of initalizers; default-initialize to null
406       EmitNullInitializationToLValue(FieldLoc, CurField->getType());
407     }
408 
409     // Unions only initialize one field.
410     // (things can get weird with designators, but they aren't
411     // supported yet.)
412     if (E->getType()->isUnionType())
413       break;
414   }
415 }
416 
417 //===----------------------------------------------------------------------===//
418 //                        Entry Points into this File
419 //===----------------------------------------------------------------------===//
420 
421 /// EmitAggExpr - Emit the computation of the specified expression of
422 /// aggregate type.  The result is computed into DestPtr.  Note that if
423 /// DestPtr is null, the value of the aggregate expression is not needed.
424 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
425                                   bool VolatileDest) {
426   assert(E && hasAggregateLLVMType(E->getType()) &&
427          "Invalid aggregate expression to emit");
428 
429   AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E));
430 }
431