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