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