blob: 4cf94c033bb4723c0a0f916c318bdd47a098f125 [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
Chris Lattner4758b402007-08-21 04:25:47 +0000101 void VisitStmt(Stmt *S) {
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000102 CGF.ErrorUnsupported(S, "aggregate expression");
Chris Lattner4758b402007-08-21 04:25:47 +0000103 }
104 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
Peter Collingbourne91147592011-04-15 00:35:48 +0000105 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
106 Visit(GE->getResultExpr());
107 }
Eli Friedman3f66b842009-01-27 09:03:41 +0000108 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000109 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
110 return Visit(E->getReplacement());
111 }
Chris Lattner4758b402007-08-21 04:25:47 +0000112
113 // l-values.
John McCall113bee02012-03-10 09:33:50 +0000114 void VisitDeclRefExpr(DeclRefExpr *E) {
John McCall71335052012-03-10 03:05:10 +0000115 // For aggregates, we should always be able to emit the variable
116 // as an l-value unless it's a reference. This is due to the fact
117 // that we can't actually ever see a normal l2r conversion on an
118 // aggregate in C++, and in C there's no language standard
119 // actively preventing us from listing variables in the captures
120 // list of a block.
John McCall113bee02012-03-10 09:33:50 +0000121 if (E->getDecl()->getType()->isReferenceType()) {
John McCall71335052012-03-10 03:05:10 +0000122 if (CodeGenFunction::ConstantEmission result
John McCall113bee02012-03-10 09:33:50 +0000123 = CGF.tryEmitAsConstant(E)) {
John McCall4e8ca4f2012-07-02 23:58:38 +0000124 EmitFinalDestCopy(E->getType(), result.getReferenceLValue(CGF, E));
John McCall71335052012-03-10 03:05:10 +0000125 return;
126 }
127 }
128
John McCall113bee02012-03-10 09:33:50 +0000129 EmitAggLoadOfLValue(E);
John McCall71335052012-03-10 03:05:10 +0000130 }
131
Seo Sanghyeond4d8c3c2007-12-14 02:04:12 +0000132 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
133 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
Daniel Dunbard443c0a2010-01-04 18:47:06 +0000134 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000135 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Seo Sanghyeond4d8c3c2007-12-14 02:04:12 +0000136 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
137 EmitAggLoadOfLValue(E);
138 }
Chris Lattner2f343dd2009-04-21 23:00:09 +0000139 void VisitPredefinedExpr(const PredefinedExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000140 EmitAggLoadOfLValue(E);
Chris Lattner2f343dd2009-04-21 23:00:09 +0000141 }
Mike Stump11289f42009-09-09 15:08:12 +0000142
Chris Lattner4758b402007-08-21 04:25:47 +0000143 // Operators.
Anders Carlssonec143772009-08-07 23:22:37 +0000144 void VisitCastExpr(CastExpr *E);
Anders Carlsson0370eb22007-10-31 22:04:46 +0000145 void VisitCallExpr(const CallExpr *E);
Chris Lattner49e3bfa2007-08-31 22:54:14 +0000146 void VisitStmtExpr(const StmtExpr *E);
Chris Lattner4758b402007-08-21 04:25:47 +0000147 void VisitBinaryOperator(const BinaryOperator *BO);
Fariborz Jahanianffba6622009-10-22 22:57:31 +0000148 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
Chris Lattnercd9fb242007-08-21 04:43:17 +0000149 void VisitBinAssign(const BinaryOperator *E);
Eli Friedman4b0e2a32008-05-20 07:56:31 +0000150 void VisitBinComma(const BinaryOperator *E);
Chris Lattner4758b402007-08-21 04:25:47 +0000151
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000152 void VisitObjCMessageExpr(ObjCMessageExpr *E);
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000153 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
154 EmitAggLoadOfLValue(E);
155 }
Mike Stump11289f42009-09-09 15:08:12 +0000156
John McCallc07a0c72011-02-17 10:25:35 +0000157 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
Anders Carlsson5b2095c2009-07-08 18:33:14 +0000158 void VisitChooseExpr(const ChooseExpr *CE);
Devang Patel87174172007-10-26 17:44:44 +0000159 void VisitInitListExpr(InitListExpr *E);
Anders Carlsson18ada982009-12-16 06:57:54 +0000160 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000161 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
162 Visit(DAE->getExpr());
163 }
Richard Smith852c9db2013-04-20 22:23:05 +0000164 void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
165 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
166 Visit(DIE->getExpr());
167 }
Anders Carlsson3be22e22009-05-30 23:23:33 +0000168 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
Anders Carlsson1619a5042009-05-03 17:47:16 +0000169 void VisitCXXConstructExpr(const CXXConstructExpr *E);
Eli Friedmanc370a7e2012-02-09 03:32:31 +0000170 void VisitLambdaExpr(LambdaExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000171 void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
John McCall5d413782010-12-06 08:20:24 +0000172 void VisitExprWithCleanups(ExprWithCleanups *E);
Douglas Gregor747eb782010-07-08 06:14:04 +0000173 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Mike Stump5bbbb132009-11-18 00:40:12 +0000174 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
Douglas Gregorfe314812011-06-21 17:03:29 +0000175 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
John McCall1bf58462011-02-16 08:02:54 +0000176 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
177
John McCallfe96e0b2011-11-06 09:01:30 +0000178 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
179 if (E->isGLValue()) {
180 LValue LV = CGF.EmitPseudoObjectLValue(E);
John McCall4e8ca4f2012-07-02 23:58:38 +0000181 return EmitFinalDestCopy(E->getType(), LV);
John McCallfe96e0b2011-11-06 09:01:30 +0000182 }
183
184 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
185 }
186
Eli Friedman21911e82008-05-27 15:51:49 +0000187 void VisitVAArgExpr(VAArgExpr *E);
Chris Lattner579a05d2008-04-04 18:42:16 +0000188
Chad Rosier615ed1a2012-03-29 17:37:10 +0000189 void EmitInitializationToLValue(Expr *E, LValue Address);
John McCall1553b192011-06-16 04:16:24 +0000190 void EmitNullInitializationToLValue(LValue Address);
Chris Lattner4758b402007-08-21 04:25:47 +0000191 // case Expr::ChooseExprClass:
Mike Stumpf16b8c32009-12-09 19:24:08 +0000192 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000193 void VisitAtomicExpr(AtomicExpr *E) {
194 CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
195 }
Chris Lattner4758b402007-08-21 04:25:47 +0000196};
197} // end anonymous namespace.
198
Chris Lattner835635d2007-08-21 04:59:27 +0000199//===----------------------------------------------------------------------===//
200// Utilities
201//===----------------------------------------------------------------------===//
Chris Lattner4758b402007-08-21 04:25:47 +0000202
Chris Lattner6278e6a2007-08-11 00:04:45 +0000203/// EmitAggLoadOfLValue - Given an expression with aggregate type that
204/// represents a value lvalue, this method emits the address of the lvalue,
205/// then loads the result into DestPtr.
Chris Lattner4758b402007-08-21 04:25:47 +0000206void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
207 LValue LV = CGF.EmitLValue(E);
John McCalla8ec7eb2013-03-07 21:37:17 +0000208
209 // If the type of the l-value is atomic, then do an atomic load.
210 if (LV.getType()->isAtomicType()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000211 CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
John McCalla8ec7eb2013-03-07 21:37:17 +0000212 return;
213 }
214
John McCall4e8ca4f2012-07-02 23:58:38 +0000215 EmitFinalDestCopy(E->getType(), LV);
Mike Stumpca9fc092009-05-23 20:28:01 +0000216}
217
John McCallcc04e9f2010-05-22 22:13:32 +0000218/// \brief True if the given aggregate type requires special GC API calls.
219bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
220 // Only record types have members that might require garbage collection.
221 const RecordType *RecordTy = T->getAs<RecordType>();
222 if (!RecordTy) return false;
223
224 // Don't mess with non-trivial C++ types.
225 RecordDecl *Record = RecordTy->getDecl();
226 if (isa<CXXRecordDecl>(Record) &&
Richard Smith16488472012-11-16 00:53:38 +0000227 (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
John McCallcc04e9f2010-05-22 22:13:32 +0000228 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
229 return false;
230
231 // Check whether the type has an object member.
232 return Record->hasObjectMember();
233}
234
John McCalla5efa732011-08-25 23:04:34 +0000235/// \brief Perform the final move to DestPtr if for some reason
236/// getReturnValueSlot() didn't use it directly.
John McCallcc04e9f2010-05-22 22:13:32 +0000237///
238/// The idea is that you do something like this:
239/// RValue Result = EmitSomething(..., getReturnValueSlot());
John McCalla5efa732011-08-25 23:04:34 +0000240/// EmitMoveFromReturnSlot(E, Result);
241///
242/// If nothing interferes, this will cause the result to be emitted
243/// directly into the return value slot. Otherwise, a final move
244/// will be performed.
John McCall4e8ca4f2012-07-02 23:58:38 +0000245void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
John McCalla5efa732011-08-25 23:04:34 +0000246 if (shouldUseDestForReturnSlot()) {
247 // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
248 // The possibility of undef rvalues complicates that a lot,
249 // though, so we can't really assert.
250 return;
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000251 }
John McCalla5efa732011-08-25 23:04:34 +0000252
John McCall4e8ca4f2012-07-02 23:58:38 +0000253 // Otherwise, copy from there to the destination.
254 assert(Dest.getAddr() != src.getAggregateAddr());
255 std::pair<CharUnits, CharUnits> typeInfo =
Chad Rosier1e303ee2012-04-17 01:14:29 +0000256 CGF.getContext().getTypeInfoInChars(E->getType());
John McCall4e8ca4f2012-07-02 23:58:38 +0000257 EmitFinalDestCopy(E->getType(), src, typeInfo.second);
John McCallcc04e9f2010-05-22 22:13:32 +0000258}
259
Mike Stumpca9fc092009-05-23 20:28:01 +0000260/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
John McCall4e8ca4f2012-07-02 23:58:38 +0000261void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src,
262 CharUnits srcAlign) {
263 assert(src.isAggregate() && "value must be aggregate value!");
264 LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddr(), type, srcAlign);
265 EmitFinalDestCopy(type, srcLV);
266}
Mike Stumpca9fc092009-05-23 20:28:01 +0000267
John McCall4e8ca4f2012-07-02 23:58:38 +0000268/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
269void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src) {
John McCall7a626f62010-09-15 10:14:12 +0000270 // If Dest is ignored, then we're evaluating an aggregate expression
John McCall4e8ca4f2012-07-02 23:58:38 +0000271 // in a context that doesn't care about the result. Note that loads
272 // from volatile l-values force the existence of a non-ignored
273 // destination.
274 if (Dest.isIgnored())
275 return;
Fariborz Jahanianc1236232010-10-22 22:05:03 +0000276
John McCall4e8ca4f2012-07-02 23:58:38 +0000277 AggValueSlot srcAgg =
278 AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
279 needsGC(type), AggValueSlot::IsAliased);
280 EmitCopy(type, Dest, srcAgg);
281}
Chris Lattner6278e6a2007-08-11 00:04:45 +0000282
John McCall4e8ca4f2012-07-02 23:58:38 +0000283/// Perform a copy from the source into the destination.
284///
285/// \param type - the type of the aggregate being copied; qualifiers are
286/// ignored
287void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
288 const AggValueSlot &src) {
289 if (dest.requiresGCollection()) {
290 CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
291 llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
Fariborz Jahanian879d7262009-08-31 19:33:16 +0000292 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
John McCall4e8ca4f2012-07-02 23:58:38 +0000293 dest.getAddr(),
294 src.getAddr(),
295 size);
Fariborz Jahanian879d7262009-08-31 19:33:16 +0000296 return;
297 }
John McCall4e8ca4f2012-07-02 23:58:38 +0000298
Mike Stumpca9fc092009-05-23 20:28:01 +0000299 // If the result of the assignment is used, copy the LHS there also.
John McCall4e8ca4f2012-07-02 23:58:38 +0000300 // It's volatile if either side is. Use the minimum alignment of
301 // the two sides.
302 CGF.EmitAggregateCopy(dest.getAddr(), src.getAddr(), type,
303 dest.isVolatile() || src.isVolatile(),
304 std::min(dest.getAlignment(), src.getAlignment()));
Chris Lattner6278e6a2007-08-11 00:04:45 +0000305}
306
Sebastian Redlc83ed822012-02-17 08:42:25 +0000307/// \brief Emit the initializer for a std::initializer_list initialized with a
308/// real initializer list.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000309void
310AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
311 // Emit an array containing the elements. The array is externally destructed
312 // if the std::initializer_list object is.
313 ASTContext &Ctx = CGF.getContext();
314 LValue Array = CGF.EmitLValue(E->getSubExpr());
315 assert(Array.isSimple() && "initializer_list array not a simple lvalue");
316 llvm::Value *ArrayPtr = Array.getAddress();
Sebastian Redlc83ed822012-02-17 08:42:25 +0000317
Richard Smithcc1b96d2013-06-12 22:31:48 +0000318 const ConstantArrayType *ArrayType =
319 Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
320 assert(ArrayType && "std::initializer_list constructed from non-array");
Sebastian Redlc83ed822012-02-17 08:42:25 +0000321
Richard Smithcc1b96d2013-06-12 22:31:48 +0000322 // FIXME: Perform the checks on the field types in SemaInit.
323 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
324 RecordDecl::field_iterator Field = Record->field_begin();
325 if (Field == Record->field_end()) {
326 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlf2e0a302012-02-25 20:51:13 +0000327 return;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000328 }
329
Sebastian Redlc83ed822012-02-17 08:42:25 +0000330 // Start pointer.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000331 if (!Field->getType()->isPointerType() ||
332 !Ctx.hasSameType(Field->getType()->getPointeeType(),
333 ArrayType->getElementType())) {
334 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlf2e0a302012-02-25 20:51:13 +0000335 return;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000336 }
Sebastian Redlc83ed822012-02-17 08:42:25 +0000337
Richard Smithcc1b96d2013-06-12 22:31:48 +0000338 AggValueSlot Dest = EnsureSlot(E->getType());
339 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
340 Dest.getAlignment());
341 LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
342 llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
343 llvm::Value *IdxStart[] = { Zero, Zero };
344 llvm::Value *ArrayStart =
345 Builder.CreateInBoundsGEP(ArrayPtr, IdxStart, "arraystart");
346 CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
347 ++Field;
348
349 if (Field == Record->field_end()) {
350 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlf2e0a302012-02-25 20:51:13 +0000351 return;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000352 }
Richard Smithcc1b96d2013-06-12 22:31:48 +0000353
354 llvm::Value *Size = Builder.getInt(ArrayType->getSize());
355 LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
356 if (Field->getType()->isPointerType() &&
357 Ctx.hasSameType(Field->getType()->getPointeeType(),
358 ArrayType->getElementType())) {
Sebastian Redlc83ed822012-02-17 08:42:25 +0000359 // End pointer.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000360 llvm::Value *IdxEnd[] = { Zero, Size };
361 llvm::Value *ArrayEnd =
362 Builder.CreateInBoundsGEP(ArrayPtr, IdxEnd, "arrayend");
363 CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
364 } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
Sebastian Redlc83ed822012-02-17 08:42:25 +0000365 // Length.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000366 CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000367 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +0000368 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlf2e0a302012-02-25 20:51:13 +0000369 return;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000370 }
Sebastian Redlc83ed822012-02-17 08:42:25 +0000371}
372
Richard Smith8edda962014-06-13 23:04:49 +0000373/// \brief Determine if E is a trivial array filler, that is, one that is
374/// equivalent to zero-initialization.
375static bool isTrivialFiller(Expr *E) {
376 if (!E)
377 return true;
378
379 if (isa<ImplicitValueInitExpr>(E))
380 return true;
381
382 if (auto *ILE = dyn_cast<InitListExpr>(E)) {
383 if (ILE->getNumInits())
384 return false;
385 return isTrivialFiller(ILE->getArrayFiller());
386 }
387
388 if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
389 return Cons->getConstructor()->isDefaultConstructor() &&
390 Cons->getConstructor()->isTrivial();
391
392 // FIXME: Are there other cases where we can avoid emitting an initializer?
393 return false;
394}
395
Sebastian Redlc83ed822012-02-17 08:42:25 +0000396/// \brief Emit initialization of an array from an initializer list.
397void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
398 QualType elementType, InitListExpr *E) {
399 uint64_t NumInitElements = E->getNumInits();
400
401 uint64_t NumArrayElements = AType->getNumElements();
402 assert(NumInitElements <= NumArrayElements);
403
404 // DestPtr is an array*. Construct an elementType* by drilling
405 // down a level.
406 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
407 llvm::Value *indices[] = { zero, zero };
408 llvm::Value *begin =
409 Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
410
411 // Exception safety requires us to destroy all the
412 // already-constructed members if an initializer throws.
413 // For that, we'll need an EH cleanup.
414 QualType::DestructionKind dtorKind = elementType.isDestructedType();
Craig Topper8a13c412014-05-21 05:09:00 +0000415 llvm::AllocaInst *endOfInit = nullptr;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000416 EHScopeStack::stable_iterator cleanup;
Craig Topper8a13c412014-05-21 05:09:00 +0000417 llvm::Instruction *cleanupDominator = nullptr;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000418 if (CGF.needsEHCleanup(dtorKind)) {
419 // In principle we could tell the cleanup where we are more
420 // directly, but the control flow can get so varied here that it
421 // would actually be quite complex. Therefore we go through an
422 // alloca.
423 endOfInit = CGF.CreateTempAlloca(begin->getType(),
424 "arrayinit.endOfInit");
425 cleanupDominator = Builder.CreateStore(begin, endOfInit);
426 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
427 CGF.getDestroyer(dtorKind));
428 cleanup = CGF.EHStack.stable_begin();
429
430 // Otherwise, remember that we didn't need a cleanup.
431 } else {
432 dtorKind = QualType::DK_none;
433 }
434
435 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
436
437 // The 'current element to initialize'. The invariants on this
438 // variable are complicated. Essentially, after each iteration of
439 // the loop, it points to the last initialized element, except
440 // that it points to the beginning of the array before any
441 // elements have been initialized.
442 llvm::Value *element = begin;
443
444 // Emit the explicit initializers.
445 for (uint64_t i = 0; i != NumInitElements; ++i) {
446 // Advance to the next element.
447 if (i > 0) {
448 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
449
450 // Tell the cleanup that it needs to destroy up to this
451 // element. TODO: some of these stores can be trivially
452 // observed to be unnecessary.
453 if (endOfInit) Builder.CreateStore(element, endOfInit);
454 }
455
Richard Smithcc1b96d2013-06-12 22:31:48 +0000456 LValue elementLV = CGF.MakeAddrLValue(element, elementType);
457 EmitInitializationToLValue(E->getInit(i), elementLV);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000458 }
459
460 // Check whether there's a non-trivial array-fill expression.
Sebastian Redlc83ed822012-02-17 08:42:25 +0000461 Expr *filler = E->getArrayFiller();
Richard Smith8edda962014-06-13 23:04:49 +0000462 bool hasTrivialFiller = isTrivialFiller(filler);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000463
464 // Any remaining elements need to be zero-initialized, possibly
465 // using the filler expression. We can skip this if the we're
466 // emitting to zeroed memory.
467 if (NumInitElements != NumArrayElements &&
468 !(Dest.isZeroed() && hasTrivialFiller &&
469 CGF.getTypes().isZeroInitializable(elementType))) {
470
471 // Use an actual loop. This is basically
472 // do { *array++ = filler; } while (array != end);
473
474 // Advance to the start of the rest of the array.
475 if (NumInitElements) {
476 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
477 if (endOfInit) Builder.CreateStore(element, endOfInit);
478 }
479
480 // Compute the end of the array.
481 llvm::Value *end = Builder.CreateInBoundsGEP(begin,
482 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
483 "arrayinit.end");
484
485 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
486 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
487
488 // Jump into the body.
489 CGF.EmitBlock(bodyBB);
490 llvm::PHINode *currentElement =
491 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
492 currentElement->addIncoming(element, entryBB);
493
494 // Emit the actual filler expression.
495 LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
496 if (filler)
Chad Rosier615ed1a2012-03-29 17:37:10 +0000497 EmitInitializationToLValue(filler, elementLV);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000498 else
499 EmitNullInitializationToLValue(elementLV);
500
501 // Move on to the next element.
502 llvm::Value *nextElement =
503 Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
504
505 // Tell the EH cleanup that we finished with the last element.
506 if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
507
508 // Leave the loop if we're done.
509 llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
510 "arrayinit.done");
511 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
512 Builder.CreateCondBr(done, endBB, bodyBB);
513 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
514
515 CGF.EmitBlock(endBB);
516 }
517
518 // Leave the partial-array cleanup if we entered one.
519 if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
520}
521
Chris Lattner835635d2007-08-21 04:59:27 +0000522//===----------------------------------------------------------------------===//
523// Visitor Methods
524//===----------------------------------------------------------------------===//
525
Douglas Gregorfe314812011-06-21 17:03:29 +0000526void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
527 Visit(E->GetTemporaryExpr());
528}
529
John McCall1bf58462011-02-16 08:02:54 +0000530void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
John McCall4e8ca4f2012-07-02 23:58:38 +0000531 EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e));
John McCall1bf58462011-02-16 08:02:54 +0000532}
533
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000534void
535AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCallbea4c3d2013-03-07 21:36:54 +0000536 if (Dest.isPotentiallyAliased() &&
537 E->getType().isPODType(CGF.getContext())) {
Douglas Gregor6c9d31e2011-06-17 16:37:20 +0000538 // For a POD type, just emit a load of the lvalue + a copy, because our
539 // compound literal might alias the destination.
Douglas Gregor6c9d31e2011-06-17 16:37:20 +0000540 EmitAggLoadOfLValue(E);
541 return;
542 }
543
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000544 AggValueSlot Slot = EnsureSlot(E->getType());
545 CGF.EmitAggExpr(E->getInitializer(), Slot);
546}
547
John McCalla8ec7eb2013-03-07 21:37:17 +0000548/// Attempt to look through various unimportant expressions to find a
549/// cast of the given kind.
550static Expr *findPeephole(Expr *op, CastKind kind) {
551 while (true) {
552 op = op->IgnoreParens();
553 if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
554 if (castE->getCastKind() == kind)
555 return castE->getSubExpr();
556 if (castE->getCastKind() == CK_NoOp)
557 continue;
558 }
Craig Topper8a13c412014-05-21 05:09:00 +0000559 return nullptr;
John McCalla8ec7eb2013-03-07 21:37:17 +0000560 }
561}
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000562
Anders Carlssonec143772009-08-07 23:22:37 +0000563void AggExprEmitter::VisitCastExpr(CastExpr *E) {
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000564 switch (E->getCastKind()) {
Anders Carlsson8a01a752011-04-11 02:03:26 +0000565 case CK_Dynamic: {
Richard Smith69d0d262012-08-24 00:54:33 +0000566 // FIXME: Can this actually happen? We have no test coverage for it.
Douglas Gregor1c073f42010-05-14 21:31:02 +0000567 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
Richard Smith69d0d262012-08-24 00:54:33 +0000568 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
Richard Smith4d1458e2012-09-08 02:08:36 +0000569 CodeGenFunction::TCK_Load);
Douglas Gregor1c073f42010-05-14 21:31:02 +0000570 // FIXME: Do we also need to handle property references here?
571 if (LV.isSimple())
572 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
573 else
574 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
575
John McCall7a626f62010-09-15 10:14:12 +0000576 if (!Dest.isIgnored())
577 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
Douglas Gregor1c073f42010-05-14 21:31:02 +0000578 break;
579 }
580
John McCalle3027922010-08-25 11:45:40 +0000581 case CK_ToUnion: {
John McCall58989b72011-04-12 22:02:02 +0000582 if (Dest.isIgnored()) break;
583
Anders Carlssonec143772009-08-07 23:22:37 +0000584 // GCC union extension
Daniel Dunbar2e442a02010-08-21 03:15:20 +0000585 QualType Ty = E->getSubExpr()->getType();
586 QualType PtrTy = CGF.getContext().getPointerType(Ty);
John McCall7a626f62010-09-15 10:14:12 +0000587 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
Eli Friedmandd274842009-06-03 20:45:06 +0000588 CGF.ConvertType(PtrTy));
John McCall1553b192011-06-16 04:16:24 +0000589 EmitInitializationToLValue(E->getSubExpr(),
Chad Rosier615ed1a2012-03-29 17:37:10 +0000590 CGF.MakeAddrLValue(CastPtr, Ty));
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000591 break;
Nuno Lopes7ffcf932009-01-15 20:14:33 +0000592 }
Mike Stump11289f42009-09-09 15:08:12 +0000593
John McCalle3027922010-08-25 11:45:40 +0000594 case CK_DerivedToBase:
595 case CK_BaseToDerived:
596 case CK_UncheckedDerivedToBase: {
David Blaikie83d382b2011-09-23 05:06:16 +0000597 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
Douglas Gregoraae38d62010-05-22 05:17:18 +0000598 "should have been unpacked before we got here");
Douglas Gregoraae38d62010-05-22 05:17:18 +0000599 }
600
John McCalla8ec7eb2013-03-07 21:37:17 +0000601 case CK_NonAtomicToAtomic:
602 case CK_AtomicToNonAtomic: {
603 bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
604
605 // Determine the atomic and value types.
606 QualType atomicType = E->getSubExpr()->getType();
607 QualType valueType = E->getType();
608 if (isToAtomic) std::swap(atomicType, valueType);
609
610 assert(atomicType->isAtomicType());
611 assert(CGF.getContext().hasSameUnqualifiedType(valueType,
612 atomicType->castAs<AtomicType>()->getValueType()));
613
614 // Just recurse normally if we're ignoring the result or the
615 // atomic type doesn't change representation.
616 if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
617 return Visit(E->getSubExpr());
618 }
619
620 CastKind peepholeTarget =
621 (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
622
623 // These two cases are reverses of each other; try to peephole them.
624 if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
625 assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
626 E->getType()) &&
627 "peephole significantly changed types?");
628 return Visit(op);
629 }
630
631 // If we're converting an r-value of non-atomic type to an r-value
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000632 // of atomic type, just emit directly into the relevant sub-object.
John McCalla8ec7eb2013-03-07 21:37:17 +0000633 if (isToAtomic) {
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000634 AggValueSlot valueDest = Dest;
635 if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
636 // Zero-initialize. (Strictly speaking, we only need to intialize
637 // the padding at the end, but this is simpler.)
638 if (!Dest.isZeroed())
Eli Friedman035b39e2013-07-11 02:28:36 +0000639 CGF.EmitNullInitialization(Dest.getAddr(), atomicType);
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000640
641 // Build a GEP to refer to the subobject.
642 llvm::Value *valueAddr =
643 CGF.Builder.CreateStructGEP(valueDest.getAddr(), 0);
644 valueDest = AggValueSlot::forAddr(valueAddr,
645 valueDest.getAlignment(),
646 valueDest.getQualifiers(),
647 valueDest.isExternallyDestructed(),
648 valueDest.requiresGCollection(),
649 valueDest.isPotentiallyAliased(),
650 AggValueSlot::IsZeroed);
651 }
652
Eli Friedman035b39e2013-07-11 02:28:36 +0000653 CGF.EmitAggExpr(E->getSubExpr(), valueDest);
John McCalla8ec7eb2013-03-07 21:37:17 +0000654 return;
655 }
656
657 // Otherwise, we're converting an atomic type to a non-atomic type.
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000658 // Make an atomic temporary, emit into that, and then copy the value out.
John McCalla8ec7eb2013-03-07 21:37:17 +0000659 AggValueSlot atomicSlot =
660 CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
661 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
662
663 llvm::Value *valueAddr =
664 Builder.CreateStructGEP(atomicSlot.getAddr(), 0);
665 RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
666 return EmitFinalDestCopy(valueType, rvalue);
667 }
668
John McCall4e8ca4f2012-07-02 23:58:38 +0000669 case CK_LValueToRValue:
670 // If we're loading from a volatile type, force the destination
671 // into existence.
672 if (E->getSubExpr()->getType().isVolatileQualified()) {
673 EnsureDest(E->getType());
674 return Visit(E->getSubExpr());
675 }
John McCalla8ec7eb2013-03-07 21:37:17 +0000676
John McCall4e8ca4f2012-07-02 23:58:38 +0000677 // fallthrough
678
John McCalle3027922010-08-25 11:45:40 +0000679 case CK_NoOp:
680 case CK_UserDefinedConversion:
681 case CK_ConstructorConversion:
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000682 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
683 E->getType()) &&
684 "Implicit cast types must be compatible");
685 Visit(E->getSubExpr());
686 break;
John McCallf3735e02010-12-01 04:43:34 +0000687
John McCalle3027922010-08-25 11:45:40 +0000688 case CK_LValueBitCast:
John McCallf3735e02010-12-01 04:43:34 +0000689 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
John McCall31996342011-04-07 08:22:57 +0000690
John McCallf3735e02010-12-01 04:43:34 +0000691 case CK_Dependent:
692 case CK_BitCast:
693 case CK_ArrayToPointerDecay:
694 case CK_FunctionToPointerDecay:
695 case CK_NullToPointer:
696 case CK_NullToMemberPointer:
697 case CK_BaseToDerivedMemberPointer:
698 case CK_DerivedToBaseMemberPointer:
699 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +0000700 case CK_ReinterpretMemberPointer:
John McCallf3735e02010-12-01 04:43:34 +0000701 case CK_IntegralToPointer:
702 case CK_PointerToIntegral:
703 case CK_PointerToBoolean:
704 case CK_ToVoid:
705 case CK_VectorSplat:
706 case CK_IntegralCast:
707 case CK_IntegralToBoolean:
708 case CK_IntegralToFloating:
709 case CK_FloatingToIntegral:
710 case CK_FloatingToBoolean:
711 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +0000712 case CK_CPointerToObjCPointerCast:
713 case CK_BlockPointerToObjCPointerCast:
John McCallf3735e02010-12-01 04:43:34 +0000714 case CK_AnyPointerToBlockPointerCast:
715 case CK_ObjCObjectLValueCast:
716 case CK_FloatingRealToComplex:
717 case CK_FloatingComplexToReal:
718 case CK_FloatingComplexToBoolean:
719 case CK_FloatingComplexCast:
720 case CK_FloatingComplexToIntegralComplex:
721 case CK_IntegralRealToComplex:
722 case CK_IntegralComplexToReal:
723 case CK_IntegralComplexToBoolean:
724 case CK_IntegralComplexCast:
725 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +0000726 case CK_ARCProduceObject:
727 case CK_ARCConsumeObject:
728 case CK_ARCReclaimReturnedObject:
729 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +0000730 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +0000731 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000732 case CK_ZeroToOCLEvent:
David Tweede1468322013-12-11 13:39:46 +0000733 case CK_AddressSpaceConversion:
John McCallf3735e02010-12-01 04:43:34 +0000734 llvm_unreachable("cast kind invalid for aggregate types");
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000735 }
Anders Carlsson1ba25ca2008-01-14 06:28:57 +0000736}
737
Chris Lattner0f398c42008-07-26 22:37:01 +0000738void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
Anders Carlssonddcbfe72009-05-27 16:45:02 +0000739 if (E->getCallReturnType()->isReferenceType()) {
740 EmitAggLoadOfLValue(E);
741 return;
742 }
Mike Stump11289f42009-09-09 15:08:12 +0000743
John McCallcc04e9f2010-05-22 22:13:32 +0000744 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
John McCalla5efa732011-08-25 23:04:34 +0000745 EmitMoveFromReturnSlot(E, RV);
Anders Carlsson0370eb22007-10-31 22:04:46 +0000746}
Chris Lattner0f398c42008-07-26 22:37:01 +0000747
748void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCallcc04e9f2010-05-22 22:13:32 +0000749 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
John McCalla5efa732011-08-25 23:04:34 +0000750 EmitMoveFromReturnSlot(E, RV);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000751}
Anders Carlsson0370eb22007-10-31 22:04:46 +0000752
Chris Lattner0f398c42008-07-26 22:37:01 +0000753void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCalla2342eb2010-12-05 02:00:02 +0000754 CGF.EmitIgnoredExpr(E->getLHS());
John McCall7a626f62010-09-15 10:14:12 +0000755 Visit(E->getRHS());
Eli Friedman4b0e2a32008-05-20 07:56:31 +0000756}
757
Chris Lattner49e3bfa2007-08-31 22:54:14 +0000758void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCallce1de612011-01-26 04:00:11 +0000759 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall7a626f62010-09-15 10:14:12 +0000760 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
Chris Lattner49e3bfa2007-08-31 22:54:14 +0000761}
762
Chris Lattner4758b402007-08-21 04:25:47 +0000763void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000764 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +0000765 VisitPointerToDataMemberBinaryOperator(E);
766 else
767 CGF.ErrorUnsupported(E, "aggregate binary expression");
768}
769
770void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
771 const BinaryOperator *E) {
772 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
John McCall4e8ca4f2012-07-02 23:58:38 +0000773 EmitFinalDestCopy(E->getType(), LV);
774}
775
776/// Is the value of the given expression possibly a reference to or
777/// into a __block variable?
778static bool isBlockVarRef(const Expr *E) {
779 // Make sure we look through parens.
780 E = E->IgnoreParens();
781
782 // Check for a direct reference to a __block variable.
783 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
784 const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
785 return (var && var->hasAttr<BlocksAttr>());
786 }
787
788 // More complicated stuff.
789
790 // Binary operators.
791 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
792 // For an assignment or pointer-to-member operation, just care
793 // about the LHS.
794 if (op->isAssignmentOp() || op->isPtrMemOp())
795 return isBlockVarRef(op->getLHS());
796
797 // For a comma, just care about the RHS.
798 if (op->getOpcode() == BO_Comma)
799 return isBlockVarRef(op->getRHS());
800
801 // FIXME: pointer arithmetic?
802 return false;
803
804 // Check both sides of a conditional operator.
805 } else if (const AbstractConditionalOperator *op
806 = dyn_cast<AbstractConditionalOperator>(E)) {
807 return isBlockVarRef(op->getTrueExpr())
808 || isBlockVarRef(op->getFalseExpr());
809
810 // OVEs are required to support BinaryConditionalOperators.
811 } else if (const OpaqueValueExpr *op
812 = dyn_cast<OpaqueValueExpr>(E)) {
813 if (const Expr *src = op->getSourceExpr())
814 return isBlockVarRef(src);
815
816 // Casts are necessary to get things like (*(int*)&var) = foo().
817 // We don't really care about the kind of cast here, except
818 // we don't want to look through l2r casts, because it's okay
819 // to get the *value* in a __block variable.
820 } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
821 if (cast->getCastKind() == CK_LValueToRValue)
822 return false;
823 return isBlockVarRef(cast->getSubExpr());
824
825 // Handle unary operators. Again, just aggressively look through
826 // it, ignoring the operation.
827 } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
828 return isBlockVarRef(uop->getSubExpr());
829
830 // Look into the base of a field access.
831 } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
832 return isBlockVarRef(mem->getBase());
833
834 // Look into the base of a subscript.
835 } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
836 return isBlockVarRef(sub->getBase());
837 }
838
839 return false;
Chris Lattner835635d2007-08-21 04:59:27 +0000840}
841
Chris Lattnercd9fb242007-08-21 04:43:17 +0000842void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Eli Friedmanf54c4e52008-02-11 01:09:17 +0000843 // For an assignment to work, the value on the right has
844 // to be compatible with the value on the left.
Eli Friedman2a695472009-05-28 23:04:00 +0000845 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
846 E->getRHS()->getType())
Eli Friedmanf54c4e52008-02-11 01:09:17 +0000847 && "Invalid assignment");
John McCalld0a30012010-12-06 06:10:02 +0000848
John McCall4e8ca4f2012-07-02 23:58:38 +0000849 // If the LHS might be a __block variable, and the RHS can
850 // potentially cause a block copy, we need to evaluate the RHS first
851 // so that the assignment goes the right place.
852 // This is pretty semantically fragile.
853 if (isBlockVarRef(E->getLHS()) &&
854 E->getRHS()->HasSideEffects(CGF.getContext())) {
855 // Ensure that we have a destination, and evaluate the RHS into that.
856 EnsureDest(E->getRHS()->getType());
857 Visit(E->getRHS());
858
859 // Now emit the LHS and copy into it.
Richard Smithe30752c2012-10-09 19:52:38 +0000860 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall4e8ca4f2012-07-02 23:58:38 +0000861
John McCalla8ec7eb2013-03-07 21:37:17 +0000862 // That copy is an atomic copy if the LHS is atomic.
863 if (LHS.getType()->isAtomicType()) {
864 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
865 return;
866 }
867
John McCall4e8ca4f2012-07-02 23:58:38 +0000868 EmitCopy(E->getLHS()->getType(),
869 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
870 needsGC(E->getLHS()->getType()),
871 AggValueSlot::IsAliased),
872 Dest);
873 return;
874 }
Chad Rosier615ed1a2012-03-29 17:37:10 +0000875
Chris Lattner4758b402007-08-21 04:25:47 +0000876 LValue LHS = CGF.EmitLValue(E->getLHS());
Chris Lattner6278e6a2007-08-11 00:04:45 +0000877
John McCalla8ec7eb2013-03-07 21:37:17 +0000878 // If we have an atomic type, evaluate into the destination and then
879 // do an atomic copy.
880 if (LHS.getType()->isAtomicType()) {
881 EnsureDest(E->getRHS()->getType());
882 Visit(E->getRHS());
883 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
884 return;
885 }
886
John McCallc109a252011-11-07 03:59:57 +0000887 // Codegen the RHS so that it stores directly into the LHS.
888 AggValueSlot LHSSlot =
889 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
890 needsGC(E->getLHS()->getType()),
Chad Rosier615ed1a2012-03-29 17:37:10 +0000891 AggValueSlot::IsAliased);
Fariborz Jahanian78652202013-01-25 23:57:05 +0000892 // A non-volatile aggregate destination might have volatile member.
893 if (!LHSSlot.isVolatile() &&
894 CGF.hasVolatileMember(E->getLHS()->getType()))
895 LHSSlot.setVolatile(true);
896
John McCall4e8ca4f2012-07-02 23:58:38 +0000897 CGF.EmitAggExpr(E->getRHS(), LHSSlot);
898
899 // Copy into the destination if the assignment isn't ignored.
900 EmitFinalDestCopy(E->getType(), LHS);
Chris Lattner6278e6a2007-08-11 00:04:45 +0000901}
902
John McCallc07a0c72011-02-17 10:25:35 +0000903void AggExprEmitter::
904VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Daniel Dunbara612e792008-11-13 01:38:36 +0000905 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
906 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
907 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Mike Stump11289f42009-09-09 15:08:12 +0000908
John McCallc07a0c72011-02-17 10:25:35 +0000909 // Bind the common expression if necessary.
Eli Friedman48fd89a2012-01-06 20:42:20 +0000910 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCallc07a0c72011-02-17 10:25:35 +0000911
Justin Bogneref512b92014-01-06 22:27:43 +0000912 RegionCounter Cnt = CGF.getPGORegionCounter(E);
John McCallce1de612011-01-26 04:00:11 +0000913 CodeGenFunction::ConditionalEvaluation eval(CGF);
Justin Bogneref512b92014-01-06 22:27:43 +0000914 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock, Cnt.getCount());
Mike Stump11289f42009-09-09 15:08:12 +0000915
John McCall5b26f652010-11-17 00:07:33 +0000916 // Save whether the destination's lifetime is externally managed.
John McCallcac93852011-08-26 08:02:37 +0000917 bool isExternallyDestructed = Dest.isExternallyDestructed();
Chris Lattner6278e6a2007-08-11 00:04:45 +0000918
John McCallce1de612011-01-26 04:00:11 +0000919 eval.begin(CGF);
920 CGF.EmitBlock(LHSBlock);
Justin Bogneref512b92014-01-06 22:27:43 +0000921 Cnt.beginRegion(Builder);
John McCallc07a0c72011-02-17 10:25:35 +0000922 Visit(E->getTrueExpr());
John McCallce1de612011-01-26 04:00:11 +0000923 eval.end(CGF);
Mike Stump11289f42009-09-09 15:08:12 +0000924
John McCallce1de612011-01-26 04:00:11 +0000925 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
926 CGF.Builder.CreateBr(ContBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000927
John McCall5b26f652010-11-17 00:07:33 +0000928 // If the result of an agg expression is unused, then the emission
929 // of the LHS might need to create a destination slot. That's fine
930 // with us, and we can safely emit the RHS into the same slot, but
John McCallcac93852011-08-26 08:02:37 +0000931 // we shouldn't claim that it's already being destructed.
932 Dest.setExternallyDestructed(isExternallyDestructed);
John McCall5b26f652010-11-17 00:07:33 +0000933
John McCallce1de612011-01-26 04:00:11 +0000934 eval.begin(CGF);
935 CGF.EmitBlock(RHSBlock);
John McCallc07a0c72011-02-17 10:25:35 +0000936 Visit(E->getFalseExpr());
John McCallce1de612011-01-26 04:00:11 +0000937 eval.end(CGF);
Mike Stump11289f42009-09-09 15:08:12 +0000938
Chris Lattner4758b402007-08-21 04:25:47 +0000939 CGF.EmitBlock(ContBlock);
Chris Lattner6278e6a2007-08-11 00:04:45 +0000940}
Chris Lattner835635d2007-08-21 04:59:27 +0000941
Anders Carlsson5b2095c2009-07-08 18:33:14 +0000942void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
Eli Friedman75807f22013-07-20 00:40:58 +0000943 Visit(CE->getChosenSubExpr());
Anders Carlsson5b2095c2009-07-08 18:33:14 +0000944}
945
Eli Friedman21911e82008-05-27 15:51:49 +0000946void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Daniel Dunbare9fcadd22009-02-11 22:25:55 +0000947 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson13abd7e2008-11-04 05:30:00 +0000948 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
949
Sebastian Redl020cddc2009-01-09 21:09:38 +0000950 if (!ArgPtr) {
Mark Seaborn74020862014-01-22 20:11:01 +0000951 // If EmitVAArg fails, we fall back to the LLVM instruction.
952 llvm::Value *Val =
953 Builder.CreateVAArg(ArgValue, CGF.ConvertType(VE->getType()));
954 if (!Dest.isIgnored())
955 Builder.CreateStore(Val, Dest.getAddr());
Sebastian Redl020cddc2009-01-09 21:09:38 +0000956 return;
957 }
958
John McCall4e8ca4f2012-07-02 23:58:38 +0000959 EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
Eli Friedman21911e82008-05-27 15:51:49 +0000960}
961
Anders Carlsson3be22e22009-05-30 23:23:33 +0000962void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +0000963 // Ensure that we have a slot, but if we already do, remember
John McCallcac93852011-08-26 08:02:37 +0000964 // whether it was externally destructed.
965 bool wasExternallyDestructed = Dest.isExternallyDestructed();
John McCall4e8ca4f2012-07-02 23:58:38 +0000966 EnsureDest(E->getType());
John McCallcac93852011-08-26 08:02:37 +0000967
968 // We're going to push a destructor if there isn't already one.
969 Dest.setExternallyDestructed();
Mike Stump11289f42009-09-09 15:08:12 +0000970
John McCall7a626f62010-09-15 10:14:12 +0000971 Visit(E->getSubExpr());
Anders Carlsson3be22e22009-05-30 23:23:33 +0000972
John McCallcac93852011-08-26 08:02:37 +0000973 // Push that destructor we promised.
974 if (!wasExternallyDestructed)
Peter Collingbourne702b2842011-11-27 22:09:22 +0000975 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
Anders Carlsson3be22e22009-05-30 23:23:33 +0000976}
977
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000978void
Anders Carlsson1619a5042009-05-03 17:47:16 +0000979AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +0000980 AggValueSlot Slot = EnsureSlot(E->getType());
981 CGF.EmitCXXConstructExpr(E, Slot);
Anders Carlssonc82b86d2009-05-19 04:48:36 +0000982}
983
Eli Friedmanc370a7e2012-02-09 03:32:31 +0000984void
985AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
986 AggValueSlot Slot = EnsureSlot(E->getType());
987 CGF.EmitLambdaExpr(E, Slot);
988}
989
John McCall5d413782010-12-06 08:20:24 +0000990void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall08ef4662011-11-10 08:15:53 +0000991 CGF.enterFullExpression(E);
992 CodeGenFunction::RunCleanupsScope cleanups(CGF);
993 Visit(E->getSubExpr());
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000994}
995
Douglas Gregor747eb782010-07-08 06:14:04 +0000996void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +0000997 QualType T = E->getType();
998 AggValueSlot Slot = EnsureSlot(T);
John McCall1553b192011-06-16 04:16:24 +0000999 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Anders Carlsson18ada982009-12-16 06:57:54 +00001000}
1001
1002void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +00001003 QualType T = E->getType();
1004 AggValueSlot Slot = EnsureSlot(T);
John McCall1553b192011-06-16 04:16:24 +00001005 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Nuno Lopesff3507b2009-10-18 15:18:11 +00001006}
1007
Chris Lattner27a36312010-12-02 07:07:26 +00001008/// isSimpleZero - If emitting this value will obviously just cause a store of
1009/// zero to memory, return true. This can return false if uncertain, so it just
1010/// handles simple cases.
1011static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001012 E = E->IgnoreParens();
1013
Chris Lattner27a36312010-12-02 07:07:26 +00001014 // 0
1015 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1016 return IL->getValue() == 0;
1017 // +0.0
1018 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1019 return FL->getValue().isPosZero();
1020 // int()
1021 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
1022 CGF.getTypes().isZeroInitializable(E->getType()))
1023 return true;
1024 // (int*)0 - Null pointer expressions.
1025 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1026 return ICE->getCastKind() == CK_NullToPointer;
1027 // '\0'
1028 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1029 return CL->getValue() == 0;
1030
1031 // Otherwise, hard case: conservatively return false.
1032 return false;
1033}
1034
1035
Anders Carlssonb2473502010-02-03 17:33:16 +00001036void
Nick Lewycky2d84e842013-10-02 02:29:49 +00001037AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
John McCall1553b192011-06-16 04:16:24 +00001038 QualType type = LV.getType();
Mike Stumpdf0fe272009-05-29 15:46:01 +00001039 // FIXME: Ignore result?
Chris Lattner579a05d2008-04-04 18:42:16 +00001040 // FIXME: Are initializers affected by volatile?
Chris Lattner27a36312010-12-02 07:07:26 +00001041 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
1042 // Storing "i32 0" to a zero'd memory location is a noop.
John McCall47fb9502013-03-07 21:37:08 +00001043 return;
Richard Smithd82a2ce2012-12-21 03:17:28 +00001044 } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
John McCall47fb9502013-03-07 21:37:08 +00001045 return EmitNullInitializationToLValue(LV);
John McCall1553b192011-06-16 04:16:24 +00001046 } else if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001047 RValue RV = CGF.EmitReferenceBindingToExpr(E);
John McCall47fb9502013-03-07 21:37:08 +00001048 return CGF.EmitStoreThroughLValue(RV, LV);
1049 }
1050
1051 switch (CGF.getEvaluationKind(type)) {
1052 case TEK_Complex:
1053 CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1054 return;
1055 case TEK_Aggregate:
John McCall8d6fc952011-08-25 20:40:09 +00001056 CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
1057 AggValueSlot::IsDestructed,
1058 AggValueSlot::DoesNotNeedGCBarriers,
John McCalla5efa732011-08-25 23:04:34 +00001059 AggValueSlot::IsNotAliased,
John McCall1553b192011-06-16 04:16:24 +00001060 Dest.isZeroed()));
John McCall47fb9502013-03-07 21:37:08 +00001061 return;
1062 case TEK_Scalar:
1063 if (LV.isSimple()) {
Craig Topper8a13c412014-05-21 05:09:00 +00001064 CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
John McCall47fb9502013-03-07 21:37:08 +00001065 } else {
1066 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1067 }
1068 return;
Chris Lattner579a05d2008-04-04 18:42:16 +00001069 }
John McCall47fb9502013-03-07 21:37:08 +00001070 llvm_unreachable("bad evaluation kind");
Chris Lattner579a05d2008-04-04 18:42:16 +00001071}
1072
John McCall1553b192011-06-16 04:16:24 +00001073void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1074 QualType type = lv.getType();
1075
Chris Lattner27a36312010-12-02 07:07:26 +00001076 // If the destination slot is already zeroed out before the aggregate is
1077 // copied into it, we don't have to emit any zeros here.
John McCall1553b192011-06-16 04:16:24 +00001078 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
Chris Lattner27a36312010-12-02 07:07:26 +00001079 return;
1080
John McCall47fb9502013-03-07 21:37:08 +00001081 if (CGF.hasScalarEvaluationKind(type)) {
Richard Smithd82a2ce2012-12-21 03:17:28 +00001082 // For non-aggregates, we can store the appropriate null constant.
1083 llvm::Value *null = CGF.CGM.EmitNullConstant(type);
Eli Friedman91d5bb12012-02-22 05:38:59 +00001084 // Note that the following is not equivalent to
1085 // EmitStoreThroughBitfieldLValue for ARC types.
Eli Friedmancb3785e2012-02-24 23:53:49 +00001086 if (lv.isBitField()) {
Eli Friedman91d5bb12012-02-22 05:38:59 +00001087 CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
Eli Friedmancb3785e2012-02-24 23:53:49 +00001088 } else {
1089 assert(lv.isSimple());
1090 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1091 }
Lauro Ramos Venancioe2162c62008-02-19 19:27:31 +00001092 } else {
Chris Lattner579a05d2008-04-04 18:42:16 +00001093 // There's a potential optimization opportunity in combining
1094 // memsets; that would be easy for arrays, but relatively
1095 // difficult for structures with the current code.
John McCall1553b192011-06-16 04:16:24 +00001096 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
Chris Lattner579a05d2008-04-04 18:42:16 +00001097 }
1098}
1099
Chris Lattner579a05d2008-04-04 18:42:16 +00001100void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
Eli Friedmanf5d08c92008-12-02 01:17:45 +00001101#if 0
Eli Friedman6d11ec82009-12-04 01:30:56 +00001102 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
1103 // (Length of globals? Chunks of zeroed-out space?).
Eli Friedmanf5d08c92008-12-02 01:17:45 +00001104 //
Mike Stump18bb9282009-05-16 07:57:57 +00001105 // If we can, prefer a copy from a global; this is a lot less code for long
1106 // globals, and it's easier for the current optimizers to analyze.
Eli Friedman6d11ec82009-12-04 01:30:56 +00001107 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
Eli Friedmanc59bb482008-11-30 02:11:09 +00001108 llvm::GlobalVariable* GV =
Eli Friedman6d11ec82009-12-04 01:30:56 +00001109 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1110 llvm::GlobalValue::InternalLinkage, C, "");
John McCall4e8ca4f2012-07-02 23:58:38 +00001111 EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
Eli Friedmanc59bb482008-11-30 02:11:09 +00001112 return;
1113 }
Eli Friedmanf5d08c92008-12-02 01:17:45 +00001114#endif
Chris Lattnerf53c0962010-09-06 00:11:41 +00001115 if (E->hadArrayRangeDesignator())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001116 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001117
Richard Smithbe93c002013-05-23 21:54:14 +00001118 AggValueSlot Dest = EnsureSlot(E->getType());
1119
Eli Friedman7f1ff602012-04-16 03:54:45 +00001120 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
1121 Dest.getAlignment());
John McCall7a626f62010-09-15 10:14:12 +00001122
Chris Lattner579a05d2008-04-04 18:42:16 +00001123 // Handle initialization of an array.
1124 if (E->getType()->isArrayType()) {
Richard Smith9ec1e482012-04-15 02:50:59 +00001125 if (E->isStringLiteralInit())
1126 return Visit(E->getInit(0));
Eli Friedmanf23b6fa2008-05-19 17:51:16 +00001127
Eli Friedman91f5ae52012-02-23 02:25:10 +00001128 QualType elementType =
1129 CGF.getContext().getAsArrayType(E->getType())->getElementType();
Argyrios Kyrtzidise07425a52011-04-28 18:53:58 +00001130
Sebastian Redlc83ed822012-02-17 08:42:25 +00001131 llvm::PointerType *APType =
Eli Friedman7f1ff602012-04-16 03:54:45 +00001132 cast<llvm::PointerType>(Dest.getAddr()->getType());
Sebastian Redlc83ed822012-02-17 08:42:25 +00001133 llvm::ArrayType *AType =
1134 cast<llvm::ArrayType>(APType->getElementType());
Chris Lattner27a36312010-12-02 07:07:26 +00001135
Eli Friedman7f1ff602012-04-16 03:54:45 +00001136 EmitArrayInit(Dest.getAddr(), AType, elementType, E);
Chris Lattner579a05d2008-04-04 18:42:16 +00001137 return;
1138 }
Mike Stump11289f42009-09-09 15:08:12 +00001139
Richard Smith77be48a2014-07-31 06:31:19 +00001140 if (E->getType()->isAtomicType()) {
1141 // An _Atomic(T) object can be list-initialized from an expression
1142 // of the same type.
1143 assert(E->getNumInits() == 1 &&
1144 CGF.getContext().hasSameUnqualifiedType(E->getInit(0)->getType(),
1145 E->getType()) &&
1146 "unexpected list initialization for atomic object");
1147 return Visit(E->getInit(0));
1148 }
1149
Chris Lattner579a05d2008-04-04 18:42:16 +00001150 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
Mike Stump11289f42009-09-09 15:08:12 +00001151
Chris Lattner579a05d2008-04-04 18:42:16 +00001152 // Do struct initialization; this code just sets each individual member
1153 // to the approprate value. This makes bitfield support automatic;
1154 // the disadvantage is that the generated code is more difficult for
1155 // the optimizer, especially with bitfields.
1156 unsigned NumInitElements = E->getNumInits();
John McCall3b935d32011-07-11 19:35:02 +00001157 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001158
1159 // Prepare a 'this' for CXXDefaultInitExprs.
1160 CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddr());
1161
John McCall3b935d32011-07-11 19:35:02 +00001162 if (record->isUnion()) {
Douglas Gregor51695702009-01-29 16:53:55 +00001163 // Only initialize one field of a union. The field itself is
1164 // specified by the initializer list.
1165 if (!E->getInitializedFieldInUnion()) {
1166 // Empty union; we have nothing to do.
Mike Stump11289f42009-09-09 15:08:12 +00001167
Douglas Gregor51695702009-01-29 16:53:55 +00001168#ifndef NDEBUG
1169 // Make sure that it's really an empty and not a failure of
1170 // semantic analysis.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001171 for (const auto *Field : record->fields())
Douglas Gregor51695702009-01-29 16:53:55 +00001172 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1173#endif
1174 return;
1175 }
1176
1177 // FIXME: volatility
1178 FieldDecl *Field = E->getInitializedFieldInUnion();
Douglas Gregor51695702009-01-29 16:53:55 +00001179
Eli Friedman7f1ff602012-04-16 03:54:45 +00001180 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001181 if (NumInitElements) {
1182 // Store the initializer into the field
Chad Rosier615ed1a2012-03-29 17:37:10 +00001183 EmitInitializationToLValue(E->getInit(0), FieldLoc);
Douglas Gregor51695702009-01-29 16:53:55 +00001184 } else {
Chris Lattner27a36312010-12-02 07:07:26 +00001185 // Default-initialize to null.
John McCall1553b192011-06-16 04:16:24 +00001186 EmitNullInitializationToLValue(FieldLoc);
Douglas Gregor51695702009-01-29 16:53:55 +00001187 }
1188
1189 return;
1190 }
Mike Stump11289f42009-09-09 15:08:12 +00001191
John McCall3b935d32011-07-11 19:35:02 +00001192 // We'll need to enter cleanup scopes in case any of the member
1193 // initializers throw an exception.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001194 SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
Craig Topper8a13c412014-05-21 05:09:00 +00001195 llvm::Instruction *cleanupDominator = nullptr;
John McCall3b935d32011-07-11 19:35:02 +00001196
Chris Lattner579a05d2008-04-04 18:42:16 +00001197 // Here we iterate over the fields; this makes it simpler to both
1198 // default-initialize fields and skip over unnamed fields.
John McCall3b935d32011-07-11 19:35:02 +00001199 unsigned curInitIndex = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001200 for (const auto *field : record->fields()) {
John McCall3b935d32011-07-11 19:35:02 +00001201 // We're done once we hit the flexible array member.
1202 if (field->getType()->isIncompleteArrayType())
Douglas Gregor91f84212008-12-11 16:49:14 +00001203 break;
1204
John McCall3b935d32011-07-11 19:35:02 +00001205 // Always skip anonymous bitfields.
1206 if (field->isUnnamedBitfield())
Chris Lattner579a05d2008-04-04 18:42:16 +00001207 continue;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001208
John McCall3b935d32011-07-11 19:35:02 +00001209 // We're done if we reach the end of the explicit initializers, we
1210 // have a zeroed object, and the rest of the fields are
1211 // zero-initializable.
1212 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
Chris Lattner27a36312010-12-02 07:07:26 +00001213 CGF.getTypes().isZeroInitializable(E->getType()))
1214 break;
1215
Eli Friedman7f1ff602012-04-16 03:54:45 +00001216
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001217 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
Fariborz Jahanian7c1baf42009-05-27 19:54:11 +00001218 // We never generate write-barries for initialized fields.
John McCall3b935d32011-07-11 19:35:02 +00001219 LV.setNonGC(true);
Chris Lattner27a36312010-12-02 07:07:26 +00001220
John McCall3b935d32011-07-11 19:35:02 +00001221 if (curInitIndex < NumInitElements) {
Chris Lattnere18aaf22010-03-08 21:08:07 +00001222 // Store the initializer into the field.
Chad Rosier615ed1a2012-03-29 17:37:10 +00001223 EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
Chris Lattner579a05d2008-04-04 18:42:16 +00001224 } else {
1225 // We're out of initalizers; default-initialize to null
John McCall3b935d32011-07-11 19:35:02 +00001226 EmitNullInitializationToLValue(LV);
1227 }
1228
1229 // Push a destructor if necessary.
1230 // FIXME: if we have an array of structures, all explicitly
1231 // initialized, we can end up pushing a linear number of cleanups.
1232 bool pushedCleanup = false;
1233 if (QualType::DestructionKind dtorKind
1234 = field->getType().isDestructedType()) {
1235 assert(LV.isSimple());
1236 if (CGF.needsEHCleanup(dtorKind)) {
John McCallf4beacd2011-11-10 10:43:54 +00001237 if (!cleanupDominator)
1238 cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1239
John McCall3b935d32011-07-11 19:35:02 +00001240 CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1241 CGF.getDestroyer(dtorKind), false);
1242 cleanups.push_back(CGF.EHStack.stable_begin());
1243 pushedCleanup = true;
1244 }
Chris Lattner579a05d2008-04-04 18:42:16 +00001245 }
Chris Lattner27a36312010-12-02 07:07:26 +00001246
1247 // If the GEP didn't get used because of a dead zero init or something
1248 // else, clean it up for -O0 builds and general tidiness.
John McCall3b935d32011-07-11 19:35:02 +00001249 if (!pushedCleanup && LV.isSimple())
Chris Lattner27a36312010-12-02 07:07:26 +00001250 if (llvm::GetElementPtrInst *GEP =
John McCall3b935d32011-07-11 19:35:02 +00001251 dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
Chris Lattner27a36312010-12-02 07:07:26 +00001252 if (GEP->use_empty())
1253 GEP->eraseFromParent();
Lauro Ramos Venancioe2162c62008-02-19 19:27:31 +00001254 }
John McCall3b935d32011-07-11 19:35:02 +00001255
1256 // Deactivate all the partial cleanups in reverse order, which
1257 // generally means popping them.
1258 for (unsigned i = cleanups.size(); i != 0; --i)
John McCallf4beacd2011-11-10 10:43:54 +00001259 CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1260
1261 // Destroy the placeholder if we made one.
1262 if (cleanupDominator)
1263 cleanupDominator->eraseFromParent();
Devang Patel87174172007-10-26 17:44:44 +00001264}
1265
Chris Lattner835635d2007-08-21 04:59:27 +00001266//===----------------------------------------------------------------------===//
1267// Entry Points into this File
1268//===----------------------------------------------------------------------===//
1269
Chris Lattner27a36312010-12-02 07:07:26 +00001270/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1271/// non-zero bytes that will be stored when outputting the initializer for the
1272/// specified initializer expression.
Ken Dyckdf94cb72011-04-24 17:17:56 +00001273static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001274 E = E->IgnoreParens();
Chris Lattner27a36312010-12-02 07:07:26 +00001275
1276 // 0 and 0.0 won't require any non-zero stores!
Ken Dyckdf94cb72011-04-24 17:17:56 +00001277 if (isSimpleZero(E, CGF)) return CharUnits::Zero();
Chris Lattner27a36312010-12-02 07:07:26 +00001278
1279 // If this is an initlist expr, sum up the size of sizes of the (present)
1280 // elements. If this is something weird, assume the whole thing is non-zero.
1281 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00001282 if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
Ken Dyckdf94cb72011-04-24 17:17:56 +00001283 return CGF.getContext().getTypeSizeInChars(E->getType());
Chris Lattner27a36312010-12-02 07:07:26 +00001284
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001285 // InitListExprs for structs have to be handled carefully. If there are
1286 // reference members, we need to consider the size of the reference, not the
1287 // referencee. InitListExprs for unions and arrays can't have references.
Chris Lattner5cd84752010-12-02 22:52:04 +00001288 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1289 if (!RT->isUnionType()) {
1290 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
Ken Dyckdf94cb72011-04-24 17:17:56 +00001291 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner5cd84752010-12-02 22:52:04 +00001292
1293 unsigned ILEElement = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001294 for (const auto *Field : SD->fields()) {
Chris Lattner5cd84752010-12-02 22:52:04 +00001295 // We're done once we hit the flexible array member or run out of
1296 // InitListExpr elements.
1297 if (Field->getType()->isIncompleteArrayType() ||
1298 ILEElement == ILE->getNumInits())
1299 break;
1300 if (Field->isUnnamedBitfield())
1301 continue;
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001302
Chris Lattner5cd84752010-12-02 22:52:04 +00001303 const Expr *E = ILE->getInit(ILEElement++);
1304
1305 // Reference values are always non-null and have the width of a pointer.
1306 if (Field->getType()->isReferenceType())
Ken Dyckdf94cb72011-04-24 17:17:56 +00001307 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00001308 CGF.getTarget().getPointerWidth(0));
Chris Lattner5cd84752010-12-02 22:52:04 +00001309 else
1310 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1311 }
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001312
Chris Lattner5cd84752010-12-02 22:52:04 +00001313 return NumNonZeroBytes;
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001314 }
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001315 }
1316
1317
Ken Dyckdf94cb72011-04-24 17:17:56 +00001318 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner27a36312010-12-02 07:07:26 +00001319 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1320 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1321 return NumNonZeroBytes;
1322}
1323
1324/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1325/// zeros in it, emit a memset and avoid storing the individual zeros.
1326///
1327static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1328 CodeGenFunction &CGF) {
1329 // If the slot is already known to be zeroed, nothing to do. Don't mess with
1330 // volatile stores.
Craig Topper8a13c412014-05-21 05:09:00 +00001331 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == nullptr)
1332 return;
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +00001333
1334 // C++ objects with a user-declared constructor don't need zero'ing.
Richard Smith9c6890a2012-11-01 22:30:59 +00001335 if (CGF.getLangOpts().CPlusPlus)
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +00001336 if (const RecordType *RT = CGF.getContext()
1337 .getBaseElementType(E->getType())->getAs<RecordType>()) {
1338 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1339 if (RD->hasUserDeclaredConstructor())
1340 return;
1341 }
1342
Chris Lattner27a36312010-12-02 07:07:26 +00001343 // If the type is 16-bytes or smaller, prefer individual stores over memset.
Ken Dyck239a3352011-04-24 17:25:32 +00001344 std::pair<CharUnits, CharUnits> TypeInfo =
1345 CGF.getContext().getTypeInfoInChars(E->getType());
1346 if (TypeInfo.first <= CharUnits::fromQuantity(16))
Chris Lattner27a36312010-12-02 07:07:26 +00001347 return;
1348
1349 // Check to see if over 3/4 of the initializer are known to be zero. If so,
1350 // we prefer to emit memset + individual stores for the rest.
Ken Dyck239a3352011-04-24 17:25:32 +00001351 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1352 if (NumNonZeroBytes*4 > TypeInfo.first)
Chris Lattner27a36312010-12-02 07:07:26 +00001353 return;
1354
1355 // Okay, it seems like a good idea to use an initial memset, emit the call.
Ken Dyck239a3352011-04-24 17:25:32 +00001356 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1357 CharUnits Align = TypeInfo.second;
Chris Lattner27a36312010-12-02 07:07:26 +00001358
1359 llvm::Value *Loc = Slot.getAddr();
Chris Lattner27a36312010-12-02 07:07:26 +00001360
Chris Lattnerece04092012-02-07 00:39:47 +00001361 Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
Ken Dyck239a3352011-04-24 17:25:32 +00001362 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1363 Align.getQuantity(), false);
Chris Lattner27a36312010-12-02 07:07:26 +00001364
1365 // Tell the AggExprEmitter that the slot is known zero.
1366 Slot.setZeroed();
1367}
1368
1369
1370
1371
Mike Stump25306ca2009-05-26 18:57:45 +00001372/// EmitAggExpr - Emit the computation of the specified expression of aggregate
1373/// type. The result is computed into DestPtr. Note that if DestPtr is null,
1374/// the value of the aggregate expression is not needed. If VolatileDest is
1375/// true, DestPtr cannot be 0.
John McCall4e8ca4f2012-07-02 23:58:38 +00001376void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
John McCall47fb9502013-03-07 21:37:08 +00001377 assert(E && hasAggregateEvaluationKind(E->getType()) &&
Chris Lattner835635d2007-08-21 04:59:27 +00001378 "Invalid aggregate expression to emit");
Craig Topper8a13c412014-05-21 05:09:00 +00001379 assert((Slot.getAddr() != nullptr || Slot.isIgnored()) &&
Chris Lattner27a36312010-12-02 07:07:26 +00001380 "slot has bits but no address");
Mike Stump11289f42009-09-09 15:08:12 +00001381
Chris Lattner27a36312010-12-02 07:07:26 +00001382 // Optimize the slot if possible.
1383 CheckAggExprForMemSetUse(Slot, E, *this);
1384
John McCall4e8ca4f2012-07-02 23:58:38 +00001385 AggExprEmitter(*this, Slot).Visit(const_cast<Expr*>(E));
Chris Lattner835635d2007-08-21 04:59:27 +00001386}
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00001387
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00001388LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
John McCall47fb9502013-03-07 21:37:08 +00001389 assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
Daniel Dunbara7566f12010-02-09 02:48:28 +00001390 llvm::Value *Temp = CreateMemTemp(E->getType());
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001391 LValue LV = MakeAddrLValue(Temp, E->getType());
John McCall8d6fc952011-08-25 20:40:09 +00001392 EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
John McCall46759f42011-08-26 07:31:35 +00001393 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001394 AggValueSlot::IsNotAliased));
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001395 return LV;
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00001396}
1397
Chad Rosier615ed1a2012-03-29 17:37:10 +00001398void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1399 llvm::Value *SrcPtr, QualType Ty,
John McCall4e8ca4f2012-07-02 23:58:38 +00001400 bool isVolatile,
Benjamin Kramer1ca66912012-09-30 12:43:37 +00001401 CharUnits alignment,
1402 bool isAssignment) {
Chad Rosier615ed1a2012-03-29 17:37:10 +00001403 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
Mike Stump11289f42009-09-09 15:08:12 +00001404
Richard Smith9c6890a2012-11-01 22:30:59 +00001405 if (getLangOpts().CPlusPlus) {
Chad Rosier615ed1a2012-03-29 17:37:10 +00001406 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1407 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1408 assert((Record->hasTrivialCopyConstructor() ||
1409 Record->hasTrivialCopyAssignment() ||
1410 Record->hasTrivialMoveConstructor() ||
1411 Record->hasTrivialMoveAssignment()) &&
Richard Smith16488472012-11-16 00:53:38 +00001412 "Trying to aggregate-copy a type without a trivial copy/move "
Douglas Gregorf22101a2010-05-20 15:39:01 +00001413 "constructor or assignment operator");
Chad Rosier615ed1a2012-03-29 17:37:10 +00001414 // Ignore empty classes in C++.
1415 if (Record->isEmpty())
Anders Carlsson16e94af2010-05-03 01:20:20 +00001416 return;
1417 }
1418 }
1419
Chris Lattnerca05dfe2009-02-28 18:31:01 +00001420 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
Chris Lattner3ef668c2009-02-28 18:18:58 +00001421 // C99 6.5.16.1p3, which states "If the value being stored in an object is
1422 // read from another object that overlaps in anyway the storage of the first
1423 // object, then the overlap shall be exact and the two objects shall have
1424 // qualified or unqualified versions of a compatible type."
1425 //
Chris Lattnerca05dfe2009-02-28 18:31:01 +00001426 // memcpy is not defined if the source and destination pointers are exactly
Chris Lattner3ef668c2009-02-28 18:18:58 +00001427 // equal, but other compilers do this optimization, and almost every memcpy
1428 // implementation handles this case safely. If there is a libc that does not
1429 // safely handle this, we can add a target hook.
Chad Rosier615ed1a2012-03-29 17:37:10 +00001430
Benjamin Kramer1ca66912012-09-30 12:43:37 +00001431 // Get data size and alignment info for this aggregate. If this is an
1432 // assignment don't copy the tail padding. Otherwise copying it is fine.
1433 std::pair<CharUnits, CharUnits> TypeInfo;
1434 if (isAssignment)
1435 TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
1436 else
1437 TypeInfo = getContext().getTypeInfoInChars(Ty);
Chad Rosier615ed1a2012-03-29 17:37:10 +00001438
John McCall4e8ca4f2012-07-02 23:58:38 +00001439 if (alignment.isZero())
1440 alignment = TypeInfo.second;
Chad Rosier615ed1a2012-03-29 17:37:10 +00001441
1442 // FIXME: Handle variable sized types.
1443
1444 // FIXME: If we have a volatile struct, the optimizer can remove what might
1445 // appear to be `extra' memory ops:
1446 //
1447 // volatile struct { int i; } a, b;
1448 //
1449 // int main() {
1450 // a = b;
1451 // a = b;
1452 // }
1453 //
1454 // we need to use a different call here. We use isVolatile to indicate when
1455 // either the source or the destination is volatile.
1456
1457 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1458 llvm::Type *DBP =
1459 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1460 DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1461
1462 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1463 llvm::Type *SBP =
1464 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1465 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1466
1467 // Don't do any of the memmove_collectable tests if GC isn't set.
1468 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1469 // fall through
1470 } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1471 RecordDecl *Record = RecordTy->getDecl();
1472 if (Record->hasObjectMember()) {
1473 CharUnits size = TypeInfo.first;
1474 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1475 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
1476 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1477 SizeVal);
1478 return;
1479 }
1480 } else if (Ty->isArrayType()) {
1481 QualType BaseType = getContext().getBaseElementType(Ty);
1482 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1483 if (RecordTy->getDecl()->hasObjectMember()) {
1484 CharUnits size = TypeInfo.first;
1485 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1486 llvm::Value *SizeVal =
1487 llvm::ConstantInt::get(SizeTy, size.getQuantity());
1488 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1489 SizeVal);
1490 return;
1491 }
1492 }
1493 }
Dan Gohman22695fc2012-09-28 21:58:29 +00001494
1495 // Determine the metadata to describe the position of any padding in this
1496 // memcpy, as well as the TBAA tags for the members of the struct, in case
1497 // the optimizer wishes to expand it in to scalar memory operations.
1498 llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty);
Craig Topper8a13c412014-05-21 05:09:00 +00001499
Chad Rosier615ed1a2012-03-29 17:37:10 +00001500 Builder.CreateMemCpy(DestPtr, SrcPtr,
1501 llvm::ConstantInt::get(IntPtrTy,
1502 TypeInfo.first.getQuantity()),
Dan Gohman22695fc2012-09-28 21:58:29 +00001503 alignment.getQuantity(), isVolatile,
Craig Topper8a13c412014-05-21 05:09:00 +00001504 /*TBAATag=*/nullptr, TBAAStructTag);
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00001505}