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