blob: 1ac13c01ed4e6dddf4c49df6d0d337f6455df6f7 [file] [log] [blame]
Chris Lattner566b6ce2007-08-24 02:22:53 +00001//===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
Chris Lattneraf6f5282007-08-10 20:13:28 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattneraf6f5282007-08-10 20:13:28 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Aggregate Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000015#include "CGObjCRuntime.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Anders Carlssonb14095a2009-04-17 00:06:03 +000018#include "clang/AST/DeclCXX.h"
Sebastian Redl32cf1f22012-02-17 08:42:25 +000019#include "clang/AST/DeclTemplate.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/StmtVisitor.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000021#include "llvm/IR/Constants.h"
22#include "llvm/IR/Function.h"
23#include "llvm/IR/GlobalVariable.h"
24#include "llvm/IR/Intrinsics.h"
Chris Lattneraf6f5282007-08-10 20:13:28 +000025using namespace clang;
26using namespace CodeGen;
Chris Lattner883f6a72007-08-11 00:04:45 +000027
Chris Lattner9c033562007-08-21 04:25:47 +000028//===----------------------------------------------------------------------===//
29// Aggregate Expression Emitter
30//===----------------------------------------------------------------------===//
31
John McCall9eda3ab2013-03-07 21:37:17 +000032llvm::Value *AggValueSlot::getPaddedAtomicAddr() const {
33 assert(isValueOfAtomic());
34 llvm::GEPOperator *op = cast<llvm::GEPOperator>(getAddr());
35 assert(op->getNumIndices() == 2);
36 assert(op->hasAllZeroIndices());
37 return op->getPointerOperand();
38}
39
Chris Lattner9c033562007-08-21 04:25:47 +000040namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000041class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
Chris Lattner9c033562007-08-21 04:25:47 +000042 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000043 CGBuilderTy &Builder;
John McCall558d2ab2010-09-15 10:14:12 +000044 AggValueSlot Dest;
John McCallef072fd2010-05-22 01:48:05 +000045
John McCall410ffb22011-08-25 23:04:34 +000046 /// We want to use 'dest' as the return slot except under two
47 /// conditions:
48 /// - The destination slot requires garbage collection, so we
49 /// need to use the GC API.
50 /// - The destination slot is potentially aliased.
51 bool shouldUseDestForReturnSlot() const {
52 return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
53 }
54
John McCallef072fd2010-05-22 01:48:05 +000055 ReturnValueSlot getReturnValueSlot() const {
John McCall410ffb22011-08-25 23:04:34 +000056 if (!shouldUseDestForReturnSlot())
57 return ReturnValueSlot();
John McCallfa037bd2010-05-22 22:13:32 +000058
John McCall558d2ab2010-09-15 10:14:12 +000059 return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
60 }
61
62 AggValueSlot EnsureSlot(QualType T) {
63 if (!Dest.isIgnored()) return Dest;
64 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
John McCallef072fd2010-05-22 01:48:05 +000065 }
John McCalle0c11682012-07-02 23:58:38 +000066 void EnsureDest(QualType T) {
67 if (!Dest.isIgnored()) return;
68 Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
69 }
John McCallfa037bd2010-05-22 22:13:32 +000070
Chris Lattner9c033562007-08-21 04:25:47 +000071public:
John McCalle0c11682012-07-02 23:58:38 +000072 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest)
73 : CGF(cgf), Builder(CGF.Builder), Dest(Dest) {
Chris Lattner9c033562007-08-21 04:25:47 +000074 }
75
Chris Lattneree755f92007-08-21 04:59:27 +000076 //===--------------------------------------------------------------------===//
77 // Utilities
78 //===--------------------------------------------------------------------===//
79
Chris Lattner9c033562007-08-21 04:25:47 +000080 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
81 /// represents a value lvalue, this method emits the address of the lvalue,
82 /// then loads the result into DestPtr.
83 void EmitAggLoadOfLValue(const Expr *E);
Eli Friedman922696f2008-05-19 17:51:16 +000084
Mike Stump4ac20dd2009-05-23 20:28:01 +000085 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
John McCalle0c11682012-07-02 23:58:38 +000086 void EmitFinalDestCopy(QualType type, const LValue &src);
87 void EmitFinalDestCopy(QualType type, RValue src,
88 CharUnits srcAlignment = CharUnits::Zero());
89 void EmitCopy(QualType type, const AggValueSlot &dest,
90 const AggValueSlot &src);
Mike Stump4ac20dd2009-05-23 20:28:01 +000091
John McCall410ffb22011-08-25 23:04:34 +000092 void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
John McCallfa037bd2010-05-22 22:13:32 +000093
Sebastian Redlaf130fd2012-02-19 12:28:02 +000094 void EmitStdInitializerList(llvm::Value *DestPtr, InitListExpr *InitList);
Sebastian Redl32cf1f22012-02-17 08:42:25 +000095 void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
96 QualType elementType, InitListExpr *E);
97
John McCall7c2349b2011-08-25 20:40:09 +000098 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
David Blaikie4e4d0842012-03-11 07:00:24 +000099 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
John McCall7c2349b2011-08-25 20:40:09 +0000100 return AggValueSlot::NeedsGCBarriers;
101 return AggValueSlot::DoesNotNeedGCBarriers;
102 }
103
John McCallfa037bd2010-05-22 22:13:32 +0000104 bool TypeRequiresGCollection(QualType T);
105
Chris Lattneree755f92007-08-21 04:59:27 +0000106 //===--------------------------------------------------------------------===//
107 // Visitor Methods
108 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Chris Lattner9c033562007-08-21 04:25:47 +0000110 void VisitStmt(Stmt *S) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000111 CGF.ErrorUnsupported(S, "aggregate expression");
Chris Lattner9c033562007-08-21 04:25:47 +0000112 }
113 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000114 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
115 Visit(GE->getResultExpr());
116 }
Eli Friedman12444a22009-01-27 09:03:41 +0000117 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
John McCall91a57552011-07-15 05:09:51 +0000118 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
119 return Visit(E->getReplacement());
120 }
Chris Lattner9c033562007-08-21 04:25:47 +0000121
122 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000123 void VisitDeclRefExpr(DeclRefExpr *E) {
John McCalldd2ecee2012-03-10 03:05:10 +0000124 // For aggregates, we should always be able to emit the variable
125 // as an l-value unless it's a reference. This is due to the fact
126 // that we can't actually ever see a normal l2r conversion on an
127 // aggregate in C++, and in C there's no language standard
128 // actively preventing us from listing variables in the captures
129 // list of a block.
John McCallf4b88a42012-03-10 09:33:50 +0000130 if (E->getDecl()->getType()->isReferenceType()) {
John McCalldd2ecee2012-03-10 03:05:10 +0000131 if (CodeGenFunction::ConstantEmission result
John McCallf4b88a42012-03-10 09:33:50 +0000132 = CGF.tryEmitAsConstant(E)) {
John McCalle0c11682012-07-02 23:58:38 +0000133 EmitFinalDestCopy(E->getType(), result.getReferenceLValue(CGF, E));
John McCalldd2ecee2012-03-10 03:05:10 +0000134 return;
135 }
136 }
137
John McCallf4b88a42012-03-10 09:33:50 +0000138 EmitAggLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000139 }
140
Seo Sanghyeon9b73b392007-12-14 02:04:12 +0000141 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
142 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
Daniel Dunbar5be028f2010-01-04 18:47:06 +0000143 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000144 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Seo Sanghyeon9b73b392007-12-14 02:04:12 +0000145 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
146 EmitAggLoadOfLValue(E);
147 }
Chris Lattnerf0a990c2009-04-21 23:00:09 +0000148 void VisitPredefinedExpr(const PredefinedExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000149 EmitAggLoadOfLValue(E);
Chris Lattnerf0a990c2009-04-21 23:00:09 +0000150 }
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Chris Lattner9c033562007-08-21 04:25:47 +0000152 // Operators.
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000153 void VisitCastExpr(CastExpr *E);
Anders Carlsson148fe672007-10-31 22:04:46 +0000154 void VisitCallExpr(const CallExpr *E);
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000155 void VisitStmtExpr(const StmtExpr *E);
Chris Lattner9c033562007-08-21 04:25:47 +0000156 void VisitBinaryOperator(const BinaryOperator *BO);
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +0000157 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
Chris Lattner03d6fb92007-08-21 04:43:17 +0000158 void VisitBinAssign(const BinaryOperator *E);
Eli Friedman07fa52a2008-05-20 07:56:31 +0000159 void VisitBinComma(const BinaryOperator *E);
Chris Lattner9c033562007-08-21 04:25:47 +0000160
Chris Lattner8fdf3282008-06-24 17:04:18 +0000161 void VisitObjCMessageExpr(ObjCMessageExpr *E);
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000162 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
163 EmitAggLoadOfLValue(E);
164 }
Mike Stump1eb44332009-09-09 15:08:12 +0000165
John McCall56ca35d2011-02-17 10:25:35 +0000166 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
Anders Carlssona294ca82009-07-08 18:33:14 +0000167 void VisitChooseExpr(const ChooseExpr *CE);
Devang Patel636c3d02007-10-26 17:44:44 +0000168 void VisitInitListExpr(InitListExpr *E);
Anders Carlsson30311fa2009-12-16 06:57:54 +0000169 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
Chris Lattner04421082008-04-08 04:40:51 +0000170 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
171 Visit(DAE->getExpr());
172 }
Anders Carlssonb58d0172009-05-30 23:23:33 +0000173 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
Anders Carlsson31ccf372009-05-03 17:47:16 +0000174 void VisitCXXConstructExpr(const CXXConstructExpr *E);
Eli Friedman4c5d8af2012-02-09 03:32:31 +0000175 void VisitLambdaExpr(LambdaExpr *E);
John McCall4765fa02010-12-06 08:20:24 +0000176 void VisitExprWithCleanups(ExprWithCleanups *E);
Douglas Gregored8abf12010-07-08 06:14:04 +0000177 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Mike Stump2710c412009-11-18 00:40:12 +0000178 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor03e80032011-06-21 17:03:29 +0000179 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
John McCalle996ffd2011-02-16 08:02:54 +0000180 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
181
John McCall4b9c2d22011-11-06 09:01:30 +0000182 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
183 if (E->isGLValue()) {
184 LValue LV = CGF.EmitPseudoObjectLValue(E);
John McCalle0c11682012-07-02 23:58:38 +0000185 return EmitFinalDestCopy(E->getType(), LV);
John McCall4b9c2d22011-11-06 09:01:30 +0000186 }
187
188 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
189 }
190
Eli Friedmanb1851242008-05-27 15:51:49 +0000191 void VisitVAArgExpr(VAArgExpr *E);
Chris Lattnerf81557c2008-04-04 18:42:16 +0000192
Chad Rosier649b4a12012-03-29 17:37:10 +0000193 void EmitInitializationToLValue(Expr *E, LValue Address);
John McCalla07398e2011-06-16 04:16:24 +0000194 void EmitNullInitializationToLValue(LValue Address);
Chris Lattner9c033562007-08-21 04:25:47 +0000195 // case Expr::ChooseExprClass:
Mike Stump39406b12009-12-09 19:24:08 +0000196 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
Eli Friedman276b0612011-10-11 02:20:01 +0000197 void VisitAtomicExpr(AtomicExpr *E) {
198 CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
199 }
Chris Lattner9c033562007-08-21 04:25:47 +0000200};
John McCall9eda3ab2013-03-07 21:37:17 +0000201
202/// A helper class for emitting expressions into the value sub-object
203/// of a padded atomic type.
204class ValueDestForAtomic {
205 AggValueSlot Dest;
206public:
207 ValueDestForAtomic(CodeGenFunction &CGF, AggValueSlot dest, QualType type)
208 : Dest(dest) {
209 assert(!Dest.isValueOfAtomic());
210 if (!Dest.isIgnored() && CGF.CGM.isPaddedAtomicType(type)) {
211 llvm::Value *valueAddr = CGF.Builder.CreateStructGEP(Dest.getAddr(), 0);
212 Dest = AggValueSlot::forAddr(valueAddr,
213 Dest.getAlignment(),
214 Dest.getQualifiers(),
215 Dest.isExternallyDestructed(),
216 Dest.requiresGCollection(),
217 Dest.isPotentiallyAliased(),
218 Dest.isZeroed(),
219 AggValueSlot::IsValueOfAtomic);
220 }
221 }
222
223 const AggValueSlot &getDest() const { return Dest; }
224
225 ~ValueDestForAtomic() {
226 // Kill the GEP if we made one and it didn't end up used.
227 if (Dest.isValueOfAtomic()) {
228 llvm::Instruction *addr = cast<llvm::GetElementPtrInst>(Dest.getAddr());
229 if (addr->use_empty()) addr->eraseFromParent();
230 }
231 }
232};
Chris Lattner9c033562007-08-21 04:25:47 +0000233} // end anonymous namespace.
234
Chris Lattneree755f92007-08-21 04:59:27 +0000235//===----------------------------------------------------------------------===//
236// Utilities
237//===----------------------------------------------------------------------===//
Chris Lattner9c033562007-08-21 04:25:47 +0000238
Chris Lattner883f6a72007-08-11 00:04:45 +0000239/// EmitAggLoadOfLValue - Given an expression with aggregate type that
240/// represents a value lvalue, this method emits the address of the lvalue,
241/// then loads the result into DestPtr.
Chris Lattner9c033562007-08-21 04:25:47 +0000242void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
243 LValue LV = CGF.EmitLValue(E);
John McCall9eda3ab2013-03-07 21:37:17 +0000244
245 // If the type of the l-value is atomic, then do an atomic load.
246 if (LV.getType()->isAtomicType()) {
247 ValueDestForAtomic valueDest(CGF, Dest, LV.getType());
248 CGF.EmitAtomicLoad(LV, valueDest.getDest());
249 return;
250 }
251
John McCalle0c11682012-07-02 23:58:38 +0000252 EmitFinalDestCopy(E->getType(), LV);
Mike Stump4ac20dd2009-05-23 20:28:01 +0000253}
254
John McCallfa037bd2010-05-22 22:13:32 +0000255/// \brief True if the given aggregate type requires special GC API calls.
256bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
257 // Only record types have members that might require garbage collection.
258 const RecordType *RecordTy = T->getAs<RecordType>();
259 if (!RecordTy) return false;
260
261 // Don't mess with non-trivial C++ types.
262 RecordDecl *Record = RecordTy->getDecl();
263 if (isa<CXXRecordDecl>(Record) &&
Richard Smith426391c2012-11-16 00:53:38 +0000264 (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
John McCallfa037bd2010-05-22 22:13:32 +0000265 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
266 return false;
267
268 // Check whether the type has an object member.
269 return Record->hasObjectMember();
270}
271
John McCall410ffb22011-08-25 23:04:34 +0000272/// \brief Perform the final move to DestPtr if for some reason
273/// getReturnValueSlot() didn't use it directly.
John McCallfa037bd2010-05-22 22:13:32 +0000274///
275/// The idea is that you do something like this:
276/// RValue Result = EmitSomething(..., getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000277/// EmitMoveFromReturnSlot(E, Result);
278///
279/// If nothing interferes, this will cause the result to be emitted
280/// directly into the return value slot. Otherwise, a final move
281/// will be performed.
John McCalle0c11682012-07-02 23:58:38 +0000282void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
John McCall410ffb22011-08-25 23:04:34 +0000283 if (shouldUseDestForReturnSlot()) {
284 // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
285 // The possibility of undef rvalues complicates that a lot,
286 // though, so we can't really assert.
287 return;
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000288 }
John McCall410ffb22011-08-25 23:04:34 +0000289
John McCalle0c11682012-07-02 23:58:38 +0000290 // Otherwise, copy from there to the destination.
291 assert(Dest.getAddr() != src.getAggregateAddr());
292 std::pair<CharUnits, CharUnits> typeInfo =
Chad Rosier26397ed2012-04-17 01:14:29 +0000293 CGF.getContext().getTypeInfoInChars(E->getType());
John McCalle0c11682012-07-02 23:58:38 +0000294 EmitFinalDestCopy(E->getType(), src, typeInfo.second);
John McCallfa037bd2010-05-22 22:13:32 +0000295}
296
Mike Stump4ac20dd2009-05-23 20:28:01 +0000297/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
John McCalle0c11682012-07-02 23:58:38 +0000298void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src,
299 CharUnits srcAlign) {
300 assert(src.isAggregate() && "value must be aggregate value!");
301 LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddr(), type, srcAlign);
302 EmitFinalDestCopy(type, srcLV);
303}
Mike Stump4ac20dd2009-05-23 20:28:01 +0000304
John McCalle0c11682012-07-02 23:58:38 +0000305/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
306void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src) {
John McCall558d2ab2010-09-15 10:14:12 +0000307 // If Dest is ignored, then we're evaluating an aggregate expression
John McCalle0c11682012-07-02 23:58:38 +0000308 // in a context that doesn't care about the result. Note that loads
309 // from volatile l-values force the existence of a non-ignored
310 // destination.
311 if (Dest.isIgnored())
312 return;
Fariborz Jahanian8a970052010-10-22 22:05:03 +0000313
John McCalle0c11682012-07-02 23:58:38 +0000314 AggValueSlot srcAgg =
315 AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
316 needsGC(type), AggValueSlot::IsAliased);
317 EmitCopy(type, Dest, srcAgg);
318}
Chris Lattner883f6a72007-08-11 00:04:45 +0000319
John McCalle0c11682012-07-02 23:58:38 +0000320/// Perform a copy from the source into the destination.
321///
322/// \param type - the type of the aggregate being copied; qualifiers are
323/// ignored
324void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
325 const AggValueSlot &src) {
326 if (dest.requiresGCollection()) {
327 CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
328 llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
Fariborz Jahanian08c32132009-08-31 19:33:16 +0000329 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
John McCalle0c11682012-07-02 23:58:38 +0000330 dest.getAddr(),
331 src.getAddr(),
332 size);
Fariborz Jahanian08c32132009-08-31 19:33:16 +0000333 return;
334 }
John McCalle0c11682012-07-02 23:58:38 +0000335
Mike Stump4ac20dd2009-05-23 20:28:01 +0000336 // If the result of the assignment is used, copy the LHS there also.
John McCalle0c11682012-07-02 23:58:38 +0000337 // It's volatile if either side is. Use the minimum alignment of
338 // the two sides.
339 CGF.EmitAggregateCopy(dest.getAddr(), src.getAddr(), type,
340 dest.isVolatile() || src.isVolatile(),
341 std::min(dest.getAlignment(), src.getAlignment()));
Chris Lattner883f6a72007-08-11 00:04:45 +0000342}
343
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000344static QualType GetStdInitializerListElementType(QualType T) {
345 // Just assume that this is really std::initializer_list.
346 ClassTemplateSpecializationDecl *specialization =
347 cast<ClassTemplateSpecializationDecl>(T->castAs<RecordType>()->getDecl());
348 return specialization->getTemplateArgs()[0].getAsType();
349}
350
351/// \brief Prepare cleanup for the temporary array.
352static void EmitStdInitializerListCleanup(CodeGenFunction &CGF,
353 QualType arrayType,
354 llvm::Value *addr,
355 const InitListExpr *initList) {
356 QualType::DestructionKind dtorKind = arrayType.isDestructedType();
357 if (!dtorKind)
358 return; // Type doesn't need destroying.
359 if (dtorKind != QualType::DK_cxx_destructor) {
360 CGF.ErrorUnsupported(initList, "ObjC ARC type in initializer_list");
361 return;
362 }
363
364 CodeGenFunction::Destroyer *destroyer = CGF.getDestroyer(dtorKind);
365 CGF.pushDestroy(NormalAndEHCleanup, addr, arrayType, destroyer,
366 /*EHCleanup=*/true);
367}
368
369/// \brief Emit the initializer for a std::initializer_list initialized with a
370/// real initializer list.
Sebastian Redlaf130fd2012-02-19 12:28:02 +0000371void AggExprEmitter::EmitStdInitializerList(llvm::Value *destPtr,
372 InitListExpr *initList) {
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000373 // We emit an array containing the elements, then have the init list point
374 // at the array.
375 ASTContext &ctx = CGF.getContext();
376 unsigned numInits = initList->getNumInits();
377 QualType element = GetStdInitializerListElementType(initList->getType());
378 llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
379 QualType array = ctx.getConstantArrayType(element, size, ArrayType::Normal,0);
380 llvm::Type *LTy = CGF.ConvertTypeForMem(array);
381 llvm::AllocaInst *alloc = CGF.CreateTempAlloca(LTy);
382 alloc->setAlignment(ctx.getTypeAlignInChars(array).getQuantity());
383 alloc->setName(".initlist.");
384
385 EmitArrayInit(alloc, cast<llvm::ArrayType>(LTy), element, initList);
386
387 // FIXME: The diagnostics are somewhat out of place here.
388 RecordDecl *record = initList->getType()->castAs<RecordType>()->getDecl();
389 RecordDecl::field_iterator field = record->field_begin();
390 if (field == record->field_end()) {
391 CGF.ErrorUnsupported(initList, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000392 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000393 }
394
395 QualType elementPtr = ctx.getPointerType(element.withConst());
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000396
397 // Start pointer.
398 if (!ctx.hasSameType(field->getType(), elementPtr)) {
399 CGF.ErrorUnsupported(initList, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000400 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000401 }
Eli Friedman377ecc72012-04-16 03:54:45 +0000402 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(destPtr, initList->getType());
David Blaikie581deb32012-06-06 20:45:41 +0000403 LValue start = CGF.EmitLValueForFieldInitialization(DestLV, *field);
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000404 llvm::Value *arrayStart = Builder.CreateStructGEP(alloc, 0, "arraystart");
405 CGF.EmitStoreThroughLValue(RValue::get(arrayStart), start);
406 ++field;
407
408 if (field == record->field_end()) {
409 CGF.ErrorUnsupported(initList, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000410 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000411 }
David Blaikie581deb32012-06-06 20:45:41 +0000412 LValue endOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *field);
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000413 if (ctx.hasSameType(field->getType(), elementPtr)) {
414 // End pointer.
415 llvm::Value *arrayEnd = Builder.CreateStructGEP(alloc,numInits, "arrayend");
416 CGF.EmitStoreThroughLValue(RValue::get(arrayEnd), endOrLength);
417 } else if(ctx.hasSameType(field->getType(), ctx.getSizeType())) {
418 // Length.
419 CGF.EmitStoreThroughLValue(RValue::get(Builder.getInt(size)), endOrLength);
420 } else {
421 CGF.ErrorUnsupported(initList, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000422 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000423 }
424
425 if (!Dest.isExternallyDestructed())
426 EmitStdInitializerListCleanup(CGF, array, alloc, initList);
427}
428
429/// \brief Emit initialization of an array from an initializer list.
430void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
431 QualType elementType, InitListExpr *E) {
432 uint64_t NumInitElements = E->getNumInits();
433
434 uint64_t NumArrayElements = AType->getNumElements();
435 assert(NumInitElements <= NumArrayElements);
436
437 // DestPtr is an array*. Construct an elementType* by drilling
438 // down a level.
439 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
440 llvm::Value *indices[] = { zero, zero };
441 llvm::Value *begin =
442 Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
443
444 // Exception safety requires us to destroy all the
445 // already-constructed members if an initializer throws.
446 // For that, we'll need an EH cleanup.
447 QualType::DestructionKind dtorKind = elementType.isDestructedType();
448 llvm::AllocaInst *endOfInit = 0;
449 EHScopeStack::stable_iterator cleanup;
450 llvm::Instruction *cleanupDominator = 0;
451 if (CGF.needsEHCleanup(dtorKind)) {
452 // In principle we could tell the cleanup where we are more
453 // directly, but the control flow can get so varied here that it
454 // would actually be quite complex. Therefore we go through an
455 // alloca.
456 endOfInit = CGF.CreateTempAlloca(begin->getType(),
457 "arrayinit.endOfInit");
458 cleanupDominator = Builder.CreateStore(begin, endOfInit);
459 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
460 CGF.getDestroyer(dtorKind));
461 cleanup = CGF.EHStack.stable_begin();
462
463 // Otherwise, remember that we didn't need a cleanup.
464 } else {
465 dtorKind = QualType::DK_none;
466 }
467
468 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
469
470 // The 'current element to initialize'. The invariants on this
471 // variable are complicated. Essentially, after each iteration of
472 // the loop, it points to the last initialized element, except
473 // that it points to the beginning of the array before any
474 // elements have been initialized.
475 llvm::Value *element = begin;
476
477 // Emit the explicit initializers.
478 for (uint64_t i = 0; i != NumInitElements; ++i) {
479 // Advance to the next element.
480 if (i > 0) {
481 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
482
483 // Tell the cleanup that it needs to destroy up to this
484 // element. TODO: some of these stores can be trivially
485 // observed to be unnecessary.
486 if (endOfInit) Builder.CreateStore(element, endOfInit);
487 }
488
Sebastian Redlaf130fd2012-02-19 12:28:02 +0000489 // If these are nested std::initializer_list inits, do them directly,
490 // because they are conceptually the same "location".
491 InitListExpr *initList = dyn_cast<InitListExpr>(E->getInit(i));
492 if (initList && initList->initializesStdInitializerList()) {
493 EmitStdInitializerList(element, initList);
494 } else {
495 LValue elementLV = CGF.MakeAddrLValue(element, elementType);
Chad Rosier649b4a12012-03-29 17:37:10 +0000496 EmitInitializationToLValue(E->getInit(i), elementLV);
Sebastian Redlaf130fd2012-02-19 12:28:02 +0000497 }
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000498 }
499
500 // Check whether there's a non-trivial array-fill expression.
501 // Note that this will be a CXXConstructExpr even if the element
502 // type is an array (or array of array, etc.) of class type.
503 Expr *filler = E->getArrayFiller();
504 bool hasTrivialFiller = true;
505 if (CXXConstructExpr *cons = dyn_cast_or_null<CXXConstructExpr>(filler)) {
506 assert(cons->getConstructor()->isDefaultConstructor());
507 hasTrivialFiller = cons->getConstructor()->isTrivial();
508 }
509
510 // Any remaining elements need to be zero-initialized, possibly
511 // using the filler expression. We can skip this if the we're
512 // emitting to zeroed memory.
513 if (NumInitElements != NumArrayElements &&
514 !(Dest.isZeroed() && hasTrivialFiller &&
515 CGF.getTypes().isZeroInitializable(elementType))) {
516
517 // Use an actual loop. This is basically
518 // do { *array++ = filler; } while (array != end);
519
520 // Advance to the start of the rest of the array.
521 if (NumInitElements) {
522 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
523 if (endOfInit) Builder.CreateStore(element, endOfInit);
524 }
525
526 // Compute the end of the array.
527 llvm::Value *end = Builder.CreateInBoundsGEP(begin,
528 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
529 "arrayinit.end");
530
531 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
532 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
533
534 // Jump into the body.
535 CGF.EmitBlock(bodyBB);
536 llvm::PHINode *currentElement =
537 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
538 currentElement->addIncoming(element, entryBB);
539
540 // Emit the actual filler expression.
541 LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
542 if (filler)
Chad Rosier649b4a12012-03-29 17:37:10 +0000543 EmitInitializationToLValue(filler, elementLV);
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000544 else
545 EmitNullInitializationToLValue(elementLV);
546
547 // Move on to the next element.
548 llvm::Value *nextElement =
549 Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
550
551 // Tell the EH cleanup that we finished with the last element.
552 if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
553
554 // Leave the loop if we're done.
555 llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
556 "arrayinit.done");
557 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
558 Builder.CreateCondBr(done, endBB, bodyBB);
559 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
560
561 CGF.EmitBlock(endBB);
562 }
563
564 // Leave the partial-array cleanup if we entered one.
565 if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
566}
567
Chris Lattneree755f92007-08-21 04:59:27 +0000568//===----------------------------------------------------------------------===//
569// Visitor Methods
570//===----------------------------------------------------------------------===//
571
Douglas Gregor03e80032011-06-21 17:03:29 +0000572void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
573 Visit(E->GetTemporaryExpr());
574}
575
John McCalle996ffd2011-02-16 08:02:54 +0000576void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
John McCalle0c11682012-07-02 23:58:38 +0000577 EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e));
John McCalle996ffd2011-02-16 08:02:54 +0000578}
579
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000580void
581AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCall1723f632013-03-07 21:36:54 +0000582 if (Dest.isPotentiallyAliased() &&
583 E->getType().isPODType(CGF.getContext())) {
Douglas Gregor673e98b2011-06-17 16:37:20 +0000584 // For a POD type, just emit a load of the lvalue + a copy, because our
585 // compound literal might alias the destination.
Douglas Gregor673e98b2011-06-17 16:37:20 +0000586 EmitAggLoadOfLValue(E);
587 return;
588 }
589
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000590 AggValueSlot Slot = EnsureSlot(E->getType());
591 CGF.EmitAggExpr(E->getInitializer(), Slot);
592}
593
John McCall9eda3ab2013-03-07 21:37:17 +0000594/// Attempt to look through various unimportant expressions to find a
595/// cast of the given kind.
596static Expr *findPeephole(Expr *op, CastKind kind) {
597 while (true) {
598 op = op->IgnoreParens();
599 if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
600 if (castE->getCastKind() == kind)
601 return castE->getSubExpr();
602 if (castE->getCastKind() == CK_NoOp)
603 continue;
604 }
605 return 0;
606 }
607}
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000608
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000609void AggExprEmitter::VisitCastExpr(CastExpr *E) {
Anders Carlsson30168422009-09-29 01:23:39 +0000610 switch (E->getCastKind()) {
Anders Carlsson575b3742011-04-11 02:03:26 +0000611 case CK_Dynamic: {
Richard Smith2c9f87c2012-08-24 00:54:33 +0000612 // FIXME: Can this actually happen? We have no test coverage for it.
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000613 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
Richard Smith2c9f87c2012-08-24 00:54:33 +0000614 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
Richard Smith7ac9ef12012-09-08 02:08:36 +0000615 CodeGenFunction::TCK_Load);
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000616 // FIXME: Do we also need to handle property references here?
617 if (LV.isSimple())
618 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
619 else
620 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
621
John McCall558d2ab2010-09-15 10:14:12 +0000622 if (!Dest.isIgnored())
623 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000624 break;
625 }
626
John McCall2de56d12010-08-25 11:45:40 +0000627 case CK_ToUnion: {
John McCall65912712011-04-12 22:02:02 +0000628 if (Dest.isIgnored()) break;
629
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000630 // GCC union extension
Daniel Dunbar79c39282010-08-21 03:15:20 +0000631 QualType Ty = E->getSubExpr()->getType();
632 QualType PtrTy = CGF.getContext().getPointerType(Ty);
John McCall558d2ab2010-09-15 10:14:12 +0000633 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
Eli Friedman34ebf4d2009-06-03 20:45:06 +0000634 CGF.ConvertType(PtrTy));
John McCalla07398e2011-06-16 04:16:24 +0000635 EmitInitializationToLValue(E->getSubExpr(),
Chad Rosier649b4a12012-03-29 17:37:10 +0000636 CGF.MakeAddrLValue(CastPtr, Ty));
Anders Carlsson30168422009-09-29 01:23:39 +0000637 break;
Nuno Lopes7e916272009-01-15 20:14:33 +0000638 }
Mike Stump1eb44332009-09-09 15:08:12 +0000639
John McCall2de56d12010-08-25 11:45:40 +0000640 case CK_DerivedToBase:
641 case CK_BaseToDerived:
642 case CK_UncheckedDerivedToBase: {
David Blaikieb219cfc2011-09-23 05:06:16 +0000643 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000644 "should have been unpacked before we got here");
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000645 }
646
John McCall9eda3ab2013-03-07 21:37:17 +0000647 case CK_NonAtomicToAtomic:
648 case CK_AtomicToNonAtomic: {
649 bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
650
651 // Determine the atomic and value types.
652 QualType atomicType = E->getSubExpr()->getType();
653 QualType valueType = E->getType();
654 if (isToAtomic) std::swap(atomicType, valueType);
655
656 assert(atomicType->isAtomicType());
657 assert(CGF.getContext().hasSameUnqualifiedType(valueType,
658 atomicType->castAs<AtomicType>()->getValueType()));
659
660 // Just recurse normally if we're ignoring the result or the
661 // atomic type doesn't change representation.
662 if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
663 return Visit(E->getSubExpr());
664 }
665
666 CastKind peepholeTarget =
667 (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
668
669 // These two cases are reverses of each other; try to peephole them.
670 if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
671 assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
672 E->getType()) &&
673 "peephole significantly changed types?");
674 return Visit(op);
675 }
676
677 // If we're converting an r-value of non-atomic type to an r-value
678 // of atomic type, just make an atomic temporary, emit into that,
679 // and then copy the value out. (FIXME: do we need to
680 // zero-initialize it first?)
681 if (isToAtomic) {
682 ValueDestForAtomic valueDest(CGF, Dest, atomicType);
683 CGF.EmitAggExpr(E->getSubExpr(), valueDest.getDest());
684 return;
685 }
686
687 // Otherwise, we're converting an atomic type to a non-atomic type.
688
689 // If the dest is a value-of-atomic subobject, drill back out.
690 if (Dest.isValueOfAtomic()) {
691 AggValueSlot atomicSlot =
692 AggValueSlot::forAddr(Dest.getPaddedAtomicAddr(),
693 Dest.getAlignment(),
694 Dest.getQualifiers(),
695 Dest.isExternallyDestructed(),
696 Dest.requiresGCollection(),
697 Dest.isPotentiallyAliased(),
698 Dest.isZeroed(),
699 AggValueSlot::IsNotValueOfAtomic);
700 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
701 return;
702 }
703
704 // Otherwise, make an atomic temporary, emit into that, and then
705 // copy the value out.
706 AggValueSlot atomicSlot =
707 CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
708 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
709
710 llvm::Value *valueAddr =
711 Builder.CreateStructGEP(atomicSlot.getAddr(), 0);
712 RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
713 return EmitFinalDestCopy(valueType, rvalue);
714 }
715
John McCalle0c11682012-07-02 23:58:38 +0000716 case CK_LValueToRValue:
717 // If we're loading from a volatile type, force the destination
718 // into existence.
719 if (E->getSubExpr()->getType().isVolatileQualified()) {
720 EnsureDest(E->getType());
721 return Visit(E->getSubExpr());
722 }
John McCall9eda3ab2013-03-07 21:37:17 +0000723
John McCalle0c11682012-07-02 23:58:38 +0000724 // fallthrough
725
John McCall2de56d12010-08-25 11:45:40 +0000726 case CK_NoOp:
727 case CK_UserDefinedConversion:
728 case CK_ConstructorConversion:
Anders Carlsson30168422009-09-29 01:23:39 +0000729 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
730 E->getType()) &&
731 "Implicit cast types must be compatible");
732 Visit(E->getSubExpr());
733 break;
John McCall0ae287a2010-12-01 04:43:34 +0000734
John McCall2de56d12010-08-25 11:45:40 +0000735 case CK_LValueBitCast:
John McCall0ae287a2010-12-01 04:43:34 +0000736 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
John McCall1de4d4e2011-04-07 08:22:57 +0000737
John McCall0ae287a2010-12-01 04:43:34 +0000738 case CK_Dependent:
739 case CK_BitCast:
740 case CK_ArrayToPointerDecay:
741 case CK_FunctionToPointerDecay:
742 case CK_NullToPointer:
743 case CK_NullToMemberPointer:
744 case CK_BaseToDerivedMemberPointer:
745 case CK_DerivedToBaseMemberPointer:
746 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +0000747 case CK_ReinterpretMemberPointer:
John McCall0ae287a2010-12-01 04:43:34 +0000748 case CK_IntegralToPointer:
749 case CK_PointerToIntegral:
750 case CK_PointerToBoolean:
751 case CK_ToVoid:
752 case CK_VectorSplat:
753 case CK_IntegralCast:
754 case CK_IntegralToBoolean:
755 case CK_IntegralToFloating:
756 case CK_FloatingToIntegral:
757 case CK_FloatingToBoolean:
758 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +0000759 case CK_CPointerToObjCPointerCast:
760 case CK_BlockPointerToObjCPointerCast:
John McCall0ae287a2010-12-01 04:43:34 +0000761 case CK_AnyPointerToBlockPointerCast:
762 case CK_ObjCObjectLValueCast:
763 case CK_FloatingRealToComplex:
764 case CK_FloatingComplexToReal:
765 case CK_FloatingComplexToBoolean:
766 case CK_FloatingComplexCast:
767 case CK_FloatingComplexToIntegralComplex:
768 case CK_IntegralRealToComplex:
769 case CK_IntegralComplexToReal:
770 case CK_IntegralComplexToBoolean:
771 case CK_IntegralComplexCast:
772 case CK_IntegralComplexToFloatingComplex:
John McCall33e56f32011-09-10 06:18:15 +0000773 case CK_ARCProduceObject:
774 case CK_ARCConsumeObject:
775 case CK_ARCReclaimReturnedObject:
776 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +0000777 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000778 case CK_BuiltinFnToFnPtr:
Guy Benyeie6b9d802013-01-20 12:31:11 +0000779 case CK_ZeroToOCLEvent:
John McCall0ae287a2010-12-01 04:43:34 +0000780 llvm_unreachable("cast kind invalid for aggregate types");
Anders Carlsson30168422009-09-29 01:23:39 +0000781 }
Anders Carlssone4707ff2008-01-14 06:28:57 +0000782}
783
Chris Lattner96196622008-07-26 22:37:01 +0000784void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
Anders Carlssone70e8f72009-05-27 16:45:02 +0000785 if (E->getCallReturnType()->isReferenceType()) {
786 EmitAggLoadOfLValue(E);
787 return;
788 }
Mike Stump1eb44332009-09-09 15:08:12 +0000789
John McCallfa037bd2010-05-22 22:13:32 +0000790 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000791 EmitMoveFromReturnSlot(E, RV);
Anders Carlsson148fe672007-10-31 22:04:46 +0000792}
Chris Lattner96196622008-07-26 22:37:01 +0000793
794void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCallfa037bd2010-05-22 22:13:32 +0000795 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000796 EmitMoveFromReturnSlot(E, RV);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000797}
Anders Carlsson148fe672007-10-31 22:04:46 +0000798
Chris Lattner96196622008-07-26 22:37:01 +0000799void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +0000800 CGF.EmitIgnoredExpr(E->getLHS());
John McCall558d2ab2010-09-15 10:14:12 +0000801 Visit(E->getRHS());
Eli Friedman07fa52a2008-05-20 07:56:31 +0000802}
803
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000804void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +0000805 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall558d2ab2010-09-15 10:14:12 +0000806 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000807}
808
Chris Lattner9c033562007-08-21 04:25:47 +0000809void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000810 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +0000811 VisitPointerToDataMemberBinaryOperator(E);
812 else
813 CGF.ErrorUnsupported(E, "aggregate binary expression");
814}
815
816void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
817 const BinaryOperator *E) {
818 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
John McCalle0c11682012-07-02 23:58:38 +0000819 EmitFinalDestCopy(E->getType(), LV);
820}
821
822/// Is the value of the given expression possibly a reference to or
823/// into a __block variable?
824static bool isBlockVarRef(const Expr *E) {
825 // Make sure we look through parens.
826 E = E->IgnoreParens();
827
828 // Check for a direct reference to a __block variable.
829 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
830 const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
831 return (var && var->hasAttr<BlocksAttr>());
832 }
833
834 // More complicated stuff.
835
836 // Binary operators.
837 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
838 // For an assignment or pointer-to-member operation, just care
839 // about the LHS.
840 if (op->isAssignmentOp() || op->isPtrMemOp())
841 return isBlockVarRef(op->getLHS());
842
843 // For a comma, just care about the RHS.
844 if (op->getOpcode() == BO_Comma)
845 return isBlockVarRef(op->getRHS());
846
847 // FIXME: pointer arithmetic?
848 return false;
849
850 // Check both sides of a conditional operator.
851 } else if (const AbstractConditionalOperator *op
852 = dyn_cast<AbstractConditionalOperator>(E)) {
853 return isBlockVarRef(op->getTrueExpr())
854 || isBlockVarRef(op->getFalseExpr());
855
856 // OVEs are required to support BinaryConditionalOperators.
857 } else if (const OpaqueValueExpr *op
858 = dyn_cast<OpaqueValueExpr>(E)) {
859 if (const Expr *src = op->getSourceExpr())
860 return isBlockVarRef(src);
861
862 // Casts are necessary to get things like (*(int*)&var) = foo().
863 // We don't really care about the kind of cast here, except
864 // we don't want to look through l2r casts, because it's okay
865 // to get the *value* in a __block variable.
866 } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
867 if (cast->getCastKind() == CK_LValueToRValue)
868 return false;
869 return isBlockVarRef(cast->getSubExpr());
870
871 // Handle unary operators. Again, just aggressively look through
872 // it, ignoring the operation.
873 } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
874 return isBlockVarRef(uop->getSubExpr());
875
876 // Look into the base of a field access.
877 } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
878 return isBlockVarRef(mem->getBase());
879
880 // Look into the base of a subscript.
881 } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
882 return isBlockVarRef(sub->getBase());
883 }
884
885 return false;
Chris Lattneree755f92007-08-21 04:59:27 +0000886}
887
Chris Lattner03d6fb92007-08-21 04:43:17 +0000888void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Eli Friedmanff6e2b72008-02-11 01:09:17 +0000889 // For an assignment to work, the value on the right has
890 // to be compatible with the value on the left.
Eli Friedman2dce5f82009-05-28 23:04:00 +0000891 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
892 E->getRHS()->getType())
Eli Friedmanff6e2b72008-02-11 01:09:17 +0000893 && "Invalid assignment");
John McCallcd940a12010-12-06 06:10:02 +0000894
John McCalle0c11682012-07-02 23:58:38 +0000895 // If the LHS might be a __block variable, and the RHS can
896 // potentially cause a block copy, we need to evaluate the RHS first
897 // so that the assignment goes the right place.
898 // This is pretty semantically fragile.
899 if (isBlockVarRef(E->getLHS()) &&
900 E->getRHS()->HasSideEffects(CGF.getContext())) {
901 // Ensure that we have a destination, and evaluate the RHS into that.
902 EnsureDest(E->getRHS()->getType());
903 Visit(E->getRHS());
904
905 // Now emit the LHS and copy into it.
Richard Smith4def70d2012-10-09 19:52:38 +0000906 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCalle0c11682012-07-02 23:58:38 +0000907
John McCall9eda3ab2013-03-07 21:37:17 +0000908 // That copy is an atomic copy if the LHS is atomic.
909 if (LHS.getType()->isAtomicType()) {
910 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
911 return;
912 }
913
John McCalle0c11682012-07-02 23:58:38 +0000914 EmitCopy(E->getLHS()->getType(),
915 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
916 needsGC(E->getLHS()->getType()),
917 AggValueSlot::IsAliased),
918 Dest);
919 return;
920 }
Chad Rosier649b4a12012-03-29 17:37:10 +0000921
Chris Lattner9c033562007-08-21 04:25:47 +0000922 LValue LHS = CGF.EmitLValue(E->getLHS());
Chris Lattner883f6a72007-08-11 00:04:45 +0000923
John McCall9eda3ab2013-03-07 21:37:17 +0000924 // If we have an atomic type, evaluate into the destination and then
925 // do an atomic copy.
926 if (LHS.getType()->isAtomicType()) {
927 EnsureDest(E->getRHS()->getType());
928 Visit(E->getRHS());
929 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
930 return;
931 }
932
John McCalldb458062011-11-07 03:59:57 +0000933 // Codegen the RHS so that it stores directly into the LHS.
934 AggValueSlot LHSSlot =
935 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
936 needsGC(E->getLHS()->getType()),
Chad Rosier649b4a12012-03-29 17:37:10 +0000937 AggValueSlot::IsAliased);
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +0000938 // A non-volatile aggregate destination might have volatile member.
939 if (!LHSSlot.isVolatile() &&
940 CGF.hasVolatileMember(E->getLHS()->getType()))
941 LHSSlot.setVolatile(true);
942
John McCalle0c11682012-07-02 23:58:38 +0000943 CGF.EmitAggExpr(E->getRHS(), LHSSlot);
944
945 // Copy into the destination if the assignment isn't ignored.
946 EmitFinalDestCopy(E->getType(), LHS);
Chris Lattner883f6a72007-08-11 00:04:45 +0000947}
948
John McCall56ca35d2011-02-17 10:25:35 +0000949void AggExprEmitter::
950VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000951 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
952 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
953 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000954
John McCall56ca35d2011-02-17 10:25:35 +0000955 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +0000956 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCall56ca35d2011-02-17 10:25:35 +0000957
John McCall150b4622011-01-26 04:00:11 +0000958 CodeGenFunction::ConditionalEvaluation eval(CGF);
Eli Friedman8e274bd2009-12-25 06:17:05 +0000959 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000960
John McCall74fb0ed2010-11-17 00:07:33 +0000961 // Save whether the destination's lifetime is externally managed.
John McCallfd71fb82011-08-26 08:02:37 +0000962 bool isExternallyDestructed = Dest.isExternallyDestructed();
Chris Lattner883f6a72007-08-11 00:04:45 +0000963
John McCall150b4622011-01-26 04:00:11 +0000964 eval.begin(CGF);
965 CGF.EmitBlock(LHSBlock);
John McCall56ca35d2011-02-17 10:25:35 +0000966 Visit(E->getTrueExpr());
John McCall150b4622011-01-26 04:00:11 +0000967 eval.end(CGF);
Mike Stump1eb44332009-09-09 15:08:12 +0000968
John McCall150b4622011-01-26 04:00:11 +0000969 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
970 CGF.Builder.CreateBr(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000971
John McCall74fb0ed2010-11-17 00:07:33 +0000972 // If the result of an agg expression is unused, then the emission
973 // of the LHS might need to create a destination slot. That's fine
974 // with us, and we can safely emit the RHS into the same slot, but
John McCallfd71fb82011-08-26 08:02:37 +0000975 // we shouldn't claim that it's already being destructed.
976 Dest.setExternallyDestructed(isExternallyDestructed);
John McCall74fb0ed2010-11-17 00:07:33 +0000977
John McCall150b4622011-01-26 04:00:11 +0000978 eval.begin(CGF);
979 CGF.EmitBlock(RHSBlock);
John McCall56ca35d2011-02-17 10:25:35 +0000980 Visit(E->getFalseExpr());
John McCall150b4622011-01-26 04:00:11 +0000981 eval.end(CGF);
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Chris Lattner9c033562007-08-21 04:25:47 +0000983 CGF.EmitBlock(ContBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000984}
Chris Lattneree755f92007-08-21 04:59:27 +0000985
Anders Carlssona294ca82009-07-08 18:33:14 +0000986void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
987 Visit(CE->getChosenSubExpr(CGF.getContext()));
988}
989
Eli Friedmanb1851242008-05-27 15:51:49 +0000990void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Daniel Dunbar07855702009-02-11 22:25:55 +0000991 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000992 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
993
Sebastian Redl0262f022009-01-09 21:09:38 +0000994 if (!ArgPtr) {
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000995 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
Sebastian Redl0262f022009-01-09 21:09:38 +0000996 return;
997 }
998
John McCalle0c11682012-07-02 23:58:38 +0000999 EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
Eli Friedmanb1851242008-05-27 15:51:49 +00001000}
1001
Anders Carlssonb58d0172009-05-30 23:23:33 +00001002void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +00001003 // Ensure that we have a slot, but if we already do, remember
John McCallfd71fb82011-08-26 08:02:37 +00001004 // whether it was externally destructed.
1005 bool wasExternallyDestructed = Dest.isExternallyDestructed();
John McCalle0c11682012-07-02 23:58:38 +00001006 EnsureDest(E->getType());
John McCallfd71fb82011-08-26 08:02:37 +00001007
1008 // We're going to push a destructor if there isn't already one.
1009 Dest.setExternallyDestructed();
Mike Stump1eb44332009-09-09 15:08:12 +00001010
John McCall558d2ab2010-09-15 10:14:12 +00001011 Visit(E->getSubExpr());
Anders Carlssonb58d0172009-05-30 23:23:33 +00001012
John McCallfd71fb82011-08-26 08:02:37 +00001013 // Push that destructor we promised.
1014 if (!wasExternallyDestructed)
Peter Collingbourne86811602011-11-27 22:09:22 +00001015 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
Anders Carlssonb58d0172009-05-30 23:23:33 +00001016}
1017
Anders Carlssonb14095a2009-04-17 00:06:03 +00001018void
Anders Carlsson31ccf372009-05-03 17:47:16 +00001019AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +00001020 AggValueSlot Slot = EnsureSlot(E->getType());
1021 CGF.EmitCXXConstructExpr(E, Slot);
Anders Carlsson7f6ad152009-05-19 04:48:36 +00001022}
1023
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001024void
1025AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1026 AggValueSlot Slot = EnsureSlot(E->getType());
1027 CGF.EmitLambdaExpr(E, Slot);
1028}
1029
John McCall4765fa02010-12-06 08:20:24 +00001030void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +00001031 CGF.enterFullExpression(E);
1032 CodeGenFunction::RunCleanupsScope cleanups(CGF);
1033 Visit(E->getSubExpr());
Anders Carlssonb14095a2009-04-17 00:06:03 +00001034}
1035
Douglas Gregored8abf12010-07-08 06:14:04 +00001036void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +00001037 QualType T = E->getType();
1038 AggValueSlot Slot = EnsureSlot(T);
John McCalla07398e2011-06-16 04:16:24 +00001039 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Anders Carlsson30311fa2009-12-16 06:57:54 +00001040}
1041
1042void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +00001043 QualType T = E->getType();
1044 AggValueSlot Slot = EnsureSlot(T);
John McCalla07398e2011-06-16 04:16:24 +00001045 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Nuno Lopes329763b2009-10-18 15:18:11 +00001046}
1047
Chris Lattner1b726772010-12-02 07:07:26 +00001048/// isSimpleZero - If emitting this value will obviously just cause a store of
1049/// zero to memory, return true. This can return false if uncertain, so it just
1050/// handles simple cases.
1051static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001052 E = E->IgnoreParens();
1053
Chris Lattner1b726772010-12-02 07:07:26 +00001054 // 0
1055 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1056 return IL->getValue() == 0;
1057 // +0.0
1058 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1059 return FL->getValue().isPosZero();
1060 // int()
1061 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
1062 CGF.getTypes().isZeroInitializable(E->getType()))
1063 return true;
1064 // (int*)0 - Null pointer expressions.
1065 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1066 return ICE->getCastKind() == CK_NullToPointer;
1067 // '\0'
1068 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1069 return CL->getValue() == 0;
1070
1071 // Otherwise, hard case: conservatively return false.
1072 return false;
1073}
1074
1075
Anders Carlsson78e83f82010-02-03 17:33:16 +00001076void
Chad Rosier649b4a12012-03-29 17:37:10 +00001077AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
John McCalla07398e2011-06-16 04:16:24 +00001078 QualType type = LV.getType();
Mike Stump7f79f9b2009-05-29 15:46:01 +00001079 // FIXME: Ignore result?
Chris Lattnerf81557c2008-04-04 18:42:16 +00001080 // FIXME: Are initializers affected by volatile?
Chris Lattner1b726772010-12-02 07:07:26 +00001081 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
1082 // Storing "i32 0" to a zero'd memory location is a noop.
John McCall9d232c82013-03-07 21:37:08 +00001083 return;
Richard Smith0dbe2fb2012-12-21 03:17:28 +00001084 } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
John McCall9d232c82013-03-07 21:37:08 +00001085 return EmitNullInitializationToLValue(LV);
John McCalla07398e2011-06-16 04:16:24 +00001086 } else if (type->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +00001087 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
John McCall9d232c82013-03-07 21:37:08 +00001088 return CGF.EmitStoreThroughLValue(RV, LV);
1089 }
1090
1091 switch (CGF.getEvaluationKind(type)) {
1092 case TEK_Complex:
1093 CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1094 return;
1095 case TEK_Aggregate:
John McCall7c2349b2011-08-25 20:40:09 +00001096 CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
1097 AggValueSlot::IsDestructed,
1098 AggValueSlot::DoesNotNeedGCBarriers,
John McCall410ffb22011-08-25 23:04:34 +00001099 AggValueSlot::IsNotAliased,
John McCalla07398e2011-06-16 04:16:24 +00001100 Dest.isZeroed()));
John McCall9d232c82013-03-07 21:37:08 +00001101 return;
1102 case TEK_Scalar:
1103 if (LV.isSimple()) {
1104 CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
1105 } else {
1106 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1107 }
1108 return;
Chris Lattnerf81557c2008-04-04 18:42:16 +00001109 }
John McCall9d232c82013-03-07 21:37:08 +00001110 llvm_unreachable("bad evaluation kind");
Chris Lattnerf81557c2008-04-04 18:42:16 +00001111}
1112
John McCalla07398e2011-06-16 04:16:24 +00001113void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1114 QualType type = lv.getType();
1115
Chris Lattner1b726772010-12-02 07:07:26 +00001116 // If the destination slot is already zeroed out before the aggregate is
1117 // copied into it, we don't have to emit any zeros here.
John McCalla07398e2011-06-16 04:16:24 +00001118 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
Chris Lattner1b726772010-12-02 07:07:26 +00001119 return;
1120
John McCall9d232c82013-03-07 21:37:08 +00001121 if (CGF.hasScalarEvaluationKind(type)) {
Richard Smith0dbe2fb2012-12-21 03:17:28 +00001122 // For non-aggregates, we can store the appropriate null constant.
1123 llvm::Value *null = CGF.CGM.EmitNullConstant(type);
Eli Friedmanb1e3f322012-02-22 05:38:59 +00001124 // Note that the following is not equivalent to
1125 // EmitStoreThroughBitfieldLValue for ARC types.
Eli Friedman5a13d4d2012-02-24 23:53:49 +00001126 if (lv.isBitField()) {
Eli Friedmanb1e3f322012-02-22 05:38:59 +00001127 CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
Eli Friedman5a13d4d2012-02-24 23:53:49 +00001128 } else {
1129 assert(lv.isSimple());
1130 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1131 }
Lauro Ramos Venancio145cd892008-02-19 19:27:31 +00001132 } else {
Chris Lattnerf81557c2008-04-04 18:42:16 +00001133 // There's a potential optimization opportunity in combining
1134 // memsets; that would be easy for arrays, but relatively
1135 // difficult for structures with the current code.
John McCalla07398e2011-06-16 04:16:24 +00001136 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
Chris Lattnerf81557c2008-04-04 18:42:16 +00001137 }
1138}
1139
Chris Lattnerf81557c2008-04-04 18:42:16 +00001140void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
Eli Friedmana385b3c2008-12-02 01:17:45 +00001141#if 0
Eli Friedman13a5be12009-12-04 01:30:56 +00001142 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
1143 // (Length of globals? Chunks of zeroed-out space?).
Eli Friedmana385b3c2008-12-02 01:17:45 +00001144 //
Mike Stumpf5408fe2009-05-16 07:57:57 +00001145 // If we can, prefer a copy from a global; this is a lot less code for long
1146 // globals, and it's easier for the current optimizers to analyze.
Eli Friedman13a5be12009-12-04 01:30:56 +00001147 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
Eli Friedman994ffef2008-11-30 02:11:09 +00001148 llvm::GlobalVariable* GV =
Eli Friedman13a5be12009-12-04 01:30:56 +00001149 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1150 llvm::GlobalValue::InternalLinkage, C, "");
John McCalle0c11682012-07-02 23:58:38 +00001151 EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
Eli Friedman994ffef2008-11-30 02:11:09 +00001152 return;
1153 }
Eli Friedmana385b3c2008-12-02 01:17:45 +00001154#endif
Chris Lattnerd0db03a2010-09-06 00:11:41 +00001155 if (E->hadArrayRangeDesignator())
Douglas Gregora9c87802009-01-29 19:42:23 +00001156 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Douglas Gregora9c87802009-01-29 19:42:23 +00001157
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001158 if (E->initializesStdInitializerList()) {
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001159 EmitStdInitializerList(Dest.getAddr(), E);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001160 return;
1161 }
1162
Eli Friedman377ecc72012-04-16 03:54:45 +00001163 AggValueSlot Dest = EnsureSlot(E->getType());
1164 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
1165 Dest.getAlignment());
John McCall558d2ab2010-09-15 10:14:12 +00001166
Chris Lattnerf81557c2008-04-04 18:42:16 +00001167 // Handle initialization of an array.
1168 if (E->getType()->isArrayType()) {
Richard Smithfe587202012-04-15 02:50:59 +00001169 if (E->isStringLiteralInit())
1170 return Visit(E->getInit(0));
Eli Friedman922696f2008-05-19 17:51:16 +00001171
Eli Friedman5c89c392012-02-23 02:25:10 +00001172 QualType elementType =
1173 CGF.getContext().getAsArrayType(E->getType())->getElementType();
Argyrios Kyrtzidis3b4d4902011-04-28 18:53:58 +00001174
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001175 llvm::PointerType *APType =
Eli Friedman377ecc72012-04-16 03:54:45 +00001176 cast<llvm::PointerType>(Dest.getAddr()->getType());
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001177 llvm::ArrayType *AType =
1178 cast<llvm::ArrayType>(APType->getElementType());
Chris Lattner1b726772010-12-02 07:07:26 +00001179
Eli Friedman377ecc72012-04-16 03:54:45 +00001180 EmitArrayInit(Dest.getAddr(), AType, elementType, E);
Chris Lattnerf81557c2008-04-04 18:42:16 +00001181 return;
1182 }
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Chris Lattnerf81557c2008-04-04 18:42:16 +00001184 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Chris Lattnerf81557c2008-04-04 18:42:16 +00001186 // Do struct initialization; this code just sets each individual member
1187 // to the approprate value. This makes bitfield support automatic;
1188 // the disadvantage is that the generated code is more difficult for
1189 // the optimizer, especially with bitfields.
1190 unsigned NumInitElements = E->getNumInits();
John McCall2b30dcf2011-07-11 19:35:02 +00001191 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
Chris Lattnerbd7de382010-09-06 00:13:11 +00001192
John McCall2b30dcf2011-07-11 19:35:02 +00001193 if (record->isUnion()) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001194 // Only initialize one field of a union. The field itself is
1195 // specified by the initializer list.
1196 if (!E->getInitializedFieldInUnion()) {
1197 // Empty union; we have nothing to do.
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Douglas Gregor0bb76892009-01-29 16:53:55 +00001199#ifndef NDEBUG
1200 // Make sure that it's really an empty and not a failure of
1201 // semantic analysis.
John McCall2b30dcf2011-07-11 19:35:02 +00001202 for (RecordDecl::field_iterator Field = record->field_begin(),
1203 FieldEnd = record->field_end();
Douglas Gregor0bb76892009-01-29 16:53:55 +00001204 Field != FieldEnd; ++Field)
1205 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1206#endif
1207 return;
1208 }
1209
1210 // FIXME: volatility
1211 FieldDecl *Field = E->getInitializedFieldInUnion();
Douglas Gregor0bb76892009-01-29 16:53:55 +00001212
Eli Friedman377ecc72012-04-16 03:54:45 +00001213 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001214 if (NumInitElements) {
1215 // Store the initializer into the field
Chad Rosier649b4a12012-03-29 17:37:10 +00001216 EmitInitializationToLValue(E->getInit(0), FieldLoc);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001217 } else {
Chris Lattner1b726772010-12-02 07:07:26 +00001218 // Default-initialize to null.
John McCalla07398e2011-06-16 04:16:24 +00001219 EmitNullInitializationToLValue(FieldLoc);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001220 }
1221
1222 return;
1223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
John McCall2b30dcf2011-07-11 19:35:02 +00001225 // We'll need to enter cleanup scopes in case any of the member
1226 // initializers throw an exception.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001227 SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
John McCall6f103ba2011-11-10 10:43:54 +00001228 llvm::Instruction *cleanupDominator = 0;
John McCall2b30dcf2011-07-11 19:35:02 +00001229
Chris Lattnerf81557c2008-04-04 18:42:16 +00001230 // Here we iterate over the fields; this makes it simpler to both
1231 // default-initialize fields and skip over unnamed fields.
John McCall2b30dcf2011-07-11 19:35:02 +00001232 unsigned curInitIndex = 0;
1233 for (RecordDecl::field_iterator field = record->field_begin(),
1234 fieldEnd = record->field_end();
1235 field != fieldEnd; ++field) {
1236 // We're done once we hit the flexible array member.
1237 if (field->getType()->isIncompleteArrayType())
Douglas Gregor44b43212008-12-11 16:49:14 +00001238 break;
1239
John McCall2b30dcf2011-07-11 19:35:02 +00001240 // Always skip anonymous bitfields.
1241 if (field->isUnnamedBitfield())
Chris Lattnerf81557c2008-04-04 18:42:16 +00001242 continue;
Douglas Gregor34e79462009-01-28 23:36:17 +00001243
John McCall2b30dcf2011-07-11 19:35:02 +00001244 // We're done if we reach the end of the explicit initializers, we
1245 // have a zeroed object, and the rest of the fields are
1246 // zero-initializable.
1247 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
Chris Lattner1b726772010-12-02 07:07:26 +00001248 CGF.getTypes().isZeroInitializable(E->getType()))
1249 break;
1250
Eli Friedman377ecc72012-04-16 03:54:45 +00001251
David Blaikie581deb32012-06-06 20:45:41 +00001252 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, *field);
Fariborz Jahanian14674ff2009-05-27 19:54:11 +00001253 // We never generate write-barries for initialized fields.
John McCall2b30dcf2011-07-11 19:35:02 +00001254 LV.setNonGC(true);
Chris Lattner1b726772010-12-02 07:07:26 +00001255
John McCall2b30dcf2011-07-11 19:35:02 +00001256 if (curInitIndex < NumInitElements) {
Chris Lattnerb35baae2010-03-08 21:08:07 +00001257 // Store the initializer into the field.
Chad Rosier649b4a12012-03-29 17:37:10 +00001258 EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
Chris Lattnerf81557c2008-04-04 18:42:16 +00001259 } else {
1260 // We're out of initalizers; default-initialize to null
John McCall2b30dcf2011-07-11 19:35:02 +00001261 EmitNullInitializationToLValue(LV);
1262 }
1263
1264 // Push a destructor if necessary.
1265 // FIXME: if we have an array of structures, all explicitly
1266 // initialized, we can end up pushing a linear number of cleanups.
1267 bool pushedCleanup = false;
1268 if (QualType::DestructionKind dtorKind
1269 = field->getType().isDestructedType()) {
1270 assert(LV.isSimple());
1271 if (CGF.needsEHCleanup(dtorKind)) {
John McCall6f103ba2011-11-10 10:43:54 +00001272 if (!cleanupDominator)
1273 cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1274
John McCall2b30dcf2011-07-11 19:35:02 +00001275 CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1276 CGF.getDestroyer(dtorKind), false);
1277 cleanups.push_back(CGF.EHStack.stable_begin());
1278 pushedCleanup = true;
1279 }
Chris Lattnerf81557c2008-04-04 18:42:16 +00001280 }
Chris Lattner1b726772010-12-02 07:07:26 +00001281
1282 // If the GEP didn't get used because of a dead zero init or something
1283 // else, clean it up for -O0 builds and general tidiness.
John McCall2b30dcf2011-07-11 19:35:02 +00001284 if (!pushedCleanup && LV.isSimple())
Chris Lattner1b726772010-12-02 07:07:26 +00001285 if (llvm::GetElementPtrInst *GEP =
John McCall2b30dcf2011-07-11 19:35:02 +00001286 dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
Chris Lattner1b726772010-12-02 07:07:26 +00001287 if (GEP->use_empty())
1288 GEP->eraseFromParent();
Lauro Ramos Venancio145cd892008-02-19 19:27:31 +00001289 }
John McCall2b30dcf2011-07-11 19:35:02 +00001290
1291 // Deactivate all the partial cleanups in reverse order, which
1292 // generally means popping them.
1293 for (unsigned i = cleanups.size(); i != 0; --i)
John McCall6f103ba2011-11-10 10:43:54 +00001294 CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1295
1296 // Destroy the placeholder if we made one.
1297 if (cleanupDominator)
1298 cleanupDominator->eraseFromParent();
Devang Patel636c3d02007-10-26 17:44:44 +00001299}
1300
Chris Lattneree755f92007-08-21 04:59:27 +00001301//===----------------------------------------------------------------------===//
1302// Entry Points into this File
1303//===----------------------------------------------------------------------===//
1304
Chris Lattner1b726772010-12-02 07:07:26 +00001305/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1306/// non-zero bytes that will be stored when outputting the initializer for the
1307/// specified initializer expression.
Ken Dyck02c45332011-04-24 17:17:56 +00001308static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001309 E = E->IgnoreParens();
Chris Lattner1b726772010-12-02 07:07:26 +00001310
1311 // 0 and 0.0 won't require any non-zero stores!
Ken Dyck02c45332011-04-24 17:17:56 +00001312 if (isSimpleZero(E, CGF)) return CharUnits::Zero();
Chris Lattner1b726772010-12-02 07:07:26 +00001313
1314 // If this is an initlist expr, sum up the size of sizes of the (present)
1315 // elements. If this is something weird, assume the whole thing is non-zero.
1316 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
1317 if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
Ken Dyck02c45332011-04-24 17:17:56 +00001318 return CGF.getContext().getTypeSizeInChars(E->getType());
Chris Lattner1b726772010-12-02 07:07:26 +00001319
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001320 // InitListExprs for structs have to be handled carefully. If there are
1321 // reference members, we need to consider the size of the reference, not the
1322 // referencee. InitListExprs for unions and arrays can't have references.
Chris Lattner8c00ad12010-12-02 22:52:04 +00001323 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1324 if (!RT->isUnionType()) {
1325 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
Ken Dyck02c45332011-04-24 17:17:56 +00001326 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner8c00ad12010-12-02 22:52:04 +00001327
1328 unsigned ILEElement = 0;
1329 for (RecordDecl::field_iterator Field = SD->field_begin(),
1330 FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
1331 // We're done once we hit the flexible array member or run out of
1332 // InitListExpr elements.
1333 if (Field->getType()->isIncompleteArrayType() ||
1334 ILEElement == ILE->getNumInits())
1335 break;
1336 if (Field->isUnnamedBitfield())
1337 continue;
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001338
Chris Lattner8c00ad12010-12-02 22:52:04 +00001339 const Expr *E = ILE->getInit(ILEElement++);
1340
1341 // Reference values are always non-null and have the width of a pointer.
1342 if (Field->getType()->isReferenceType())
Ken Dyck02c45332011-04-24 17:17:56 +00001343 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001344 CGF.getContext().getTargetInfo().getPointerWidth(0));
Chris Lattner8c00ad12010-12-02 22:52:04 +00001345 else
1346 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1347 }
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001348
Chris Lattner8c00ad12010-12-02 22:52:04 +00001349 return NumNonZeroBytes;
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001350 }
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001351 }
1352
1353
Ken Dyck02c45332011-04-24 17:17:56 +00001354 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner1b726772010-12-02 07:07:26 +00001355 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1356 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1357 return NumNonZeroBytes;
1358}
1359
1360/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1361/// zeros in it, emit a memset and avoid storing the individual zeros.
1362///
1363static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1364 CodeGenFunction &CGF) {
1365 // If the slot is already known to be zeroed, nothing to do. Don't mess with
1366 // volatile stores.
1367 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +00001368
1369 // C++ objects with a user-declared constructor don't need zero'ing.
Richard Smith7edf9e32012-11-01 22:30:59 +00001370 if (CGF.getLangOpts().CPlusPlus)
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +00001371 if (const RecordType *RT = CGF.getContext()
1372 .getBaseElementType(E->getType())->getAs<RecordType>()) {
1373 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1374 if (RD->hasUserDeclaredConstructor())
1375 return;
1376 }
1377
Chris Lattner1b726772010-12-02 07:07:26 +00001378 // If the type is 16-bytes or smaller, prefer individual stores over memset.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001379 std::pair<CharUnits, CharUnits> TypeInfo =
1380 CGF.getContext().getTypeInfoInChars(E->getType());
1381 if (TypeInfo.first <= CharUnits::fromQuantity(16))
Chris Lattner1b726772010-12-02 07:07:26 +00001382 return;
1383
1384 // Check to see if over 3/4 of the initializer are known to be zero. If so,
1385 // we prefer to emit memset + individual stores for the rest.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001386 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1387 if (NumNonZeroBytes*4 > TypeInfo.first)
Chris Lattner1b726772010-12-02 07:07:26 +00001388 return;
1389
1390 // Okay, it seems like a good idea to use an initial memset, emit the call.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001391 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1392 CharUnits Align = TypeInfo.second;
Chris Lattner1b726772010-12-02 07:07:26 +00001393
1394 llvm::Value *Loc = Slot.getAddr();
Chris Lattner1b726772010-12-02 07:07:26 +00001395
Chris Lattner8b418682012-02-07 00:39:47 +00001396 Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
Ken Dyck5ff1a352011-04-24 17:25:32 +00001397 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1398 Align.getQuantity(), false);
Chris Lattner1b726772010-12-02 07:07:26 +00001399
1400 // Tell the AggExprEmitter that the slot is known zero.
1401 Slot.setZeroed();
1402}
1403
1404
1405
1406
Mike Stumpe1129a92009-05-26 18:57:45 +00001407/// EmitAggExpr - Emit the computation of the specified expression of aggregate
1408/// type. The result is computed into DestPtr. Note that if DestPtr is null,
1409/// the value of the aggregate expression is not needed. If VolatileDest is
1410/// true, DestPtr cannot be 0.
John McCalle0c11682012-07-02 23:58:38 +00001411void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
John McCall9d232c82013-03-07 21:37:08 +00001412 assert(E && hasAggregateEvaluationKind(E->getType()) &&
Chris Lattneree755f92007-08-21 04:59:27 +00001413 "Invalid aggregate expression to emit");
Chris Lattner1b726772010-12-02 07:07:26 +00001414 assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
1415 "slot has bits but no address");
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Chris Lattner1b726772010-12-02 07:07:26 +00001417 // Optimize the slot if possible.
1418 CheckAggExprForMemSetUse(Slot, E, *this);
1419
John McCalle0c11682012-07-02 23:58:38 +00001420 AggExprEmitter(*this, Slot).Visit(const_cast<Expr*>(E));
Chris Lattneree755f92007-08-21 04:59:27 +00001421}
Daniel Dunbar7482d122008-09-09 20:49:46 +00001422
Daniel Dunbar18aba0d2010-02-05 19:38:31 +00001423LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
John McCall9d232c82013-03-07 21:37:08 +00001424 assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
Daniel Dunbar195337d2010-02-09 02:48:28 +00001425 llvm::Value *Temp = CreateMemTemp(E->getType());
Daniel Dunbar79c39282010-08-21 03:15:20 +00001426 LValue LV = MakeAddrLValue(Temp, E->getType());
John McCall7c2349b2011-08-25 20:40:09 +00001427 EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
John McCall44184392011-08-26 07:31:35 +00001428 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001429 AggValueSlot::IsNotAliased));
Daniel Dunbar79c39282010-08-21 03:15:20 +00001430 return LV;
Daniel Dunbar18aba0d2010-02-05 19:38:31 +00001431}
1432
Chad Rosier649b4a12012-03-29 17:37:10 +00001433void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1434 llvm::Value *SrcPtr, QualType Ty,
John McCalle0c11682012-07-02 23:58:38 +00001435 bool isVolatile,
Benjamin Kramer6cacae82012-09-30 12:43:37 +00001436 CharUnits alignment,
1437 bool isAssignment) {
Chad Rosier649b4a12012-03-29 17:37:10 +00001438 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Richard Smith7edf9e32012-11-01 22:30:59 +00001440 if (getLangOpts().CPlusPlus) {
Chad Rosier649b4a12012-03-29 17:37:10 +00001441 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1442 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1443 assert((Record->hasTrivialCopyConstructor() ||
1444 Record->hasTrivialCopyAssignment() ||
1445 Record->hasTrivialMoveConstructor() ||
1446 Record->hasTrivialMoveAssignment()) &&
Richard Smith426391c2012-11-16 00:53:38 +00001447 "Trying to aggregate-copy a type without a trivial copy/move "
Douglas Gregore9979482010-05-20 15:39:01 +00001448 "constructor or assignment operator");
Chad Rosier649b4a12012-03-29 17:37:10 +00001449 // Ignore empty classes in C++.
1450 if (Record->isEmpty())
Anders Carlsson0d7c5832010-05-03 01:20:20 +00001451 return;
1452 }
1453 }
1454
Chris Lattner83c96292009-02-28 18:31:01 +00001455 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
Chris Lattnerca4fc2c2009-02-28 18:18:58 +00001456 // C99 6.5.16.1p3, which states "If the value being stored in an object is
1457 // read from another object that overlaps in anyway the storage of the first
1458 // object, then the overlap shall be exact and the two objects shall have
1459 // qualified or unqualified versions of a compatible type."
1460 //
Chris Lattner83c96292009-02-28 18:31:01 +00001461 // memcpy is not defined if the source and destination pointers are exactly
Chris Lattnerca4fc2c2009-02-28 18:18:58 +00001462 // equal, but other compilers do this optimization, and almost every memcpy
1463 // implementation handles this case safely. If there is a libc that does not
1464 // safely handle this, we can add a target hook.
Chad Rosier649b4a12012-03-29 17:37:10 +00001465
Benjamin Kramer6cacae82012-09-30 12:43:37 +00001466 // Get data size and alignment info for this aggregate. If this is an
1467 // assignment don't copy the tail padding. Otherwise copying it is fine.
1468 std::pair<CharUnits, CharUnits> TypeInfo;
1469 if (isAssignment)
1470 TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
1471 else
1472 TypeInfo = getContext().getTypeInfoInChars(Ty);
Chad Rosier649b4a12012-03-29 17:37:10 +00001473
John McCalle0c11682012-07-02 23:58:38 +00001474 if (alignment.isZero())
1475 alignment = TypeInfo.second;
Chad Rosier649b4a12012-03-29 17:37:10 +00001476
1477 // FIXME: Handle variable sized types.
1478
1479 // FIXME: If we have a volatile struct, the optimizer can remove what might
1480 // appear to be `extra' memory ops:
1481 //
1482 // volatile struct { int i; } a, b;
1483 //
1484 // int main() {
1485 // a = b;
1486 // a = b;
1487 // }
1488 //
1489 // we need to use a different call here. We use isVolatile to indicate when
1490 // either the source or the destination is volatile.
1491
1492 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1493 llvm::Type *DBP =
1494 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1495 DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1496
1497 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1498 llvm::Type *SBP =
1499 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1500 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1501
1502 // Don't do any of the memmove_collectable tests if GC isn't set.
1503 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1504 // fall through
1505 } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1506 RecordDecl *Record = RecordTy->getDecl();
1507 if (Record->hasObjectMember()) {
1508 CharUnits size = TypeInfo.first;
1509 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1510 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
1511 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1512 SizeVal);
1513 return;
1514 }
1515 } else if (Ty->isArrayType()) {
1516 QualType BaseType = getContext().getBaseElementType(Ty);
1517 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1518 if (RecordTy->getDecl()->hasObjectMember()) {
1519 CharUnits size = TypeInfo.first;
1520 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1521 llvm::Value *SizeVal =
1522 llvm::ConstantInt::get(SizeTy, size.getQuantity());
1523 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1524 SizeVal);
1525 return;
1526 }
1527 }
1528 }
Dan Gohmanb22c7dc2012-09-28 21:58:29 +00001529
1530 // Determine the metadata to describe the position of any padding in this
1531 // memcpy, as well as the TBAA tags for the members of the struct, in case
1532 // the optimizer wishes to expand it in to scalar memory operations.
1533 llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty);
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00001534
Chad Rosier649b4a12012-03-29 17:37:10 +00001535 Builder.CreateMemCpy(DestPtr, SrcPtr,
1536 llvm::ConstantInt::get(IntPtrTy,
1537 TypeInfo.first.getQuantity()),
Dan Gohmanb22c7dc2012-09-28 21:58:29 +00001538 alignment.getQuantity(), isVolatile,
1539 /*TBAATag=*/0, TBAAStructTag);
Daniel Dunbar7482d122008-09-09 20:49:46 +00001540}
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001541
Sebastian Redl972edf02012-02-19 16:03:09 +00001542void CodeGenFunction::MaybeEmitStdInitializerListCleanup(llvm::Value *loc,
1543 const Expr *init) {
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001544 const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(init);
Sebastian Redl972edf02012-02-19 16:03:09 +00001545 if (cleanups)
1546 init = cleanups->getSubExpr();
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001547
1548 if (isa<InitListExpr>(init) &&
1549 cast<InitListExpr>(init)->initializesStdInitializerList()) {
1550 // We initialized this std::initializer_list with an initializer list.
1551 // A backing array was created. Push a cleanup for it.
Sebastian Redl972edf02012-02-19 16:03:09 +00001552 EmitStdInitializerListCleanup(loc, cast<InitListExpr>(init));
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001553 }
1554}
1555
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001556static void EmitRecursiveStdInitializerListCleanup(CodeGenFunction &CGF,
1557 llvm::Value *arrayStart,
1558 const InitListExpr *init) {
1559 // Check if there are any recursive cleanups to do, i.e. if we have
1560 // std::initializer_list<std::initializer_list<obj>> list = {{obj()}};
1561 // then we need to destroy the inner array as well.
1562 for (unsigned i = 0, e = init->getNumInits(); i != e; ++i) {
1563 const InitListExpr *subInit = dyn_cast<InitListExpr>(init->getInit(i));
1564 if (!subInit || !subInit->initializesStdInitializerList())
1565 continue;
1566
1567 // This one needs to be destroyed. Get the address of the std::init_list.
1568 llvm::Value *offset = llvm::ConstantInt::get(CGF.SizeTy, i);
1569 llvm::Value *loc = CGF.Builder.CreateInBoundsGEP(arrayStart, offset,
1570 "std.initlist");
1571 CGF.EmitStdInitializerListCleanup(loc, subInit);
1572 }
1573}
1574
1575void CodeGenFunction::EmitStdInitializerListCleanup(llvm::Value *loc,
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001576 const InitListExpr *init) {
1577 ASTContext &ctx = getContext();
1578 QualType element = GetStdInitializerListElementType(init->getType());
1579 unsigned numInits = init->getNumInits();
1580 llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
1581 QualType array =ctx.getConstantArrayType(element, size, ArrayType::Normal, 0);
1582 QualType arrayPtr = ctx.getPointerType(array);
1583 llvm::Type *arrayPtrType = ConvertType(arrayPtr);
1584
1585 // lvalue is the location of a std::initializer_list, which as its first
1586 // element has a pointer to the array we want to destroy.
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001587 llvm::Value *startPointer = Builder.CreateStructGEP(loc, 0, "startPointer");
1588 llvm::Value *startAddress = Builder.CreateLoad(startPointer, "startAddress");
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001589
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001590 ::EmitRecursiveStdInitializerListCleanup(*this, startAddress, init);
1591
1592 llvm::Value *arrayAddress =
1593 Builder.CreateBitCast(startAddress, arrayPtrType, "arrayAddress");
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001594 ::EmitStdInitializerListCleanup(*this, array, arrayAddress, init);
1595}