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     // There's a potential optimization opportunity in combining
316     // memsets; that would be easy for arrays, but relatively
317     // difficult for structures with the current code.
318     CGF.EmitMemSetToZero(LV.getAddress(), T);
319   }
320 }
321 
322 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
323 #if 0
324   // FIXME: Disabled while we figure out what to do about
325   // test/CodeGen/bitfield.c
326   //
327   // If we can, prefer a copy from a global; this is a lot less
328   // code for long globals, and it's easier for the current optimizers
329   // to analyze.
330   // FIXME: Should we really be doing this? Should we try to avoid
331   // cases where we emit a global with a lot of zeros?  Should
332   // we try to avoid short globals?
333   if (E->isConstantInitializer(CGF.getContext(), 0)) {
334     llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, &CGF);
335     llvm::GlobalVariable* GV =
336     new llvm::GlobalVariable(C->getType(), true,
337                              llvm::GlobalValue::InternalLinkage,
338                              C, "", &CGF.CGM.getModule(), 0);
339     CGF.EmitAggregateCopy(DestPtr, GV, E->getType());
340     return;
341   }
342 #endif
343   if (E->hadArrayRangeDesignator()) {
344     CGF.ErrorUnsupported(E, "GNU array range designator extension");
345   }
346 
347   // Handle initialization of an array.
348   if (E->getType()->isArrayType()) {
349     const llvm::PointerType *APType =
350       cast<llvm::PointerType>(DestPtr->getType());
351     const llvm::ArrayType *AType =
352       cast<llvm::ArrayType>(APType->getElementType());
353 
354     uint64_t NumInitElements = E->getNumInits();
355 
356     if (E->getNumInits() > 0) {
357       QualType T1 = E->getType();
358       QualType T2 = E->getInit(0)->getType();
359       if (CGF.getContext().getCanonicalType(T1).getUnqualifiedType() ==
360           CGF.getContext().getCanonicalType(T2).getUnqualifiedType()) {
361         EmitAggLoadOfLValue(E->getInit(0));
362         return;
363       }
364     }
365 
366     uint64_t NumArrayElements = AType->getNumElements();
367     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
368     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
369 
370     unsigned CVRqualifier = ElementType.getCVRQualifiers();
371 
372     for (uint64_t i = 0; i != NumArrayElements; ++i) {
373       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
374       if (i < NumInitElements)
375         EmitInitializationToLValue(E->getInit(i),
376                                    LValue::MakeAddr(NextVal, CVRqualifier));
377       else
378         EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, CVRqualifier),
379                                        ElementType);
380     }
381     return;
382   }
383 
384   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
385 
386   // Do struct initialization; this code just sets each individual member
387   // to the approprate value.  This makes bitfield support automatic;
388   // the disadvantage is that the generated code is more difficult for
389   // the optimizer, especially with bitfields.
390   unsigned NumInitElements = E->getNumInits();
391   RecordDecl *SD = E->getType()->getAsRecordType()->getDecl();
392   unsigned CurInitVal = 0;
393 
394   if (E->getType()->isUnionType()) {
395     // Only initialize one field of a union. The field itself is
396     // specified by the initializer list.
397     if (!E->getInitializedFieldInUnion()) {
398       // Empty union; we have nothing to do.
399 
400 #ifndef NDEBUG
401       // Make sure that it's really an empty and not a failure of
402       // semantic analysis.
403       for (RecordDecl::field_iterator Field = SD->field_begin(CGF.getContext()),
404                                    FieldEnd = SD->field_end(CGF.getContext());
405            Field != FieldEnd; ++Field)
406         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
407 #endif
408       return;
409     }
410 
411     // FIXME: volatility
412     FieldDecl *Field = E->getInitializedFieldInUnion();
413     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, Field, true, 0);
414 
415     if (NumInitElements) {
416       // Store the initializer into the field
417       EmitInitializationToLValue(E->getInit(0), FieldLoc);
418     } else {
419       // Default-initialize to null
420       EmitNullInitializationToLValue(FieldLoc, Field->getType());
421     }
422 
423     return;
424   }
425 
426   // Here we iterate over the fields; this makes it simpler to both
427   // default-initialize fields and skip over unnamed fields.
428   for (RecordDecl::field_iterator Field = SD->field_begin(CGF.getContext()),
429                                FieldEnd = SD->field_end(CGF.getContext());
430        Field != FieldEnd; ++Field) {
431     // We're done once we hit the flexible array member
432     if (Field->getType()->isIncompleteArrayType())
433       break;
434 
435     if (Field->isUnnamedBitfield())
436       continue;
437 
438     // FIXME: volatility
439     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, false, 0);
440     if (CurInitVal < NumInitElements) {
441       // Store the initializer into the field
442       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc);
443     } else {
444       // We're out of initalizers; default-initialize to null
445       EmitNullInitializationToLValue(FieldLoc, Field->getType());
446     }
447   }
448 }
449 
450 //===----------------------------------------------------------------------===//
451 //                        Entry Points into this File
452 //===----------------------------------------------------------------------===//
453 
454 /// EmitAggExpr - Emit the computation of the specified expression of
455 /// aggregate type.  The result is computed into DestPtr.  Note that if
456 /// DestPtr is null, the value of the aggregate expression is not needed.
457 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
458                                   bool VolatileDest) {
459   assert(E && hasAggregateLLVMType(E->getType()) &&
460          "Invalid aggregate expression to emit");
461 
462   AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E));
463 }
464 
465 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
466   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
467 
468   EmitMemSetToZero(DestPtr, Ty);
469 }
470 
471 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
472                                         llvm::Value *SrcPtr, QualType Ty) {
473   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
474 
475   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
476   // C99 6.5.16.1p3, which states "If the value being stored in an object is
477   // read from another object that overlaps in anyway the storage of the first
478   // object, then the overlap shall be exact and the two objects shall have
479   // qualified or unqualified versions of a compatible type."
480   //
481   // memcpy is not defined if the source and destination pointers are exactly
482   // equal, but other compilers do this optimization, and almost every memcpy
483   // implementation handles this case safely.  If there is a libc that does not
484   // safely handle this, we can add a target hook.
485   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
486   if (DestPtr->getType() != BP)
487     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
488   if (SrcPtr->getType() != BP)
489     SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
490 
491   // Get size and alignment info for this aggregate.
492   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
493 
494   // FIXME: Handle variable sized types.
495   const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
496 
497   Builder.CreateCall4(CGM.getMemCpyFn(),
498                       DestPtr, SrcPtr,
499                       // TypeInfo.first describes size in bits.
500                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
501                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
502                                              TypeInfo.second/8));
503 }
504