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   void VisitObjCKVCRefExpr(ObjCKVCRefExpr *E);
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 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
111 /// represents a value lvalue, this method emits the address of the lvalue,
112 /// then loads the result into DestPtr.
113 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
114   LValue LV = CGF.EmitLValue(E);
115   assert(LV.isSimple() && "Can't have aggregate bitfield, vector, etc");
116   llvm::Value *SrcPtr = LV.getAddress();
117 
118   // If the result is ignored, don't copy from the value.
119   if (DestPtr == 0)
120     // FIXME: If the source is volatile, we must read from it.
121     return;
122 
123   CGF.EmitAggregateCopy(DestPtr, SrcPtr, E->getType());
124 }
125 
126 //===----------------------------------------------------------------------===//
127 //                            Visitor Methods
128 //===----------------------------------------------------------------------===//
129 
130 void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
131   assert(CGF.getContext().typesAreCompatible(
132                           E->getSubExpr()->getType().getUnqualifiedType(),
133                           E->getType().getUnqualifiedType()) &&
134          "Implicit cast types must be compatible");
135   Visit(E->getSubExpr());
136 }
137 
138 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
139   RValue RV = CGF.EmitCallExpr(E);
140   assert(RV.isAggregate() && "Return value must be aggregate value!");
141 
142   // If the result is ignored, don't copy from the value.
143   if (DestPtr == 0)
144     // FIXME: If the source is volatile, we must read from it.
145     return;
146 
147   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
148 }
149 
150 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
151   RValue RV = CGF.EmitObjCMessageExpr(E);
152   assert(RV.isAggregate() && "Return value must be aggregate value!");
153 
154   // If the result is ignored, don't copy from the value.
155   if (DestPtr == 0)
156     // FIXME: If the source is volatile, we must read from it.
157     return;
158 
159   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
160 }
161 
162 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
163   RValue RV = CGF.EmitObjCPropertyGet(E);
164   assert(RV.isAggregate() && "Return value must be aggregate value!");
165 
166   // If the result is ignored, don't copy from the value.
167   if (DestPtr == 0)
168     // FIXME: If the source is volatile, we must read from it.
169     return;
170 
171   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
172 }
173 
174 void AggExprEmitter::VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
175   RValue RV = CGF.EmitObjCPropertyGet(E);
176   assert(RV.isAggregate() && "Return value must be aggregate value!");
177 
178   // If the result is ignored, don't copy from the value.
179   if (DestPtr == 0)
180     // FIXME: If the source is volatile, we must read from it.
181     return;
182 
183   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
184 }
185 
186 void AggExprEmitter::VisitOverloadExpr(const OverloadExpr *E) {
187   RValue RV = CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
188                                E->arg_end(CGF.getContext()));
189 
190   assert(RV.isAggregate() && "Return value must be aggregate value!");
191 
192   // If the result is ignored, don't copy from the value.
193   if (DestPtr == 0)
194     // FIXME: If the source is volatile, we must read from it.
195     return;
196 
197   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
198 }
199 
200 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
201   CGF.EmitAnyExpr(E->getLHS());
202   CGF.EmitAggExpr(E->getRHS(), DestPtr, false);
203 }
204 
205 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
206   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
207 }
208 
209 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
210   CGF.ErrorUnsupported(E, "aggregate binary expression");
211 }
212 
213 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
214   // For an assignment to work, the value on the right has
215   // to be compatible with the value on the left.
216   assert(CGF.getContext().typesAreCompatible(
217              E->getLHS()->getType().getUnqualifiedType(),
218              E->getRHS()->getType().getUnqualifiedType())
219          && "Invalid assignment");
220   LValue LHS = CGF.EmitLValue(E->getLHS());
221 
222   // We have to special case property setters, otherwise we must have
223   // a simple lvalue (no aggregates inside vectors, bitfields).
224   if (LHS.isPropertyRef()) {
225     // FIXME: Volatility?
226     llvm::Value *AggLoc = DestPtr;
227     if (!AggLoc)
228       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
229     CGF.EmitAggExpr(E->getRHS(), AggLoc, false);
230     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
231                             RValue::getAggregate(AggLoc));
232   }
233   else if (LHS.isKVCRef()) {
234     // FIXME: Volatility?
235     llvm::Value *AggLoc = DestPtr;
236     if (!AggLoc)
237       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
238     CGF.EmitAggExpr(E->getRHS(), AggLoc, false);
239     CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
240                             RValue::getAggregate(AggLoc));
241   } else {
242     // Codegen the RHS so that it stores directly into the LHS.
243     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), false /*FIXME: VOLATILE LHS*/);
244 
245     if (DestPtr == 0)
246       return;
247 
248     // If the result of the assignment is used, copy the RHS there also.
249     CGF.EmitAggregateCopy(DestPtr, LHS.getAddress(), E->getType());
250   }
251 }
252 
253 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
254   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
255   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
256   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
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   CGF.EmitBranch(ContBlock);
268 
269   CGF.EmitBlock(RHSBlock);
270 
271   Visit(E->getRHS());
272   CGF.EmitBranch(ContBlock);
273 
274   CGF.EmitBlock(ContBlock);
275 }
276 
277 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
278   llvm::Value *ArgValue = CGF.EmitLValue(VE->getSubExpr()).getAddress();
279   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
280 
281   if (!ArgPtr)
282     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
283 
284   if (DestPtr)
285     // FIXME: volatility
286     CGF.EmitAggregateCopy(DestPtr, ArgPtr, VE->getType());
287 }
288 
289 void AggExprEmitter::EmitNonConstInit(InitListExpr *E) {
290   if (E->hadDesignators()) {
291     CGF.ErrorUnsupported(E, "initializer list with designators");
292     return;
293   }
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         CGF.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     const llvm::Type *SizeTy = llvm::Type::Int64Ty;
353     llvm::Value *MemSet = CGF.CGM.getIntrinsic(llvm::Intrinsic::memset,
354                                                &SizeTy, 1);
355     uint64_t Size = CGF.getContext().getTypeSize(T);
356 
357     const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
358     llvm::Value* DestPtr = Builder.CreateBitCast(LV.getAddress(), BP, "tmp");
359     Builder.CreateCall4(MemSet, DestPtr,
360                         llvm::ConstantInt::get(llvm::Type::Int8Ty, 0),
361                         llvm::ConstantInt::get(SizeTy, Size/8),
362                         llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
363   }
364 }
365 
366 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
367   if (E->hadDesignators()) {
368     CGF.ErrorUnsupported(E, "initializer list with designators");
369     return;
370   }
371 
372 #if 0
373   // FIXME: Disabled while we figure out what to do about
374   // test/CodeGen/bitfield.c
375   //
376   // If we can, prefer a copy from a global; this is a lot less
377   // code for long globals, and it's easier for the current optimizers
378   // to analyze.
379   // FIXME: Should we really be doing this? Should we try to avoid
380   // cases where we emit a global with a lot of zeros?  Should
381   // we try to avoid short globals?
382   if (E->isConstantExpr(CGF.getContext(), 0)) {
383     llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, &CGF);
384     llvm::GlobalVariable* GV =
385     new llvm::GlobalVariable(C->getType(), true,
386                              llvm::GlobalValue::InternalLinkage,
387                              C, "", &CGF.CGM.getModule(), 0);
388     CGF.EmitAggregateCopy(DestPtr, GV, E->getType());
389     return;
390   }
391 #endif
392   // Handle initialization of an array.
393   if (E->getType()->isArrayType()) {
394     const llvm::PointerType *APType =
395       cast<llvm::PointerType>(DestPtr->getType());
396     const llvm::ArrayType *AType =
397       cast<llvm::ArrayType>(APType->getElementType());
398 
399     uint64_t NumInitElements = E->getNumInits();
400 
401     if (E->getNumInits() > 0) {
402       QualType T1 = E->getType();
403       QualType T2 = E->getInit(0)->getType();
404       if (CGF.getContext().getCanonicalType(T1).getUnqualifiedType() ==
405           CGF.getContext().getCanonicalType(T2).getUnqualifiedType()) {
406         EmitAggLoadOfLValue(E->getInit(0));
407         return;
408       }
409     }
410 
411     uint64_t NumArrayElements = AType->getNumElements();
412     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
413     ElementType =CGF.getContext().getAsArrayType(ElementType)->getElementType();
414 
415     unsigned CVRqualifier = ElementType.getCVRQualifiers();
416 
417     for (uint64_t i = 0; i != NumArrayElements; ++i) {
418       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
419       if (i < NumInitElements)
420         EmitInitializationToLValue(E->getInit(i),
421                                    LValue::MakeAddr(NextVal, CVRqualifier));
422       else
423         EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, CVRqualifier),
424                                        ElementType);
425     }
426     return;
427   }
428 
429   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
430 
431   // Do struct initialization; this code just sets each individual member
432   // to the approprate value.  This makes bitfield support automatic;
433   // the disadvantage is that the generated code is more difficult for
434   // the optimizer, especially with bitfields.
435   unsigned NumInitElements = E->getNumInits();
436   RecordDecl *SD = E->getType()->getAsRecordType()->getDecl();
437   unsigned CurInitVal = 0;
438   bool isUnion = E->getType()->isUnionType();
439 
440   // Here we iterate over the fields; this makes it simpler to both
441   // default-initialize fields and skip over unnamed fields.
442   for (RecordDecl::field_iterator Field = SD->field_begin(),
443                                FieldEnd = SD->field_end();
444        Field != FieldEnd; ++Field) {
445     // We're done once we hit the flexible array member
446     if (Field->getType()->isIncompleteArrayType())
447       break;
448 
449     if (Field->getIdentifier() == 0) {
450       // Initializers can't initialize unnamed fields, e.g. "int : 20;"
451       continue;
452     }
453     // FIXME: volatility
454     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, isUnion,0);
455     if (CurInitVal < NumInitElements) {
456       // Store the initializer into the field
457       // This will probably have to get a bit smarter when we support
458       // designators in initializers
459       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc);
460     } else {
461       // We're out of initalizers; default-initialize to null
462       EmitNullInitializationToLValue(FieldLoc, Field->getType());
463     }
464 
465     // Unions only initialize one field.
466     // (things can get weird with designators, but they aren't
467     // supported yet.)
468     if (E->getType()->isUnionType())
469       break;
470   }
471 }
472 
473 //===----------------------------------------------------------------------===//
474 //                        Entry Points into this File
475 //===----------------------------------------------------------------------===//
476 
477 /// EmitAggExpr - Emit the computation of the specified expression of
478 /// aggregate type.  The result is computed into DestPtr.  Note that if
479 /// DestPtr is null, the value of the aggregate expression is not needed.
480 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
481                                   bool VolatileDest) {
482   assert(E && hasAggregateLLVMType(E->getType()) &&
483          "Invalid aggregate expression to emit");
484 
485   AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E));
486 }
487 
488 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
489   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
490 
491   EmitMemSetToZero(DestPtr, Ty);
492 }
493 
494 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
495                                         llvm::Value *SrcPtr, QualType Ty) {
496   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
497 
498   // Aggregate assignment turns into llvm.memmove.
499   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
500   if (DestPtr->getType() != BP)
501     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
502   if (SrcPtr->getType() != BP)
503     SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
504 
505   // Get size and alignment info for this aggregate.
506   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
507 
508   // FIXME: Handle variable sized types.
509   const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
510 
511   Builder.CreateCall4(CGM.getMemMoveFn(),
512                       DestPtr, SrcPtr,
513                       // TypeInfo.first describes size in bits.
514                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
515                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
516                                              TypeInfo.second/8));
517 }
518