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