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/DeclCXX.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Intrinsics.h"
24 using namespace clang;
25 using namespace CodeGen;
26 
27 //===----------------------------------------------------------------------===//
28 //                        Aggregate Expression Emitter
29 //===----------------------------------------------------------------------===//
30 
31 namespace  {
32 class VISIBILITY_HIDDEN AggExprEmitter : public StmtVisitor<AggExprEmitter> {
33   CodeGenFunction &CGF;
34   CGBuilderTy &Builder;
35   llvm::Value *DestPtr;
36   bool VolatileDest;
37   bool IgnoreResult;
38 
39 public:
40   AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v,
41                  bool ignore)
42     : CGF(cgf), Builder(CGF.Builder),
43       DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore) {
44   }
45 
46   //===--------------------------------------------------------------------===//
47   //                               Utilities
48   //===--------------------------------------------------------------------===//
49 
50   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
51   /// represents a value lvalue, this method emits the address of the lvalue,
52   /// then loads the result into DestPtr.
53   void EmitAggLoadOfLValue(const Expr *E);
54 
55   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
56   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
57   void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
58 
59   //===--------------------------------------------------------------------===//
60   //                            Visitor Methods
61   //===--------------------------------------------------------------------===//
62 
63   void VisitStmt(Stmt *S) {
64     CGF.ErrorUnsupported(S, "aggregate expression");
65   }
66   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
67   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
68 
69   // l-values.
70   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
71   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
72   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
73   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
74   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
75     EmitAggLoadOfLValue(E);
76   }
77   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
78     EmitAggLoadOfLValue(E);
79   }
80   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
81     EmitAggLoadOfLValue(E);
82   }
83   void VisitPredefinedExpr(const PredefinedExpr *E) {
84     EmitAggLoadOfLValue(E);
85   }
86 
87   // Operators.
88   void VisitCStyleCastExpr(CStyleCastExpr *E);
89   void VisitImplicitCastExpr(ImplicitCastExpr *E);
90   void VisitCallExpr(const CallExpr *E);
91   void VisitStmtExpr(const StmtExpr *E);
92   void VisitBinaryOperator(const BinaryOperator *BO);
93   void VisitBinAssign(const BinaryOperator *E);
94   void VisitBinComma(const BinaryOperator *E);
95 
96   void VisitObjCMessageExpr(ObjCMessageExpr *E);
97   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
98     EmitAggLoadOfLValue(E);
99   }
100   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
101   void VisitObjCKVCRefExpr(ObjCKVCRefExpr *E);
102 
103   void VisitConditionalOperator(const ConditionalOperator *CO);
104   void VisitInitListExpr(InitListExpr *E);
105   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
106     Visit(DAE->getExpr());
107   }
108   void VisitCXXConstructExpr(const CXXConstructExpr *E);
109   void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E);
110 
111   void VisitVAArgExpr(VAArgExpr *E);
112 
113   void EmitInitializationToLValue(Expr *E, LValue Address);
114   void EmitNullInitializationToLValue(LValue Address, QualType T);
115   //  case Expr::ChooseExprClass:
116 
117 };
118 }  // end anonymous namespace.
119 
120 //===----------------------------------------------------------------------===//
121 //                                Utilities
122 //===----------------------------------------------------------------------===//
123 
124 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
125 /// represents a value lvalue, this method emits the address of the lvalue,
126 /// then loads the result into DestPtr.
127 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
128   LValue LV = CGF.EmitLValue(E);
129   EmitFinalDestCopy(E, LV);
130 }
131 
132 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
133 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
134   assert(Src.isAggregate() && "value must be aggregate value!");
135 
136   // If the result is ignored, don't copy from the value.
137   if (DestPtr == 0) {
138     if (!Src.isVolatileQualified() || (IgnoreResult && Ignore))
139       return;
140     // If the source is volatile, we must read from it; to do that, we need
141     // some place to put it.
142     DestPtr = CGF.CreateTempAlloca(CGF.ConvertType(E->getType()), "agg.tmp");
143   }
144 
145   // If the result of the assignment is used, copy the LHS there also.
146   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
147   // from the source as well, as we can't eliminate it if either operand
148   // is volatile, unless copy has volatile for both source and destination..
149   CGF.EmitAggregateCopy(DestPtr, Src.getAggregateAddr(), E->getType(),
150                         VolatileDest|Src.isVolatileQualified());
151 }
152 
153 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
154 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
155   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
156 
157   EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
158                                             Src.isVolatileQualified()),
159                     Ignore);
160 }
161 
162 //===----------------------------------------------------------------------===//
163 //                            Visitor Methods
164 //===----------------------------------------------------------------------===//
165 
166 void AggExprEmitter::VisitCStyleCastExpr(CStyleCastExpr *E) {
167   // GCC union extension
168   if (E->getType()->isUnionType()) {
169     RecordDecl *SD = E->getType()->getAsRecordType()->getDecl();
170     LValue FieldLoc = CGF.EmitLValueForField(DestPtr,
171                                              *SD->field_begin(CGF.getContext()),
172                                              true, 0);
173     EmitInitializationToLValue(E->getSubExpr(), FieldLoc);
174     return;
175   }
176 
177   Visit(E->getSubExpr());
178 }
179 
180 void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
181   assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
182                                                  E->getType()) &&
183          "Implicit cast types must be compatible");
184   Visit(E->getSubExpr());
185 }
186 
187 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
188   if (E->getCallReturnType()->isReferenceType()) {
189     EmitAggLoadOfLValue(E);
190     return;
191   }
192 
193   RValue RV = CGF.EmitCallExpr(E);
194   EmitFinalDestCopy(E, RV);
195 }
196 
197 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
198   RValue RV = CGF.EmitObjCMessageExpr(E);
199   EmitFinalDestCopy(E, RV);
200 }
201 
202 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
203   RValue RV = CGF.EmitObjCPropertyGet(E);
204   EmitFinalDestCopy(E, RV);
205 }
206 
207 void AggExprEmitter::VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
208   RValue RV = CGF.EmitObjCPropertyGet(E);
209   EmitFinalDestCopy(E, RV);
210 }
211 
212 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
213   CGF.EmitAnyExpr(E->getLHS(), 0, false, true);
214   CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest);
215 }
216 
217 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
218   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
219 }
220 
221 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
222   CGF.ErrorUnsupported(E, "aggregate binary expression");
223 }
224 
225 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
226   // For an assignment to work, the value on the right has
227   // to be compatible with the value on the left.
228   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
229                                                  E->getRHS()->getType())
230          && "Invalid assignment");
231   LValue LHS = CGF.EmitLValue(E->getLHS());
232 
233   // We have to special case property setters, otherwise we must have
234   // a simple lvalue (no aggregates inside vectors, bitfields).
235   if (LHS.isPropertyRef()) {
236     llvm::Value *AggLoc = DestPtr;
237     if (!AggLoc)
238       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
239     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
240     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
241                             RValue::getAggregate(AggLoc, VolatileDest));
242   }
243   else if (LHS.isKVCRef()) {
244     llvm::Value *AggLoc = DestPtr;
245     if (!AggLoc)
246       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
247     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
248     CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
249                             RValue::getAggregate(AggLoc, VolatileDest));
250   } else {
251     // Codegen the RHS so that it stores directly into the LHS.
252     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified());
253     EmitFinalDestCopy(E, LHS, true);
254   }
255 }
256 
257 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
258   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
259   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
260   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
261 
262   llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
263   Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
264 
265   CGF.EmitBlock(LHSBlock);
266 
267   // Handle the GNU extension for missing LHS.
268   assert(E->getLHS() && "Must have LHS for aggregate value");
269 
270   Visit(E->getLHS());
271   CGF.EmitBranch(ContBlock);
272 
273   CGF.EmitBlock(RHSBlock);
274 
275   Visit(E->getRHS());
276   CGF.EmitBranch(ContBlock);
277 
278   CGF.EmitBlock(ContBlock);
279 }
280 
281 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
282   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
283   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
284 
285   if (!ArgPtr) {
286     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
287     return;
288   }
289 
290   EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, 0));
291 }
292 
293 void
294 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
295   llvm::Value *V = DestPtr;
296 
297   if (!V) {
298     assert(isa<CXXTempVarDecl>(E->getVarDecl()) &&
299            "Must have a temp var decl when there's no destination!");
300 
301     V = CGF.CreateTempAlloca(CGF.ConvertType(E->getVarDecl()->getType()),
302                              "tmpvar");
303   }
304 
305   CGF.EmitCXXConstructExpr(V, E);
306 }
307 
308 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
309   // FIXME: Do something with the temporaries!
310   Visit(E->getSubExpr());
311 }
312 
313 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
314   // FIXME: Ignore result?
315   // FIXME: Are initializers affected by volatile?
316   if (isa<ImplicitValueInitExpr>(E)) {
317     EmitNullInitializationToLValue(LV, E->getType());
318   } else if (E->getType()->isComplexType()) {
319     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
320   } else if (CGF.hasAggregateLLVMType(E->getType())) {
321     CGF.EmitAnyExpr(E, LV.getAddress(), false);
322   } else {
323     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType());
324   }
325 }
326 
327 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
328   if (!CGF.hasAggregateLLVMType(T)) {
329     // For non-aggregates, we can store zero
330     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
331     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
332   } else {
333     // Otherwise, just memset the whole thing to zero.  This is legal
334     // because in LLVM, all default initializers are guaranteed to have a
335     // bit pattern of all zeros.
336     // FIXME: That isn't true for member pointers!
337     // There's a potential optimization opportunity in combining
338     // memsets; that would be easy for arrays, but relatively
339     // difficult for structures with the current code.
340     CGF.EmitMemSetToZero(LV.getAddress(), T);
341   }
342 }
343 
344 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
345 #if 0
346   // FIXME: Disabled while we figure out what to do about
347   // test/CodeGen/bitfield.c
348   //
349   // If we can, prefer a copy from a global; this is a lot less code for long
350   // globals, and it's easier for the current optimizers to analyze.
351   // FIXME: Should we really be doing this? Should we try to avoid cases where
352   // we emit a global with a lot of zeros?  Should we try to avoid short
353   // globals?
354   if (E->isConstantInitializer(CGF.getContext(), 0)) {
355     llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, &CGF);
356     llvm::GlobalVariable* GV =
357     new llvm::GlobalVariable(C->getType(), true,
358                              llvm::GlobalValue::InternalLinkage,
359                              C, "", &CGF.CGM.getModule(), 0);
360     EmitFinalDestCopy(E, LValue::MakeAddr(GV, 0));
361     return;
362   }
363 #endif
364   if (E->hadArrayRangeDesignator()) {
365     CGF.ErrorUnsupported(E, "GNU array range designator extension");
366   }
367 
368   // Handle initialization of an array.
369   if (E->getType()->isArrayType()) {
370     const llvm::PointerType *APType =
371       cast<llvm::PointerType>(DestPtr->getType());
372     const llvm::ArrayType *AType =
373       cast<llvm::ArrayType>(APType->getElementType());
374 
375     uint64_t NumInitElements = E->getNumInits();
376 
377     if (E->getNumInits() > 0) {
378       QualType T1 = E->getType();
379       QualType T2 = E->getInit(0)->getType();
380       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
381         EmitAggLoadOfLValue(E->getInit(0));
382         return;
383       }
384     }
385 
386     uint64_t NumArrayElements = AType->getNumElements();
387     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
388     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
389 
390     unsigned CVRqualifier = ElementType.getCVRQualifiers();
391 
392     for (uint64_t i = 0; i != NumArrayElements; ++i) {
393       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
394       if (i < NumInitElements)
395         EmitInitializationToLValue(E->getInit(i),
396                                    LValue::MakeAddr(NextVal, CVRqualifier));
397       else
398         EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, CVRqualifier),
399                                        ElementType);
400     }
401     return;
402   }
403 
404   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
405 
406   // Do struct initialization; this code just sets each individual member
407   // to the approprate value.  This makes bitfield support automatic;
408   // the disadvantage is that the generated code is more difficult for
409   // the optimizer, especially with bitfields.
410   unsigned NumInitElements = E->getNumInits();
411   RecordDecl *SD = E->getType()->getAsRecordType()->getDecl();
412   unsigned CurInitVal = 0;
413 
414   if (E->getType()->isUnionType()) {
415     // Only initialize one field of a union. The field itself is
416     // specified by the initializer list.
417     if (!E->getInitializedFieldInUnion()) {
418       // Empty union; we have nothing to do.
419 
420 #ifndef NDEBUG
421       // Make sure that it's really an empty and not a failure of
422       // semantic analysis.
423       for (RecordDecl::field_iterator Field = SD->field_begin(CGF.getContext()),
424                                    FieldEnd = SD->field_end(CGF.getContext());
425            Field != FieldEnd; ++Field)
426         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
427 #endif
428       return;
429     }
430 
431     // FIXME: volatility
432     FieldDecl *Field = E->getInitializedFieldInUnion();
433     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, Field, true, 0);
434 
435     if (NumInitElements) {
436       // Store the initializer into the field
437       EmitInitializationToLValue(E->getInit(0), FieldLoc);
438     } else {
439       // Default-initialize to null
440       EmitNullInitializationToLValue(FieldLoc, Field->getType());
441     }
442 
443     return;
444   }
445 
446   // Here we iterate over the fields; this makes it simpler to both
447   // default-initialize fields and skip over unnamed fields.
448   for (RecordDecl::field_iterator Field = SD->field_begin(CGF.getContext()),
449                                FieldEnd = SD->field_end(CGF.getContext());
450        Field != FieldEnd; ++Field) {
451     // We're done once we hit the flexible array member
452     if (Field->getType()->isIncompleteArrayType())
453       break;
454 
455     if (Field->isUnnamedBitfield())
456       continue;
457 
458     // FIXME: volatility
459     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, false, 0);
460     // We never generate write-barries for initialized fields.
461     LValue::SetObjCNonGC(FieldLoc, true);
462     if (CurInitVal < NumInitElements) {
463       // Store the initializer into the field
464       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc);
465     } else {
466       // We're out of initalizers; default-initialize to null
467       EmitNullInitializationToLValue(FieldLoc, Field->getType());
468     }
469   }
470 }
471 
472 //===----------------------------------------------------------------------===//
473 //                        Entry Points into this File
474 //===----------------------------------------------------------------------===//
475 
476 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
477 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
478 /// the value of the aggregate expression is not needed.  If VolatileDest is
479 /// true, DestPtr cannot be 0.
480 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
481                                   bool VolatileDest, bool IgnoreResult) {
482   assert(E && hasAggregateLLVMType(E->getType()) &&
483          "Invalid aggregate expression to emit");
484   assert ((DestPtr != 0 || VolatileDest == false)
485           && "volatile aggregate can't be 0");
486 
487   AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult)
488     .Visit(const_cast<Expr*>(E));
489 }
490 
491 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
492   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
493 
494   EmitMemSetToZero(DestPtr, Ty);
495 }
496 
497 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
498                                         llvm::Value *SrcPtr, QualType Ty,
499                                         bool isVolatile) {
500   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
501 
502   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
503   // C99 6.5.16.1p3, which states "If the value being stored in an object is
504   // read from another object that overlaps in anyway the storage of the first
505   // object, then the overlap shall be exact and the two objects shall have
506   // qualified or unqualified versions of a compatible type."
507   //
508   // memcpy is not defined if the source and destination pointers are exactly
509   // equal, but other compilers do this optimization, and almost every memcpy
510   // implementation handles this case safely.  If there is a libc that does not
511   // safely handle this, we can add a target hook.
512   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
513   if (DestPtr->getType() != BP)
514     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
515   if (SrcPtr->getType() != BP)
516     SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
517 
518   // Get size and alignment info for this aggregate.
519   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
520 
521   // FIXME: Handle variable sized types.
522   const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
523 
524   // FIXME: If we have a volatile struct, the optimizer can remove what might
525   // appear to be `extra' memory ops:
526   //
527   // volatile struct { int i; } a, b;
528   //
529   // int main() {
530   //   a = b;
531   //   a = b;
532   // }
533   //
534   // we need to use a differnt call here.  We use isVolatile to indicate when
535   // either the source or the destination is volatile.
536   Builder.CreateCall4(CGM.getMemCpyFn(),
537                       DestPtr, SrcPtr,
538                       // TypeInfo.first describes size in bits.
539                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
540                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
541                                              TypeInfo.second/8));
542 }
543