blob: 8f0d1db353640ff4896668ae4b93766a580e5444 [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"
Chris Lattner883f6a72007-08-11 00:04:45 +000015#include "CodeGenModule.h"
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000016#include "CGObjCRuntime.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"
Chris Lattner883f6a72007-08-11 00:04:45 +000021#include "llvm/Constants.h"
22#include "llvm/Function.h"
Devang Patel636c3d02007-10-26 17:44:44 +000023#include "llvm/GlobalVariable.h"
Chris Lattnerf81557c2008-04-04 18:42:16 +000024#include "llvm/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
32namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000033class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
Chris Lattner9c033562007-08-21 04:25:47 +000034 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000035 CGBuilderTy &Builder;
John McCall558d2ab2010-09-15 10:14:12 +000036 AggValueSlot Dest;
Mike Stump49d1cd52009-05-26 22:03:21 +000037 bool IgnoreResult;
John McCallef072fd2010-05-22 01:48:05 +000038
John McCall410ffb22011-08-25 23:04:34 +000039 /// We want to use 'dest' as the return slot except under two
40 /// conditions:
41 /// - The destination slot requires garbage collection, so we
42 /// need to use the GC API.
43 /// - The destination slot is potentially aliased.
44 bool shouldUseDestForReturnSlot() const {
45 return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
46 }
47
John McCallef072fd2010-05-22 01:48:05 +000048 ReturnValueSlot getReturnValueSlot() const {
John McCall410ffb22011-08-25 23:04:34 +000049 if (!shouldUseDestForReturnSlot())
50 return ReturnValueSlot();
John McCallfa037bd2010-05-22 22:13:32 +000051
John McCall558d2ab2010-09-15 10:14:12 +000052 return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
53 }
54
55 AggValueSlot EnsureSlot(QualType T) {
56 if (!Dest.isIgnored()) return Dest;
57 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
John McCallef072fd2010-05-22 01:48:05 +000058 }
John McCallfa037bd2010-05-22 22:13:32 +000059
Chris Lattner9c033562007-08-21 04:25:47 +000060public:
John McCall558d2ab2010-09-15 10:14:12 +000061 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest,
Fariborz Jahanian474e2fe2010-09-16 00:20:07 +000062 bool ignore)
John McCall558d2ab2010-09-15 10:14:12 +000063 : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
Fariborz Jahanian474e2fe2010-09-16 00:20:07 +000064 IgnoreResult(ignore) {
Chris Lattner9c033562007-08-21 04:25:47 +000065 }
66
Chris Lattneree755f92007-08-21 04:59:27 +000067 //===--------------------------------------------------------------------===//
68 // Utilities
69 //===--------------------------------------------------------------------===//
70
Chris Lattner9c033562007-08-21 04:25:47 +000071 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
72 /// represents a value lvalue, this method emits the address of the lvalue,
73 /// then loads the result into DestPtr.
74 void EmitAggLoadOfLValue(const Expr *E);
Eli Friedman922696f2008-05-19 17:51:16 +000075
Mike Stump4ac20dd2009-05-23 20:28:01 +000076 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
Mike Stump49d1cd52009-05-26 22:03:21 +000077 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
Eli Friedmanbd7d8282011-12-05 22:23:28 +000078 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false,
79 unsigned Alignment = 0);
Mike Stump4ac20dd2009-05-23 20:28:01 +000080
John McCall410ffb22011-08-25 23:04:34 +000081 void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
John McCallfa037bd2010-05-22 22:13:32 +000082
Sebastian Redlaf130fd2012-02-19 12:28:02 +000083 void EmitStdInitializerList(llvm::Value *DestPtr, InitListExpr *InitList);
Sebastian Redl32cf1f22012-02-17 08:42:25 +000084 void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
85 QualType elementType, InitListExpr *E);
86
John McCall7c2349b2011-08-25 20:40:09 +000087 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
David Blaikie4e4d0842012-03-11 07:00:24 +000088 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
John McCall7c2349b2011-08-25 20:40:09 +000089 return AggValueSlot::NeedsGCBarriers;
90 return AggValueSlot::DoesNotNeedGCBarriers;
91 }
92
John McCallfa037bd2010-05-22 22:13:32 +000093 bool TypeRequiresGCollection(QualType T);
94
Chris Lattneree755f92007-08-21 04:59:27 +000095 //===--------------------------------------------------------------------===//
96 // Visitor Methods
97 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +000098
Chris Lattner9c033562007-08-21 04:25:47 +000099 void VisitStmt(Stmt *S) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000100 CGF.ErrorUnsupported(S, "aggregate expression");
Chris Lattner9c033562007-08-21 04:25:47 +0000101 }
102 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000103 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
104 Visit(GE->getResultExpr());
105 }
Eli Friedman12444a22009-01-27 09:03:41 +0000106 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
John McCall91a57552011-07-15 05:09:51 +0000107 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
108 return Visit(E->getReplacement());
109 }
Chris Lattner9c033562007-08-21 04:25:47 +0000110
111 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000112 void VisitDeclRefExpr(DeclRefExpr *E) {
John McCalldd2ecee2012-03-10 03:05:10 +0000113 // For aggregates, we should always be able to emit the variable
114 // as an l-value unless it's a reference. This is due to the fact
115 // that we can't actually ever see a normal l2r conversion on an
116 // aggregate in C++, and in C there's no language standard
117 // actively preventing us from listing variables in the captures
118 // list of a block.
John McCallf4b88a42012-03-10 09:33:50 +0000119 if (E->getDecl()->getType()->isReferenceType()) {
John McCalldd2ecee2012-03-10 03:05:10 +0000120 if (CodeGenFunction::ConstantEmission result
John McCallf4b88a42012-03-10 09:33:50 +0000121 = CGF.tryEmitAsConstant(E)) {
122 EmitFinalDestCopy(E, result.getReferenceLValue(CGF, E));
John McCalldd2ecee2012-03-10 03:05:10 +0000123 return;
124 }
125 }
126
John McCallf4b88a42012-03-10 09:33:50 +0000127 EmitAggLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000128 }
129
Seo Sanghyeon9b73b392007-12-14 02:04:12 +0000130 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
131 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
Daniel Dunbar5be028f2010-01-04 18:47:06 +0000132 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000133 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Seo Sanghyeon9b73b392007-12-14 02:04:12 +0000134 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
135 EmitAggLoadOfLValue(E);
136 }
Chris Lattnerf0a990c2009-04-21 23:00:09 +0000137 void VisitPredefinedExpr(const PredefinedExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000138 EmitAggLoadOfLValue(E);
Chris Lattnerf0a990c2009-04-21 23:00:09 +0000139 }
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Chris Lattner9c033562007-08-21 04:25:47 +0000141 // Operators.
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000142 void VisitCastExpr(CastExpr *E);
Anders Carlsson148fe672007-10-31 22:04:46 +0000143 void VisitCallExpr(const CallExpr *E);
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000144 void VisitStmtExpr(const StmtExpr *E);
Chris Lattner9c033562007-08-21 04:25:47 +0000145 void VisitBinaryOperator(const BinaryOperator *BO);
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +0000146 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
Chris Lattner03d6fb92007-08-21 04:43:17 +0000147 void VisitBinAssign(const BinaryOperator *E);
Eli Friedman07fa52a2008-05-20 07:56:31 +0000148 void VisitBinComma(const BinaryOperator *E);
Chris Lattner9c033562007-08-21 04:25:47 +0000149
Chris Lattner8fdf3282008-06-24 17:04:18 +0000150 void VisitObjCMessageExpr(ObjCMessageExpr *E);
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000151 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
152 EmitAggLoadOfLValue(E);
153 }
Mike Stump1eb44332009-09-09 15:08:12 +0000154
John McCall56ca35d2011-02-17 10:25:35 +0000155 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
Anders Carlssona294ca82009-07-08 18:33:14 +0000156 void VisitChooseExpr(const ChooseExpr *CE);
Devang Patel636c3d02007-10-26 17:44:44 +0000157 void VisitInitListExpr(InitListExpr *E);
Anders Carlsson30311fa2009-12-16 06:57:54 +0000158 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
Chris Lattner04421082008-04-08 04:40:51 +0000159 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
160 Visit(DAE->getExpr());
161 }
Anders Carlssonb58d0172009-05-30 23:23:33 +0000162 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
Anders Carlsson31ccf372009-05-03 17:47:16 +0000163 void VisitCXXConstructExpr(const CXXConstructExpr *E);
Eli Friedman4c5d8af2012-02-09 03:32:31 +0000164 void VisitLambdaExpr(LambdaExpr *E);
John McCall4765fa02010-12-06 08:20:24 +0000165 void VisitExprWithCleanups(ExprWithCleanups *E);
Douglas Gregored8abf12010-07-08 06:14:04 +0000166 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Mike Stump2710c412009-11-18 00:40:12 +0000167 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor03e80032011-06-21 17:03:29 +0000168 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
John McCalle996ffd2011-02-16 08:02:54 +0000169 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
170
John McCall4b9c2d22011-11-06 09:01:30 +0000171 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
172 if (E->isGLValue()) {
173 LValue LV = CGF.EmitPseudoObjectLValue(E);
174 return EmitFinalDestCopy(E, LV);
175 }
176
177 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
178 }
179
Eli Friedmanb1851242008-05-27 15:51:49 +0000180 void VisitVAArgExpr(VAArgExpr *E);
Chris Lattnerf81557c2008-04-04 18:42:16 +0000181
John McCall57cd1b82012-03-28 23:30:44 +0000182 void EmitInitializationToLValue(Expr *E, LValue Address,
183 AggValueSlot::IsCompleteObject_t isCompleteObject);
John McCalla07398e2011-06-16 04:16:24 +0000184 void EmitNullInitializationToLValue(LValue Address);
Chris Lattner9c033562007-08-21 04:25:47 +0000185 // case Expr::ChooseExprClass:
Mike Stump39406b12009-12-09 19:24:08 +0000186 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
Eli Friedman276b0612011-10-11 02:20:01 +0000187 void VisitAtomicExpr(AtomicExpr *E) {
188 CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
189 }
Chris Lattner9c033562007-08-21 04:25:47 +0000190};
191} // end anonymous namespace.
192
Chris Lattneree755f92007-08-21 04:59:27 +0000193//===----------------------------------------------------------------------===//
194// Utilities
195//===----------------------------------------------------------------------===//
Chris Lattner9c033562007-08-21 04:25:47 +0000196
Chris Lattner883f6a72007-08-11 00:04:45 +0000197/// EmitAggLoadOfLValue - Given an expression with aggregate type that
198/// represents a value lvalue, this method emits the address of the lvalue,
199/// then loads the result into DestPtr.
Chris Lattner9c033562007-08-21 04:25:47 +0000200void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
201 LValue LV = CGF.EmitLValue(E);
Mike Stump4ac20dd2009-05-23 20:28:01 +0000202 EmitFinalDestCopy(E, LV);
203}
204
John McCallfa037bd2010-05-22 22:13:32 +0000205/// \brief True if the given aggregate type requires special GC API calls.
206bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
207 // Only record types have members that might require garbage collection.
208 const RecordType *RecordTy = T->getAs<RecordType>();
209 if (!RecordTy) return false;
210
211 // Don't mess with non-trivial C++ types.
212 RecordDecl *Record = RecordTy->getDecl();
213 if (isa<CXXRecordDecl>(Record) &&
214 (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
215 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
216 return false;
217
218 // Check whether the type has an object member.
219 return Record->hasObjectMember();
220}
221
John McCall410ffb22011-08-25 23:04:34 +0000222/// \brief Perform the final move to DestPtr if for some reason
223/// getReturnValueSlot() didn't use it directly.
John McCallfa037bd2010-05-22 22:13:32 +0000224///
225/// The idea is that you do something like this:
226/// RValue Result = EmitSomething(..., getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000227/// EmitMoveFromReturnSlot(E, Result);
228///
229/// If nothing interferes, this will cause the result to be emitted
230/// directly into the return value slot. Otherwise, a final move
231/// will be performed.
232void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue Src) {
233 if (shouldUseDestForReturnSlot()) {
234 // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
235 // The possibility of undef rvalues complicates that a lot,
236 // though, so we can't really assert.
237 return;
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000238 }
John McCall410ffb22011-08-25 23:04:34 +0000239
240 // Otherwise, do a final copy,
241 assert(Dest.getAddr() != Src.getAggregateAddr());
242 EmitFinalDestCopy(E, Src, /*Ignore*/ true);
John McCallfa037bd2010-05-22 22:13:32 +0000243}
244
Mike Stump4ac20dd2009-05-23 20:28:01 +0000245/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
Eli Friedmanbd7d8282011-12-05 22:23:28 +0000246void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore,
247 unsigned Alignment) {
Mike Stump4ac20dd2009-05-23 20:28:01 +0000248 assert(Src.isAggregate() && "value must be aggregate value!");
249
John McCall558d2ab2010-09-15 10:14:12 +0000250 // If Dest is ignored, then we're evaluating an aggregate expression
John McCalla8f28da2010-08-25 02:50:31 +0000251 // in a context (like an expression statement) that doesn't care
252 // about the result. C says that an lvalue-to-rvalue conversion is
253 // performed in these cases; C++ says that it is not. In either
254 // case, we don't actually need to do anything unless the value is
255 // volatile.
John McCall558d2ab2010-09-15 10:14:12 +0000256 if (Dest.isIgnored()) {
John McCalla8f28da2010-08-25 02:50:31 +0000257 if (!Src.isVolatileQualified() ||
David Blaikie4e4d0842012-03-11 07:00:24 +0000258 CGF.CGM.getLangOpts().CPlusPlus ||
John McCalla8f28da2010-08-25 02:50:31 +0000259 (IgnoreResult && Ignore))
Mike Stump9ccb1032009-05-23 22:01:27 +0000260 return;
Fariborz Jahanian8a970052010-10-22 22:05:03 +0000261
Mike Stump49d1cd52009-05-26 22:03:21 +0000262 // If the source is volatile, we must read from it; to do that, we need
263 // some place to put it.
John McCall558d2ab2010-09-15 10:14:12 +0000264 Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
Mike Stump9ccb1032009-05-23 22:01:27 +0000265 }
Chris Lattner883f6a72007-08-11 00:04:45 +0000266
John McCalld1a5f132010-09-16 03:13:23 +0000267 if (Dest.requiresGCollection()) {
Ken Dyck479b61c2011-04-24 17:08:00 +0000268 CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
Chris Lattner2acc6e32011-07-18 04:24:23 +0000269 llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
Ken Dyck479b61c2011-04-24 17:08:00 +0000270 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
Fariborz Jahanian08c32132009-08-31 19:33:16 +0000271 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
John McCall558d2ab2010-09-15 10:14:12 +0000272 Dest.getAddr(),
273 Src.getAggregateAddr(),
274 SizeVal);
Fariborz Jahanian08c32132009-08-31 19:33:16 +0000275 return;
276 }
Mike Stump4ac20dd2009-05-23 20:28:01 +0000277 // If the result of the assignment is used, copy the LHS there also.
278 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile
279 // from the source as well, as we can't eliminate it if either operand
280 // is volatile, unless copy has volatile for both source and destination..
John McCall558d2ab2010-09-15 10:14:12 +0000281 CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
Eli Friedmanbd7d8282011-12-05 22:23:28 +0000282 Dest.isVolatile()|Src.isVolatileQualified(),
John McCall57cd1b82012-03-28 23:30:44 +0000283 Alignment, Dest.isCompleteObject());
Mike Stump4ac20dd2009-05-23 20:28:01 +0000284}
285
286/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
Mike Stump49d1cd52009-05-26 22:03:21 +0000287void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
Mike Stump4ac20dd2009-05-23 20:28:01 +0000288 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
289
Eli Friedmanbd7d8282011-12-05 22:23:28 +0000290 CharUnits Alignment = std::min(Src.getAlignment(), Dest.getAlignment());
291 EmitFinalDestCopy(E, Src.asAggregateRValue(), Ignore, Alignment.getQuantity());
Chris Lattner883f6a72007-08-11 00:04:45 +0000292}
293
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000294static QualType GetStdInitializerListElementType(QualType T) {
295 // Just assume that this is really std::initializer_list.
296 ClassTemplateSpecializationDecl *specialization =
297 cast<ClassTemplateSpecializationDecl>(T->castAs<RecordType>()->getDecl());
298 return specialization->getTemplateArgs()[0].getAsType();
299}
300
301/// \brief Prepare cleanup for the temporary array.
302static void EmitStdInitializerListCleanup(CodeGenFunction &CGF,
303 QualType arrayType,
304 llvm::Value *addr,
305 const InitListExpr *initList) {
306 QualType::DestructionKind dtorKind = arrayType.isDestructedType();
307 if (!dtorKind)
308 return; // Type doesn't need destroying.
309 if (dtorKind != QualType::DK_cxx_destructor) {
310 CGF.ErrorUnsupported(initList, "ObjC ARC type in initializer_list");
311 return;
312 }
313
314 CodeGenFunction::Destroyer *destroyer = CGF.getDestroyer(dtorKind);
315 CGF.pushDestroy(NormalAndEHCleanup, addr, arrayType, destroyer,
316 /*EHCleanup=*/true);
317}
318
319/// \brief Emit the initializer for a std::initializer_list initialized with a
320/// real initializer list.
Sebastian Redlaf130fd2012-02-19 12:28:02 +0000321void AggExprEmitter::EmitStdInitializerList(llvm::Value *destPtr,
322 InitListExpr *initList) {
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000323 // We emit an array containing the elements, then have the init list point
324 // at the array.
325 ASTContext &ctx = CGF.getContext();
326 unsigned numInits = initList->getNumInits();
327 QualType element = GetStdInitializerListElementType(initList->getType());
328 llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
329 QualType array = ctx.getConstantArrayType(element, size, ArrayType::Normal,0);
330 llvm::Type *LTy = CGF.ConvertTypeForMem(array);
331 llvm::AllocaInst *alloc = CGF.CreateTempAlloca(LTy);
332 alloc->setAlignment(ctx.getTypeAlignInChars(array).getQuantity());
333 alloc->setName(".initlist.");
334
335 EmitArrayInit(alloc, cast<llvm::ArrayType>(LTy), element, initList);
336
337 // FIXME: The diagnostics are somewhat out of place here.
338 RecordDecl *record = initList->getType()->castAs<RecordType>()->getDecl();
339 RecordDecl::field_iterator field = record->field_begin();
340 if (field == record->field_end()) {
341 CGF.ErrorUnsupported(initList, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000342 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000343 }
344
345 QualType elementPtr = ctx.getPointerType(element.withConst());
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000346
347 // Start pointer.
348 if (!ctx.hasSameType(field->getType(), elementPtr)) {
349 CGF.ErrorUnsupported(initList, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000350 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000351 }
352 LValue start = CGF.EmitLValueForFieldInitialization(destPtr, *field, 0);
353 llvm::Value *arrayStart = Builder.CreateStructGEP(alloc, 0, "arraystart");
354 CGF.EmitStoreThroughLValue(RValue::get(arrayStart), start);
355 ++field;
356
357 if (field == record->field_end()) {
358 CGF.ErrorUnsupported(initList, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000359 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000360 }
361 LValue endOrLength = CGF.EmitLValueForFieldInitialization(destPtr, *field, 0);
362 if (ctx.hasSameType(field->getType(), elementPtr)) {
363 // End pointer.
364 llvm::Value *arrayEnd = Builder.CreateStructGEP(alloc,numInits, "arrayend");
365 CGF.EmitStoreThroughLValue(RValue::get(arrayEnd), endOrLength);
366 } else if(ctx.hasSameType(field->getType(), ctx.getSizeType())) {
367 // Length.
368 CGF.EmitStoreThroughLValue(RValue::get(Builder.getInt(size)), endOrLength);
369 } else {
370 CGF.ErrorUnsupported(initList, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000371 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000372 }
373
374 if (!Dest.isExternallyDestructed())
375 EmitStdInitializerListCleanup(CGF, array, alloc, initList);
376}
377
378/// \brief Emit initialization of an array from an initializer list.
379void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
380 QualType elementType, InitListExpr *E) {
381 uint64_t NumInitElements = E->getNumInits();
382
383 uint64_t NumArrayElements = AType->getNumElements();
384 assert(NumInitElements <= NumArrayElements);
385
386 // DestPtr is an array*. Construct an elementType* by drilling
387 // down a level.
388 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
389 llvm::Value *indices[] = { zero, zero };
390 llvm::Value *begin =
391 Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
392
393 // Exception safety requires us to destroy all the
394 // already-constructed members if an initializer throws.
395 // For that, we'll need an EH cleanup.
396 QualType::DestructionKind dtorKind = elementType.isDestructedType();
397 llvm::AllocaInst *endOfInit = 0;
398 EHScopeStack::stable_iterator cleanup;
399 llvm::Instruction *cleanupDominator = 0;
400 if (CGF.needsEHCleanup(dtorKind)) {
401 // In principle we could tell the cleanup where we are more
402 // directly, but the control flow can get so varied here that it
403 // would actually be quite complex. Therefore we go through an
404 // alloca.
405 endOfInit = CGF.CreateTempAlloca(begin->getType(),
406 "arrayinit.endOfInit");
407 cleanupDominator = Builder.CreateStore(begin, endOfInit);
408 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
409 CGF.getDestroyer(dtorKind));
410 cleanup = CGF.EHStack.stable_begin();
411
412 // Otherwise, remember that we didn't need a cleanup.
413 } else {
414 dtorKind = QualType::DK_none;
415 }
416
417 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
418
419 // The 'current element to initialize'. The invariants on this
420 // variable are complicated. Essentially, after each iteration of
421 // the loop, it points to the last initialized element, except
422 // that it points to the beginning of the array before any
423 // elements have been initialized.
424 llvm::Value *element = begin;
425
426 // Emit the explicit initializers.
427 for (uint64_t i = 0; i != NumInitElements; ++i) {
428 // Advance to the next element.
429 if (i > 0) {
430 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
431
432 // Tell the cleanup that it needs to destroy up to this
433 // element. TODO: some of these stores can be trivially
434 // observed to be unnecessary.
435 if (endOfInit) Builder.CreateStore(element, endOfInit);
436 }
437
Sebastian Redlaf130fd2012-02-19 12:28:02 +0000438 // If these are nested std::initializer_list inits, do them directly,
439 // because they are conceptually the same "location".
440 InitListExpr *initList = dyn_cast<InitListExpr>(E->getInit(i));
441 if (initList && initList->initializesStdInitializerList()) {
442 EmitStdInitializerList(element, initList);
443 } else {
444 LValue elementLV = CGF.MakeAddrLValue(element, elementType);
John McCall57cd1b82012-03-28 23:30:44 +0000445 EmitInitializationToLValue(E->getInit(i), elementLV,
446 AggValueSlot::IsCompleteObject);
Sebastian Redlaf130fd2012-02-19 12:28:02 +0000447 }
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000448 }
449
450 // Check whether there's a non-trivial array-fill expression.
451 // Note that this will be a CXXConstructExpr even if the element
452 // type is an array (or array of array, etc.) of class type.
453 Expr *filler = E->getArrayFiller();
454 bool hasTrivialFiller = true;
455 if (CXXConstructExpr *cons = dyn_cast_or_null<CXXConstructExpr>(filler)) {
456 assert(cons->getConstructor()->isDefaultConstructor());
457 hasTrivialFiller = cons->getConstructor()->isTrivial();
458 }
459
460 // Any remaining elements need to be zero-initialized, possibly
461 // using the filler expression. We can skip this if the we're
462 // emitting to zeroed memory.
463 if (NumInitElements != NumArrayElements &&
464 !(Dest.isZeroed() && hasTrivialFiller &&
465 CGF.getTypes().isZeroInitializable(elementType))) {
466
467 // Use an actual loop. This is basically
468 // do { *array++ = filler; } while (array != end);
469
470 // Advance to the start of the rest of the array.
471 if (NumInitElements) {
472 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
473 if (endOfInit) Builder.CreateStore(element, endOfInit);
474 }
475
476 // Compute the end of the array.
477 llvm::Value *end = Builder.CreateInBoundsGEP(begin,
478 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
479 "arrayinit.end");
480
481 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
482 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
483
484 // Jump into the body.
485 CGF.EmitBlock(bodyBB);
486 llvm::PHINode *currentElement =
487 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
488 currentElement->addIncoming(element, entryBB);
489
490 // Emit the actual filler expression.
491 LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
492 if (filler)
John McCall57cd1b82012-03-28 23:30:44 +0000493 EmitInitializationToLValue(filler, elementLV,
494 AggValueSlot::IsCompleteObject);
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000495 else
496 EmitNullInitializationToLValue(elementLV);
497
498 // Move on to the next element.
499 llvm::Value *nextElement =
500 Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
501
502 // Tell the EH cleanup that we finished with the last element.
503 if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
504
505 // Leave the loop if we're done.
506 llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
507 "arrayinit.done");
508 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
509 Builder.CreateCondBr(done, endBB, bodyBB);
510 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
511
512 CGF.EmitBlock(endBB);
513 }
514
515 // Leave the partial-array cleanup if we entered one.
516 if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
517}
518
Chris Lattneree755f92007-08-21 04:59:27 +0000519//===----------------------------------------------------------------------===//
520// Visitor Methods
521//===----------------------------------------------------------------------===//
522
Douglas Gregor03e80032011-06-21 17:03:29 +0000523void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
524 Visit(E->GetTemporaryExpr());
525}
526
John McCalle996ffd2011-02-16 08:02:54 +0000527void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
John McCall56ca35d2011-02-17 10:25:35 +0000528 EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e));
John McCalle996ffd2011-02-16 08:02:54 +0000529}
530
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000531void
532AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
Douglas Gregor673e98b2011-06-17 16:37:20 +0000533 if (E->getType().isPODType(CGF.getContext())) {
534 // For a POD type, just emit a load of the lvalue + a copy, because our
535 // compound literal might alias the destination.
536 // FIXME: This is a band-aid; the real problem appears to be in our handling
537 // of assignments, where we store directly into the LHS without checking
538 // whether anything in the RHS aliases.
539 EmitAggLoadOfLValue(E);
540 return;
541 }
542
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000543 AggValueSlot Slot = EnsureSlot(E->getType());
544 CGF.EmitAggExpr(E->getInitializer(), Slot);
545}
546
547
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000548void AggExprEmitter::VisitCastExpr(CastExpr *E) {
Anders Carlsson30168422009-09-29 01:23:39 +0000549 switch (E->getCastKind()) {
Anders Carlsson575b3742011-04-11 02:03:26 +0000550 case CK_Dynamic: {
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000551 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
552 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
553 // FIXME: Do we also need to handle property references here?
554 if (LV.isSimple())
555 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
556 else
557 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
558
John McCall558d2ab2010-09-15 10:14:12 +0000559 if (!Dest.isIgnored())
560 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000561 break;
562 }
563
John McCall2de56d12010-08-25 11:45:40 +0000564 case CK_ToUnion: {
John McCall65912712011-04-12 22:02:02 +0000565 if (Dest.isIgnored()) break;
566
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000567 // GCC union extension
Daniel Dunbar79c39282010-08-21 03:15:20 +0000568 QualType Ty = E->getSubExpr()->getType();
569 QualType PtrTy = CGF.getContext().getPointerType(Ty);
John McCall558d2ab2010-09-15 10:14:12 +0000570 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
Eli Friedman34ebf4d2009-06-03 20:45:06 +0000571 CGF.ConvertType(PtrTy));
John McCalla07398e2011-06-16 04:16:24 +0000572 EmitInitializationToLValue(E->getSubExpr(),
John McCall57cd1b82012-03-28 23:30:44 +0000573 CGF.MakeAddrLValue(CastPtr, Ty),
574 Dest.isCompleteObject());
Anders Carlsson30168422009-09-29 01:23:39 +0000575 break;
Nuno Lopes7e916272009-01-15 20:14:33 +0000576 }
Mike Stump1eb44332009-09-09 15:08:12 +0000577
John McCall2de56d12010-08-25 11:45:40 +0000578 case CK_DerivedToBase:
579 case CK_BaseToDerived:
580 case CK_UncheckedDerivedToBase: {
David Blaikieb219cfc2011-09-23 05:06:16 +0000581 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000582 "should have been unpacked before we got here");
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000583 }
584
John McCallf6a16482010-12-04 03:47:34 +0000585 case CK_LValueToRValue: // hope for downstream optimization
John McCall2de56d12010-08-25 11:45:40 +0000586 case CK_NoOp:
David Chisnall7a7ee302012-01-16 17:27:18 +0000587 case CK_AtomicToNonAtomic:
588 case CK_NonAtomicToAtomic:
John McCall2de56d12010-08-25 11:45:40 +0000589 case CK_UserDefinedConversion:
590 case CK_ConstructorConversion:
Anders Carlsson30168422009-09-29 01:23:39 +0000591 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
592 E->getType()) &&
593 "Implicit cast types must be compatible");
594 Visit(E->getSubExpr());
595 break;
John McCall0ae287a2010-12-01 04:43:34 +0000596
John McCall2de56d12010-08-25 11:45:40 +0000597 case CK_LValueBitCast:
John McCall0ae287a2010-12-01 04:43:34 +0000598 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
John McCall1de4d4e2011-04-07 08:22:57 +0000599
John McCall0ae287a2010-12-01 04:43:34 +0000600 case CK_Dependent:
601 case CK_BitCast:
602 case CK_ArrayToPointerDecay:
603 case CK_FunctionToPointerDecay:
604 case CK_NullToPointer:
605 case CK_NullToMemberPointer:
606 case CK_BaseToDerivedMemberPointer:
607 case CK_DerivedToBaseMemberPointer:
608 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +0000609 case CK_ReinterpretMemberPointer:
John McCall0ae287a2010-12-01 04:43:34 +0000610 case CK_IntegralToPointer:
611 case CK_PointerToIntegral:
612 case CK_PointerToBoolean:
613 case CK_ToVoid:
614 case CK_VectorSplat:
615 case CK_IntegralCast:
616 case CK_IntegralToBoolean:
617 case CK_IntegralToFloating:
618 case CK_FloatingToIntegral:
619 case CK_FloatingToBoolean:
620 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +0000621 case CK_CPointerToObjCPointerCast:
622 case CK_BlockPointerToObjCPointerCast:
John McCall0ae287a2010-12-01 04:43:34 +0000623 case CK_AnyPointerToBlockPointerCast:
624 case CK_ObjCObjectLValueCast:
625 case CK_FloatingRealToComplex:
626 case CK_FloatingComplexToReal:
627 case CK_FloatingComplexToBoolean:
628 case CK_FloatingComplexCast:
629 case CK_FloatingComplexToIntegralComplex:
630 case CK_IntegralRealToComplex:
631 case CK_IntegralComplexToReal:
632 case CK_IntegralComplexToBoolean:
633 case CK_IntegralComplexCast:
634 case CK_IntegralComplexToFloatingComplex:
John McCall33e56f32011-09-10 06:18:15 +0000635 case CK_ARCProduceObject:
636 case CK_ARCConsumeObject:
637 case CK_ARCReclaimReturnedObject:
638 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +0000639 case CK_CopyAndAutoreleaseBlockObject:
John McCall0ae287a2010-12-01 04:43:34 +0000640 llvm_unreachable("cast kind invalid for aggregate types");
Anders Carlsson30168422009-09-29 01:23:39 +0000641 }
Anders Carlssone4707ff2008-01-14 06:28:57 +0000642}
643
Chris Lattner96196622008-07-26 22:37:01 +0000644void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
Anders Carlssone70e8f72009-05-27 16:45:02 +0000645 if (E->getCallReturnType()->isReferenceType()) {
646 EmitAggLoadOfLValue(E);
647 return;
648 }
Mike Stump1eb44332009-09-09 15:08:12 +0000649
John McCallfa037bd2010-05-22 22:13:32 +0000650 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000651 EmitMoveFromReturnSlot(E, RV);
Anders Carlsson148fe672007-10-31 22:04:46 +0000652}
Chris Lattner96196622008-07-26 22:37:01 +0000653
654void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCallfa037bd2010-05-22 22:13:32 +0000655 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000656 EmitMoveFromReturnSlot(E, RV);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000657}
Anders Carlsson148fe672007-10-31 22:04:46 +0000658
Chris Lattner96196622008-07-26 22:37:01 +0000659void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +0000660 CGF.EmitIgnoredExpr(E->getLHS());
John McCall558d2ab2010-09-15 10:14:12 +0000661 Visit(E->getRHS());
Eli Friedman07fa52a2008-05-20 07:56:31 +0000662}
663
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000664void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +0000665 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall558d2ab2010-09-15 10:14:12 +0000666 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000667}
668
Chris Lattner9c033562007-08-21 04:25:47 +0000669void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000670 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +0000671 VisitPointerToDataMemberBinaryOperator(E);
672 else
673 CGF.ErrorUnsupported(E, "aggregate binary expression");
674}
675
676void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
677 const BinaryOperator *E) {
678 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
679 EmitFinalDestCopy(E, LV);
Chris Lattneree755f92007-08-21 04:59:27 +0000680}
681
John McCall57cd1b82012-03-28 23:30:44 +0000682/// Quickly check whether the object looks like it might be a complete
683/// object.
684static AggValueSlot::IsCompleteObject_t isCompleteObject(const Expr *E) {
685 E = E->IgnoreParens();
686
687 QualType objectType;
688 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
689 objectType = DRE->getDecl()->getType();
690 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
691 objectType = ME->getMemberDecl()->getType();
692 } else {
693 // Be conservative.
694 return AggValueSlot::MayNotBeCompleteObject;
695 }
696
697 // The expression refers directly to some sort of object.
698 // If that object has reference type, be conservative.
699 if (objectType->isReferenceType())
700 return AggValueSlot::MayNotBeCompleteObject;
701
702 return AggValueSlot::IsCompleteObject;
703}
704
Chris Lattner03d6fb92007-08-21 04:43:17 +0000705void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Eli Friedmanff6e2b72008-02-11 01:09:17 +0000706 // For an assignment to work, the value on the right has
707 // to be compatible with the value on the left.
Eli Friedman2dce5f82009-05-28 23:04:00 +0000708 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
709 E->getRHS()->getType())
Eli Friedmanff6e2b72008-02-11 01:09:17 +0000710 && "Invalid assignment");
John McCallcd940a12010-12-06 06:10:02 +0000711
John McCall57cd1b82012-03-28 23:30:44 +0000712 if (const DeclRefExpr *DRE
713 = dyn_cast<DeclRefExpr>(E->getLHS()->IgnoreParens()))
Fariborz Jahanian73a6f8e2011-04-29 22:11:28 +0000714 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Fariborz Jahanian2c7168c2011-04-29 21:53:21 +0000715 if (VD->hasAttr<BlocksAttr>() &&
716 E->getRHS()->HasSideEffects(CGF.getContext())) {
717 // When __block variable on LHS, the RHS must be evaluated first
718 // as it may change the 'forwarding' field via call to Block_copy.
719 LValue RHS = CGF.EmitLValue(E->getRHS());
720 LValue LHS = CGF.EmitLValue(E->getLHS());
John McCall7c2349b2011-08-25 20:40:09 +0000721 Dest = AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000722 needsGC(E->getLHS()->getType()),
John McCall57cd1b82012-03-28 23:30:44 +0000723 AggValueSlot::IsAliased,
724 AggValueSlot::IsCompleteObject);
Fariborz Jahanian2c7168c2011-04-29 21:53:21 +0000725 EmitFinalDestCopy(E, RHS, true);
726 return;
727 }
John McCall57cd1b82012-03-28 23:30:44 +0000728
Chris Lattner9c033562007-08-21 04:25:47 +0000729 LValue LHS = CGF.EmitLValue(E->getLHS());
Chris Lattner883f6a72007-08-11 00:04:45 +0000730
John McCalldb458062011-11-07 03:59:57 +0000731 // Codegen the RHS so that it stores directly into the LHS.
732 AggValueSlot LHSSlot =
733 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
734 needsGC(E->getLHS()->getType()),
John McCall57cd1b82012-03-28 23:30:44 +0000735 AggValueSlot::IsAliased,
736 isCompleteObject(E->getLHS()));
John McCalldb458062011-11-07 03:59:57 +0000737 CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
738 EmitFinalDestCopy(E, LHS, true);
Chris Lattner883f6a72007-08-11 00:04:45 +0000739}
740
John McCall56ca35d2011-02-17 10:25:35 +0000741void AggExprEmitter::
742VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000743 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
744 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
745 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000746
John McCall56ca35d2011-02-17 10:25:35 +0000747 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +0000748 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCall56ca35d2011-02-17 10:25:35 +0000749
John McCall150b4622011-01-26 04:00:11 +0000750 CodeGenFunction::ConditionalEvaluation eval(CGF);
Eli Friedman8e274bd2009-12-25 06:17:05 +0000751 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000752
John McCall74fb0ed2010-11-17 00:07:33 +0000753 // Save whether the destination's lifetime is externally managed.
John McCallfd71fb82011-08-26 08:02:37 +0000754 bool isExternallyDestructed = Dest.isExternallyDestructed();
Chris Lattner883f6a72007-08-11 00:04:45 +0000755
John McCall150b4622011-01-26 04:00:11 +0000756 eval.begin(CGF);
757 CGF.EmitBlock(LHSBlock);
John McCall56ca35d2011-02-17 10:25:35 +0000758 Visit(E->getTrueExpr());
John McCall150b4622011-01-26 04:00:11 +0000759 eval.end(CGF);
Mike Stump1eb44332009-09-09 15:08:12 +0000760
John McCall150b4622011-01-26 04:00:11 +0000761 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
762 CGF.Builder.CreateBr(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000763
John McCall74fb0ed2010-11-17 00:07:33 +0000764 // If the result of an agg expression is unused, then the emission
765 // of the LHS might need to create a destination slot. That's fine
766 // with us, and we can safely emit the RHS into the same slot, but
John McCallfd71fb82011-08-26 08:02:37 +0000767 // we shouldn't claim that it's already being destructed.
768 Dest.setExternallyDestructed(isExternallyDestructed);
John McCall74fb0ed2010-11-17 00:07:33 +0000769
John McCall150b4622011-01-26 04:00:11 +0000770 eval.begin(CGF);
771 CGF.EmitBlock(RHSBlock);
John McCall56ca35d2011-02-17 10:25:35 +0000772 Visit(E->getFalseExpr());
John McCall150b4622011-01-26 04:00:11 +0000773 eval.end(CGF);
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Chris Lattner9c033562007-08-21 04:25:47 +0000775 CGF.EmitBlock(ContBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000776}
Chris Lattneree755f92007-08-21 04:59:27 +0000777
Anders Carlssona294ca82009-07-08 18:33:14 +0000778void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
779 Visit(CE->getChosenSubExpr(CGF.getContext()));
780}
781
Eli Friedmanb1851242008-05-27 15:51:49 +0000782void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Daniel Dunbar07855702009-02-11 22:25:55 +0000783 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000784 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
785
Sebastian Redl0262f022009-01-09 21:09:38 +0000786 if (!ArgPtr) {
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000787 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
Sebastian Redl0262f022009-01-09 21:09:38 +0000788 return;
789 }
790
Daniel Dunbar79c39282010-08-21 03:15:20 +0000791 EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
Eli Friedmanb1851242008-05-27 15:51:49 +0000792}
793
Anders Carlssonb58d0172009-05-30 23:23:33 +0000794void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000795 // Ensure that we have a slot, but if we already do, remember
John McCallfd71fb82011-08-26 08:02:37 +0000796 // whether it was externally destructed.
797 bool wasExternallyDestructed = Dest.isExternallyDestructed();
John McCall558d2ab2010-09-15 10:14:12 +0000798 Dest = EnsureSlot(E->getType());
John McCallfd71fb82011-08-26 08:02:37 +0000799
800 // We're going to push a destructor if there isn't already one.
801 Dest.setExternallyDestructed();
Mike Stump1eb44332009-09-09 15:08:12 +0000802
John McCall558d2ab2010-09-15 10:14:12 +0000803 Visit(E->getSubExpr());
Anders Carlssonb58d0172009-05-30 23:23:33 +0000804
John McCallfd71fb82011-08-26 08:02:37 +0000805 // Push that destructor we promised.
806 if (!wasExternallyDestructed)
Peter Collingbourne86811602011-11-27 22:09:22 +0000807 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
Anders Carlssonb58d0172009-05-30 23:23:33 +0000808}
809
Anders Carlssonb14095a2009-04-17 00:06:03 +0000810void
Anders Carlsson31ccf372009-05-03 17:47:16 +0000811AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000812 AggValueSlot Slot = EnsureSlot(E->getType());
813 CGF.EmitCXXConstructExpr(E, Slot);
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000814}
815
Eli Friedman4c5d8af2012-02-09 03:32:31 +0000816void
817AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
818 AggValueSlot Slot = EnsureSlot(E->getType());
819 CGF.EmitLambdaExpr(E, Slot);
820}
821
John McCall4765fa02010-12-06 08:20:24 +0000822void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000823 CGF.enterFullExpression(E);
824 CodeGenFunction::RunCleanupsScope cleanups(CGF);
825 Visit(E->getSubExpr());
Anders Carlssonb14095a2009-04-17 00:06:03 +0000826}
827
Douglas Gregored8abf12010-07-08 06:14:04 +0000828void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000829 QualType T = E->getType();
830 AggValueSlot Slot = EnsureSlot(T);
John McCalla07398e2011-06-16 04:16:24 +0000831 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Anders Carlsson30311fa2009-12-16 06:57:54 +0000832}
833
834void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000835 QualType T = E->getType();
836 AggValueSlot Slot = EnsureSlot(T);
John McCalla07398e2011-06-16 04:16:24 +0000837 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Nuno Lopes329763b2009-10-18 15:18:11 +0000838}
839
Chris Lattner1b726772010-12-02 07:07:26 +0000840/// isSimpleZero - If emitting this value will obviously just cause a store of
841/// zero to memory, return true. This can return false if uncertain, so it just
842/// handles simple cases.
843static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000844 E = E->IgnoreParens();
845
Chris Lattner1b726772010-12-02 07:07:26 +0000846 // 0
847 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
848 return IL->getValue() == 0;
849 // +0.0
850 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
851 return FL->getValue().isPosZero();
852 // int()
853 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
854 CGF.getTypes().isZeroInitializable(E->getType()))
855 return true;
856 // (int*)0 - Null pointer expressions.
857 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
858 return ICE->getCastKind() == CK_NullToPointer;
859 // '\0'
860 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
861 return CL->getValue() == 0;
862
863 // Otherwise, hard case: conservatively return false.
864 return false;
865}
866
867
Anders Carlsson78e83f82010-02-03 17:33:16 +0000868void
John McCall57cd1b82012-03-28 23:30:44 +0000869AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV,
870 AggValueSlot::IsCompleteObject_t isCompleteObject) {
John McCalla07398e2011-06-16 04:16:24 +0000871 QualType type = LV.getType();
Mike Stump7f79f9b2009-05-29 15:46:01 +0000872 // FIXME: Ignore result?
Chris Lattnerf81557c2008-04-04 18:42:16 +0000873 // FIXME: Are initializers affected by volatile?
Chris Lattner1b726772010-12-02 07:07:26 +0000874 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
875 // Storing "i32 0" to a zero'd memory location is a noop.
876 } else if (isa<ImplicitValueInitExpr>(E)) {
John McCalla07398e2011-06-16 04:16:24 +0000877 EmitNullInitializationToLValue(LV);
878 } else if (type->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000879 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
John McCall545d9962011-06-25 02:11:03 +0000880 CGF.EmitStoreThroughLValue(RV, LV);
John McCalla07398e2011-06-16 04:16:24 +0000881 } else if (type->isAnyComplexType()) {
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000882 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
John McCalla07398e2011-06-16 04:16:24 +0000883 } else if (CGF.hasAggregateLLVMType(type)) {
John McCall7c2349b2011-08-25 20:40:09 +0000884 CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
885 AggValueSlot::IsDestructed,
886 AggValueSlot::DoesNotNeedGCBarriers,
John McCall410ffb22011-08-25 23:04:34 +0000887 AggValueSlot::IsNotAliased,
John McCall57cd1b82012-03-28 23:30:44 +0000888 isCompleteObject,
John McCalla07398e2011-06-16 04:16:24 +0000889 Dest.isZeroed()));
John McCallf85e1932011-06-15 23:02:42 +0000890 } else if (LV.isSimple()) {
John McCalla07398e2011-06-16 04:16:24 +0000891 CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
Eli Friedmanc8ba9612008-05-12 15:06:05 +0000892 } else {
John McCall545d9962011-06-25 02:11:03 +0000893 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
Chris Lattnerf81557c2008-04-04 18:42:16 +0000894 }
Chris Lattnerf81557c2008-04-04 18:42:16 +0000895}
896
John McCalla07398e2011-06-16 04:16:24 +0000897void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
898 QualType type = lv.getType();
899
Chris Lattner1b726772010-12-02 07:07:26 +0000900 // If the destination slot is already zeroed out before the aggregate is
901 // copied into it, we don't have to emit any zeros here.
John McCalla07398e2011-06-16 04:16:24 +0000902 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
Chris Lattner1b726772010-12-02 07:07:26 +0000903 return;
904
John McCalla07398e2011-06-16 04:16:24 +0000905 if (!CGF.hasAggregateLLVMType(type)) {
Eli Friedmanb1e3f322012-02-22 05:38:59 +0000906 // For non-aggregates, we can store zero.
John McCalla07398e2011-06-16 04:16:24 +0000907 llvm::Value *null = llvm::Constant::getNullValue(CGF.ConvertType(type));
Eli Friedmanb1e3f322012-02-22 05:38:59 +0000908 // Note that the following is not equivalent to
909 // EmitStoreThroughBitfieldLValue for ARC types.
Eli Friedman5a13d4d2012-02-24 23:53:49 +0000910 if (lv.isBitField()) {
Eli Friedmanb1e3f322012-02-22 05:38:59 +0000911 CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
Eli Friedman5a13d4d2012-02-24 23:53:49 +0000912 } else {
913 assert(lv.isSimple());
914 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
915 }
Lauro Ramos Venancio145cd892008-02-19 19:27:31 +0000916 } else {
Chris Lattnerf81557c2008-04-04 18:42:16 +0000917 // There's a potential optimization opportunity in combining
918 // memsets; that would be easy for arrays, but relatively
919 // difficult for structures with the current code.
John McCalla07398e2011-06-16 04:16:24 +0000920 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
Chris Lattnerf81557c2008-04-04 18:42:16 +0000921 }
922}
923
Chris Lattnerf81557c2008-04-04 18:42:16 +0000924void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
Eli Friedmana385b3c2008-12-02 01:17:45 +0000925#if 0
Eli Friedman13a5be12009-12-04 01:30:56 +0000926 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
927 // (Length of globals? Chunks of zeroed-out space?).
Eli Friedmana385b3c2008-12-02 01:17:45 +0000928 //
Mike Stumpf5408fe2009-05-16 07:57:57 +0000929 // If we can, prefer a copy from a global; this is a lot less code for long
930 // globals, and it's easier for the current optimizers to analyze.
Eli Friedman13a5be12009-12-04 01:30:56 +0000931 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
Eli Friedman994ffef2008-11-30 02:11:09 +0000932 llvm::GlobalVariable* GV =
Eli Friedman13a5be12009-12-04 01:30:56 +0000933 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
934 llvm::GlobalValue::InternalLinkage, C, "");
Daniel Dunbar79c39282010-08-21 03:15:20 +0000935 EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
Eli Friedman994ffef2008-11-30 02:11:09 +0000936 return;
937 }
Eli Friedmana385b3c2008-12-02 01:17:45 +0000938#endif
Chris Lattnerd0db03a2010-09-06 00:11:41 +0000939 if (E->hadArrayRangeDesignator())
Douglas Gregora9c87802009-01-29 19:42:23 +0000940 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Douglas Gregora9c87802009-01-29 19:42:23 +0000941
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000942 if (E->initializesStdInitializerList()) {
Sebastian Redlaf130fd2012-02-19 12:28:02 +0000943 EmitStdInitializerList(Dest.getAddr(), E);
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000944 return;
945 }
946
Eli Friedmanc60ccf52012-02-29 00:00:28 +0000947 llvm::Value *DestPtr = EnsureSlot(E->getType()).getAddr();
John McCall558d2ab2010-09-15 10:14:12 +0000948
Chris Lattnerf81557c2008-04-04 18:42:16 +0000949 // Handle initialization of an array.
950 if (E->getType()->isArrayType()) {
Chris Lattner96196622008-07-26 22:37:01 +0000951 if (E->getNumInits() > 0) {
952 QualType T1 = E->getType();
953 QualType T2 = E->getInit(0)->getType();
Eli Friedman2dce5f82009-05-28 23:04:00 +0000954 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
Chris Lattner96196622008-07-26 22:37:01 +0000955 EmitAggLoadOfLValue(E->getInit(0));
956 return;
957 }
Eli Friedman922696f2008-05-19 17:51:16 +0000958 }
959
Eli Friedman5c89c392012-02-23 02:25:10 +0000960 QualType elementType =
961 CGF.getContext().getAsArrayType(E->getType())->getElementType();
Argyrios Kyrtzidis3b4d4902011-04-28 18:53:58 +0000962
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000963 llvm::PointerType *APType =
964 cast<llvm::PointerType>(DestPtr->getType());
965 llvm::ArrayType *AType =
966 cast<llvm::ArrayType>(APType->getElementType());
Chris Lattner1b726772010-12-02 07:07:26 +0000967
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000968 EmitArrayInit(DestPtr, AType, elementType, E);
Chris Lattnerf81557c2008-04-04 18:42:16 +0000969 return;
970 }
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Chris Lattnerf81557c2008-04-04 18:42:16 +0000972 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Chris Lattnerf81557c2008-04-04 18:42:16 +0000974 // Do struct initialization; this code just sets each individual member
975 // to the approprate value. This makes bitfield support automatic;
976 // the disadvantage is that the generated code is more difficult for
977 // the optimizer, especially with bitfields.
978 unsigned NumInitElements = E->getNumInits();
John McCall2b30dcf2011-07-11 19:35:02 +0000979 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
Chris Lattnerbd7de382010-09-06 00:13:11 +0000980
John McCall2b30dcf2011-07-11 19:35:02 +0000981 if (record->isUnion()) {
Douglas Gregor0bb76892009-01-29 16:53:55 +0000982 // Only initialize one field of a union. The field itself is
983 // specified by the initializer list.
984 if (!E->getInitializedFieldInUnion()) {
985 // Empty union; we have nothing to do.
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Douglas Gregor0bb76892009-01-29 16:53:55 +0000987#ifndef NDEBUG
988 // Make sure that it's really an empty and not a failure of
989 // semantic analysis.
John McCall2b30dcf2011-07-11 19:35:02 +0000990 for (RecordDecl::field_iterator Field = record->field_begin(),
991 FieldEnd = record->field_end();
Douglas Gregor0bb76892009-01-29 16:53:55 +0000992 Field != FieldEnd; ++Field)
993 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
994#endif
995 return;
996 }
997
998 // FIXME: volatility
999 FieldDecl *Field = E->getInitializedFieldInUnion();
Douglas Gregor0bb76892009-01-29 16:53:55 +00001000
Chris Lattner1b726772010-12-02 07:07:26 +00001001 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001002 if (NumInitElements) {
1003 // Store the initializer into the field
John McCall57cd1b82012-03-28 23:30:44 +00001004 EmitInitializationToLValue(E->getInit(0), FieldLoc,
1005 AggValueSlot::IsCompleteObject);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001006 } else {
Chris Lattner1b726772010-12-02 07:07:26 +00001007 // Default-initialize to null.
John McCalla07398e2011-06-16 04:16:24 +00001008 EmitNullInitializationToLValue(FieldLoc);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001009 }
1010
1011 return;
1012 }
Mike Stump1eb44332009-09-09 15:08:12 +00001013
John McCall2b30dcf2011-07-11 19:35:02 +00001014 // We'll need to enter cleanup scopes in case any of the member
1015 // initializers throw an exception.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001016 SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
John McCall6f103ba2011-11-10 10:43:54 +00001017 llvm::Instruction *cleanupDominator = 0;
John McCall2b30dcf2011-07-11 19:35:02 +00001018
Chris Lattnerf81557c2008-04-04 18:42:16 +00001019 // Here we iterate over the fields; this makes it simpler to both
1020 // default-initialize fields and skip over unnamed fields.
John McCall2b30dcf2011-07-11 19:35:02 +00001021 unsigned curInitIndex = 0;
1022 for (RecordDecl::field_iterator field = record->field_begin(),
1023 fieldEnd = record->field_end();
1024 field != fieldEnd; ++field) {
1025 // We're done once we hit the flexible array member.
1026 if (field->getType()->isIncompleteArrayType())
Douglas Gregor44b43212008-12-11 16:49:14 +00001027 break;
1028
John McCall2b30dcf2011-07-11 19:35:02 +00001029 // Always skip anonymous bitfields.
1030 if (field->isUnnamedBitfield())
Chris Lattnerf81557c2008-04-04 18:42:16 +00001031 continue;
Douglas Gregor34e79462009-01-28 23:36:17 +00001032
John McCall2b30dcf2011-07-11 19:35:02 +00001033 // We're done if we reach the end of the explicit initializers, we
1034 // have a zeroed object, and the rest of the fields are
1035 // zero-initializable.
1036 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
Chris Lattner1b726772010-12-02 07:07:26 +00001037 CGF.getTypes().isZeroInitializable(E->getType()))
1038 break;
1039
Eli Friedman1e692ac2008-06-13 23:01:12 +00001040 // FIXME: volatility
John McCall2b30dcf2011-07-11 19:35:02 +00001041 LValue LV = CGF.EmitLValueForFieldInitialization(DestPtr, *field, 0);
Fariborz Jahanian14674ff2009-05-27 19:54:11 +00001042 // We never generate write-barries for initialized fields.
John McCall2b30dcf2011-07-11 19:35:02 +00001043 LV.setNonGC(true);
Chris Lattner1b726772010-12-02 07:07:26 +00001044
John McCall2b30dcf2011-07-11 19:35:02 +00001045 if (curInitIndex < NumInitElements) {
Chris Lattnerb35baae2010-03-08 21:08:07 +00001046 // Store the initializer into the field.
John McCall57cd1b82012-03-28 23:30:44 +00001047 EmitInitializationToLValue(E->getInit(curInitIndex++), LV,
1048 AggValueSlot::IsCompleteObject);
Chris Lattnerf81557c2008-04-04 18:42:16 +00001049 } else {
1050 // We're out of initalizers; default-initialize to null
John McCall2b30dcf2011-07-11 19:35:02 +00001051 EmitNullInitializationToLValue(LV);
1052 }
1053
1054 // Push a destructor if necessary.
1055 // FIXME: if we have an array of structures, all explicitly
1056 // initialized, we can end up pushing a linear number of cleanups.
1057 bool pushedCleanup = false;
1058 if (QualType::DestructionKind dtorKind
1059 = field->getType().isDestructedType()) {
1060 assert(LV.isSimple());
1061 if (CGF.needsEHCleanup(dtorKind)) {
John McCall6f103ba2011-11-10 10:43:54 +00001062 if (!cleanupDominator)
1063 cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1064
John McCall2b30dcf2011-07-11 19:35:02 +00001065 CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1066 CGF.getDestroyer(dtorKind), false);
1067 cleanups.push_back(CGF.EHStack.stable_begin());
1068 pushedCleanup = true;
1069 }
Chris Lattnerf81557c2008-04-04 18:42:16 +00001070 }
Chris Lattner1b726772010-12-02 07:07:26 +00001071
1072 // If the GEP didn't get used because of a dead zero init or something
1073 // else, clean it up for -O0 builds and general tidiness.
John McCall2b30dcf2011-07-11 19:35:02 +00001074 if (!pushedCleanup && LV.isSimple())
Chris Lattner1b726772010-12-02 07:07:26 +00001075 if (llvm::GetElementPtrInst *GEP =
John McCall2b30dcf2011-07-11 19:35:02 +00001076 dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
Chris Lattner1b726772010-12-02 07:07:26 +00001077 if (GEP->use_empty())
1078 GEP->eraseFromParent();
Lauro Ramos Venancio145cd892008-02-19 19:27:31 +00001079 }
John McCall2b30dcf2011-07-11 19:35:02 +00001080
1081 // Deactivate all the partial cleanups in reverse order, which
1082 // generally means popping them.
1083 for (unsigned i = cleanups.size(); i != 0; --i)
John McCall6f103ba2011-11-10 10:43:54 +00001084 CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1085
1086 // Destroy the placeholder if we made one.
1087 if (cleanupDominator)
1088 cleanupDominator->eraseFromParent();
Devang Patel636c3d02007-10-26 17:44:44 +00001089}
1090
Chris Lattneree755f92007-08-21 04:59:27 +00001091//===----------------------------------------------------------------------===//
1092// Entry Points into this File
1093//===----------------------------------------------------------------------===//
1094
Chris Lattner1b726772010-12-02 07:07:26 +00001095/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1096/// non-zero bytes that will be stored when outputting the initializer for the
1097/// specified initializer expression.
Ken Dyck02c45332011-04-24 17:17:56 +00001098static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001099 E = E->IgnoreParens();
Chris Lattner1b726772010-12-02 07:07:26 +00001100
1101 // 0 and 0.0 won't require any non-zero stores!
Ken Dyck02c45332011-04-24 17:17:56 +00001102 if (isSimpleZero(E, CGF)) return CharUnits::Zero();
Chris Lattner1b726772010-12-02 07:07:26 +00001103
1104 // If this is an initlist expr, sum up the size of sizes of the (present)
1105 // elements. If this is something weird, assume the whole thing is non-zero.
1106 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
1107 if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
Ken Dyck02c45332011-04-24 17:17:56 +00001108 return CGF.getContext().getTypeSizeInChars(E->getType());
Chris Lattner1b726772010-12-02 07:07:26 +00001109
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001110 // InitListExprs for structs have to be handled carefully. If there are
1111 // reference members, we need to consider the size of the reference, not the
1112 // referencee. InitListExprs for unions and arrays can't have references.
Chris Lattner8c00ad12010-12-02 22:52:04 +00001113 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1114 if (!RT->isUnionType()) {
1115 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
Ken Dyck02c45332011-04-24 17:17:56 +00001116 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner8c00ad12010-12-02 22:52:04 +00001117
1118 unsigned ILEElement = 0;
1119 for (RecordDecl::field_iterator Field = SD->field_begin(),
1120 FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
1121 // We're done once we hit the flexible array member or run out of
1122 // InitListExpr elements.
1123 if (Field->getType()->isIncompleteArrayType() ||
1124 ILEElement == ILE->getNumInits())
1125 break;
1126 if (Field->isUnnamedBitfield())
1127 continue;
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001128
Chris Lattner8c00ad12010-12-02 22:52:04 +00001129 const Expr *E = ILE->getInit(ILEElement++);
1130
1131 // Reference values are always non-null and have the width of a pointer.
1132 if (Field->getType()->isReferenceType())
Ken Dyck02c45332011-04-24 17:17:56 +00001133 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001134 CGF.getContext().getTargetInfo().getPointerWidth(0));
Chris Lattner8c00ad12010-12-02 22:52:04 +00001135 else
1136 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1137 }
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001138
Chris Lattner8c00ad12010-12-02 22:52:04 +00001139 return NumNonZeroBytes;
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001140 }
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001141 }
1142
1143
Ken Dyck02c45332011-04-24 17:17:56 +00001144 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner1b726772010-12-02 07:07:26 +00001145 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1146 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1147 return NumNonZeroBytes;
1148}
1149
1150/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1151/// zeros in it, emit a memset and avoid storing the individual zeros.
1152///
1153static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1154 CodeGenFunction &CGF) {
1155 // If the slot is already known to be zeroed, nothing to do. Don't mess with
1156 // volatile stores.
1157 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +00001158
1159 // C++ objects with a user-declared constructor don't need zero'ing.
David Blaikie4e4d0842012-03-11 07:00:24 +00001160 if (CGF.getContext().getLangOpts().CPlusPlus)
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +00001161 if (const RecordType *RT = CGF.getContext()
1162 .getBaseElementType(E->getType())->getAs<RecordType>()) {
1163 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1164 if (RD->hasUserDeclaredConstructor())
1165 return;
1166 }
1167
Chris Lattner1b726772010-12-02 07:07:26 +00001168 // If the type is 16-bytes or smaller, prefer individual stores over memset.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001169 std::pair<CharUnits, CharUnits> TypeInfo =
1170 CGF.getContext().getTypeInfoInChars(E->getType());
1171 if (TypeInfo.first <= CharUnits::fromQuantity(16))
Chris Lattner1b726772010-12-02 07:07:26 +00001172 return;
1173
1174 // Check to see if over 3/4 of the initializer are known to be zero. If so,
1175 // we prefer to emit memset + individual stores for the rest.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001176 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1177 if (NumNonZeroBytes*4 > TypeInfo.first)
Chris Lattner1b726772010-12-02 07:07:26 +00001178 return;
1179
1180 // Okay, it seems like a good idea to use an initial memset, emit the call.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001181 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1182 CharUnits Align = TypeInfo.second;
Chris Lattner1b726772010-12-02 07:07:26 +00001183
1184 llvm::Value *Loc = Slot.getAddr();
Chris Lattner1b726772010-12-02 07:07:26 +00001185
Chris Lattner8b418682012-02-07 00:39:47 +00001186 Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
Ken Dyck5ff1a352011-04-24 17:25:32 +00001187 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1188 Align.getQuantity(), false);
Chris Lattner1b726772010-12-02 07:07:26 +00001189
1190 // Tell the AggExprEmitter that the slot is known zero.
1191 Slot.setZeroed();
1192}
1193
1194
1195
1196
Mike Stumpe1129a92009-05-26 18:57:45 +00001197/// EmitAggExpr - Emit the computation of the specified expression of aggregate
1198/// type. The result is computed into DestPtr. Note that if DestPtr is null,
1199/// the value of the aggregate expression is not needed. If VolatileDest is
1200/// true, DestPtr cannot be 0.
John McCall558d2ab2010-09-15 10:14:12 +00001201///
1202/// \param IsInitializer - true if this evaluation is initializing an
1203/// object whose lifetime is already being managed.
John McCall558d2ab2010-09-15 10:14:12 +00001204void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
Fariborz Jahanian474e2fe2010-09-16 00:20:07 +00001205 bool IgnoreResult) {
Chris Lattneree755f92007-08-21 04:59:27 +00001206 assert(E && hasAggregateLLVMType(E->getType()) &&
1207 "Invalid aggregate expression to emit");
Chris Lattner1b726772010-12-02 07:07:26 +00001208 assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
1209 "slot has bits but no address");
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Chris Lattner1b726772010-12-02 07:07:26 +00001211 // Optimize the slot if possible.
1212 CheckAggExprForMemSetUse(Slot, E, *this);
1213
1214 AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E));
Chris Lattneree755f92007-08-21 04:59:27 +00001215}
Daniel Dunbar7482d122008-09-09 20:49:46 +00001216
Daniel Dunbar18aba0d2010-02-05 19:38:31 +00001217LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1218 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
Daniel Dunbar195337d2010-02-09 02:48:28 +00001219 llvm::Value *Temp = CreateMemTemp(E->getType());
Daniel Dunbar79c39282010-08-21 03:15:20 +00001220 LValue LV = MakeAddrLValue(Temp, E->getType());
John McCall7c2349b2011-08-25 20:40:09 +00001221 EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
John McCall44184392011-08-26 07:31:35 +00001222 AggValueSlot::DoesNotNeedGCBarriers,
John McCall57cd1b82012-03-28 23:30:44 +00001223 AggValueSlot::IsNotAliased,
1224 AggValueSlot::IsCompleteObject));
Daniel Dunbar79c39282010-08-21 03:15:20 +00001225 return LV;
Daniel Dunbar18aba0d2010-02-05 19:38:31 +00001226}
1227
John McCall57cd1b82012-03-28 23:30:44 +00001228void CodeGenFunction::EmitAggregateCopy(llvm::Value *dest, llvm::Value *src,
1229 QualType type,
1230 bool isVolatile, unsigned alignment,
1231 bool destIsCompleteObject) {
1232 assert(!type->isAnyComplexType() && "Shouldn't happen for complex");
Mike Stump1eb44332009-09-09 15:08:12 +00001233
John McCall57cd1b82012-03-28 23:30:44 +00001234 // Get size and alignment info for this type. Note that the type
1235 // might include an alignment attribute, so we can't just rely on
1236 // the layout.
1237 // FIXME: Do we need to handle VLAs here?
1238 std::pair<CharUnits, CharUnits> typeInfo =
1239 getContext().getTypeInfoInChars(type);
1240
1241 // If we weren't given an alignment, use the natural alignment.
1242 if (!alignment) alignment = typeInfo.second.getQuantity();
1243
1244 CharUnits sizeToCopy = typeInfo.first;
1245
1246 // There's some special logic that applies to C++ classes:
David Blaikie4e4d0842012-03-11 07:00:24 +00001247 if (getContext().getLangOpts().CPlusPlus) {
John McCall57cd1b82012-03-28 23:30:44 +00001248 if (const RecordType *RT = type->getAs<RecordType>()) {
1249 // First, we want to assert that we're not doing this to
1250 // something with a non-trivial operator/constructor.
1251 CXXRecordDecl *record = cast<CXXRecordDecl>(RT->getDecl());
1252 assert((record->hasTrivialCopyConstructor() ||
1253 record->hasTrivialCopyAssignment() ||
1254 record->hasTrivialMoveConstructor() ||
1255 record->hasTrivialMoveAssignment()) &&
Douglas Gregore9979482010-05-20 15:39:01 +00001256 "Trying to aggregate-copy a type without a trivial copy "
1257 "constructor or assignment operator");
John McCall57cd1b82012-03-28 23:30:44 +00001258
1259 // Second, we want to ignore empty classes.
1260 if (record->isEmpty())
Anders Carlsson0d7c5832010-05-03 01:20:20 +00001261 return;
John McCall57cd1b82012-03-28 23:30:44 +00001262
1263 // Third, if it's possible that the destination might not be a
1264 // complete object, then we need to make sure we only copy the
1265 // data size, not the full sizeof, so that we don't overwrite
1266 // subclass fields in the tailing padding. It's generally going
1267 // to be more efficient to copy the sizeof, since we can use
1268 // larger stores.
1269 //
1270 // Unions and final classes can never be base classes.
1271 if (!destIsCompleteObject && !record->isUnion() &&
1272 !record->hasAttr<FinalAttr>()) {
1273 const ASTRecordLayout &layout
1274 = getContext().getASTRecordLayout(record);
1275 sizeToCopy = layout.getDataSize();
1276 }
Anders Carlsson0d7c5832010-05-03 01:20:20 +00001277 }
1278 }
1279
John McCall57cd1b82012-03-28 23:30:44 +00001280 llvm::PointerType *DPT = cast<llvm::PointerType>(dest->getType());
1281 llvm::Type *DBP =
1282 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1283 dest = Builder.CreateBitCast(dest, DBP);
1284
1285 llvm::PointerType *SPT = cast<llvm::PointerType>(src->getType());
1286 llvm::Type *SBP =
1287 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1288 src = Builder.CreateBitCast(src, SBP);
1289
1290 llvm::Value *sizeVal =
1291 llvm::ConstantInt::get(CGM.SizeTy, sizeToCopy.getQuantity());
1292
1293 // Don't do any of the memmove_collectable tests if GC isn't set.
1294 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1295 // fall through
1296 } else if (const RecordType *RT = type->getAs<RecordType>()) {
1297 if (RT->getDecl()->hasObjectMember()) {
1298 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, dest, src, sizeVal);
1299 return;
1300 }
1301 } else if (type->isArrayType()) {
1302 QualType baseType = getContext().getBaseElementType(type);
1303 if (const RecordType *RT = baseType->getAs<RecordType>()) {
1304 if (RT->getDecl()->hasObjectMember()) {
1305 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, dest, src,sizeVal);
1306 return;
1307 }
1308 }
1309 }
1310
Chris Lattner83c96292009-02-28 18:31:01 +00001311 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
Chris Lattnerca4fc2c2009-02-28 18:18:58 +00001312 // C99 6.5.16.1p3, which states "If the value being stored in an object is
1313 // read from another object that overlaps in anyway the storage of the first
1314 // object, then the overlap shall be exact and the two objects shall have
1315 // qualified or unqualified versions of a compatible type."
1316 //
Chris Lattner83c96292009-02-28 18:31:01 +00001317 // memcpy is not defined if the source and destination pointers are exactly
Chris Lattnerca4fc2c2009-02-28 18:18:58 +00001318 // equal, but other compilers do this optimization, and almost every memcpy
1319 // implementation handles this case safely. If there is a libc that does not
1320 // safely handle this, we can add a target hook.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00001321
John McCall57cd1b82012-03-28 23:30:44 +00001322 Builder.CreateMemCpy(dest, src, sizeVal, alignment, isVolatile);
Daniel Dunbar7482d122008-09-09 20:49:46 +00001323}
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001324
Sebastian Redl972edf02012-02-19 16:03:09 +00001325void CodeGenFunction::MaybeEmitStdInitializerListCleanup(llvm::Value *loc,
1326 const Expr *init) {
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001327 const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(init);
Sebastian Redl972edf02012-02-19 16:03:09 +00001328 if (cleanups)
1329 init = cleanups->getSubExpr();
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001330
1331 if (isa<InitListExpr>(init) &&
1332 cast<InitListExpr>(init)->initializesStdInitializerList()) {
1333 // We initialized this std::initializer_list with an initializer list.
1334 // A backing array was created. Push a cleanup for it.
Sebastian Redl972edf02012-02-19 16:03:09 +00001335 EmitStdInitializerListCleanup(loc, cast<InitListExpr>(init));
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001336 }
1337}
1338
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001339static void EmitRecursiveStdInitializerListCleanup(CodeGenFunction &CGF,
1340 llvm::Value *arrayStart,
1341 const InitListExpr *init) {
1342 // Check if there are any recursive cleanups to do, i.e. if we have
1343 // std::initializer_list<std::initializer_list<obj>> list = {{obj()}};
1344 // then we need to destroy the inner array as well.
1345 for (unsigned i = 0, e = init->getNumInits(); i != e; ++i) {
1346 const InitListExpr *subInit = dyn_cast<InitListExpr>(init->getInit(i));
1347 if (!subInit || !subInit->initializesStdInitializerList())
1348 continue;
1349
1350 // This one needs to be destroyed. Get the address of the std::init_list.
1351 llvm::Value *offset = llvm::ConstantInt::get(CGF.SizeTy, i);
1352 llvm::Value *loc = CGF.Builder.CreateInBoundsGEP(arrayStart, offset,
1353 "std.initlist");
1354 CGF.EmitStdInitializerListCleanup(loc, subInit);
1355 }
1356}
1357
1358void CodeGenFunction::EmitStdInitializerListCleanup(llvm::Value *loc,
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001359 const InitListExpr *init) {
1360 ASTContext &ctx = getContext();
1361 QualType element = GetStdInitializerListElementType(init->getType());
1362 unsigned numInits = init->getNumInits();
1363 llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
1364 QualType array =ctx.getConstantArrayType(element, size, ArrayType::Normal, 0);
1365 QualType arrayPtr = ctx.getPointerType(array);
1366 llvm::Type *arrayPtrType = ConvertType(arrayPtr);
1367
1368 // lvalue is the location of a std::initializer_list, which as its first
1369 // element has a pointer to the array we want to destroy.
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001370 llvm::Value *startPointer = Builder.CreateStructGEP(loc, 0, "startPointer");
1371 llvm::Value *startAddress = Builder.CreateLoad(startPointer, "startAddress");
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001372
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001373 ::EmitRecursiveStdInitializerListCleanup(*this, startAddress, init);
1374
1375 llvm::Value *arrayAddress =
1376 Builder.CreateBitCast(startAddress, arrayPtrType, "arrayAddress");
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001377 ::EmitStdInitializerListCleanup(*this, array, arrayAddress, init);
1378}