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