blob: 6fedf0efda9d8f87f60bd716706b281177dff3a2 [file] [log] [blame]
Chris Lattner11e0de52007-08-24 02:22:53 +00001//===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
Chris Lattnerd79671f2007-08-10 20:13:28 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnerd79671f2007-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 Jahanian5f21d2f2009-07-08 01:18:33 +000015#include "CGObjCRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CodeGenModule.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Anders Carlssonb7f8f592009-04-17 00:06:03 +000018#include "clang/AST/DeclCXX.h"
Sebastian Redlc83ed822012-02-17 08:42:25 +000019#include "clang/AST/DeclTemplate.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000020#include "clang/AST/StmtVisitor.h"
Chandler Carruthffd55512013-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 Lattnerd79671f2007-08-10 20:13:28 +000025using namespace clang;
26using namespace CodeGen;
Chris Lattner6278e6a2007-08-11 00:04:45 +000027
Chris Lattner4758b402007-08-21 04:25:47 +000028//===----------------------------------------------------------------------===//
29// Aggregate Expression Emitter
30//===----------------------------------------------------------------------===//
31
32namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000033class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
Chris Lattner4758b402007-08-21 04:25:47 +000034 CodeGenFunction &CGF;
Daniel Dunbarcb463852008-11-01 01:53:16 +000035 CGBuilderTy &Builder;
John McCall7a626f62010-09-15 10:14:12 +000036 AggValueSlot Dest;
John McCall78a15112010-05-22 01:48:05 +000037
John McCalla5efa732011-08-25 23:04:34 +000038 /// We want to use 'dest' as the return slot except under two
39 /// conditions:
40 /// - The destination slot requires garbage collection, so we
41 /// need to use the GC API.
42 /// - The destination slot is potentially aliased.
43 bool shouldUseDestForReturnSlot() const {
44 return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
45 }
46
John McCall78a15112010-05-22 01:48:05 +000047 ReturnValueSlot getReturnValueSlot() const {
John McCalla5efa732011-08-25 23:04:34 +000048 if (!shouldUseDestForReturnSlot())
49 return ReturnValueSlot();
John McCallcc04e9f2010-05-22 22:13:32 +000050
John McCall7a626f62010-09-15 10:14:12 +000051 return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
52 }
53
54 AggValueSlot EnsureSlot(QualType T) {
55 if (!Dest.isIgnored()) return Dest;
56 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
John McCall78a15112010-05-22 01:48:05 +000057 }
John McCall4e8ca4f2012-07-02 23:58:38 +000058 void EnsureDest(QualType T) {
59 if (!Dest.isIgnored()) return;
60 Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
61 }
John McCallcc04e9f2010-05-22 22:13:32 +000062
Chris Lattner4758b402007-08-21 04:25:47 +000063public:
John McCall4e8ca4f2012-07-02 23:58:38 +000064 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest)
65 : CGF(cgf), Builder(CGF.Builder), Dest(Dest) {
Chris Lattner4758b402007-08-21 04:25:47 +000066 }
67
Chris Lattner835635d2007-08-21 04:59:27 +000068 //===--------------------------------------------------------------------===//
69 // Utilities
70 //===--------------------------------------------------------------------===//
71
Chris Lattner4758b402007-08-21 04:25:47 +000072 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
73 /// represents a value lvalue, this method emits the address of the lvalue,
74 /// then loads the result into DestPtr.
75 void EmitAggLoadOfLValue(const Expr *E);
Eli Friedmanf23b6fa2008-05-19 17:51:16 +000076
Mike Stumpca9fc092009-05-23 20:28:01 +000077 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
John McCall4e8ca4f2012-07-02 23:58:38 +000078 void EmitFinalDestCopy(QualType type, const LValue &src);
79 void EmitFinalDestCopy(QualType type, RValue src,
80 CharUnits srcAlignment = CharUnits::Zero());
81 void EmitCopy(QualType type, const AggValueSlot &dest,
82 const AggValueSlot &src);
Mike Stumpca9fc092009-05-23 20:28:01 +000083
John McCalla5efa732011-08-25 23:04:34 +000084 void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
John McCallcc04e9f2010-05-22 22:13:32 +000085
Sebastian Redlc83ed822012-02-17 08:42:25 +000086 void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
87 QualType elementType, InitListExpr *E);
88
John McCall8d6fc952011-08-25 20:40:09 +000089 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000090 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
John McCall8d6fc952011-08-25 20:40:09 +000091 return AggValueSlot::NeedsGCBarriers;
92 return AggValueSlot::DoesNotNeedGCBarriers;
93 }
94
John McCallcc04e9f2010-05-22 22:13:32 +000095 bool TypeRequiresGCollection(QualType T);
96
Chris Lattner835635d2007-08-21 04:59:27 +000097 //===--------------------------------------------------------------------===//
98 // Visitor Methods
99 //===--------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000100
David Blaikie01fb5fb2015-01-18 01:48:19 +0000101 void Visit(Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000102 ApplyDebugLocation DL(CGF, E);
David Blaikie01fb5fb2015-01-18 01:48:19 +0000103 StmtVisitor<AggExprEmitter>::Visit(E);
104 }
105
Chris Lattner4758b402007-08-21 04:25:47 +0000106 void VisitStmt(Stmt *S) {
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000107 CGF.ErrorUnsupported(S, "aggregate expression");
Chris Lattner4758b402007-08-21 04:25:47 +0000108 }
109 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
Peter Collingbourne91147592011-04-15 00:35:48 +0000110 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
111 Visit(GE->getResultExpr());
112 }
Eli Friedman3f66b842009-01-27 09:03:41 +0000113 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000114 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
115 return Visit(E->getReplacement());
116 }
Chris Lattner4758b402007-08-21 04:25:47 +0000117
118 // l-values.
John McCall113bee02012-03-10 09:33:50 +0000119 void VisitDeclRefExpr(DeclRefExpr *E) {
John McCall71335052012-03-10 03:05:10 +0000120 // For aggregates, we should always be able to emit the variable
121 // as an l-value unless it's a reference. This is due to the fact
122 // that we can't actually ever see a normal l2r conversion on an
123 // aggregate in C++, and in C there's no language standard
124 // actively preventing us from listing variables in the captures
125 // list of a block.
John McCall113bee02012-03-10 09:33:50 +0000126 if (E->getDecl()->getType()->isReferenceType()) {
John McCall71335052012-03-10 03:05:10 +0000127 if (CodeGenFunction::ConstantEmission result
John McCall113bee02012-03-10 09:33:50 +0000128 = CGF.tryEmitAsConstant(E)) {
John McCall4e8ca4f2012-07-02 23:58:38 +0000129 EmitFinalDestCopy(E->getType(), result.getReferenceLValue(CGF, E));
John McCall71335052012-03-10 03:05:10 +0000130 return;
131 }
132 }
133
John McCall113bee02012-03-10 09:33:50 +0000134 EmitAggLoadOfLValue(E);
John McCall71335052012-03-10 03:05:10 +0000135 }
136
Seo Sanghyeond4d8c3c2007-12-14 02:04:12 +0000137 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
138 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
Daniel Dunbard443c0a2010-01-04 18:47:06 +0000139 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000140 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Seo Sanghyeond4d8c3c2007-12-14 02:04:12 +0000141 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
142 EmitAggLoadOfLValue(E);
143 }
Chris Lattner2f343dd2009-04-21 23:00:09 +0000144 void VisitPredefinedExpr(const PredefinedExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000145 EmitAggLoadOfLValue(E);
Chris Lattner2f343dd2009-04-21 23:00:09 +0000146 }
Mike Stump11289f42009-09-09 15:08:12 +0000147
Chris Lattner4758b402007-08-21 04:25:47 +0000148 // Operators.
Anders Carlssonec143772009-08-07 23:22:37 +0000149 void VisitCastExpr(CastExpr *E);
Anders Carlsson0370eb22007-10-31 22:04:46 +0000150 void VisitCallExpr(const CallExpr *E);
Chris Lattner49e3bfa2007-08-31 22:54:14 +0000151 void VisitStmtExpr(const StmtExpr *E);
Chris Lattner4758b402007-08-21 04:25:47 +0000152 void VisitBinaryOperator(const BinaryOperator *BO);
Fariborz Jahanianffba6622009-10-22 22:57:31 +0000153 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
Chris Lattnercd9fb242007-08-21 04:43:17 +0000154 void VisitBinAssign(const BinaryOperator *E);
Eli Friedman4b0e2a32008-05-20 07:56:31 +0000155 void VisitBinComma(const BinaryOperator *E);
Chris Lattner4758b402007-08-21 04:25:47 +0000156
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000157 void VisitObjCMessageExpr(ObjCMessageExpr *E);
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000158 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
159 EmitAggLoadOfLValue(E);
160 }
Mike Stump11289f42009-09-09 15:08:12 +0000161
John McCallc07a0c72011-02-17 10:25:35 +0000162 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
Anders Carlsson5b2095c2009-07-08 18:33:14 +0000163 void VisitChooseExpr(const ChooseExpr *CE);
Devang Patel87174172007-10-26 17:44:44 +0000164 void VisitInitListExpr(InitListExpr *E);
Anders Carlsson18ada982009-12-16 06:57:54 +0000165 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000166 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
167 Visit(DAE->getExpr());
168 }
Richard Smith852c9db2013-04-20 22:23:05 +0000169 void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
170 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
171 Visit(DIE->getExpr());
172 }
Anders Carlsson3be22e22009-05-30 23:23:33 +0000173 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
Anders Carlsson1619a5042009-05-03 17:47:16 +0000174 void VisitCXXConstructExpr(const CXXConstructExpr *E);
Eli Friedmanc370a7e2012-02-09 03:32:31 +0000175 void VisitLambdaExpr(LambdaExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000176 void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
John McCall5d413782010-12-06 08:20:24 +0000177 void VisitExprWithCleanups(ExprWithCleanups *E);
Douglas Gregor747eb782010-07-08 06:14:04 +0000178 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Mike Stump5bbbb132009-11-18 00:40:12 +0000179 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
Douglas Gregorfe314812011-06-21 17:03:29 +0000180 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
John McCall1bf58462011-02-16 08:02:54 +0000181 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
182
John McCallfe96e0b2011-11-06 09:01:30 +0000183 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
184 if (E->isGLValue()) {
185 LValue LV = CGF.EmitPseudoObjectLValue(E);
John McCall4e8ca4f2012-07-02 23:58:38 +0000186 return EmitFinalDestCopy(E->getType(), LV);
John McCallfe96e0b2011-11-06 09:01:30 +0000187 }
188
189 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
190 }
191
Eli Friedman21911e82008-05-27 15:51:49 +0000192 void VisitVAArgExpr(VAArgExpr *E);
Chris Lattner579a05d2008-04-04 18:42:16 +0000193
Chad Rosier615ed1a2012-03-29 17:37:10 +0000194 void EmitInitializationToLValue(Expr *E, LValue Address);
John McCall1553b192011-06-16 04:16:24 +0000195 void EmitNullInitializationToLValue(LValue Address);
Chris Lattner4758b402007-08-21 04:25:47 +0000196 // case Expr::ChooseExprClass:
Mike Stumpf16b8c32009-12-09 19:24:08 +0000197 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000198 void VisitAtomicExpr(AtomicExpr *E) {
199 CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
200 }
Chris Lattner4758b402007-08-21 04:25:47 +0000201};
202} // end anonymous namespace.
203
Chris Lattner835635d2007-08-21 04:59:27 +0000204//===----------------------------------------------------------------------===//
205// Utilities
206//===----------------------------------------------------------------------===//
Chris Lattner4758b402007-08-21 04:25:47 +0000207
Chris Lattner6278e6a2007-08-11 00:04:45 +0000208/// EmitAggLoadOfLValue - Given an expression with aggregate type that
209/// represents a value lvalue, this method emits the address of the lvalue,
210/// then loads the result into DestPtr.
Chris Lattner4758b402007-08-21 04:25:47 +0000211void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
212 LValue LV = CGF.EmitLValue(E);
John McCalla8ec7eb2013-03-07 21:37:17 +0000213
214 // If the type of the l-value is atomic, then do an atomic load.
David Majnemera5b195a2015-02-14 01:35:12 +0000215 if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000216 CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
John McCalla8ec7eb2013-03-07 21:37:17 +0000217 return;
218 }
219
John McCall4e8ca4f2012-07-02 23:58:38 +0000220 EmitFinalDestCopy(E->getType(), LV);
Mike Stumpca9fc092009-05-23 20:28:01 +0000221}
222
John McCallcc04e9f2010-05-22 22:13:32 +0000223/// \brief True if the given aggregate type requires special GC API calls.
224bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
225 // Only record types have members that might require garbage collection.
226 const RecordType *RecordTy = T->getAs<RecordType>();
227 if (!RecordTy) return false;
228
229 // Don't mess with non-trivial C++ types.
230 RecordDecl *Record = RecordTy->getDecl();
231 if (isa<CXXRecordDecl>(Record) &&
Richard Smith16488472012-11-16 00:53:38 +0000232 (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
John McCallcc04e9f2010-05-22 22:13:32 +0000233 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
234 return false;
235
236 // Check whether the type has an object member.
237 return Record->hasObjectMember();
238}
239
John McCalla5efa732011-08-25 23:04:34 +0000240/// \brief Perform the final move to DestPtr if for some reason
241/// getReturnValueSlot() didn't use it directly.
John McCallcc04e9f2010-05-22 22:13:32 +0000242///
243/// The idea is that you do something like this:
244/// RValue Result = EmitSomething(..., getReturnValueSlot());
John McCalla5efa732011-08-25 23:04:34 +0000245/// EmitMoveFromReturnSlot(E, Result);
246///
247/// If nothing interferes, this will cause the result to be emitted
248/// directly into the return value slot. Otherwise, a final move
249/// will be performed.
John McCall4e8ca4f2012-07-02 23:58:38 +0000250void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
John McCalla5efa732011-08-25 23:04:34 +0000251 if (shouldUseDestForReturnSlot()) {
252 // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
253 // The possibility of undef rvalues complicates that a lot,
254 // though, so we can't really assert.
255 return;
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000256 }
John McCalla5efa732011-08-25 23:04:34 +0000257
John McCall4e8ca4f2012-07-02 23:58:38 +0000258 // Otherwise, copy from there to the destination.
259 assert(Dest.getAddr() != src.getAggregateAddr());
260 std::pair<CharUnits, CharUnits> typeInfo =
Chad Rosier1e303ee2012-04-17 01:14:29 +0000261 CGF.getContext().getTypeInfoInChars(E->getType());
John McCall4e8ca4f2012-07-02 23:58:38 +0000262 EmitFinalDestCopy(E->getType(), src, typeInfo.second);
John McCallcc04e9f2010-05-22 22:13:32 +0000263}
264
Mike Stumpca9fc092009-05-23 20:28:01 +0000265/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
John McCall4e8ca4f2012-07-02 23:58:38 +0000266void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src,
267 CharUnits srcAlign) {
268 assert(src.isAggregate() && "value must be aggregate value!");
269 LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddr(), type, srcAlign);
270 EmitFinalDestCopy(type, srcLV);
271}
Mike Stumpca9fc092009-05-23 20:28:01 +0000272
John McCall4e8ca4f2012-07-02 23:58:38 +0000273/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
274void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src) {
John McCall7a626f62010-09-15 10:14:12 +0000275 // If Dest is ignored, then we're evaluating an aggregate expression
John McCall4e8ca4f2012-07-02 23:58:38 +0000276 // in a context that doesn't care about the result. Note that loads
277 // from volatile l-values force the existence of a non-ignored
278 // destination.
279 if (Dest.isIgnored())
280 return;
Fariborz Jahanianc1236232010-10-22 22:05:03 +0000281
John McCall4e8ca4f2012-07-02 23:58:38 +0000282 AggValueSlot srcAgg =
283 AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
284 needsGC(type), AggValueSlot::IsAliased);
285 EmitCopy(type, Dest, srcAgg);
286}
Chris Lattner6278e6a2007-08-11 00:04:45 +0000287
John McCall4e8ca4f2012-07-02 23:58:38 +0000288/// Perform a copy from the source into the destination.
289///
290/// \param type - the type of the aggregate being copied; qualifiers are
291/// ignored
292void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
293 const AggValueSlot &src) {
294 if (dest.requiresGCollection()) {
295 CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
296 llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
Fariborz Jahanian879d7262009-08-31 19:33:16 +0000297 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
John McCall4e8ca4f2012-07-02 23:58:38 +0000298 dest.getAddr(),
299 src.getAddr(),
300 size);
Fariborz Jahanian879d7262009-08-31 19:33:16 +0000301 return;
302 }
John McCall4e8ca4f2012-07-02 23:58:38 +0000303
Mike Stumpca9fc092009-05-23 20:28:01 +0000304 // If the result of the assignment is used, copy the LHS there also.
John McCall4e8ca4f2012-07-02 23:58:38 +0000305 // It's volatile if either side is. Use the minimum alignment of
306 // the two sides.
307 CGF.EmitAggregateCopy(dest.getAddr(), src.getAddr(), type,
308 dest.isVolatile() || src.isVolatile(),
309 std::min(dest.getAlignment(), src.getAlignment()));
Chris Lattner6278e6a2007-08-11 00:04:45 +0000310}
311
Sebastian Redlc83ed822012-02-17 08:42:25 +0000312/// \brief Emit the initializer for a std::initializer_list initialized with a
313/// real initializer list.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000314void
315AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
316 // Emit an array containing the elements. The array is externally destructed
317 // if the std::initializer_list object is.
318 ASTContext &Ctx = CGF.getContext();
319 LValue Array = CGF.EmitLValue(E->getSubExpr());
320 assert(Array.isSimple() && "initializer_list array not a simple lvalue");
321 llvm::Value *ArrayPtr = Array.getAddress();
Sebastian Redlc83ed822012-02-17 08:42:25 +0000322
Richard Smithcc1b96d2013-06-12 22:31:48 +0000323 const ConstantArrayType *ArrayType =
324 Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
325 assert(ArrayType && "std::initializer_list constructed from non-array");
Sebastian Redlc83ed822012-02-17 08:42:25 +0000326
Richard Smithcc1b96d2013-06-12 22:31:48 +0000327 // FIXME: Perform the checks on the field types in SemaInit.
328 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
329 RecordDecl::field_iterator Field = Record->field_begin();
330 if (Field == Record->field_end()) {
331 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlf2e0a302012-02-25 20:51:13 +0000332 return;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000333 }
334
Sebastian Redlc83ed822012-02-17 08:42:25 +0000335 // Start pointer.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000336 if (!Field->getType()->isPointerType() ||
337 !Ctx.hasSameType(Field->getType()->getPointeeType(),
338 ArrayType->getElementType())) {
339 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlf2e0a302012-02-25 20:51:13 +0000340 return;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000341 }
Sebastian Redlc83ed822012-02-17 08:42:25 +0000342
Richard Smithcc1b96d2013-06-12 22:31:48 +0000343 AggValueSlot Dest = EnsureSlot(E->getType());
344 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
345 Dest.getAlignment());
346 LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
347 llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
348 llvm::Value *IdxStart[] = { Zero, Zero };
349 llvm::Value *ArrayStart =
350 Builder.CreateInBoundsGEP(ArrayPtr, IdxStart, "arraystart");
351 CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
352 ++Field;
353
354 if (Field == Record->field_end()) {
355 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlf2e0a302012-02-25 20:51:13 +0000356 return;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000357 }
Richard Smithcc1b96d2013-06-12 22:31:48 +0000358
359 llvm::Value *Size = Builder.getInt(ArrayType->getSize());
360 LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
361 if (Field->getType()->isPointerType() &&
362 Ctx.hasSameType(Field->getType()->getPointeeType(),
363 ArrayType->getElementType())) {
Sebastian Redlc83ed822012-02-17 08:42:25 +0000364 // End pointer.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000365 llvm::Value *IdxEnd[] = { Zero, Size };
366 llvm::Value *ArrayEnd =
367 Builder.CreateInBoundsGEP(ArrayPtr, IdxEnd, "arrayend");
368 CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
369 } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
Sebastian Redlc83ed822012-02-17 08:42:25 +0000370 // Length.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000371 CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000372 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +0000373 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlf2e0a302012-02-25 20:51:13 +0000374 return;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000375 }
Sebastian Redlc83ed822012-02-17 08:42:25 +0000376}
377
Richard Smith8edda962014-06-13 23:04:49 +0000378/// \brief Determine if E is a trivial array filler, that is, one that is
379/// equivalent to zero-initialization.
380static bool isTrivialFiller(Expr *E) {
381 if (!E)
382 return true;
383
384 if (isa<ImplicitValueInitExpr>(E))
385 return true;
386
387 if (auto *ILE = dyn_cast<InitListExpr>(E)) {
388 if (ILE->getNumInits())
389 return false;
390 return isTrivialFiller(ILE->getArrayFiller());
391 }
392
393 if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
394 return Cons->getConstructor()->isDefaultConstructor() &&
395 Cons->getConstructor()->isTrivial();
396
397 // FIXME: Are there other cases where we can avoid emitting an initializer?
398 return false;
399}
400
Sebastian Redlc83ed822012-02-17 08:42:25 +0000401/// \brief Emit initialization of an array from an initializer list.
402void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
403 QualType elementType, InitListExpr *E) {
404 uint64_t NumInitElements = E->getNumInits();
405
406 uint64_t NumArrayElements = AType->getNumElements();
407 assert(NumInitElements <= NumArrayElements);
408
409 // DestPtr is an array*. Construct an elementType* by drilling
410 // down a level.
411 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
412 llvm::Value *indices[] = { zero, zero };
413 llvm::Value *begin =
414 Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
415
416 // Exception safety requires us to destroy all the
417 // already-constructed members if an initializer throws.
418 // For that, we'll need an EH cleanup.
419 QualType::DestructionKind dtorKind = elementType.isDestructedType();
Craig Topper8a13c412014-05-21 05:09:00 +0000420 llvm::AllocaInst *endOfInit = nullptr;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000421 EHScopeStack::stable_iterator cleanup;
Craig Topper8a13c412014-05-21 05:09:00 +0000422 llvm::Instruction *cleanupDominator = nullptr;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000423 if (CGF.needsEHCleanup(dtorKind)) {
424 // In principle we could tell the cleanup where we are more
425 // directly, but the control flow can get so varied here that it
426 // would actually be quite complex. Therefore we go through an
427 // alloca.
428 endOfInit = CGF.CreateTempAlloca(begin->getType(),
429 "arrayinit.endOfInit");
430 cleanupDominator = Builder.CreateStore(begin, endOfInit);
431 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
432 CGF.getDestroyer(dtorKind));
433 cleanup = CGF.EHStack.stable_begin();
434
435 // Otherwise, remember that we didn't need a cleanup.
436 } else {
437 dtorKind = QualType::DK_none;
438 }
439
440 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
441
442 // The 'current element to initialize'. The invariants on this
443 // variable are complicated. Essentially, after each iteration of
444 // the loop, it points to the last initialized element, except
445 // that it points to the beginning of the array before any
446 // elements have been initialized.
447 llvm::Value *element = begin;
448
449 // Emit the explicit initializers.
450 for (uint64_t i = 0; i != NumInitElements; ++i) {
451 // Advance to the next element.
452 if (i > 0) {
453 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
454
455 // Tell the cleanup that it needs to destroy up to this
456 // element. TODO: some of these stores can be trivially
457 // observed to be unnecessary.
458 if (endOfInit) Builder.CreateStore(element, endOfInit);
459 }
460
Richard Smithcc1b96d2013-06-12 22:31:48 +0000461 LValue elementLV = CGF.MakeAddrLValue(element, elementType);
462 EmitInitializationToLValue(E->getInit(i), elementLV);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000463 }
464
465 // Check whether there's a non-trivial array-fill expression.
Sebastian Redlc83ed822012-02-17 08:42:25 +0000466 Expr *filler = E->getArrayFiller();
Richard Smith8edda962014-06-13 23:04:49 +0000467 bool hasTrivialFiller = isTrivialFiller(filler);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000468
469 // Any remaining elements need to be zero-initialized, possibly
470 // using the filler expression. We can skip this if the we're
471 // emitting to zeroed memory.
472 if (NumInitElements != NumArrayElements &&
473 !(Dest.isZeroed() && hasTrivialFiller &&
474 CGF.getTypes().isZeroInitializable(elementType))) {
475
476 // Use an actual loop. This is basically
477 // do { *array++ = filler; } while (array != end);
478
479 // Advance to the start of the rest of the array.
480 if (NumInitElements) {
481 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
482 if (endOfInit) Builder.CreateStore(element, endOfInit);
483 }
484
485 // Compute the end of the array.
486 llvm::Value *end = Builder.CreateInBoundsGEP(begin,
487 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
488 "arrayinit.end");
489
490 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
491 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
492
493 // Jump into the body.
494 CGF.EmitBlock(bodyBB);
495 llvm::PHINode *currentElement =
496 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
497 currentElement->addIncoming(element, entryBB);
498
499 // Emit the actual filler expression.
500 LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
501 if (filler)
Chad Rosier615ed1a2012-03-29 17:37:10 +0000502 EmitInitializationToLValue(filler, elementLV);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000503 else
504 EmitNullInitializationToLValue(elementLV);
505
506 // Move on to the next element.
507 llvm::Value *nextElement =
508 Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
509
510 // Tell the EH cleanup that we finished with the last element.
511 if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
512
513 // Leave the loop if we're done.
514 llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
515 "arrayinit.done");
516 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
517 Builder.CreateCondBr(done, endBB, bodyBB);
518 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
519
520 CGF.EmitBlock(endBB);
521 }
522
523 // Leave the partial-array cleanup if we entered one.
524 if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
525}
526
Chris Lattner835635d2007-08-21 04:59:27 +0000527//===----------------------------------------------------------------------===//
528// Visitor Methods
529//===----------------------------------------------------------------------===//
530
Douglas Gregorfe314812011-06-21 17:03:29 +0000531void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
532 Visit(E->GetTemporaryExpr());
533}
534
John McCall1bf58462011-02-16 08:02:54 +0000535void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
John McCall4e8ca4f2012-07-02 23:58:38 +0000536 EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e));
John McCall1bf58462011-02-16 08:02:54 +0000537}
538
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000539void
540AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCallbea4c3d2013-03-07 21:36:54 +0000541 if (Dest.isPotentiallyAliased() &&
542 E->getType().isPODType(CGF.getContext())) {
Douglas Gregor6c9d31e2011-06-17 16:37:20 +0000543 // For a POD type, just emit a load of the lvalue + a copy, because our
544 // compound literal might alias the destination.
Douglas Gregor6c9d31e2011-06-17 16:37:20 +0000545 EmitAggLoadOfLValue(E);
546 return;
547 }
548
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000549 AggValueSlot Slot = EnsureSlot(E->getType());
550 CGF.EmitAggExpr(E->getInitializer(), Slot);
551}
552
John McCalla8ec7eb2013-03-07 21:37:17 +0000553/// Attempt to look through various unimportant expressions to find a
554/// cast of the given kind.
555static Expr *findPeephole(Expr *op, CastKind kind) {
556 while (true) {
557 op = op->IgnoreParens();
558 if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
559 if (castE->getCastKind() == kind)
560 return castE->getSubExpr();
561 if (castE->getCastKind() == CK_NoOp)
562 continue;
563 }
Craig Topper8a13c412014-05-21 05:09:00 +0000564 return nullptr;
John McCalla8ec7eb2013-03-07 21:37:17 +0000565 }
566}
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000567
Anders Carlssonec143772009-08-07 23:22:37 +0000568void AggExprEmitter::VisitCastExpr(CastExpr *E) {
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000569 switch (E->getCastKind()) {
Anders Carlsson8a01a752011-04-11 02:03:26 +0000570 case CK_Dynamic: {
Richard Smith69d0d262012-08-24 00:54:33 +0000571 // FIXME: Can this actually happen? We have no test coverage for it.
Douglas Gregor1c073f42010-05-14 21:31:02 +0000572 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
Richard Smith69d0d262012-08-24 00:54:33 +0000573 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
Richard Smith4d1458e2012-09-08 02:08:36 +0000574 CodeGenFunction::TCK_Load);
Douglas Gregor1c073f42010-05-14 21:31:02 +0000575 // FIXME: Do we also need to handle property references here?
576 if (LV.isSimple())
577 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
578 else
579 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
580
John McCall7a626f62010-09-15 10:14:12 +0000581 if (!Dest.isIgnored())
582 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
Douglas Gregor1c073f42010-05-14 21:31:02 +0000583 break;
584 }
585
John McCalle3027922010-08-25 11:45:40 +0000586 case CK_ToUnion: {
Reid Kleckner892bb0c2015-05-20 21:59:25 +0000587 // Evaluate even if the destination is ignored.
588 if (Dest.isIgnored()) {
589 CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
590 /*ignoreResult=*/true);
591 break;
592 }
John McCall58989b72011-04-12 22:02:02 +0000593
Anders Carlssonec143772009-08-07 23:22:37 +0000594 // GCC union extension
Daniel Dunbar2e442a02010-08-21 03:15:20 +0000595 QualType Ty = E->getSubExpr()->getType();
596 QualType PtrTy = CGF.getContext().getPointerType(Ty);
John McCall7a626f62010-09-15 10:14:12 +0000597 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
Eli Friedmandd274842009-06-03 20:45:06 +0000598 CGF.ConvertType(PtrTy));
John McCall1553b192011-06-16 04:16:24 +0000599 EmitInitializationToLValue(E->getSubExpr(),
Chad Rosier615ed1a2012-03-29 17:37:10 +0000600 CGF.MakeAddrLValue(CastPtr, Ty));
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000601 break;
Nuno Lopes7ffcf932009-01-15 20:14:33 +0000602 }
Mike Stump11289f42009-09-09 15:08:12 +0000603
John McCalle3027922010-08-25 11:45:40 +0000604 case CK_DerivedToBase:
605 case CK_BaseToDerived:
606 case CK_UncheckedDerivedToBase: {
David Blaikie83d382b2011-09-23 05:06:16 +0000607 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
Douglas Gregoraae38d62010-05-22 05:17:18 +0000608 "should have been unpacked before we got here");
Douglas Gregoraae38d62010-05-22 05:17:18 +0000609 }
610
John McCalla8ec7eb2013-03-07 21:37:17 +0000611 case CK_NonAtomicToAtomic:
612 case CK_AtomicToNonAtomic: {
613 bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
614
615 // Determine the atomic and value types.
616 QualType atomicType = E->getSubExpr()->getType();
617 QualType valueType = E->getType();
618 if (isToAtomic) std::swap(atomicType, valueType);
619
620 assert(atomicType->isAtomicType());
621 assert(CGF.getContext().hasSameUnqualifiedType(valueType,
622 atomicType->castAs<AtomicType>()->getValueType()));
623
624 // Just recurse normally if we're ignoring the result or the
625 // atomic type doesn't change representation.
626 if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
627 return Visit(E->getSubExpr());
628 }
629
630 CastKind peepholeTarget =
631 (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
632
633 // These two cases are reverses of each other; try to peephole them.
634 if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
635 assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
636 E->getType()) &&
637 "peephole significantly changed types?");
638 return Visit(op);
639 }
640
641 // If we're converting an r-value of non-atomic type to an r-value
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000642 // of atomic type, just emit directly into the relevant sub-object.
John McCalla8ec7eb2013-03-07 21:37:17 +0000643 if (isToAtomic) {
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000644 AggValueSlot valueDest = Dest;
645 if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
646 // Zero-initialize. (Strictly speaking, we only need to intialize
647 // the padding at the end, but this is simpler.)
648 if (!Dest.isZeroed())
Eli Friedman035b39e2013-07-11 02:28:36 +0000649 CGF.EmitNullInitialization(Dest.getAddr(), atomicType);
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000650
651 // Build a GEP to refer to the subobject.
652 llvm::Value *valueAddr =
David Blaikie1ed728c2015-04-05 22:45:47 +0000653 CGF.Builder.CreateStructGEP(nullptr, valueDest.getAddr(), 0);
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000654 valueDest = AggValueSlot::forAddr(valueAddr,
655 valueDest.getAlignment(),
656 valueDest.getQualifiers(),
657 valueDest.isExternallyDestructed(),
658 valueDest.requiresGCollection(),
659 valueDest.isPotentiallyAliased(),
660 AggValueSlot::IsZeroed);
661 }
662
Eli Friedman035b39e2013-07-11 02:28:36 +0000663 CGF.EmitAggExpr(E->getSubExpr(), valueDest);
John McCalla8ec7eb2013-03-07 21:37:17 +0000664 return;
665 }
666
667 // Otherwise, we're converting an atomic type to a non-atomic type.
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000668 // Make an atomic temporary, emit into that, and then copy the value out.
John McCalla8ec7eb2013-03-07 21:37:17 +0000669 AggValueSlot atomicSlot =
670 CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
671 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
672
673 llvm::Value *valueAddr =
David Blaikie2e804282015-04-05 22:47:07 +0000674 Builder.CreateStructGEP(nullptr, atomicSlot.getAddr(), 0);
John McCalla8ec7eb2013-03-07 21:37:17 +0000675 RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
676 return EmitFinalDestCopy(valueType, rvalue);
677 }
678
John McCall4e8ca4f2012-07-02 23:58:38 +0000679 case CK_LValueToRValue:
680 // If we're loading from a volatile type, force the destination
681 // into existence.
682 if (E->getSubExpr()->getType().isVolatileQualified()) {
683 EnsureDest(E->getType());
684 return Visit(E->getSubExpr());
685 }
John McCalla8ec7eb2013-03-07 21:37:17 +0000686
John McCall4e8ca4f2012-07-02 23:58:38 +0000687 // fallthrough
688
John McCalle3027922010-08-25 11:45:40 +0000689 case CK_NoOp:
690 case CK_UserDefinedConversion:
691 case CK_ConstructorConversion:
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000692 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
693 E->getType()) &&
694 "Implicit cast types must be compatible");
695 Visit(E->getSubExpr());
696 break;
John McCallf3735e02010-12-01 04:43:34 +0000697
John McCalle3027922010-08-25 11:45:40 +0000698 case CK_LValueBitCast:
John McCallf3735e02010-12-01 04:43:34 +0000699 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
John McCall31996342011-04-07 08:22:57 +0000700
John McCallf3735e02010-12-01 04:43:34 +0000701 case CK_Dependent:
702 case CK_BitCast:
703 case CK_ArrayToPointerDecay:
704 case CK_FunctionToPointerDecay:
705 case CK_NullToPointer:
706 case CK_NullToMemberPointer:
707 case CK_BaseToDerivedMemberPointer:
708 case CK_DerivedToBaseMemberPointer:
709 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +0000710 case CK_ReinterpretMemberPointer:
John McCallf3735e02010-12-01 04:43:34 +0000711 case CK_IntegralToPointer:
712 case CK_PointerToIntegral:
713 case CK_PointerToBoolean:
714 case CK_ToVoid:
715 case CK_VectorSplat:
716 case CK_IntegralCast:
717 case CK_IntegralToBoolean:
718 case CK_IntegralToFloating:
719 case CK_FloatingToIntegral:
720 case CK_FloatingToBoolean:
721 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +0000722 case CK_CPointerToObjCPointerCast:
723 case CK_BlockPointerToObjCPointerCast:
John McCallf3735e02010-12-01 04:43:34 +0000724 case CK_AnyPointerToBlockPointerCast:
725 case CK_ObjCObjectLValueCast:
726 case CK_FloatingRealToComplex:
727 case CK_FloatingComplexToReal:
728 case CK_FloatingComplexToBoolean:
729 case CK_FloatingComplexCast:
730 case CK_FloatingComplexToIntegralComplex:
731 case CK_IntegralRealToComplex:
732 case CK_IntegralComplexToReal:
733 case CK_IntegralComplexToBoolean:
734 case CK_IntegralComplexCast:
735 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +0000736 case CK_ARCProduceObject:
737 case CK_ARCConsumeObject:
738 case CK_ARCReclaimReturnedObject:
739 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +0000740 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +0000741 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000742 case CK_ZeroToOCLEvent:
David Tweede1468322013-12-11 13:39:46 +0000743 case CK_AddressSpaceConversion:
John McCallf3735e02010-12-01 04:43:34 +0000744 llvm_unreachable("cast kind invalid for aggregate types");
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000745 }
Anders Carlsson1ba25ca2008-01-14 06:28:57 +0000746}
747
Chris Lattner0f398c42008-07-26 22:37:01 +0000748void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
David Majnemerced8bdf2015-02-25 17:36:15 +0000749 if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
Anders Carlssonddcbfe72009-05-27 16:45:02 +0000750 EmitAggLoadOfLValue(E);
751 return;
752 }
Mike Stump11289f42009-09-09 15:08:12 +0000753
John McCallcc04e9f2010-05-22 22:13:32 +0000754 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
John McCalla5efa732011-08-25 23:04:34 +0000755 EmitMoveFromReturnSlot(E, RV);
Anders Carlsson0370eb22007-10-31 22:04:46 +0000756}
Chris Lattner0f398c42008-07-26 22:37:01 +0000757
758void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCallcc04e9f2010-05-22 22:13:32 +0000759 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
John McCalla5efa732011-08-25 23:04:34 +0000760 EmitMoveFromReturnSlot(E, RV);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000761}
Anders Carlsson0370eb22007-10-31 22:04:46 +0000762
Chris Lattner0f398c42008-07-26 22:37:01 +0000763void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCalla2342eb2010-12-05 02:00:02 +0000764 CGF.EmitIgnoredExpr(E->getLHS());
John McCall7a626f62010-09-15 10:14:12 +0000765 Visit(E->getRHS());
Eli Friedman4b0e2a32008-05-20 07:56:31 +0000766}
767
Chris Lattner49e3bfa2007-08-31 22:54:14 +0000768void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCallce1de612011-01-26 04:00:11 +0000769 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall7a626f62010-09-15 10:14:12 +0000770 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
Chris Lattner49e3bfa2007-08-31 22:54:14 +0000771}
772
Chris Lattner4758b402007-08-21 04:25:47 +0000773void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000774 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +0000775 VisitPointerToDataMemberBinaryOperator(E);
776 else
777 CGF.ErrorUnsupported(E, "aggregate binary expression");
778}
779
780void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
781 const BinaryOperator *E) {
782 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
John McCall4e8ca4f2012-07-02 23:58:38 +0000783 EmitFinalDestCopy(E->getType(), LV);
784}
785
786/// Is the value of the given expression possibly a reference to or
787/// into a __block variable?
788static bool isBlockVarRef(const Expr *E) {
789 // Make sure we look through parens.
790 E = E->IgnoreParens();
791
792 // Check for a direct reference to a __block variable.
793 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
794 const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
795 return (var && var->hasAttr<BlocksAttr>());
796 }
797
798 // More complicated stuff.
799
800 // Binary operators.
801 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
802 // For an assignment or pointer-to-member operation, just care
803 // about the LHS.
804 if (op->isAssignmentOp() || op->isPtrMemOp())
805 return isBlockVarRef(op->getLHS());
806
807 // For a comma, just care about the RHS.
808 if (op->getOpcode() == BO_Comma)
809 return isBlockVarRef(op->getRHS());
810
811 // FIXME: pointer arithmetic?
812 return false;
813
814 // Check both sides of a conditional operator.
815 } else if (const AbstractConditionalOperator *op
816 = dyn_cast<AbstractConditionalOperator>(E)) {
817 return isBlockVarRef(op->getTrueExpr())
818 || isBlockVarRef(op->getFalseExpr());
819
820 // OVEs are required to support BinaryConditionalOperators.
821 } else if (const OpaqueValueExpr *op
822 = dyn_cast<OpaqueValueExpr>(E)) {
823 if (const Expr *src = op->getSourceExpr())
824 return isBlockVarRef(src);
825
826 // Casts are necessary to get things like (*(int*)&var) = foo().
827 // We don't really care about the kind of cast here, except
828 // we don't want to look through l2r casts, because it's okay
829 // to get the *value* in a __block variable.
830 } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
831 if (cast->getCastKind() == CK_LValueToRValue)
832 return false;
833 return isBlockVarRef(cast->getSubExpr());
834
835 // Handle unary operators. Again, just aggressively look through
836 // it, ignoring the operation.
837 } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
838 return isBlockVarRef(uop->getSubExpr());
839
840 // Look into the base of a field access.
841 } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
842 return isBlockVarRef(mem->getBase());
843
844 // Look into the base of a subscript.
845 } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
846 return isBlockVarRef(sub->getBase());
847 }
848
849 return false;
Chris Lattner835635d2007-08-21 04:59:27 +0000850}
851
Chris Lattnercd9fb242007-08-21 04:43:17 +0000852void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Eli Friedmanf54c4e52008-02-11 01:09:17 +0000853 // For an assignment to work, the value on the right has
854 // to be compatible with the value on the left.
Eli Friedman2a695472009-05-28 23:04:00 +0000855 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
856 E->getRHS()->getType())
Eli Friedmanf54c4e52008-02-11 01:09:17 +0000857 && "Invalid assignment");
John McCalld0a30012010-12-06 06:10:02 +0000858
John McCall4e8ca4f2012-07-02 23:58:38 +0000859 // If the LHS might be a __block variable, and the RHS can
860 // potentially cause a block copy, we need to evaluate the RHS first
861 // so that the assignment goes the right place.
862 // This is pretty semantically fragile.
863 if (isBlockVarRef(E->getLHS()) &&
864 E->getRHS()->HasSideEffects(CGF.getContext())) {
865 // Ensure that we have a destination, and evaluate the RHS into that.
866 EnsureDest(E->getRHS()->getType());
867 Visit(E->getRHS());
868
869 // Now emit the LHS and copy into it.
Richard Smithe30752c2012-10-09 19:52:38 +0000870 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall4e8ca4f2012-07-02 23:58:38 +0000871
John McCalla8ec7eb2013-03-07 21:37:17 +0000872 // That copy is an atomic copy if the LHS is atomic.
David Majnemera5b195a2015-02-14 01:35:12 +0000873 if (LHS.getType()->isAtomicType() ||
874 CGF.LValueIsSuitableForInlineAtomic(LHS)) {
John McCalla8ec7eb2013-03-07 21:37:17 +0000875 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
876 return;
877 }
878
John McCall4e8ca4f2012-07-02 23:58:38 +0000879 EmitCopy(E->getLHS()->getType(),
880 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
881 needsGC(E->getLHS()->getType()),
882 AggValueSlot::IsAliased),
883 Dest);
884 return;
885 }
Chad Rosier615ed1a2012-03-29 17:37:10 +0000886
Chris Lattner4758b402007-08-21 04:25:47 +0000887 LValue LHS = CGF.EmitLValue(E->getLHS());
Chris Lattner6278e6a2007-08-11 00:04:45 +0000888
John McCalla8ec7eb2013-03-07 21:37:17 +0000889 // If we have an atomic type, evaluate into the destination and then
890 // do an atomic copy.
David Majnemera5b195a2015-02-14 01:35:12 +0000891 if (LHS.getType()->isAtomicType() ||
892 CGF.LValueIsSuitableForInlineAtomic(LHS)) {
John McCalla8ec7eb2013-03-07 21:37:17 +0000893 EnsureDest(E->getRHS()->getType());
894 Visit(E->getRHS());
895 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
896 return;
897 }
898
John McCallc109a252011-11-07 03:59:57 +0000899 // Codegen the RHS so that it stores directly into the LHS.
900 AggValueSlot LHSSlot =
901 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
902 needsGC(E->getLHS()->getType()),
Chad Rosier615ed1a2012-03-29 17:37:10 +0000903 AggValueSlot::IsAliased);
Fariborz Jahanian78652202013-01-25 23:57:05 +0000904 // A non-volatile aggregate destination might have volatile member.
905 if (!LHSSlot.isVolatile() &&
906 CGF.hasVolatileMember(E->getLHS()->getType()))
907 LHSSlot.setVolatile(true);
908
John McCall4e8ca4f2012-07-02 23:58:38 +0000909 CGF.EmitAggExpr(E->getRHS(), LHSSlot);
910
911 // Copy into the destination if the assignment isn't ignored.
912 EmitFinalDestCopy(E->getType(), LHS);
Chris Lattner6278e6a2007-08-11 00:04:45 +0000913}
914
John McCallc07a0c72011-02-17 10:25:35 +0000915void AggExprEmitter::
916VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Daniel Dunbara612e792008-11-13 01:38:36 +0000917 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
918 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
919 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Mike Stump11289f42009-09-09 15:08:12 +0000920
John McCallc07a0c72011-02-17 10:25:35 +0000921 // Bind the common expression if necessary.
Eli Friedman48fd89a2012-01-06 20:42:20 +0000922 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCallc07a0c72011-02-17 10:25:35 +0000923
John McCallce1de612011-01-26 04:00:11 +0000924 CodeGenFunction::ConditionalEvaluation eval(CGF);
Justin Bogner66242d62015-04-23 23:06:47 +0000925 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
926 CGF.getProfileCount(E));
Mike Stump11289f42009-09-09 15:08:12 +0000927
John McCall5b26f652010-11-17 00:07:33 +0000928 // Save whether the destination's lifetime is externally managed.
John McCallcac93852011-08-26 08:02:37 +0000929 bool isExternallyDestructed = Dest.isExternallyDestructed();
Chris Lattner6278e6a2007-08-11 00:04:45 +0000930
John McCallce1de612011-01-26 04:00:11 +0000931 eval.begin(CGF);
932 CGF.EmitBlock(LHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +0000933 CGF.incrementProfileCounter(E);
John McCallc07a0c72011-02-17 10:25:35 +0000934 Visit(E->getTrueExpr());
John McCallce1de612011-01-26 04:00:11 +0000935 eval.end(CGF);
Mike Stump11289f42009-09-09 15:08:12 +0000936
John McCallce1de612011-01-26 04:00:11 +0000937 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
938 CGF.Builder.CreateBr(ContBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000939
John McCall5b26f652010-11-17 00:07:33 +0000940 // If the result of an agg expression is unused, then the emission
941 // of the LHS might need to create a destination slot. That's fine
942 // with us, and we can safely emit the RHS into the same slot, but
John McCallcac93852011-08-26 08:02:37 +0000943 // we shouldn't claim that it's already being destructed.
944 Dest.setExternallyDestructed(isExternallyDestructed);
John McCall5b26f652010-11-17 00:07:33 +0000945
John McCallce1de612011-01-26 04:00:11 +0000946 eval.begin(CGF);
947 CGF.EmitBlock(RHSBlock);
John McCallc07a0c72011-02-17 10:25:35 +0000948 Visit(E->getFalseExpr());
John McCallce1de612011-01-26 04:00:11 +0000949 eval.end(CGF);
Mike Stump11289f42009-09-09 15:08:12 +0000950
Chris Lattner4758b402007-08-21 04:25:47 +0000951 CGF.EmitBlock(ContBlock);
Chris Lattner6278e6a2007-08-11 00:04:45 +0000952}
Chris Lattner835635d2007-08-21 04:59:27 +0000953
Anders Carlsson5b2095c2009-07-08 18:33:14 +0000954void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
Eli Friedman75807f22013-07-20 00:40:58 +0000955 Visit(CE->getChosenSubExpr());
Anders Carlsson5b2095c2009-07-08 18:33:14 +0000956}
957
Eli Friedman21911e82008-05-27 15:51:49 +0000958void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Daniel Dunbare9fcadd22009-02-11 22:25:55 +0000959 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson13abd7e2008-11-04 05:30:00 +0000960 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
961
Sebastian Redl020cddc2009-01-09 21:09:38 +0000962 if (!ArgPtr) {
Mark Seaborn74020862014-01-22 20:11:01 +0000963 // If EmitVAArg fails, we fall back to the LLVM instruction.
964 llvm::Value *Val =
965 Builder.CreateVAArg(ArgValue, CGF.ConvertType(VE->getType()));
966 if (!Dest.isIgnored())
967 Builder.CreateStore(Val, Dest.getAddr());
Sebastian Redl020cddc2009-01-09 21:09:38 +0000968 return;
969 }
970
John McCall4e8ca4f2012-07-02 23:58:38 +0000971 EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
Eli Friedman21911e82008-05-27 15:51:49 +0000972}
973
Anders Carlsson3be22e22009-05-30 23:23:33 +0000974void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +0000975 // Ensure that we have a slot, but if we already do, remember
John McCallcac93852011-08-26 08:02:37 +0000976 // whether it was externally destructed.
977 bool wasExternallyDestructed = Dest.isExternallyDestructed();
John McCall4e8ca4f2012-07-02 23:58:38 +0000978 EnsureDest(E->getType());
John McCallcac93852011-08-26 08:02:37 +0000979
980 // We're going to push a destructor if there isn't already one.
981 Dest.setExternallyDestructed();
Mike Stump11289f42009-09-09 15:08:12 +0000982
John McCall7a626f62010-09-15 10:14:12 +0000983 Visit(E->getSubExpr());
Anders Carlsson3be22e22009-05-30 23:23:33 +0000984
John McCallcac93852011-08-26 08:02:37 +0000985 // Push that destructor we promised.
986 if (!wasExternallyDestructed)
Peter Collingbourne702b2842011-11-27 22:09:22 +0000987 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
Anders Carlsson3be22e22009-05-30 23:23:33 +0000988}
989
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000990void
Anders Carlsson1619a5042009-05-03 17:47:16 +0000991AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +0000992 AggValueSlot Slot = EnsureSlot(E->getType());
993 CGF.EmitCXXConstructExpr(E, Slot);
Anders Carlssonc82b86d2009-05-19 04:48:36 +0000994}
995
Eli Friedmanc370a7e2012-02-09 03:32:31 +0000996void
997AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
998 AggValueSlot Slot = EnsureSlot(E->getType());
999 CGF.EmitLambdaExpr(E, Slot);
1000}
1001
John McCall5d413782010-12-06 08:20:24 +00001002void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall08ef4662011-11-10 08:15:53 +00001003 CGF.enterFullExpression(E);
1004 CodeGenFunction::RunCleanupsScope cleanups(CGF);
1005 Visit(E->getSubExpr());
Anders Carlssonb7f8f592009-04-17 00:06:03 +00001006}
1007
Douglas Gregor747eb782010-07-08 06:14:04 +00001008void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +00001009 QualType T = E->getType();
1010 AggValueSlot Slot = EnsureSlot(T);
John McCall1553b192011-06-16 04:16:24 +00001011 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Anders Carlsson18ada982009-12-16 06:57:54 +00001012}
1013
1014void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +00001015 QualType T = E->getType();
1016 AggValueSlot Slot = EnsureSlot(T);
John McCall1553b192011-06-16 04:16:24 +00001017 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Nuno Lopesff3507b2009-10-18 15:18:11 +00001018}
1019
Chris Lattner27a36312010-12-02 07:07:26 +00001020/// isSimpleZero - If emitting this value will obviously just cause a store of
1021/// zero to memory, return true. This can return false if uncertain, so it just
1022/// handles simple cases.
1023static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001024 E = E->IgnoreParens();
1025
Chris Lattner27a36312010-12-02 07:07:26 +00001026 // 0
1027 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1028 return IL->getValue() == 0;
1029 // +0.0
1030 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1031 return FL->getValue().isPosZero();
1032 // int()
1033 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
1034 CGF.getTypes().isZeroInitializable(E->getType()))
1035 return true;
1036 // (int*)0 - Null pointer expressions.
1037 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1038 return ICE->getCastKind() == CK_NullToPointer;
1039 // '\0'
1040 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1041 return CL->getValue() == 0;
1042
1043 // Otherwise, hard case: conservatively return false.
1044 return false;
1045}
1046
1047
Anders Carlssonb2473502010-02-03 17:33:16 +00001048void
Nick Lewycky2d84e842013-10-02 02:29:49 +00001049AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
John McCall1553b192011-06-16 04:16:24 +00001050 QualType type = LV.getType();
Mike Stumpdf0fe272009-05-29 15:46:01 +00001051 // FIXME: Ignore result?
Chris Lattner579a05d2008-04-04 18:42:16 +00001052 // FIXME: Are initializers affected by volatile?
Chris Lattner27a36312010-12-02 07:07:26 +00001053 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
1054 // Storing "i32 0" to a zero'd memory location is a noop.
John McCall47fb9502013-03-07 21:37:08 +00001055 return;
Richard Smithd82a2ce2012-12-21 03:17:28 +00001056 } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
John McCall47fb9502013-03-07 21:37:08 +00001057 return EmitNullInitializationToLValue(LV);
John McCall1553b192011-06-16 04:16:24 +00001058 } else if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001059 RValue RV = CGF.EmitReferenceBindingToExpr(E);
John McCall47fb9502013-03-07 21:37:08 +00001060 return CGF.EmitStoreThroughLValue(RV, LV);
1061 }
1062
1063 switch (CGF.getEvaluationKind(type)) {
1064 case TEK_Complex:
1065 CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1066 return;
1067 case TEK_Aggregate:
John McCall8d6fc952011-08-25 20:40:09 +00001068 CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
1069 AggValueSlot::IsDestructed,
1070 AggValueSlot::DoesNotNeedGCBarriers,
John McCalla5efa732011-08-25 23:04:34 +00001071 AggValueSlot::IsNotAliased,
John McCall1553b192011-06-16 04:16:24 +00001072 Dest.isZeroed()));
John McCall47fb9502013-03-07 21:37:08 +00001073 return;
1074 case TEK_Scalar:
1075 if (LV.isSimple()) {
Craig Topper8a13c412014-05-21 05:09:00 +00001076 CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
John McCall47fb9502013-03-07 21:37:08 +00001077 } else {
1078 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1079 }
1080 return;
Chris Lattner579a05d2008-04-04 18:42:16 +00001081 }
John McCall47fb9502013-03-07 21:37:08 +00001082 llvm_unreachable("bad evaluation kind");
Chris Lattner579a05d2008-04-04 18:42:16 +00001083}
1084
John McCall1553b192011-06-16 04:16:24 +00001085void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1086 QualType type = lv.getType();
1087
Chris Lattner27a36312010-12-02 07:07:26 +00001088 // If the destination slot is already zeroed out before the aggregate is
1089 // copied into it, we don't have to emit any zeros here.
John McCall1553b192011-06-16 04:16:24 +00001090 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
Chris Lattner27a36312010-12-02 07:07:26 +00001091 return;
1092
John McCall47fb9502013-03-07 21:37:08 +00001093 if (CGF.hasScalarEvaluationKind(type)) {
Richard Smithd82a2ce2012-12-21 03:17:28 +00001094 // For non-aggregates, we can store the appropriate null constant.
1095 llvm::Value *null = CGF.CGM.EmitNullConstant(type);
Eli Friedman91d5bb12012-02-22 05:38:59 +00001096 // Note that the following is not equivalent to
1097 // EmitStoreThroughBitfieldLValue for ARC types.
Eli Friedmancb3785e2012-02-24 23:53:49 +00001098 if (lv.isBitField()) {
Eli Friedman91d5bb12012-02-22 05:38:59 +00001099 CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
Eli Friedmancb3785e2012-02-24 23:53:49 +00001100 } else {
1101 assert(lv.isSimple());
1102 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1103 }
Lauro Ramos Venancioe2162c62008-02-19 19:27:31 +00001104 } else {
Chris Lattner579a05d2008-04-04 18:42:16 +00001105 // There's a potential optimization opportunity in combining
1106 // memsets; that would be easy for arrays, but relatively
1107 // difficult for structures with the current code.
John McCall1553b192011-06-16 04:16:24 +00001108 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
Chris Lattner579a05d2008-04-04 18:42:16 +00001109 }
1110}
1111
Chris Lattner579a05d2008-04-04 18:42:16 +00001112void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
Eli Friedmanf5d08c92008-12-02 01:17:45 +00001113#if 0
Eli Friedman6d11ec82009-12-04 01:30:56 +00001114 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
1115 // (Length of globals? Chunks of zeroed-out space?).
Eli Friedmanf5d08c92008-12-02 01:17:45 +00001116 //
Mike Stump18bb9282009-05-16 07:57:57 +00001117 // If we can, prefer a copy from a global; this is a lot less code for long
1118 // globals, and it's easier for the current optimizers to analyze.
Eli Friedman6d11ec82009-12-04 01:30:56 +00001119 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
Eli Friedmanc59bb482008-11-30 02:11:09 +00001120 llvm::GlobalVariable* GV =
Eli Friedman6d11ec82009-12-04 01:30:56 +00001121 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1122 llvm::GlobalValue::InternalLinkage, C, "");
John McCall4e8ca4f2012-07-02 23:58:38 +00001123 EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
Eli Friedmanc59bb482008-11-30 02:11:09 +00001124 return;
1125 }
Eli Friedmanf5d08c92008-12-02 01:17:45 +00001126#endif
Chris Lattnerf53c0962010-09-06 00:11:41 +00001127 if (E->hadArrayRangeDesignator())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001128 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001129
Richard Smithbe93c002013-05-23 21:54:14 +00001130 AggValueSlot Dest = EnsureSlot(E->getType());
1131
Eli Friedman7f1ff602012-04-16 03:54:45 +00001132 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
1133 Dest.getAlignment());
John McCall7a626f62010-09-15 10:14:12 +00001134
Chris Lattner579a05d2008-04-04 18:42:16 +00001135 // Handle initialization of an array.
1136 if (E->getType()->isArrayType()) {
Richard Smith9ec1e482012-04-15 02:50:59 +00001137 if (E->isStringLiteralInit())
1138 return Visit(E->getInit(0));
Eli Friedmanf23b6fa2008-05-19 17:51:16 +00001139
Eli Friedman91f5ae52012-02-23 02:25:10 +00001140 QualType elementType =
1141 CGF.getContext().getAsArrayType(E->getType())->getElementType();
Argyrios Kyrtzidise07425a52011-04-28 18:53:58 +00001142
Sebastian Redlc83ed822012-02-17 08:42:25 +00001143 llvm::PointerType *APType =
Eli Friedman7f1ff602012-04-16 03:54:45 +00001144 cast<llvm::PointerType>(Dest.getAddr()->getType());
Sebastian Redlc83ed822012-02-17 08:42:25 +00001145 llvm::ArrayType *AType =
1146 cast<llvm::ArrayType>(APType->getElementType());
Chris Lattner27a36312010-12-02 07:07:26 +00001147
Eli Friedman7f1ff602012-04-16 03:54:45 +00001148 EmitArrayInit(Dest.getAddr(), AType, elementType, E);
Chris Lattner579a05d2008-04-04 18:42:16 +00001149 return;
1150 }
Mike Stump11289f42009-09-09 15:08:12 +00001151
Richard Smith77be48a2014-07-31 06:31:19 +00001152 if (E->getType()->isAtomicType()) {
1153 // An _Atomic(T) object can be list-initialized from an expression
1154 // of the same type.
1155 assert(E->getNumInits() == 1 &&
1156 CGF.getContext().hasSameUnqualifiedType(E->getInit(0)->getType(),
1157 E->getType()) &&
1158 "unexpected list initialization for atomic object");
1159 return Visit(E->getInit(0));
1160 }
1161
Chris Lattner579a05d2008-04-04 18:42:16 +00001162 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
Mike Stump11289f42009-09-09 15:08:12 +00001163
Chris Lattner579a05d2008-04-04 18:42:16 +00001164 // Do struct initialization; this code just sets each individual member
1165 // to the approprate value. This makes bitfield support automatic;
1166 // the disadvantage is that the generated code is more difficult for
1167 // the optimizer, especially with bitfields.
1168 unsigned NumInitElements = E->getNumInits();
John McCall3b935d32011-07-11 19:35:02 +00001169 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001170
1171 // Prepare a 'this' for CXXDefaultInitExprs.
1172 CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddr());
1173
John McCall3b935d32011-07-11 19:35:02 +00001174 if (record->isUnion()) {
Douglas Gregor51695702009-01-29 16:53:55 +00001175 // Only initialize one field of a union. The field itself is
1176 // specified by the initializer list.
1177 if (!E->getInitializedFieldInUnion()) {
1178 // Empty union; we have nothing to do.
Mike Stump11289f42009-09-09 15:08:12 +00001179
Douglas Gregor51695702009-01-29 16:53:55 +00001180#ifndef NDEBUG
1181 // Make sure that it's really an empty and not a failure of
1182 // semantic analysis.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001183 for (const auto *Field : record->fields())
Douglas Gregor51695702009-01-29 16:53:55 +00001184 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1185#endif
1186 return;
1187 }
1188
1189 // FIXME: volatility
1190 FieldDecl *Field = E->getInitializedFieldInUnion();
Douglas Gregor51695702009-01-29 16:53:55 +00001191
Eli Friedman7f1ff602012-04-16 03:54:45 +00001192 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001193 if (NumInitElements) {
1194 // Store the initializer into the field
Chad Rosier615ed1a2012-03-29 17:37:10 +00001195 EmitInitializationToLValue(E->getInit(0), FieldLoc);
Douglas Gregor51695702009-01-29 16:53:55 +00001196 } else {
Chris Lattner27a36312010-12-02 07:07:26 +00001197 // Default-initialize to null.
John McCall1553b192011-06-16 04:16:24 +00001198 EmitNullInitializationToLValue(FieldLoc);
Douglas Gregor51695702009-01-29 16:53:55 +00001199 }
1200
1201 return;
1202 }
Mike Stump11289f42009-09-09 15:08:12 +00001203
John McCall3b935d32011-07-11 19:35:02 +00001204 // We'll need to enter cleanup scopes in case any of the member
1205 // initializers throw an exception.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001206 SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
Craig Topper8a13c412014-05-21 05:09:00 +00001207 llvm::Instruction *cleanupDominator = nullptr;
John McCall3b935d32011-07-11 19:35:02 +00001208
Chris Lattner579a05d2008-04-04 18:42:16 +00001209 // Here we iterate over the fields; this makes it simpler to both
1210 // default-initialize fields and skip over unnamed fields.
John McCall3b935d32011-07-11 19:35:02 +00001211 unsigned curInitIndex = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001212 for (const auto *field : record->fields()) {
John McCall3b935d32011-07-11 19:35:02 +00001213 // We're done once we hit the flexible array member.
1214 if (field->getType()->isIncompleteArrayType())
Douglas Gregor91f84212008-12-11 16:49:14 +00001215 break;
1216
John McCall3b935d32011-07-11 19:35:02 +00001217 // Always skip anonymous bitfields.
1218 if (field->isUnnamedBitfield())
Chris Lattner579a05d2008-04-04 18:42:16 +00001219 continue;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001220
John McCall3b935d32011-07-11 19:35:02 +00001221 // We're done if we reach the end of the explicit initializers, we
1222 // have a zeroed object, and the rest of the fields are
1223 // zero-initializable.
1224 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
Chris Lattner27a36312010-12-02 07:07:26 +00001225 CGF.getTypes().isZeroInitializable(E->getType()))
1226 break;
1227
Eli Friedman7f1ff602012-04-16 03:54:45 +00001228
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001229 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
Fariborz Jahanian7c1baf42009-05-27 19:54:11 +00001230 // We never generate write-barries for initialized fields.
John McCall3b935d32011-07-11 19:35:02 +00001231 LV.setNonGC(true);
Chris Lattner27a36312010-12-02 07:07:26 +00001232
John McCall3b935d32011-07-11 19:35:02 +00001233 if (curInitIndex < NumInitElements) {
Chris Lattnere18aaf22010-03-08 21:08:07 +00001234 // Store the initializer into the field.
Chad Rosier615ed1a2012-03-29 17:37:10 +00001235 EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
Chris Lattner579a05d2008-04-04 18:42:16 +00001236 } else {
1237 // We're out of initalizers; default-initialize to null
John McCall3b935d32011-07-11 19:35:02 +00001238 EmitNullInitializationToLValue(LV);
1239 }
1240
1241 // Push a destructor if necessary.
1242 // FIXME: if we have an array of structures, all explicitly
1243 // initialized, we can end up pushing a linear number of cleanups.
1244 bool pushedCleanup = false;
1245 if (QualType::DestructionKind dtorKind
1246 = field->getType().isDestructedType()) {
1247 assert(LV.isSimple());
1248 if (CGF.needsEHCleanup(dtorKind)) {
John McCallf4beacd2011-11-10 10:43:54 +00001249 if (!cleanupDominator)
1250 cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1251
John McCall3b935d32011-07-11 19:35:02 +00001252 CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1253 CGF.getDestroyer(dtorKind), false);
1254 cleanups.push_back(CGF.EHStack.stable_begin());
1255 pushedCleanup = true;
1256 }
Chris Lattner579a05d2008-04-04 18:42:16 +00001257 }
Chris Lattner27a36312010-12-02 07:07:26 +00001258
1259 // If the GEP didn't get used because of a dead zero init or something
1260 // else, clean it up for -O0 builds and general tidiness.
John McCall3b935d32011-07-11 19:35:02 +00001261 if (!pushedCleanup && LV.isSimple())
Chris Lattner27a36312010-12-02 07:07:26 +00001262 if (llvm::GetElementPtrInst *GEP =
John McCall3b935d32011-07-11 19:35:02 +00001263 dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
Chris Lattner27a36312010-12-02 07:07:26 +00001264 if (GEP->use_empty())
1265 GEP->eraseFromParent();
Lauro Ramos Venancioe2162c62008-02-19 19:27:31 +00001266 }
John McCall3b935d32011-07-11 19:35:02 +00001267
1268 // Deactivate all the partial cleanups in reverse order, which
1269 // generally means popping them.
1270 for (unsigned i = cleanups.size(); i != 0; --i)
John McCallf4beacd2011-11-10 10:43:54 +00001271 CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1272
1273 // Destroy the placeholder if we made one.
1274 if (cleanupDominator)
1275 cleanupDominator->eraseFromParent();
Devang Patel87174172007-10-26 17:44:44 +00001276}
1277
Chris Lattner835635d2007-08-21 04:59:27 +00001278//===----------------------------------------------------------------------===//
1279// Entry Points into this File
1280//===----------------------------------------------------------------------===//
1281
Chris Lattner27a36312010-12-02 07:07:26 +00001282/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1283/// non-zero bytes that will be stored when outputting the initializer for the
1284/// specified initializer expression.
Ken Dyckdf94cb72011-04-24 17:17:56 +00001285static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001286 E = E->IgnoreParens();
Chris Lattner27a36312010-12-02 07:07:26 +00001287
1288 // 0 and 0.0 won't require any non-zero stores!
Ken Dyckdf94cb72011-04-24 17:17:56 +00001289 if (isSimpleZero(E, CGF)) return CharUnits::Zero();
Chris Lattner27a36312010-12-02 07:07:26 +00001290
1291 // If this is an initlist expr, sum up the size of sizes of the (present)
1292 // elements. If this is something weird, assume the whole thing is non-zero.
1293 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00001294 if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
Ken Dyckdf94cb72011-04-24 17:17:56 +00001295 return CGF.getContext().getTypeSizeInChars(E->getType());
Chris Lattner27a36312010-12-02 07:07:26 +00001296
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001297 // InitListExprs for structs have to be handled carefully. If there are
1298 // reference members, we need to consider the size of the reference, not the
1299 // referencee. InitListExprs for unions and arrays can't have references.
Chris Lattner5cd84752010-12-02 22:52:04 +00001300 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1301 if (!RT->isUnionType()) {
1302 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
Ken Dyckdf94cb72011-04-24 17:17:56 +00001303 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner5cd84752010-12-02 22:52:04 +00001304
1305 unsigned ILEElement = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001306 for (const auto *Field : SD->fields()) {
Chris Lattner5cd84752010-12-02 22:52:04 +00001307 // We're done once we hit the flexible array member or run out of
1308 // InitListExpr elements.
1309 if (Field->getType()->isIncompleteArrayType() ||
1310 ILEElement == ILE->getNumInits())
1311 break;
1312 if (Field->isUnnamedBitfield())
1313 continue;
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001314
Chris Lattner5cd84752010-12-02 22:52:04 +00001315 const Expr *E = ILE->getInit(ILEElement++);
1316
1317 // Reference values are always non-null and have the width of a pointer.
1318 if (Field->getType()->isReferenceType())
Ken Dyckdf94cb72011-04-24 17:17:56 +00001319 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00001320 CGF.getTarget().getPointerWidth(0));
Chris Lattner5cd84752010-12-02 22:52:04 +00001321 else
1322 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1323 }
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001324
Chris Lattner5cd84752010-12-02 22:52:04 +00001325 return NumNonZeroBytes;
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001326 }
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001327 }
1328
1329
Ken Dyckdf94cb72011-04-24 17:17:56 +00001330 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner27a36312010-12-02 07:07:26 +00001331 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1332 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1333 return NumNonZeroBytes;
1334}
1335
1336/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1337/// zeros in it, emit a memset and avoid storing the individual zeros.
1338///
1339static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1340 CodeGenFunction &CGF) {
1341 // If the slot is already known to be zeroed, nothing to do. Don't mess with
1342 // volatile stores.
Craig Topper8a13c412014-05-21 05:09:00 +00001343 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == nullptr)
1344 return;
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +00001345
1346 // C++ objects with a user-declared constructor don't need zero'ing.
Richard Smith9c6890a2012-11-01 22:30:59 +00001347 if (CGF.getLangOpts().CPlusPlus)
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +00001348 if (const RecordType *RT = CGF.getContext()
1349 .getBaseElementType(E->getType())->getAs<RecordType>()) {
1350 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1351 if (RD->hasUserDeclaredConstructor())
1352 return;
1353 }
1354
Chris Lattner27a36312010-12-02 07:07:26 +00001355 // If the type is 16-bytes or smaller, prefer individual stores over memset.
Ken Dyck239a3352011-04-24 17:25:32 +00001356 std::pair<CharUnits, CharUnits> TypeInfo =
1357 CGF.getContext().getTypeInfoInChars(E->getType());
1358 if (TypeInfo.first <= CharUnits::fromQuantity(16))
Chris Lattner27a36312010-12-02 07:07:26 +00001359 return;
1360
1361 // Check to see if over 3/4 of the initializer are known to be zero. If so,
1362 // we prefer to emit memset + individual stores for the rest.
Ken Dyck239a3352011-04-24 17:25:32 +00001363 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1364 if (NumNonZeroBytes*4 > TypeInfo.first)
Chris Lattner27a36312010-12-02 07:07:26 +00001365 return;
1366
1367 // Okay, it seems like a good idea to use an initial memset, emit the call.
Ken Dyck239a3352011-04-24 17:25:32 +00001368 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1369 CharUnits Align = TypeInfo.second;
Chris Lattner27a36312010-12-02 07:07:26 +00001370
1371 llvm::Value *Loc = Slot.getAddr();
Chris Lattner27a36312010-12-02 07:07:26 +00001372
Chris Lattnerece04092012-02-07 00:39:47 +00001373 Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
Ken Dyck239a3352011-04-24 17:25:32 +00001374 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1375 Align.getQuantity(), false);
Chris Lattner27a36312010-12-02 07:07:26 +00001376
1377 // Tell the AggExprEmitter that the slot is known zero.
1378 Slot.setZeroed();
1379}
1380
1381
1382
1383
Mike Stump25306ca2009-05-26 18:57:45 +00001384/// EmitAggExpr - Emit the computation of the specified expression of aggregate
1385/// type. The result is computed into DestPtr. Note that if DestPtr is null,
1386/// the value of the aggregate expression is not needed. If VolatileDest is
1387/// true, DestPtr cannot be 0.
John McCall4e8ca4f2012-07-02 23:58:38 +00001388void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
John McCall47fb9502013-03-07 21:37:08 +00001389 assert(E && hasAggregateEvaluationKind(E->getType()) &&
Chris Lattner835635d2007-08-21 04:59:27 +00001390 "Invalid aggregate expression to emit");
Craig Topper8a13c412014-05-21 05:09:00 +00001391 assert((Slot.getAddr() != nullptr || Slot.isIgnored()) &&
Chris Lattner27a36312010-12-02 07:07:26 +00001392 "slot has bits but no address");
Mike Stump11289f42009-09-09 15:08:12 +00001393
Chris Lattner27a36312010-12-02 07:07:26 +00001394 // Optimize the slot if possible.
1395 CheckAggExprForMemSetUse(Slot, E, *this);
1396
John McCall4e8ca4f2012-07-02 23:58:38 +00001397 AggExprEmitter(*this, Slot).Visit(const_cast<Expr*>(E));
Chris Lattner835635d2007-08-21 04:59:27 +00001398}
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00001399
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00001400LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
John McCall47fb9502013-03-07 21:37:08 +00001401 assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
Daniel Dunbara7566f12010-02-09 02:48:28 +00001402 llvm::Value *Temp = CreateMemTemp(E->getType());
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001403 LValue LV = MakeAddrLValue(Temp, E->getType());
John McCall8d6fc952011-08-25 20:40:09 +00001404 EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
John McCall46759f42011-08-26 07:31:35 +00001405 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001406 AggValueSlot::IsNotAliased));
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001407 return LV;
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00001408}
1409
Chad Rosier615ed1a2012-03-29 17:37:10 +00001410void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1411 llvm::Value *SrcPtr, QualType Ty,
John McCall4e8ca4f2012-07-02 23:58:38 +00001412 bool isVolatile,
Benjamin Kramer1ca66912012-09-30 12:43:37 +00001413 CharUnits alignment,
1414 bool isAssignment) {
Chad Rosier615ed1a2012-03-29 17:37:10 +00001415 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
Mike Stump11289f42009-09-09 15:08:12 +00001416
Richard Smith9c6890a2012-11-01 22:30:59 +00001417 if (getLangOpts().CPlusPlus) {
Chad Rosier615ed1a2012-03-29 17:37:10 +00001418 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1419 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1420 assert((Record->hasTrivialCopyConstructor() ||
1421 Record->hasTrivialCopyAssignment() ||
1422 Record->hasTrivialMoveConstructor() ||
Richard Smith419bd092015-04-29 19:26:57 +00001423 Record->hasTrivialMoveAssignment() ||
1424 Record->isUnion()) &&
Richard Smith16488472012-11-16 00:53:38 +00001425 "Trying to aggregate-copy a type without a trivial copy/move "
Douglas Gregorf22101a2010-05-20 15:39:01 +00001426 "constructor or assignment operator");
Chad Rosier615ed1a2012-03-29 17:37:10 +00001427 // Ignore empty classes in C++.
1428 if (Record->isEmpty())
Anders Carlsson16e94af2010-05-03 01:20:20 +00001429 return;
1430 }
1431 }
1432
Chris Lattnerca05dfe2009-02-28 18:31:01 +00001433 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
Chris Lattner3ef668c2009-02-28 18:18:58 +00001434 // C99 6.5.16.1p3, which states "If the value being stored in an object is
1435 // read from another object that overlaps in anyway the storage of the first
1436 // object, then the overlap shall be exact and the two objects shall have
1437 // qualified or unqualified versions of a compatible type."
1438 //
Chris Lattnerca05dfe2009-02-28 18:31:01 +00001439 // memcpy is not defined if the source and destination pointers are exactly
Chris Lattner3ef668c2009-02-28 18:18:58 +00001440 // equal, but other compilers do this optimization, and almost every memcpy
1441 // implementation handles this case safely. If there is a libc that does not
1442 // safely handle this, we can add a target hook.
Chad Rosier615ed1a2012-03-29 17:37:10 +00001443
Benjamin Kramer1ca66912012-09-30 12:43:37 +00001444 // Get data size and alignment info for this aggregate. If this is an
1445 // assignment don't copy the tail padding. Otherwise copying it is fine.
1446 std::pair<CharUnits, CharUnits> TypeInfo;
1447 if (isAssignment)
1448 TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
1449 else
1450 TypeInfo = getContext().getTypeInfoInChars(Ty);
Chad Rosier615ed1a2012-03-29 17:37:10 +00001451
John McCall4e8ca4f2012-07-02 23:58:38 +00001452 if (alignment.isZero())
1453 alignment = TypeInfo.second;
Chad Rosier615ed1a2012-03-29 17:37:10 +00001454
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001455 llvm::Value *SizeVal = nullptr;
1456 if (TypeInfo.first.isZero()) {
1457 // But note that getTypeInfo returns 0 for a VLA.
1458 if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
1459 getContext().getAsArrayType(Ty))) {
1460 QualType BaseEltTy;
1461 SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
1462 TypeInfo = getContext().getTypeInfoDataSizeInChars(BaseEltTy);
1463 std::pair<CharUnits, CharUnits> LastElementTypeInfo;
1464 if (!isAssignment)
1465 LastElementTypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
1466 assert(!TypeInfo.first.isZero());
1467 SizeVal = Builder.CreateNUWMul(
1468 SizeVal,
1469 llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
1470 if (!isAssignment) {
1471 SizeVal = Builder.CreateNUWSub(
1472 SizeVal,
1473 llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
1474 SizeVal = Builder.CreateNUWAdd(
1475 SizeVal, llvm::ConstantInt::get(
1476 SizeTy, LastElementTypeInfo.first.getQuantity()));
1477 }
1478 }
1479 }
1480 if (!SizeVal) {
1481 SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity());
1482 }
Chad Rosier615ed1a2012-03-29 17:37:10 +00001483
1484 // FIXME: If we have a volatile struct, the optimizer can remove what might
1485 // appear to be `extra' memory ops:
1486 //
1487 // volatile struct { int i; } a, b;
1488 //
1489 // int main() {
1490 // a = b;
1491 // a = b;
1492 // }
1493 //
1494 // we need to use a different call here. We use isVolatile to indicate when
1495 // either the source or the destination is volatile.
1496
1497 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1498 llvm::Type *DBP =
1499 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1500 DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1501
1502 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1503 llvm::Type *SBP =
1504 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1505 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1506
1507 // Don't do any of the memmove_collectable tests if GC isn't set.
1508 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1509 // fall through
1510 } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1511 RecordDecl *Record = RecordTy->getDecl();
1512 if (Record->hasObjectMember()) {
Chad Rosier615ed1a2012-03-29 17:37:10 +00001513 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1514 SizeVal);
1515 return;
1516 }
1517 } else if (Ty->isArrayType()) {
1518 QualType BaseType = getContext().getBaseElementType(Ty);
1519 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1520 if (RecordTy->getDecl()->hasObjectMember()) {
Chad Rosier615ed1a2012-03-29 17:37:10 +00001521 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1522 SizeVal);
1523 return;
1524 }
1525 }
1526 }
Dan Gohman22695fc2012-09-28 21:58:29 +00001527
1528 // Determine the metadata to describe the position of any padding in this
1529 // memcpy, as well as the TBAA tags for the members of the struct, in case
1530 // the optimizer wishes to expand it in to scalar memory operations.
1531 llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty);
Craig Topper8a13c412014-05-21 05:09:00 +00001532
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001533 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, alignment.getQuantity(),
1534 isVolatile, /*TBAATag=*/nullptr, TBAAStructTag);
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00001535}