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