blob: 959086891c8e6eb3442df3c51ea83323f28c67eb [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"
Ivan A. Kosareve0ef3482018-02-19 09:49:11 +000017#include "ConstantEmitter.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Anders Carlssonb7f8f592009-04-17 00:06:03 +000019#include "clang/AST/DeclCXX.h"
Sebastian Redlc83ed822012-02-17 08:42:25 +000020#include "clang/AST/DeclTemplate.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000021#include "clang/AST/StmtVisitor.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/GlobalVariable.h"
25#include "llvm/IR/Intrinsics.h"
George Burgess IV4deb75d2018-03-10 23:06:31 +000026#include "llvm/IR/IntrinsicInst.h"
Chris Lattnerd79671f2007-08-10 20:13:28 +000027using namespace clang;
28using namespace CodeGen;
Chris Lattner6278e6a2007-08-11 00:04:45 +000029
Chris Lattner4758b402007-08-21 04:25:47 +000030//===----------------------------------------------------------------------===//
31// Aggregate Expression Emitter
32//===----------------------------------------------------------------------===//
33
34namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000035class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
Chris Lattner4758b402007-08-21 04:25:47 +000036 CodeGenFunction &CGF;
Daniel Dunbarcb463852008-11-01 01:53:16 +000037 CGBuilderTy &Builder;
John McCall7a626f62010-09-15 10:14:12 +000038 AggValueSlot Dest;
Leny Kholodov6aab1112015-06-08 10:23:49 +000039 bool IsResultUnused;
John McCall78a15112010-05-22 01:48:05 +000040
John McCall7a626f62010-09-15 10:14:12 +000041 AggValueSlot EnsureSlot(QualType T) {
42 if (!Dest.isIgnored()) return Dest;
43 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
John McCall78a15112010-05-22 01:48:05 +000044 }
John McCall4e8ca4f2012-07-02 23:58:38 +000045 void EnsureDest(QualType T) {
46 if (!Dest.isIgnored()) return;
47 Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
48 }
John McCallcc04e9f2010-05-22 22:13:32 +000049
George Burgess IV56e5a2e2018-03-10 01:11:17 +000050 // Calls `Fn` with a valid return value slot, potentially creating a temporary
51 // to do so. If a temporary is created, an appropriate copy into `Dest` will
George Burgess IV4deb75d2018-03-10 23:06:31 +000052 // be emitted, as will lifetime markers.
George Burgess IV56e5a2e2018-03-10 01:11:17 +000053 //
54 // The given function should take a ReturnValueSlot, and return an RValue that
55 // points to said slot.
56 void withReturnValueSlot(const Expr *E,
57 llvm::function_ref<RValue(ReturnValueSlot)> Fn);
58
Chris Lattner4758b402007-08-21 04:25:47 +000059public:
Leny Kholodov6aab1112015-06-08 10:23:49 +000060 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
61 : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
62 IsResultUnused(IsResultUnused) { }
Chris Lattner4758b402007-08-21 04:25:47 +000063
Chris Lattner835635d2007-08-21 04:59:27 +000064 //===--------------------------------------------------------------------===//
65 // Utilities
66 //===--------------------------------------------------------------------===//
67
Chris Lattner4758b402007-08-21 04:25:47 +000068 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
69 /// represents a value lvalue, this method emits the address of the lvalue,
70 /// then loads the result into DestPtr.
71 void EmitAggLoadOfLValue(const Expr *E);
Eli Friedmanf23b6fa2008-05-19 17:51:16 +000072
Akira Hatanaka7275da02018-02-28 07:15:55 +000073 enum ExprValueKind {
74 EVK_RValue,
75 EVK_NonRValue
76 };
77
Mike Stumpca9fc092009-05-23 20:28:01 +000078 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
Akira Hatanaka7275da02018-02-28 07:15:55 +000079 /// SrcIsRValue is true if source comes from an RValue.
80 void EmitFinalDestCopy(QualType type, const LValue &src,
81 ExprValueKind SrcValueKind = EVK_NonRValue);
John McCall7f416cc2015-09-08 08:05:57 +000082 void EmitFinalDestCopy(QualType type, RValue src);
John McCall4e8ca4f2012-07-02 23:58:38 +000083 void EmitCopy(QualType type, const AggValueSlot &dest,
84 const AggValueSlot &src);
Mike Stumpca9fc092009-05-23 20:28:01 +000085
John McCalla5efa732011-08-25 23:04:34 +000086 void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
John McCallcc04e9f2010-05-22 22:13:32 +000087
John McCall7f416cc2015-09-08 08:05:57 +000088 void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
Ivan A. Kosareve0ef3482018-02-19 09:49:11 +000089 QualType ArrayQTy, InitListExpr *E);
Sebastian Redlc83ed822012-02-17 08:42:25 +000090
John McCall8d6fc952011-08-25 20:40:09 +000091 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000092 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
John McCall8d6fc952011-08-25 20:40:09 +000093 return AggValueSlot::NeedsGCBarriers;
94 return AggValueSlot::DoesNotNeedGCBarriers;
95 }
96
John McCallcc04e9f2010-05-22 22:13:32 +000097 bool TypeRequiresGCollection(QualType T);
98
Chris Lattner835635d2007-08-21 04:59:27 +000099 //===--------------------------------------------------------------------===//
100 // Visitor Methods
101 //===--------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000102
David Blaikie01fb5fb2015-01-18 01:48:19 +0000103 void Visit(Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000104 ApplyDebugLocation DL(CGF, E);
David Blaikie01fb5fb2015-01-18 01:48:19 +0000105 StmtVisitor<AggExprEmitter>::Visit(E);
106 }
107
Chris Lattner4758b402007-08-21 04:25:47 +0000108 void VisitStmt(Stmt *S) {
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000109 CGF.ErrorUnsupported(S, "aggregate expression");
Chris Lattner4758b402007-08-21 04:25:47 +0000110 }
111 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
Peter Collingbourne91147592011-04-15 00:35:48 +0000112 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
113 Visit(GE->getResultExpr());
114 }
Gor Nishanov5eb58582017-03-26 02:18:05 +0000115 void VisitCoawaitExpr(CoawaitExpr *E) {
116 CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused);
117 }
118 void VisitCoyieldExpr(CoyieldExpr *E) {
119 CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused);
120 }
121 void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); }
Eli Friedman3f66b842009-01-27 09:03:41 +0000122 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000123 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
124 return Visit(E->getReplacement());
125 }
Chris Lattner4758b402007-08-21 04:25:47 +0000126
127 // l-values.
Alex Lorenz6cc83172017-08-25 10:07:00 +0000128 void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); }
Seo Sanghyeond4d8c3c2007-12-14 02:04:12 +0000129 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
130 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
Daniel Dunbard443c0a2010-01-04 18:47:06 +0000131 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000132 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Seo Sanghyeond4d8c3c2007-12-14 02:04:12 +0000133 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
134 EmitAggLoadOfLValue(E);
135 }
Chris Lattner2f343dd2009-04-21 23:00:09 +0000136 void VisitPredefinedExpr(const PredefinedExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000137 EmitAggLoadOfLValue(E);
Chris Lattner2f343dd2009-04-21 23:00:09 +0000138 }
Mike Stump11289f42009-09-09 15:08:12 +0000139
Chris Lattner4758b402007-08-21 04:25:47 +0000140 // Operators.
Anders Carlssonec143772009-08-07 23:22:37 +0000141 void VisitCastExpr(CastExpr *E);
Anders Carlsson0370eb22007-10-31 22:04:46 +0000142 void VisitCallExpr(const CallExpr *E);
Chris Lattner49e3bfa2007-08-31 22:54:14 +0000143 void VisitStmtExpr(const StmtExpr *E);
Chris Lattner4758b402007-08-21 04:25:47 +0000144 void VisitBinaryOperator(const BinaryOperator *BO);
Fariborz Jahanianffba6622009-10-22 22:57:31 +0000145 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
Chris Lattnercd9fb242007-08-21 04:43:17 +0000146 void VisitBinAssign(const BinaryOperator *E);
Eli Friedman4b0e2a32008-05-20 07:56:31 +0000147 void VisitBinComma(const BinaryOperator *E);
Chris Lattner4758b402007-08-21 04:25:47 +0000148
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000149 void VisitObjCMessageExpr(ObjCMessageExpr *E);
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000150 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
151 EmitAggLoadOfLValue(E);
152 }
Mike Stump11289f42009-09-09 15:08:12 +0000153
Yunzhong Gaocb779302015-06-10 00:27:52 +0000154 void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
John McCallc07a0c72011-02-17 10:25:35 +0000155 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
Anders Carlsson5b2095c2009-07-08 18:33:14 +0000156 void VisitChooseExpr(const ChooseExpr *CE);
Devang Patel87174172007-10-26 17:44:44 +0000157 void VisitInitListExpr(InitListExpr *E);
Richard Smith939b6882016-12-14 01:32:13 +0000158 void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
159 llvm::Value *outerBegin = nullptr);
Anders Carlsson18ada982009-12-16 06:57:54 +0000160 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000161 void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000162 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
163 Visit(DAE->getExpr());
164 }
Richard Smith852c9db2013-04-20 22:23:05 +0000165 void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
166 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
167 Visit(DIE->getExpr());
168 }
Anders Carlsson3be22e22009-05-30 23:23:33 +0000169 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
Anders Carlsson1619a5042009-05-03 17:47:16 +0000170 void VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +0000171 void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Eli Friedmanc370a7e2012-02-09 03:32:31 +0000172 void VisitLambdaExpr(LambdaExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000173 void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
John McCall5d413782010-12-06 08:20:24 +0000174 void VisitExprWithCleanups(ExprWithCleanups *E);
Douglas Gregor747eb782010-07-08 06:14:04 +0000175 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Mike Stump5bbbb132009-11-18 00:40:12 +0000176 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
Douglas Gregorfe314812011-06-21 17:03:29 +0000177 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
John McCall1bf58462011-02-16 08:02:54 +0000178 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
179
John McCallfe96e0b2011-11-06 09:01:30 +0000180 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
181 if (E->isGLValue()) {
182 LValue LV = CGF.EmitPseudoObjectLValue(E);
John McCall4e8ca4f2012-07-02 23:58:38 +0000183 return EmitFinalDestCopy(E->getType(), LV);
John McCallfe96e0b2011-11-06 09:01:30 +0000184 }
185
186 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
187 }
188
Eli Friedman21911e82008-05-27 15:51:49 +0000189 void VisitVAArgExpr(VAArgExpr *E);
Chris Lattner579a05d2008-04-04 18:42:16 +0000190
Chad Rosier615ed1a2012-03-29 17:37:10 +0000191 void EmitInitializationToLValue(Expr *E, LValue Address);
John McCall1553b192011-06-16 04:16:24 +0000192 void EmitNullInitializationToLValue(LValue Address);
Chris Lattner4758b402007-08-21 04:25:47 +0000193 // case Expr::ChooseExprClass:
Mike Stumpf16b8c32009-12-09 19:24:08 +0000194 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000195 void VisitAtomicExpr(AtomicExpr *E) {
Tim Northovercc2a6e02015-11-09 19:56:35 +0000196 RValue Res = CGF.EmitAtomicExpr(E);
197 EmitFinalDestCopy(E->getType(), Res);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000198 }
Chris Lattner4758b402007-08-21 04:25:47 +0000199};
200} // end anonymous namespace.
201
Chris Lattner835635d2007-08-21 04:59:27 +0000202//===----------------------------------------------------------------------===//
203// Utilities
204//===----------------------------------------------------------------------===//
Chris Lattner4758b402007-08-21 04:25:47 +0000205
Chris Lattner6278e6a2007-08-11 00:04:45 +0000206/// EmitAggLoadOfLValue - Given an expression with aggregate type that
207/// represents a value lvalue, this method emits the address of the lvalue,
208/// then loads the result into DestPtr.
Chris Lattner4758b402007-08-21 04:25:47 +0000209void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
210 LValue LV = CGF.EmitLValue(E);
John McCalla8ec7eb2013-03-07 21:37:17 +0000211
212 // If the type of the l-value is atomic, then do an atomic load.
David Majnemera5b195a2015-02-14 01:35:12 +0000213 if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000214 CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
John McCalla8ec7eb2013-03-07 21:37:17 +0000215 return;
216 }
217
John McCall4e8ca4f2012-07-02 23:58:38 +0000218 EmitFinalDestCopy(E->getType(), LV);
Mike Stumpca9fc092009-05-23 20:28:01 +0000219}
220
John McCallcc04e9f2010-05-22 22:13:32 +0000221/// \brief True if the given aggregate type requires special GC API calls.
222bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
223 // Only record types have members that might require garbage collection.
224 const RecordType *RecordTy = T->getAs<RecordType>();
225 if (!RecordTy) return false;
226
227 // Don't mess with non-trivial C++ types.
228 RecordDecl *Record = RecordTy->getDecl();
229 if (isa<CXXRecordDecl>(Record) &&
Richard Smith16488472012-11-16 00:53:38 +0000230 (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
John McCallcc04e9f2010-05-22 22:13:32 +0000231 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
232 return false;
233
234 // Check whether the type has an object member.
235 return Record->hasObjectMember();
236}
237
George Burgess IV56e5a2e2018-03-10 01:11:17 +0000238void AggExprEmitter::withReturnValueSlot(
239 const Expr *E, llvm::function_ref<RValue(ReturnValueSlot)> EmitCall) {
240 QualType RetTy = E->getType();
241 bool RequiresDestruction =
242 Dest.isIgnored() &&
243 RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct;
Akira Hatanaka7275da02018-02-28 07:15:55 +0000244
George Burgess IV56e5a2e2018-03-10 01:11:17 +0000245 // If it makes no observable difference, save a memcpy + temporary.
246 //
247 // We need to always provide our own temporary if destruction is required.
248 // Otherwise, EmitCall will emit its own, notice that it's "unused", and end
249 // its lifetime before we have the chance to emit a proper destructor call.
250 bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() ||
251 (RequiresDestruction && !Dest.getAddress().isValid());
252
253 Address RetAddr = Address::invalid();
George Burgess IV4deb75d2018-03-10 23:06:31 +0000254
255 EHScopeStack::stable_iterator LifetimeEndBlock;
256 llvm::Value *LifetimeSizePtr = nullptr;
257 llvm::IntrinsicInst *LifetimeStartInst = nullptr;
George Burgess IV56e5a2e2018-03-10 01:11:17 +0000258 if (!UseTemp) {
259 RetAddr = Dest.getAddress();
260 } else {
261 RetAddr = CGF.CreateMemTemp(RetTy);
262 uint64_t Size =
263 CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy));
George Burgess IV4deb75d2018-03-10 23:06:31 +0000264 LifetimeSizePtr = CGF.EmitLifetimeStart(Size, RetAddr.getPointer());
265 if (LifetimeSizePtr) {
266 LifetimeStartInst =
267 cast<llvm::IntrinsicInst>(std::prev(Builder.GetInsertPoint()));
268 assert(LifetimeStartInst->getIntrinsicID() ==
269 llvm::Intrinsic::lifetime_start &&
270 "Last insertion wasn't a lifetime.start?");
271
George Burgess IV56e5a2e2018-03-10 01:11:17 +0000272 CGF.pushFullExprCleanup<CodeGenFunction::CallLifetimeEnd>(
273 NormalEHLifetimeMarker, RetAddr, LifetimeSizePtr);
George Burgess IV4deb75d2018-03-10 23:06:31 +0000274 LifetimeEndBlock = CGF.EHStack.stable_begin();
275 }
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000276 }
John McCalla5efa732011-08-25 23:04:34 +0000277
George Burgess IV56e5a2e2018-03-10 01:11:17 +0000278 RValue Src =
279 EmitCall(ReturnValueSlot(RetAddr, Dest.isVolatile(), IsResultUnused));
280
281 if (RequiresDestruction)
282 CGF.pushDestroy(RetTy.isDestructedType(), Src.getAggregateAddress(), RetTy);
283
George Burgess IV4deb75d2018-03-10 23:06:31 +0000284 if (!UseTemp)
285 return;
286
287 assert(Dest.getPointer() != Src.getAggregatePointer());
288 EmitFinalDestCopy(E->getType(), Src);
289
290 if (!RequiresDestruction && LifetimeStartInst) {
291 // If there's no dtor to run, the copy was the last use of our temporary.
292 // Since we're not guaranteed to be in an ExprWithCleanups, clean up
293 // eagerly.
294 CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst);
295 CGF.EmitLifetimeEnd(LifetimeSizePtr, RetAddr.getPointer());
George Burgess IV56e5a2e2018-03-10 01:11:17 +0000296 }
John McCallcc04e9f2010-05-22 22:13:32 +0000297}
298
Mike Stumpca9fc092009-05-23 20:28:01 +0000299/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
John McCall7f416cc2015-09-08 08:05:57 +0000300void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {
John McCall4e8ca4f2012-07-02 23:58:38 +0000301 assert(src.isAggregate() && "value must be aggregate value!");
John McCall7f416cc2015-09-08 08:05:57 +0000302 LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);
Akira Hatanaka7275da02018-02-28 07:15:55 +0000303 EmitFinalDestCopy(type, srcLV, EVK_RValue);
John McCall4e8ca4f2012-07-02 23:58:38 +0000304}
Mike Stumpca9fc092009-05-23 20:28:01 +0000305
John McCall4e8ca4f2012-07-02 23:58:38 +0000306/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
Akira Hatanaka7275da02018-02-28 07:15:55 +0000307void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src,
308 ExprValueKind SrcValueKind) {
John McCall7a626f62010-09-15 10:14:12 +0000309 // If Dest is ignored, then we're evaluating an aggregate expression
John McCall4e8ca4f2012-07-02 23:58:38 +0000310 // in a context that doesn't care about the result. Note that loads
311 // from volatile l-values force the existence of a non-ignored
312 // destination.
313 if (Dest.isIgnored())
314 return;
Fariborz Jahanianc1236232010-10-22 22:05:03 +0000315
Akira Hatanaka7275da02018-02-28 07:15:55 +0000316 // Copy non-trivial C structs here.
317 LValue DstLV = CGF.MakeAddrLValue(
318 Dest.getAddress(), Dest.isVolatile() ? type.withVolatile() : type);
319
320 if (SrcValueKind == EVK_RValue) {
321 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) {
322 if (Dest.isPotentiallyAliased())
323 CGF.callCStructMoveAssignmentOperator(DstLV, src);
324 else
325 CGF.callCStructMoveConstructor(DstLV, src);
326 return;
327 }
328 } else {
329 if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
330 if (Dest.isPotentiallyAliased())
331 CGF.callCStructCopyAssignmentOperator(DstLV, src);
332 else
333 CGF.callCStructCopyConstructor(DstLV, src);
334 return;
335 }
336 }
337
John McCall4e8ca4f2012-07-02 23:58:38 +0000338 AggValueSlot srcAgg =
339 AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
340 needsGC(type), AggValueSlot::IsAliased);
341 EmitCopy(type, Dest, srcAgg);
342}
Chris Lattner6278e6a2007-08-11 00:04:45 +0000343
John McCall4e8ca4f2012-07-02 23:58:38 +0000344/// Perform a copy from the source into the destination.
345///
346/// \param type - the type of the aggregate being copied; qualifiers are
347/// ignored
348void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
349 const AggValueSlot &src) {
350 if (dest.requiresGCollection()) {
351 CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
352 llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
Fariborz Jahanian879d7262009-08-31 19:33:16 +0000353 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000354 dest.getAddress(),
355 src.getAddress(),
John McCall4e8ca4f2012-07-02 23:58:38 +0000356 size);
Fariborz Jahanian879d7262009-08-31 19:33:16 +0000357 return;
358 }
John McCall4e8ca4f2012-07-02 23:58:38 +0000359
Mike Stumpca9fc092009-05-23 20:28:01 +0000360 // If the result of the assignment is used, copy the LHS there also.
John McCall4e8ca4f2012-07-02 23:58:38 +0000361 // It's volatile if either side is. Use the minimum alignment of
362 // the two sides.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000363 LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type);
364 LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type);
365 CGF.EmitAggregateCopy(DestLV, SrcLV, type,
John McCall7f416cc2015-09-08 08:05:57 +0000366 dest.isVolatile() || src.isVolatile());
Chris Lattner6278e6a2007-08-11 00:04:45 +0000367}
368
Sebastian Redlc83ed822012-02-17 08:42:25 +0000369/// \brief Emit the initializer for a std::initializer_list initialized with a
370/// real initializer list.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000371void
372AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
373 // Emit an array containing the elements. The array is externally destructed
374 // if the std::initializer_list object is.
375 ASTContext &Ctx = CGF.getContext();
376 LValue Array = CGF.EmitLValue(E->getSubExpr());
377 assert(Array.isSimple() && "initializer_list array not a simple lvalue");
John McCall7f416cc2015-09-08 08:05:57 +0000378 Address ArrayPtr = Array.getAddress();
Sebastian Redlc83ed822012-02-17 08:42:25 +0000379
Richard Smithcc1b96d2013-06-12 22:31:48 +0000380 const ConstantArrayType *ArrayType =
381 Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
382 assert(ArrayType && "std::initializer_list constructed from non-array");
Sebastian Redlc83ed822012-02-17 08:42:25 +0000383
Richard Smithcc1b96d2013-06-12 22:31:48 +0000384 // FIXME: Perform the checks on the field types in SemaInit.
385 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
386 RecordDecl::field_iterator Field = Record->field_begin();
387 if (Field == Record->field_end()) {
388 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlf2e0a302012-02-25 20:51:13 +0000389 return;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000390 }
391
Sebastian Redlc83ed822012-02-17 08:42:25 +0000392 // Start pointer.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000393 if (!Field->getType()->isPointerType() ||
394 !Ctx.hasSameType(Field->getType()->getPointeeType(),
395 ArrayType->getElementType())) {
396 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlf2e0a302012-02-25 20:51:13 +0000397 return;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000398 }
Sebastian Redlc83ed822012-02-17 08:42:25 +0000399
Richard Smithcc1b96d2013-06-12 22:31:48 +0000400 AggValueSlot Dest = EnsureSlot(E->getType());
John McCall7f416cc2015-09-08 08:05:57 +0000401 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
Richard Smithcc1b96d2013-06-12 22:31:48 +0000402 LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
403 llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
404 llvm::Value *IdxStart[] = { Zero, Zero };
405 llvm::Value *ArrayStart =
John McCall7f416cc2015-09-08 08:05:57 +0000406 Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxStart, "arraystart");
Richard Smithcc1b96d2013-06-12 22:31:48 +0000407 CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
408 ++Field;
409
410 if (Field == Record->field_end()) {
411 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlf2e0a302012-02-25 20:51:13 +0000412 return;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000413 }
Richard Smithcc1b96d2013-06-12 22:31:48 +0000414
415 llvm::Value *Size = Builder.getInt(ArrayType->getSize());
416 LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
417 if (Field->getType()->isPointerType() &&
418 Ctx.hasSameType(Field->getType()->getPointeeType(),
419 ArrayType->getElementType())) {
Sebastian Redlc83ed822012-02-17 08:42:25 +0000420 // End pointer.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000421 llvm::Value *IdxEnd[] = { Zero, Size };
422 llvm::Value *ArrayEnd =
John McCall7f416cc2015-09-08 08:05:57 +0000423 Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxEnd, "arrayend");
Richard Smithcc1b96d2013-06-12 22:31:48 +0000424 CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
425 } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
Sebastian Redlc83ed822012-02-17 08:42:25 +0000426 // Length.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000427 CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000428 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +0000429 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlf2e0a302012-02-25 20:51:13 +0000430 return;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000431 }
Sebastian Redlc83ed822012-02-17 08:42:25 +0000432}
433
Richard Smith8edda962014-06-13 23:04:49 +0000434/// \brief Determine if E is a trivial array filler, that is, one that is
435/// equivalent to zero-initialization.
436static bool isTrivialFiller(Expr *E) {
437 if (!E)
438 return true;
439
440 if (isa<ImplicitValueInitExpr>(E))
441 return true;
442
443 if (auto *ILE = dyn_cast<InitListExpr>(E)) {
444 if (ILE->getNumInits())
445 return false;
446 return isTrivialFiller(ILE->getArrayFiller());
447 }
448
449 if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
450 return Cons->getConstructor()->isDefaultConstructor() &&
451 Cons->getConstructor()->isTrivial();
452
453 // FIXME: Are there other cases where we can avoid emitting an initializer?
454 return false;
455}
456
Sebastian Redlc83ed822012-02-17 08:42:25 +0000457/// \brief Emit initialization of an array from an initializer list.
John McCall7f416cc2015-09-08 08:05:57 +0000458void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
Ivan A. Kosareve0ef3482018-02-19 09:49:11 +0000459 QualType ArrayQTy, InitListExpr *E) {
Sebastian Redlc83ed822012-02-17 08:42:25 +0000460 uint64_t NumInitElements = E->getNumInits();
461
462 uint64_t NumArrayElements = AType->getNumElements();
463 assert(NumInitElements <= NumArrayElements);
464
Ivan A. Kosareve0ef3482018-02-19 09:49:11 +0000465 QualType elementType =
466 CGF.getContext().getAsArrayType(ArrayQTy)->getElementType();
467
Sebastian Redlc83ed822012-02-17 08:42:25 +0000468 // DestPtr is an array*. Construct an elementType* by drilling
469 // down a level.
470 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
471 llvm::Value *indices[] = { zero, zero };
472 llvm::Value *begin =
John McCall7f416cc2015-09-08 08:05:57 +0000473 Builder.CreateInBoundsGEP(DestPtr.getPointer(), indices, "arrayinit.begin");
474
475 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
476 CharUnits elementAlign =
477 DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000478
Ivan A. Kosareve0ef3482018-02-19 09:49:11 +0000479 // Consider initializing the array by copying from a global. For this to be
480 // more efficient than per-element initialization, the size of the elements
481 // with explicit initializers should be large enough.
482 if (NumInitElements * elementSize.getQuantity() > 16 &&
483 elementType.isTriviallyCopyableType(CGF.getContext())) {
484 CodeGen::CodeGenModule &CGM = CGF.CGM;
485 ConstantEmitter Emitter(CGM);
486 LangAS AS = ArrayQTy.getAddressSpace();
487 if (llvm::Constant *C = Emitter.tryEmitForInitializer(E, AS, ArrayQTy)) {
488 auto GV = new llvm::GlobalVariable(
489 CGM.getModule(), C->getType(),
490 CGM.isTypeConstant(ArrayQTy, /* ExcludeCtorDtor= */ true),
491 llvm::GlobalValue::PrivateLinkage, C, "constinit",
492 /* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal,
493 CGM.getContext().getTargetAddressSpace(AS));
494 Emitter.finalize(GV);
495 CharUnits Align = CGM.getContext().getTypeAlignInChars(ArrayQTy);
496 GV->setAlignment(Align.getQuantity());
497 EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GV, ArrayQTy, Align));
498 return;
499 }
500 }
501
Sebastian Redlc83ed822012-02-17 08:42:25 +0000502 // Exception safety requires us to destroy all the
503 // already-constructed members if an initializer throws.
504 // For that, we'll need an EH cleanup.
505 QualType::DestructionKind dtorKind = elementType.isDestructedType();
John McCall7f416cc2015-09-08 08:05:57 +0000506 Address endOfInit = Address::invalid();
Sebastian Redlc83ed822012-02-17 08:42:25 +0000507 EHScopeStack::stable_iterator cleanup;
Craig Topper8a13c412014-05-21 05:09:00 +0000508 llvm::Instruction *cleanupDominator = nullptr;
Sebastian Redlc83ed822012-02-17 08:42:25 +0000509 if (CGF.needsEHCleanup(dtorKind)) {
510 // In principle we could tell the cleanup where we are more
511 // directly, but the control flow can get so varied here that it
512 // would actually be quite complex. Therefore we go through an
513 // alloca.
John McCall7f416cc2015-09-08 08:05:57 +0000514 endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),
Sebastian Redlc83ed822012-02-17 08:42:25 +0000515 "arrayinit.endOfInit");
516 cleanupDominator = Builder.CreateStore(begin, endOfInit);
517 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
John McCall7f416cc2015-09-08 08:05:57 +0000518 elementAlign,
Sebastian Redlc83ed822012-02-17 08:42:25 +0000519 CGF.getDestroyer(dtorKind));
520 cleanup = CGF.EHStack.stable_begin();
521
522 // Otherwise, remember that we didn't need a cleanup.
523 } else {
524 dtorKind = QualType::DK_none;
525 }
526
527 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
528
529 // The 'current element to initialize'. The invariants on this
530 // variable are complicated. Essentially, after each iteration of
531 // the loop, it points to the last initialized element, except
532 // that it points to the beginning of the array before any
533 // elements have been initialized.
534 llvm::Value *element = begin;
535
536 // Emit the explicit initializers.
537 for (uint64_t i = 0; i != NumInitElements; ++i) {
538 // Advance to the next element.
539 if (i > 0) {
540 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
541
542 // Tell the cleanup that it needs to destroy up to this
543 // element. TODO: some of these stores can be trivially
544 // observed to be unnecessary.
John McCall7f416cc2015-09-08 08:05:57 +0000545 if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000546 }
547
John McCall7f416cc2015-09-08 08:05:57 +0000548 LValue elementLV =
549 CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000550 EmitInitializationToLValue(E->getInit(i), elementLV);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000551 }
552
553 // Check whether there's a non-trivial array-fill expression.
Sebastian Redlc83ed822012-02-17 08:42:25 +0000554 Expr *filler = E->getArrayFiller();
Richard Smith8edda962014-06-13 23:04:49 +0000555 bool hasTrivialFiller = isTrivialFiller(filler);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000556
557 // Any remaining elements need to be zero-initialized, possibly
558 // using the filler expression. We can skip this if the we're
559 // emitting to zeroed memory.
560 if (NumInitElements != NumArrayElements &&
561 !(Dest.isZeroed() && hasTrivialFiller &&
562 CGF.getTypes().isZeroInitializable(elementType))) {
563
564 // Use an actual loop. This is basically
565 // do { *array++ = filler; } while (array != end);
566
567 // Advance to the start of the rest of the array.
568 if (NumInitElements) {
569 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
John McCall7f416cc2015-09-08 08:05:57 +0000570 if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000571 }
572
573 // Compute the end of the array.
574 llvm::Value *end = Builder.CreateInBoundsGEP(begin,
575 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
576 "arrayinit.end");
577
578 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
579 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
580
581 // Jump into the body.
582 CGF.EmitBlock(bodyBB);
583 llvm::PHINode *currentElement =
584 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
585 currentElement->addIncoming(element, entryBB);
586
587 // Emit the actual filler expression.
Richard Smith72236372017-05-11 18:58:24 +0000588 {
589 // C++1z [class.temporary]p5:
590 // when a default constructor is called to initialize an element of
591 // an array with no corresponding initializer [...] the destruction of
592 // every temporary created in a default argument is sequenced before
593 // the construction of the next array element, if any
594 CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
595 LValue elementLV =
596 CGF.MakeAddrLValue(Address(currentElement, elementAlign), elementType);
597 if (filler)
598 EmitInitializationToLValue(filler, elementLV);
599 else
600 EmitNullInitializationToLValue(elementLV);
601 }
Sebastian Redlc83ed822012-02-17 08:42:25 +0000602
603 // Move on to the next element.
604 llvm::Value *nextElement =
605 Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
606
607 // Tell the EH cleanup that we finished with the last element.
John McCall7f416cc2015-09-08 08:05:57 +0000608 if (endOfInit.isValid()) Builder.CreateStore(nextElement, endOfInit);
Sebastian Redlc83ed822012-02-17 08:42:25 +0000609
610 // Leave the loop if we're done.
611 llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
612 "arrayinit.done");
613 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
614 Builder.CreateCondBr(done, endBB, bodyBB);
615 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
616
617 CGF.EmitBlock(endBB);
618 }
619
620 // Leave the partial-array cleanup if we entered one.
621 if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
622}
623
Chris Lattner835635d2007-08-21 04:59:27 +0000624//===----------------------------------------------------------------------===//
625// Visitor Methods
626//===----------------------------------------------------------------------===//
627
Douglas Gregorfe314812011-06-21 17:03:29 +0000628void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
629 Visit(E->GetTemporaryExpr());
630}
631
John McCall1bf58462011-02-16 08:02:54 +0000632void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
Akira Hatanaka797afe32018-03-20 01:47:58 +0000633 // If this is a unique OVE, just visit its source expression.
634 if (e->isUnique())
635 Visit(e->getSourceExpr());
636 else
637 EmitFinalDestCopy(e->getType(), CGF.getOrCreateOpaqueLValueMapping(e));
John McCall1bf58462011-02-16 08:02:54 +0000638}
639
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000640void
641AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCallbea4c3d2013-03-07 21:36:54 +0000642 if (Dest.isPotentiallyAliased() &&
643 E->getType().isPODType(CGF.getContext())) {
Douglas Gregor6c9d31e2011-06-17 16:37:20 +0000644 // For a POD type, just emit a load of the lvalue + a copy, because our
645 // compound literal might alias the destination.
Douglas Gregor6c9d31e2011-06-17 16:37:20 +0000646 EmitAggLoadOfLValue(E);
647 return;
648 }
649
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000650 AggValueSlot Slot = EnsureSlot(E->getType());
651 CGF.EmitAggExpr(E->getInitializer(), Slot);
652}
653
John McCalla8ec7eb2013-03-07 21:37:17 +0000654/// Attempt to look through various unimportant expressions to find a
655/// cast of the given kind.
656static Expr *findPeephole(Expr *op, CastKind kind) {
657 while (true) {
658 op = op->IgnoreParens();
659 if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
660 if (castE->getCastKind() == kind)
661 return castE->getSubExpr();
662 if (castE->getCastKind() == CK_NoOp)
663 continue;
664 }
Craig Topper8a13c412014-05-21 05:09:00 +0000665 return nullptr;
John McCalla8ec7eb2013-03-07 21:37:17 +0000666 }
667}
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000668
Anders Carlssonec143772009-08-07 23:22:37 +0000669void AggExprEmitter::VisitCastExpr(CastExpr *E) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000670 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
671 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000672 switch (E->getCastKind()) {
Anders Carlsson8a01a752011-04-11 02:03:26 +0000673 case CK_Dynamic: {
Richard Smith69d0d262012-08-24 00:54:33 +0000674 // FIXME: Can this actually happen? We have no test coverage for it.
Douglas Gregor1c073f42010-05-14 21:31:02 +0000675 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
Richard Smith69d0d262012-08-24 00:54:33 +0000676 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
Richard Smith4d1458e2012-09-08 02:08:36 +0000677 CodeGenFunction::TCK_Load);
Douglas Gregor1c073f42010-05-14 21:31:02 +0000678 // FIXME: Do we also need to handle property references here?
679 if (LV.isSimple())
680 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
681 else
682 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
683
John McCall7a626f62010-09-15 10:14:12 +0000684 if (!Dest.isIgnored())
685 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
Douglas Gregor1c073f42010-05-14 21:31:02 +0000686 break;
687 }
688
John McCalle3027922010-08-25 11:45:40 +0000689 case CK_ToUnion: {
Reid Kleckner892bb0c2015-05-20 21:59:25 +0000690 // Evaluate even if the destination is ignored.
691 if (Dest.isIgnored()) {
692 CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
693 /*ignoreResult=*/true);
694 break;
695 }
John McCall58989b72011-04-12 22:02:02 +0000696
Anders Carlssonec143772009-08-07 23:22:37 +0000697 // GCC union extension
Daniel Dunbar2e442a02010-08-21 03:15:20 +0000698 QualType Ty = E->getSubExpr()->getType();
John McCall7f416cc2015-09-08 08:05:57 +0000699 Address CastPtr =
700 Builder.CreateElementBitCast(Dest.getAddress(), CGF.ConvertType(Ty));
John McCall1553b192011-06-16 04:16:24 +0000701 EmitInitializationToLValue(E->getSubExpr(),
Chad Rosier615ed1a2012-03-29 17:37:10 +0000702 CGF.MakeAddrLValue(CastPtr, Ty));
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000703 break;
Nuno Lopes7ffcf932009-01-15 20:14:33 +0000704 }
Mike Stump11289f42009-09-09 15:08:12 +0000705
John McCalle3027922010-08-25 11:45:40 +0000706 case CK_DerivedToBase:
707 case CK_BaseToDerived:
708 case CK_UncheckedDerivedToBase: {
David Blaikie83d382b2011-09-23 05:06:16 +0000709 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
Douglas Gregoraae38d62010-05-22 05:17:18 +0000710 "should have been unpacked before we got here");
Douglas Gregoraae38d62010-05-22 05:17:18 +0000711 }
712
John McCalla8ec7eb2013-03-07 21:37:17 +0000713 case CK_NonAtomicToAtomic:
714 case CK_AtomicToNonAtomic: {
715 bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
716
717 // Determine the atomic and value types.
718 QualType atomicType = E->getSubExpr()->getType();
719 QualType valueType = E->getType();
720 if (isToAtomic) std::swap(atomicType, valueType);
721
722 assert(atomicType->isAtomicType());
723 assert(CGF.getContext().hasSameUnqualifiedType(valueType,
724 atomicType->castAs<AtomicType>()->getValueType()));
725
726 // Just recurse normally if we're ignoring the result or the
727 // atomic type doesn't change representation.
728 if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
729 return Visit(E->getSubExpr());
730 }
731
732 CastKind peepholeTarget =
733 (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
734
735 // These two cases are reverses of each other; try to peephole them.
736 if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
737 assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
738 E->getType()) &&
739 "peephole significantly changed types?");
740 return Visit(op);
741 }
742
743 // If we're converting an r-value of non-atomic type to an r-value
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000744 // of atomic type, just emit directly into the relevant sub-object.
John McCalla8ec7eb2013-03-07 21:37:17 +0000745 if (isToAtomic) {
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000746 AggValueSlot valueDest = Dest;
747 if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
748 // Zero-initialize. (Strictly speaking, we only need to intialize
749 // the padding at the end, but this is simpler.)
750 if (!Dest.isZeroed())
John McCall7f416cc2015-09-08 08:05:57 +0000751 CGF.EmitNullInitialization(Dest.getAddress(), atomicType);
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000752
753 // Build a GEP to refer to the subobject.
John McCall7f416cc2015-09-08 08:05:57 +0000754 Address valueAddr =
755 CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0,
756 CharUnits());
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000757 valueDest = AggValueSlot::forAddr(valueAddr,
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000758 valueDest.getQualifiers(),
759 valueDest.isExternallyDestructed(),
760 valueDest.requiresGCollection(),
761 valueDest.isPotentiallyAliased(),
762 AggValueSlot::IsZeroed);
763 }
764
Eli Friedman035b39e2013-07-11 02:28:36 +0000765 CGF.EmitAggExpr(E->getSubExpr(), valueDest);
John McCalla8ec7eb2013-03-07 21:37:17 +0000766 return;
767 }
768
769 // Otherwise, we're converting an atomic type to a non-atomic type.
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000770 // Make an atomic temporary, emit into that, and then copy the value out.
John McCalla8ec7eb2013-03-07 21:37:17 +0000771 AggValueSlot atomicSlot =
772 CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
773 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
774
John McCall7f416cc2015-09-08 08:05:57 +0000775 Address valueAddr =
776 Builder.CreateStructGEP(atomicSlot.getAddress(), 0, CharUnits());
John McCalla8ec7eb2013-03-07 21:37:17 +0000777 RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
778 return EmitFinalDestCopy(valueType, rvalue);
779 }
780
John McCall4e8ca4f2012-07-02 23:58:38 +0000781 case CK_LValueToRValue:
782 // If we're loading from a volatile type, force the destination
783 // into existence.
784 if (E->getSubExpr()->getType().isVolatileQualified()) {
785 EnsureDest(E->getType());
786 return Visit(E->getSubExpr());
787 }
John McCalla8ec7eb2013-03-07 21:37:17 +0000788
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000789 LLVM_FALLTHROUGH;
John McCall4e8ca4f2012-07-02 23:58:38 +0000790
John McCalle3027922010-08-25 11:45:40 +0000791 case CK_NoOp:
792 case CK_UserDefinedConversion:
793 case CK_ConstructorConversion:
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000794 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
795 E->getType()) &&
796 "Implicit cast types must be compatible");
797 Visit(E->getSubExpr());
798 break;
John McCallf3735e02010-12-01 04:43:34 +0000799
John McCalle3027922010-08-25 11:45:40 +0000800 case CK_LValueBitCast:
John McCallf3735e02010-12-01 04:43:34 +0000801 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
John McCall31996342011-04-07 08:22:57 +0000802
John McCallf3735e02010-12-01 04:43:34 +0000803 case CK_Dependent:
804 case CK_BitCast:
805 case CK_ArrayToPointerDecay:
806 case CK_FunctionToPointerDecay:
807 case CK_NullToPointer:
808 case CK_NullToMemberPointer:
809 case CK_BaseToDerivedMemberPointer:
810 case CK_DerivedToBaseMemberPointer:
811 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +0000812 case CK_ReinterpretMemberPointer:
John McCallf3735e02010-12-01 04:43:34 +0000813 case CK_IntegralToPointer:
814 case CK_PointerToIntegral:
815 case CK_PointerToBoolean:
816 case CK_ToVoid:
817 case CK_VectorSplat:
818 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000819 case CK_BooleanToSignedIntegral:
John McCallf3735e02010-12-01 04:43:34 +0000820 case CK_IntegralToBoolean:
821 case CK_IntegralToFloating:
822 case CK_FloatingToIntegral:
823 case CK_FloatingToBoolean:
824 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +0000825 case CK_CPointerToObjCPointerCast:
826 case CK_BlockPointerToObjCPointerCast:
John McCallf3735e02010-12-01 04:43:34 +0000827 case CK_AnyPointerToBlockPointerCast:
828 case CK_ObjCObjectLValueCast:
829 case CK_FloatingRealToComplex:
830 case CK_FloatingComplexToReal:
831 case CK_FloatingComplexToBoolean:
832 case CK_FloatingComplexCast:
833 case CK_FloatingComplexToIntegralComplex:
834 case CK_IntegralRealToComplex:
835 case CK_IntegralComplexToReal:
836 case CK_IntegralComplexToBoolean:
837 case CK_IntegralComplexCast:
838 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +0000839 case CK_ARCProduceObject:
840 case CK_ARCConsumeObject:
841 case CK_ARCReclaimReturnedObject:
842 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +0000843 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +0000844 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000845 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +0000846 case CK_ZeroToOCLQueue:
David Tweede1468322013-12-11 13:39:46 +0000847 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +0000848 case CK_IntToOCLSampler:
John McCallf3735e02010-12-01 04:43:34 +0000849 llvm_unreachable("cast kind invalid for aggregate types");
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000850 }
Anders Carlsson1ba25ca2008-01-14 06:28:57 +0000851}
852
Chris Lattner0f398c42008-07-26 22:37:01 +0000853void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
David Majnemerced8bdf2015-02-25 17:36:15 +0000854 if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
Anders Carlssonddcbfe72009-05-27 16:45:02 +0000855 EmitAggLoadOfLValue(E);
856 return;
857 }
Mike Stump11289f42009-09-09 15:08:12 +0000858
George Burgess IV56e5a2e2018-03-10 01:11:17 +0000859 withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
860 return CGF.EmitCallExpr(E, Slot);
861 });
Anders Carlsson0370eb22007-10-31 22:04:46 +0000862}
Chris Lattner0f398c42008-07-26 22:37:01 +0000863
864void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
George Burgess IV56e5a2e2018-03-10 01:11:17 +0000865 withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
866 return CGF.EmitObjCMessageExpr(E, Slot);
867 });
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000868}
Anders Carlsson0370eb22007-10-31 22:04:46 +0000869
Chris Lattner0f398c42008-07-26 22:37:01 +0000870void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCalla2342eb2010-12-05 02:00:02 +0000871 CGF.EmitIgnoredExpr(E->getLHS());
John McCall7a626f62010-09-15 10:14:12 +0000872 Visit(E->getRHS());
Eli Friedman4b0e2a32008-05-20 07:56:31 +0000873}
874
Chris Lattner49e3bfa2007-08-31 22:54:14 +0000875void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCallce1de612011-01-26 04:00:11 +0000876 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall7a626f62010-09-15 10:14:12 +0000877 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
Chris Lattner49e3bfa2007-08-31 22:54:14 +0000878}
879
Chris Lattner4758b402007-08-21 04:25:47 +0000880void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000881 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +0000882 VisitPointerToDataMemberBinaryOperator(E);
883 else
884 CGF.ErrorUnsupported(E, "aggregate binary expression");
885}
886
887void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
888 const BinaryOperator *E) {
889 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
John McCall4e8ca4f2012-07-02 23:58:38 +0000890 EmitFinalDestCopy(E->getType(), LV);
891}
892
893/// Is the value of the given expression possibly a reference to or
894/// into a __block variable?
895static bool isBlockVarRef(const Expr *E) {
896 // Make sure we look through parens.
897 E = E->IgnoreParens();
898
899 // Check for a direct reference to a __block variable.
900 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
901 const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
902 return (var && var->hasAttr<BlocksAttr>());
903 }
904
905 // More complicated stuff.
906
907 // Binary operators.
908 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
909 // For an assignment or pointer-to-member operation, just care
910 // about the LHS.
911 if (op->isAssignmentOp() || op->isPtrMemOp())
912 return isBlockVarRef(op->getLHS());
913
914 // For a comma, just care about the RHS.
915 if (op->getOpcode() == BO_Comma)
916 return isBlockVarRef(op->getRHS());
917
918 // FIXME: pointer arithmetic?
919 return false;
920
921 // Check both sides of a conditional operator.
922 } else if (const AbstractConditionalOperator *op
923 = dyn_cast<AbstractConditionalOperator>(E)) {
924 return isBlockVarRef(op->getTrueExpr())
925 || isBlockVarRef(op->getFalseExpr());
926
927 // OVEs are required to support BinaryConditionalOperators.
928 } else if (const OpaqueValueExpr *op
929 = dyn_cast<OpaqueValueExpr>(E)) {
930 if (const Expr *src = op->getSourceExpr())
931 return isBlockVarRef(src);
932
933 // Casts are necessary to get things like (*(int*)&var) = foo().
934 // We don't really care about the kind of cast here, except
935 // we don't want to look through l2r casts, because it's okay
936 // to get the *value* in a __block variable.
937 } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
938 if (cast->getCastKind() == CK_LValueToRValue)
939 return false;
940 return isBlockVarRef(cast->getSubExpr());
941
942 // Handle unary operators. Again, just aggressively look through
943 // it, ignoring the operation.
944 } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
945 return isBlockVarRef(uop->getSubExpr());
946
947 // Look into the base of a field access.
948 } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
949 return isBlockVarRef(mem->getBase());
950
951 // Look into the base of a subscript.
952 } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
953 return isBlockVarRef(sub->getBase());
954 }
955
956 return false;
Chris Lattner835635d2007-08-21 04:59:27 +0000957}
958
Chris Lattnercd9fb242007-08-21 04:43:17 +0000959void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Eli Friedmanf54c4e52008-02-11 01:09:17 +0000960 // For an assignment to work, the value on the right has
961 // to be compatible with the value on the left.
Eli Friedman2a695472009-05-28 23:04:00 +0000962 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
963 E->getRHS()->getType())
Eli Friedmanf54c4e52008-02-11 01:09:17 +0000964 && "Invalid assignment");
John McCalld0a30012010-12-06 06:10:02 +0000965
John McCall4e8ca4f2012-07-02 23:58:38 +0000966 // If the LHS might be a __block variable, and the RHS can
967 // potentially cause a block copy, we need to evaluate the RHS first
968 // so that the assignment goes the right place.
969 // This is pretty semantically fragile.
970 if (isBlockVarRef(E->getLHS()) &&
971 E->getRHS()->HasSideEffects(CGF.getContext())) {
972 // Ensure that we have a destination, and evaluate the RHS into that.
973 EnsureDest(E->getRHS()->getType());
974 Visit(E->getRHS());
975
976 // Now emit the LHS and copy into it.
Richard Smithe30752c2012-10-09 19:52:38 +0000977 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall4e8ca4f2012-07-02 23:58:38 +0000978
John McCalla8ec7eb2013-03-07 21:37:17 +0000979 // That copy is an atomic copy if the LHS is atomic.
David Majnemera5b195a2015-02-14 01:35:12 +0000980 if (LHS.getType()->isAtomicType() ||
981 CGF.LValueIsSuitableForInlineAtomic(LHS)) {
John McCalla8ec7eb2013-03-07 21:37:17 +0000982 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
983 return;
984 }
985
John McCall4e8ca4f2012-07-02 23:58:38 +0000986 EmitCopy(E->getLHS()->getType(),
987 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
988 needsGC(E->getLHS()->getType()),
989 AggValueSlot::IsAliased),
990 Dest);
991 return;
992 }
Chad Rosier615ed1a2012-03-29 17:37:10 +0000993
Chris Lattner4758b402007-08-21 04:25:47 +0000994 LValue LHS = CGF.EmitLValue(E->getLHS());
Chris Lattner6278e6a2007-08-11 00:04:45 +0000995
John McCalla8ec7eb2013-03-07 21:37:17 +0000996 // If we have an atomic type, evaluate into the destination and then
997 // do an atomic copy.
David Majnemera5b195a2015-02-14 01:35:12 +0000998 if (LHS.getType()->isAtomicType() ||
999 CGF.LValueIsSuitableForInlineAtomic(LHS)) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001000 EnsureDest(E->getRHS()->getType());
1001 Visit(E->getRHS());
1002 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1003 return;
1004 }
1005
John McCallc109a252011-11-07 03:59:57 +00001006 // Codegen the RHS so that it stores directly into the LHS.
1007 AggValueSlot LHSSlot =
1008 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
1009 needsGC(E->getLHS()->getType()),
Chad Rosier615ed1a2012-03-29 17:37:10 +00001010 AggValueSlot::IsAliased);
Fariborz Jahanian78652202013-01-25 23:57:05 +00001011 // A non-volatile aggregate destination might have volatile member.
1012 if (!LHSSlot.isVolatile() &&
1013 CGF.hasVolatileMember(E->getLHS()->getType()))
1014 LHSSlot.setVolatile(true);
1015
John McCall4e8ca4f2012-07-02 23:58:38 +00001016 CGF.EmitAggExpr(E->getRHS(), LHSSlot);
1017
1018 // Copy into the destination if the assignment isn't ignored.
1019 EmitFinalDestCopy(E->getType(), LHS);
Chris Lattner6278e6a2007-08-11 00:04:45 +00001020}
1021
John McCallc07a0c72011-02-17 10:25:35 +00001022void AggExprEmitter::
1023VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Daniel Dunbara612e792008-11-13 01:38:36 +00001024 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1025 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1026 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Mike Stump11289f42009-09-09 15:08:12 +00001027
John McCallc07a0c72011-02-17 10:25:35 +00001028 // Bind the common expression if necessary.
Eli Friedman48fd89a2012-01-06 20:42:20 +00001029 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCallc07a0c72011-02-17 10:25:35 +00001030
John McCallce1de612011-01-26 04:00:11 +00001031 CodeGenFunction::ConditionalEvaluation eval(CGF);
Justin Bogner66242d62015-04-23 23:06:47 +00001032 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
1033 CGF.getProfileCount(E));
Mike Stump11289f42009-09-09 15:08:12 +00001034
John McCall5b26f652010-11-17 00:07:33 +00001035 // Save whether the destination's lifetime is externally managed.
John McCallcac93852011-08-26 08:02:37 +00001036 bool isExternallyDestructed = Dest.isExternallyDestructed();
Chris Lattner6278e6a2007-08-11 00:04:45 +00001037
John McCallce1de612011-01-26 04:00:11 +00001038 eval.begin(CGF);
1039 CGF.EmitBlock(LHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00001040 CGF.incrementProfileCounter(E);
John McCallc07a0c72011-02-17 10:25:35 +00001041 Visit(E->getTrueExpr());
John McCallce1de612011-01-26 04:00:11 +00001042 eval.end(CGF);
Mike Stump11289f42009-09-09 15:08:12 +00001043
John McCallce1de612011-01-26 04:00:11 +00001044 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
1045 CGF.Builder.CreateBr(ContBlock);
Mike Stump11289f42009-09-09 15:08:12 +00001046
John McCall5b26f652010-11-17 00:07:33 +00001047 // If the result of an agg expression is unused, then the emission
1048 // of the LHS might need to create a destination slot. That's fine
1049 // with us, and we can safely emit the RHS into the same slot, but
John McCallcac93852011-08-26 08:02:37 +00001050 // we shouldn't claim that it's already being destructed.
1051 Dest.setExternallyDestructed(isExternallyDestructed);
John McCall5b26f652010-11-17 00:07:33 +00001052
John McCallce1de612011-01-26 04:00:11 +00001053 eval.begin(CGF);
1054 CGF.EmitBlock(RHSBlock);
John McCallc07a0c72011-02-17 10:25:35 +00001055 Visit(E->getFalseExpr());
John McCallce1de612011-01-26 04:00:11 +00001056 eval.end(CGF);
Mike Stump11289f42009-09-09 15:08:12 +00001057
Chris Lattner4758b402007-08-21 04:25:47 +00001058 CGF.EmitBlock(ContBlock);
Chris Lattner6278e6a2007-08-11 00:04:45 +00001059}
Chris Lattner835635d2007-08-21 04:59:27 +00001060
Anders Carlsson5b2095c2009-07-08 18:33:14 +00001061void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
Eli Friedman75807f22013-07-20 00:40:58 +00001062 Visit(CE->getChosenSubExpr());
Anders Carlsson5b2095c2009-07-08 18:33:14 +00001063}
1064
Eli Friedman21911e82008-05-27 15:51:49 +00001065void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Charles Davisc7d5c942015-09-17 20:55:33 +00001066 Address ArgValue = Address::invalid();
1067 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
Anders Carlsson13abd7e2008-11-04 05:30:00 +00001068
James Y Knight29b5f082016-02-24 02:59:33 +00001069 // If EmitVAArg fails, emit an error.
John McCall7f416cc2015-09-08 08:05:57 +00001070 if (!ArgPtr.isValid()) {
James Y Knight29b5f082016-02-24 02:59:33 +00001071 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
Sebastian Redl020cddc2009-01-09 21:09:38 +00001072 return;
1073 }
1074
John McCall4e8ca4f2012-07-02 23:58:38 +00001075 EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
Eli Friedman21911e82008-05-27 15:51:49 +00001076}
1077
Anders Carlsson3be22e22009-05-30 23:23:33 +00001078void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +00001079 // Ensure that we have a slot, but if we already do, remember
John McCallcac93852011-08-26 08:02:37 +00001080 // whether it was externally destructed.
1081 bool wasExternallyDestructed = Dest.isExternallyDestructed();
John McCall4e8ca4f2012-07-02 23:58:38 +00001082 EnsureDest(E->getType());
John McCallcac93852011-08-26 08:02:37 +00001083
1084 // We're going to push a destructor if there isn't already one.
1085 Dest.setExternallyDestructed();
Mike Stump11289f42009-09-09 15:08:12 +00001086
John McCall7a626f62010-09-15 10:14:12 +00001087 Visit(E->getSubExpr());
Anders Carlsson3be22e22009-05-30 23:23:33 +00001088
John McCallcac93852011-08-26 08:02:37 +00001089 // Push that destructor we promised.
1090 if (!wasExternallyDestructed)
John McCall7f416cc2015-09-08 08:05:57 +00001091 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
Anders Carlsson3be22e22009-05-30 23:23:33 +00001092}
1093
Anders Carlssonb7f8f592009-04-17 00:06:03 +00001094void
Anders Carlsson1619a5042009-05-03 17:47:16 +00001095AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +00001096 AggValueSlot Slot = EnsureSlot(E->getType());
1097 CGF.EmitCXXConstructExpr(E, Slot);
Anders Carlssonc82b86d2009-05-19 04:48:36 +00001098}
1099
Richard Smith5179eb72016-06-28 19:03:57 +00001100void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
1101 const CXXInheritedCtorInitExpr *E) {
1102 AggValueSlot Slot = EnsureSlot(E->getType());
1103 CGF.EmitInheritedCXXConstructorCall(
1104 E->getConstructor(), E->constructsVBase(), Slot.getAddress(),
1105 E->inheritedFromVBase(), E);
1106}
1107
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001108void
1109AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1110 AggValueSlot Slot = EnsureSlot(E->getType());
1111 CGF.EmitLambdaExpr(E, Slot);
1112}
1113
John McCall5d413782010-12-06 08:20:24 +00001114void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall08ef4662011-11-10 08:15:53 +00001115 CGF.enterFullExpression(E);
1116 CodeGenFunction::RunCleanupsScope cleanups(CGF);
1117 Visit(E->getSubExpr());
Anders Carlssonb7f8f592009-04-17 00:06:03 +00001118}
1119
Douglas Gregor747eb782010-07-08 06:14:04 +00001120void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +00001121 QualType T = E->getType();
1122 AggValueSlot Slot = EnsureSlot(T);
John McCall7f416cc2015-09-08 08:05:57 +00001123 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
Anders Carlsson18ada982009-12-16 06:57:54 +00001124}
1125
1126void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +00001127 QualType T = E->getType();
1128 AggValueSlot Slot = EnsureSlot(T);
John McCall7f416cc2015-09-08 08:05:57 +00001129 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
Nuno Lopesff3507b2009-10-18 15:18:11 +00001130}
1131
Chris Lattner27a36312010-12-02 07:07:26 +00001132/// isSimpleZero - If emitting this value will obviously just cause a store of
1133/// zero to memory, return true. This can return false if uncertain, so it just
1134/// handles simple cases.
1135static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001136 E = E->IgnoreParens();
1137
Chris Lattner27a36312010-12-02 07:07:26 +00001138 // 0
1139 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1140 return IL->getValue() == 0;
1141 // +0.0
1142 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1143 return FL->getValue().isPosZero();
1144 // int()
1145 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
1146 CGF.getTypes().isZeroInitializable(E->getType()))
1147 return true;
1148 // (int*)0 - Null pointer expressions.
1149 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
Yaxun Liu402804b2016-12-15 08:09:08 +00001150 return ICE->getCastKind() == CK_NullToPointer &&
1151 CGF.getTypes().isPointerZeroInitializable(E->getType());
Chris Lattner27a36312010-12-02 07:07:26 +00001152 // '\0'
1153 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1154 return CL->getValue() == 0;
1155
1156 // Otherwise, hard case: conservatively return false.
1157 return false;
1158}
1159
1160
Anders Carlssonb2473502010-02-03 17:33:16 +00001161void
Nick Lewycky2d84e842013-10-02 02:29:49 +00001162AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
John McCall1553b192011-06-16 04:16:24 +00001163 QualType type = LV.getType();
Mike Stumpdf0fe272009-05-29 15:46:01 +00001164 // FIXME: Ignore result?
Chris Lattner579a05d2008-04-04 18:42:16 +00001165 // FIXME: Are initializers affected by volatile?
Chris Lattner27a36312010-12-02 07:07:26 +00001166 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
1167 // Storing "i32 0" to a zero'd memory location is a noop.
John McCall47fb9502013-03-07 21:37:08 +00001168 return;
Richard Smithd82a2ce2012-12-21 03:17:28 +00001169 } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
John McCall47fb9502013-03-07 21:37:08 +00001170 return EmitNullInitializationToLValue(LV);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001171 } else if (isa<NoInitExpr>(E)) {
1172 // Do nothing.
1173 return;
John McCall1553b192011-06-16 04:16:24 +00001174 } else if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001175 RValue RV = CGF.EmitReferenceBindingToExpr(E);
John McCall47fb9502013-03-07 21:37:08 +00001176 return CGF.EmitStoreThroughLValue(RV, LV);
1177 }
1178
1179 switch (CGF.getEvaluationKind(type)) {
1180 case TEK_Complex:
1181 CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1182 return;
1183 case TEK_Aggregate:
John McCall8d6fc952011-08-25 20:40:09 +00001184 CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
1185 AggValueSlot::IsDestructed,
1186 AggValueSlot::DoesNotNeedGCBarriers,
John McCalla5efa732011-08-25 23:04:34 +00001187 AggValueSlot::IsNotAliased,
John McCall1553b192011-06-16 04:16:24 +00001188 Dest.isZeroed()));
John McCall47fb9502013-03-07 21:37:08 +00001189 return;
1190 case TEK_Scalar:
1191 if (LV.isSimple()) {
Craig Topper8a13c412014-05-21 05:09:00 +00001192 CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
John McCall47fb9502013-03-07 21:37:08 +00001193 } else {
1194 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1195 }
1196 return;
Chris Lattner579a05d2008-04-04 18:42:16 +00001197 }
John McCall47fb9502013-03-07 21:37:08 +00001198 llvm_unreachable("bad evaluation kind");
Chris Lattner579a05d2008-04-04 18:42:16 +00001199}
1200
John McCall1553b192011-06-16 04:16:24 +00001201void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1202 QualType type = lv.getType();
1203
Chris Lattner27a36312010-12-02 07:07:26 +00001204 // If the destination slot is already zeroed out before the aggregate is
1205 // copied into it, we don't have to emit any zeros here.
John McCall1553b192011-06-16 04:16:24 +00001206 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
Chris Lattner27a36312010-12-02 07:07:26 +00001207 return;
1208
John McCall47fb9502013-03-07 21:37:08 +00001209 if (CGF.hasScalarEvaluationKind(type)) {
Richard Smithd82a2ce2012-12-21 03:17:28 +00001210 // For non-aggregates, we can store the appropriate null constant.
1211 llvm::Value *null = CGF.CGM.EmitNullConstant(type);
Eli Friedman91d5bb12012-02-22 05:38:59 +00001212 // Note that the following is not equivalent to
1213 // EmitStoreThroughBitfieldLValue for ARC types.
Eli Friedmancb3785e2012-02-24 23:53:49 +00001214 if (lv.isBitField()) {
Eli Friedman91d5bb12012-02-22 05:38:59 +00001215 CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
Eli Friedmancb3785e2012-02-24 23:53:49 +00001216 } else {
1217 assert(lv.isSimple());
1218 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1219 }
Lauro Ramos Venancioe2162c62008-02-19 19:27:31 +00001220 } else {
Chris Lattner579a05d2008-04-04 18:42:16 +00001221 // There's a potential optimization opportunity in combining
1222 // memsets; that would be easy for arrays, but relatively
1223 // difficult for structures with the current code.
John McCall1553b192011-06-16 04:16:24 +00001224 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
Chris Lattner579a05d2008-04-04 18:42:16 +00001225 }
1226}
1227
Chris Lattner579a05d2008-04-04 18:42:16 +00001228void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
Eli Friedmanf5d08c92008-12-02 01:17:45 +00001229#if 0
Eli Friedman6d11ec82009-12-04 01:30:56 +00001230 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
1231 // (Length of globals? Chunks of zeroed-out space?).
Eli Friedmanf5d08c92008-12-02 01:17:45 +00001232 //
Mike Stump18bb9282009-05-16 07:57:57 +00001233 // If we can, prefer a copy from a global; this is a lot less code for long
1234 // globals, and it's easier for the current optimizers to analyze.
Eli Friedman6d11ec82009-12-04 01:30:56 +00001235 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
Eli Friedmanc59bb482008-11-30 02:11:09 +00001236 llvm::GlobalVariable* GV =
Eli Friedman6d11ec82009-12-04 01:30:56 +00001237 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1238 llvm::GlobalValue::InternalLinkage, C, "");
John McCall4e8ca4f2012-07-02 23:58:38 +00001239 EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
Eli Friedmanc59bb482008-11-30 02:11:09 +00001240 return;
1241 }
Eli Friedmanf5d08c92008-12-02 01:17:45 +00001242#endif
Chris Lattnerf53c0962010-09-06 00:11:41 +00001243 if (E->hadArrayRangeDesignator())
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001244 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001245
Richard Smith122f88d2016-12-06 23:52:28 +00001246 if (E->isTransparent())
1247 return Visit(E->getInit(0));
1248
Richard Smithbe93c002013-05-23 21:54:14 +00001249 AggValueSlot Dest = EnsureSlot(E->getType());
1250
John McCall7f416cc2015-09-08 08:05:57 +00001251 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
John McCall7a626f62010-09-15 10:14:12 +00001252
Chris Lattner579a05d2008-04-04 18:42:16 +00001253 // Handle initialization of an array.
1254 if (E->getType()->isArrayType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001255 auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
Ivan A. Kosareve0ef3482018-02-19 09:49:11 +00001256 EmitArrayInit(Dest.getAddress(), AType, E->getType(), E);
Chris Lattner579a05d2008-04-04 18:42:16 +00001257 return;
1258 }
Mike Stump11289f42009-09-09 15:08:12 +00001259
Chris Lattner579a05d2008-04-04 18:42:16 +00001260 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
Mike Stump11289f42009-09-09 15:08:12 +00001261
Chris Lattner579a05d2008-04-04 18:42:16 +00001262 // Do struct initialization; this code just sets each individual member
1263 // to the approprate value. This makes bitfield support automatic;
1264 // the disadvantage is that the generated code is more difficult for
1265 // the optimizer, especially with bitfields.
1266 unsigned NumInitElements = E->getNumInits();
John McCall3b935d32011-07-11 19:35:02 +00001267 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
Richard Smith852c9db2013-04-20 22:23:05 +00001268
Richard Smith872307e2016-03-08 22:17:41 +00001269 // We'll need to enter cleanup scopes in case any of the element
1270 // initializers throws an exception.
1271 SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
1272 llvm::Instruction *cleanupDominator = nullptr;
1273
1274 unsigned curInitIndex = 0;
1275
1276 // Emit initialization of base classes.
1277 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
1278 assert(E->getNumInits() >= CXXRD->getNumBases() &&
1279 "missing initializer for base class");
1280 for (auto &Base : CXXRD->bases()) {
1281 assert(!Base.isVirtual() && "should not see vbases here");
1282 auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
1283 Address V = CGF.GetAddressOfDirectBaseInCompleteClass(
1284 Dest.getAddress(), CXXRD, BaseRD,
1285 /*isBaseVirtual*/ false);
1286 AggValueSlot AggSlot =
1287 AggValueSlot::forAddr(V, Qualifiers(),
1288 AggValueSlot::IsDestructed,
1289 AggValueSlot::DoesNotNeedGCBarriers,
1290 AggValueSlot::IsNotAliased);
1291 CGF.EmitAggExpr(E->getInit(curInitIndex++), AggSlot);
1292
1293 if (QualType::DestructionKind dtorKind =
1294 Base.getType().isDestructedType()) {
1295 CGF.pushDestroy(dtorKind, V, Base.getType());
1296 cleanups.push_back(CGF.EHStack.stable_begin());
1297 }
1298 }
1299 }
1300
Richard Smith852c9db2013-04-20 22:23:05 +00001301 // Prepare a 'this' for CXXDefaultInitExprs.
John McCall7f416cc2015-09-08 08:05:57 +00001302 CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
Richard Smith852c9db2013-04-20 22:23:05 +00001303
John McCall3b935d32011-07-11 19:35:02 +00001304 if (record->isUnion()) {
Douglas Gregor51695702009-01-29 16:53:55 +00001305 // Only initialize one field of a union. The field itself is
1306 // specified by the initializer list.
1307 if (!E->getInitializedFieldInUnion()) {
1308 // Empty union; we have nothing to do.
Mike Stump11289f42009-09-09 15:08:12 +00001309
Douglas Gregor51695702009-01-29 16:53:55 +00001310#ifndef NDEBUG
1311 // Make sure that it's really an empty and not a failure of
1312 // semantic analysis.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001313 for (const auto *Field : record->fields())
Douglas Gregor51695702009-01-29 16:53:55 +00001314 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1315#endif
1316 return;
1317 }
1318
1319 // FIXME: volatility
1320 FieldDecl *Field = E->getInitializedFieldInUnion();
Douglas Gregor51695702009-01-29 16:53:55 +00001321
Eli Friedman7f1ff602012-04-16 03:54:45 +00001322 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001323 if (NumInitElements) {
1324 // Store the initializer into the field
Chad Rosier615ed1a2012-03-29 17:37:10 +00001325 EmitInitializationToLValue(E->getInit(0), FieldLoc);
Douglas Gregor51695702009-01-29 16:53:55 +00001326 } else {
Chris Lattner27a36312010-12-02 07:07:26 +00001327 // Default-initialize to null.
John McCall1553b192011-06-16 04:16:24 +00001328 EmitNullInitializationToLValue(FieldLoc);
Douglas Gregor51695702009-01-29 16:53:55 +00001329 }
1330
1331 return;
1332 }
Mike Stump11289f42009-09-09 15:08:12 +00001333
Chris Lattner579a05d2008-04-04 18:42:16 +00001334 // Here we iterate over the fields; this makes it simpler to both
1335 // default-initialize fields and skip over unnamed fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001336 for (const auto *field : record->fields()) {
John McCall3b935d32011-07-11 19:35:02 +00001337 // We're done once we hit the flexible array member.
1338 if (field->getType()->isIncompleteArrayType())
Douglas Gregor91f84212008-12-11 16:49:14 +00001339 break;
1340
John McCall3b935d32011-07-11 19:35:02 +00001341 // Always skip anonymous bitfields.
1342 if (field->isUnnamedBitfield())
Chris Lattner579a05d2008-04-04 18:42:16 +00001343 continue;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001344
John McCall3b935d32011-07-11 19:35:02 +00001345 // We're done if we reach the end of the explicit initializers, we
1346 // have a zeroed object, and the rest of the fields are
1347 // zero-initializable.
1348 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
Chris Lattner27a36312010-12-02 07:07:26 +00001349 CGF.getTypes().isZeroInitializable(E->getType()))
1350 break;
1351
Eli Friedman7f1ff602012-04-16 03:54:45 +00001352
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001353 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
Fariborz Jahanian7c1baf42009-05-27 19:54:11 +00001354 // We never generate write-barries for initialized fields.
John McCall3b935d32011-07-11 19:35:02 +00001355 LV.setNonGC(true);
Chris Lattner27a36312010-12-02 07:07:26 +00001356
John McCall3b935d32011-07-11 19:35:02 +00001357 if (curInitIndex < NumInitElements) {
Chris Lattnere18aaf22010-03-08 21:08:07 +00001358 // Store the initializer into the field.
Chad Rosier615ed1a2012-03-29 17:37:10 +00001359 EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
Chris Lattner579a05d2008-04-04 18:42:16 +00001360 } else {
Simon Pilgrim2c518802017-03-30 14:13:19 +00001361 // We're out of initializers; default-initialize to null
John McCall3b935d32011-07-11 19:35:02 +00001362 EmitNullInitializationToLValue(LV);
1363 }
1364
1365 // Push a destructor if necessary.
1366 // FIXME: if we have an array of structures, all explicitly
1367 // initialized, we can end up pushing a linear number of cleanups.
1368 bool pushedCleanup = false;
1369 if (QualType::DestructionKind dtorKind
1370 = field->getType().isDestructedType()) {
1371 assert(LV.isSimple());
1372 if (CGF.needsEHCleanup(dtorKind)) {
John McCallf4beacd2011-11-10 10:43:54 +00001373 if (!cleanupDominator)
John McCall7f416cc2015-09-08 08:05:57 +00001374 cleanupDominator = CGF.Builder.CreateAlignedLoad(
Reid Kleckner5ee4b9a2015-09-04 21:39:15 +00001375 CGF.Int8Ty,
John McCall7f416cc2015-09-08 08:05:57 +00001376 llvm::Constant::getNullValue(CGF.Int8PtrTy),
1377 CharUnits::One()); // placeholder
John McCallf4beacd2011-11-10 10:43:54 +00001378
John McCall3b935d32011-07-11 19:35:02 +00001379 CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1380 CGF.getDestroyer(dtorKind), false);
1381 cleanups.push_back(CGF.EHStack.stable_begin());
1382 pushedCleanup = true;
1383 }
Chris Lattner579a05d2008-04-04 18:42:16 +00001384 }
Chris Lattner27a36312010-12-02 07:07:26 +00001385
1386 // If the GEP didn't get used because of a dead zero init or something
1387 // else, clean it up for -O0 builds and general tidiness.
John McCall3b935d32011-07-11 19:35:02 +00001388 if (!pushedCleanup && LV.isSimple())
Chris Lattner27a36312010-12-02 07:07:26 +00001389 if (llvm::GetElementPtrInst *GEP =
John McCall7f416cc2015-09-08 08:05:57 +00001390 dyn_cast<llvm::GetElementPtrInst>(LV.getPointer()))
Chris Lattner27a36312010-12-02 07:07:26 +00001391 if (GEP->use_empty())
1392 GEP->eraseFromParent();
Lauro Ramos Venancioe2162c62008-02-19 19:27:31 +00001393 }
John McCall3b935d32011-07-11 19:35:02 +00001394
1395 // Deactivate all the partial cleanups in reverse order, which
1396 // generally means popping them.
1397 for (unsigned i = cleanups.size(); i != 0; --i)
John McCallf4beacd2011-11-10 10:43:54 +00001398 CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1399
1400 // Destroy the placeholder if we made one.
1401 if (cleanupDominator)
1402 cleanupDominator->eraseFromParent();
Devang Patel87174172007-10-26 17:44:44 +00001403}
1404
Richard Smith939b6882016-12-14 01:32:13 +00001405void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
1406 llvm::Value *outerBegin) {
Richard Smith410306b2016-12-12 02:53:20 +00001407 // Emit the common subexpression.
1408 CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
1409
1410 Address destPtr = EnsureSlot(E->getType()).getAddress();
1411 uint64_t numElements = E->getArraySize().getZExtValue();
1412
1413 if (!numElements)
1414 return;
1415
Richard Smith410306b2016-12-12 02:53:20 +00001416 // destPtr is an array*. Construct an elementType* by drilling down a level.
1417 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1418 llvm::Value *indices[] = {zero, zero};
1419 llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getPointer(), indices,
1420 "arrayinit.begin");
1421
Richard Smith939b6882016-12-14 01:32:13 +00001422 // Prepare to special-case multidimensional array initialization: we avoid
1423 // emitting multiple destructor loops in that case.
1424 if (!outerBegin)
1425 outerBegin = begin;
1426 ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
1427
Richard Smith30e304e2016-12-14 00:03:17 +00001428 QualType elementType =
1429 CGF.getContext().getAsArrayType(E->getType())->getElementType();
Richard Smith410306b2016-12-12 02:53:20 +00001430 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1431 CharUnits elementAlign =
1432 destPtr.getAlignment().alignmentOfArrayElement(elementSize);
1433
Richard Smith410306b2016-12-12 02:53:20 +00001434 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1435 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
1436
1437 // Jump into the body.
1438 CGF.EmitBlock(bodyBB);
1439 llvm::PHINode *index =
1440 Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
1441 index->addIncoming(zero, entryBB);
1442 llvm::Value *element = Builder.CreateInBoundsGEP(begin, index);
1443
Richard Smith30e304e2016-12-14 00:03:17 +00001444 // Prepare for a cleanup.
1445 QualType::DestructionKind dtorKind = elementType.isDestructedType();
1446 EHScopeStack::stable_iterator cleanup;
Richard Smith939b6882016-12-14 01:32:13 +00001447 if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) {
1448 if (outerBegin->getType() != element->getType())
1449 outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
1450 CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
1451 elementAlign,
1452 CGF.getDestroyer(dtorKind));
Richard Smith30e304e2016-12-14 00:03:17 +00001453 cleanup = CGF.EHStack.stable_begin();
1454 } else {
1455 dtorKind = QualType::DK_none;
1456 }
Richard Smith410306b2016-12-12 02:53:20 +00001457
1458 // Emit the actual filler expression.
1459 {
Richard Smith30e304e2016-12-14 00:03:17 +00001460 // Temporaries created in an array initialization loop are destroyed
1461 // at the end of each iteration.
1462 CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
Richard Smith410306b2016-12-12 02:53:20 +00001463 CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
1464 LValue elementLV =
1465 CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
Richard Smith939b6882016-12-14 01:32:13 +00001466
1467 if (InnerLoop) {
1468 // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
1469 auto elementSlot = AggValueSlot::forLValue(
1470 elementLV, AggValueSlot::IsDestructed,
1471 AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased);
1472 AggExprEmitter(CGF, elementSlot, false)
1473 .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
1474 } else
1475 EmitInitializationToLValue(E->getSubExpr(), elementLV);
Richard Smith410306b2016-12-12 02:53:20 +00001476 }
1477
1478 // Move on to the next element.
1479 llvm::Value *nextIndex = Builder.CreateNUWAdd(
1480 index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
1481 index->addIncoming(nextIndex, Builder.GetInsertBlock());
1482
1483 // Leave the loop if we're done.
1484 llvm::Value *done = Builder.CreateICmpEQ(
1485 nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
1486 "arrayinit.done");
1487 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
1488 Builder.CreateCondBr(done, endBB, bodyBB);
1489
1490 CGF.EmitBlock(endBB);
1491
1492 // Leave the partial-array cleanup if we entered one.
Richard Smith30e304e2016-12-14 00:03:17 +00001493 if (dtorKind)
1494 CGF.DeactivateCleanupBlock(cleanup, index);
Richard Smith410306b2016-12-12 02:53:20 +00001495}
1496
Yunzhong Gaocb779302015-06-10 00:27:52 +00001497void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
1498 AggValueSlot Dest = EnsureSlot(E->getType());
1499
John McCall7f416cc2015-09-08 08:05:57 +00001500 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
Yunzhong Gaocb779302015-06-10 00:27:52 +00001501 EmitInitializationToLValue(E->getBase(), DestLV);
1502 VisitInitListExpr(E->getUpdater());
1503}
1504
Chris Lattner835635d2007-08-21 04:59:27 +00001505//===----------------------------------------------------------------------===//
1506// Entry Points into this File
1507//===----------------------------------------------------------------------===//
1508
Chris Lattner27a36312010-12-02 07:07:26 +00001509/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1510/// non-zero bytes that will be stored when outputting the initializer for the
1511/// specified initializer expression.
Ken Dyckdf94cb72011-04-24 17:17:56 +00001512static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001513 E = E->IgnoreParens();
Chris Lattner27a36312010-12-02 07:07:26 +00001514
1515 // 0 and 0.0 won't require any non-zero stores!
Ken Dyckdf94cb72011-04-24 17:17:56 +00001516 if (isSimpleZero(E, CGF)) return CharUnits::Zero();
Chris Lattner27a36312010-12-02 07:07:26 +00001517
1518 // If this is an initlist expr, sum up the size of sizes of the (present)
1519 // elements. If this is something weird, assume the whole thing is non-zero.
1520 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00001521 if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
Ken Dyckdf94cb72011-04-24 17:17:56 +00001522 return CGF.getContext().getTypeSizeInChars(E->getType());
Chris Lattner27a36312010-12-02 07:07:26 +00001523
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001524 // InitListExprs for structs have to be handled carefully. If there are
1525 // reference members, we need to consider the size of the reference, not the
1526 // referencee. InitListExprs for unions and arrays can't have references.
Chris Lattner5cd84752010-12-02 22:52:04 +00001527 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1528 if (!RT->isUnionType()) {
1529 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
Ken Dyckdf94cb72011-04-24 17:17:56 +00001530 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner5cd84752010-12-02 22:52:04 +00001531
1532 unsigned ILEElement = 0;
Richard Smith872307e2016-03-08 22:17:41 +00001533 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))
Richard Smith6365e462016-03-08 23:16:16 +00001534 while (ILEElement != CXXRD->getNumBases())
Richard Smith872307e2016-03-08 22:17:41 +00001535 NumNonZeroBytes +=
1536 GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001537 for (const auto *Field : SD->fields()) {
Chris Lattner5cd84752010-12-02 22:52:04 +00001538 // We're done once we hit the flexible array member or run out of
1539 // InitListExpr elements.
1540 if (Field->getType()->isIncompleteArrayType() ||
1541 ILEElement == ILE->getNumInits())
1542 break;
1543 if (Field->isUnnamedBitfield())
1544 continue;
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001545
Chris Lattner5cd84752010-12-02 22:52:04 +00001546 const Expr *E = ILE->getInit(ILEElement++);
1547
1548 // Reference values are always non-null and have the width of a pointer.
1549 if (Field->getType()->isReferenceType())
Ken Dyckdf94cb72011-04-24 17:17:56 +00001550 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00001551 CGF.getTarget().getPointerWidth(0));
Chris Lattner5cd84752010-12-02 22:52:04 +00001552 else
1553 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1554 }
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001555
Chris Lattner5cd84752010-12-02 22:52:04 +00001556 return NumNonZeroBytes;
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001557 }
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +00001558 }
1559
1560
Ken Dyckdf94cb72011-04-24 17:17:56 +00001561 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner27a36312010-12-02 07:07:26 +00001562 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1563 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1564 return NumNonZeroBytes;
1565}
1566
1567/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1568/// zeros in it, emit a memset and avoid storing the individual zeros.
1569///
1570static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1571 CodeGenFunction &CGF) {
1572 // If the slot is already known to be zeroed, nothing to do. Don't mess with
1573 // volatile stores.
John McCall7f416cc2015-09-08 08:05:57 +00001574 if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid())
Craig Topper8a13c412014-05-21 05:09:00 +00001575 return;
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +00001576
1577 // C++ objects with a user-declared constructor don't need zero'ing.
Richard Smith9c6890a2012-11-01 22:30:59 +00001578 if (CGF.getLangOpts().CPlusPlus)
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +00001579 if (const RecordType *RT = CGF.getContext()
1580 .getBaseElementType(E->getType())->getAs<RecordType>()) {
1581 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1582 if (RD->hasUserDeclaredConstructor())
1583 return;
1584 }
1585
Chris Lattner27a36312010-12-02 07:07:26 +00001586 // If the type is 16-bytes or smaller, prefer individual stores over memset.
John McCall7f416cc2015-09-08 08:05:57 +00001587 CharUnits Size = CGF.getContext().getTypeSizeInChars(E->getType());
1588 if (Size <= CharUnits::fromQuantity(16))
Chris Lattner27a36312010-12-02 07:07:26 +00001589 return;
1590
1591 // Check to see if over 3/4 of the initializer are known to be zero. If so,
1592 // we prefer to emit memset + individual stores for the rest.
Ken Dyck239a3352011-04-24 17:25:32 +00001593 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
John McCall7f416cc2015-09-08 08:05:57 +00001594 if (NumNonZeroBytes*4 > Size)
Chris Lattner27a36312010-12-02 07:07:26 +00001595 return;
1596
1597 // Okay, it seems like a good idea to use an initial memset, emit the call.
John McCall7f416cc2015-09-08 08:05:57 +00001598 llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
Chris Lattner27a36312010-12-02 07:07:26 +00001599
John McCall7f416cc2015-09-08 08:05:57 +00001600 Address Loc = Slot.getAddress();
1601 Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty);
1602 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
Chris Lattner27a36312010-12-02 07:07:26 +00001603
1604 // Tell the AggExprEmitter that the slot is known zero.
1605 Slot.setZeroed();
1606}
1607
1608
1609
1610
Mike Stump25306ca2009-05-26 18:57:45 +00001611/// EmitAggExpr - Emit the computation of the specified expression of aggregate
1612/// type. The result is computed into DestPtr. Note that if DestPtr is null,
1613/// the value of the aggregate expression is not needed. If VolatileDest is
1614/// true, DestPtr cannot be 0.
John McCall4e8ca4f2012-07-02 23:58:38 +00001615void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
John McCall47fb9502013-03-07 21:37:08 +00001616 assert(E && hasAggregateEvaluationKind(E->getType()) &&
Chris Lattner835635d2007-08-21 04:59:27 +00001617 "Invalid aggregate expression to emit");
John McCall7f416cc2015-09-08 08:05:57 +00001618 assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
Chris Lattner27a36312010-12-02 07:07:26 +00001619 "slot has bits but no address");
Mike Stump11289f42009-09-09 15:08:12 +00001620
Chris Lattner27a36312010-12-02 07:07:26 +00001621 // Optimize the slot if possible.
1622 CheckAggExprForMemSetUse(Slot, E, *this);
1623
Leny Kholodov6aab1112015-06-08 10:23:49 +00001624 AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
Chris Lattner835635d2007-08-21 04:59:27 +00001625}
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00001626
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00001627LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
John McCall47fb9502013-03-07 21:37:08 +00001628 assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
John McCall7f416cc2015-09-08 08:05:57 +00001629 Address Temp = CreateMemTemp(E->getType());
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001630 LValue LV = MakeAddrLValue(Temp, E->getType());
John McCall8d6fc952011-08-25 20:40:09 +00001631 EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
John McCall46759f42011-08-26 07:31:35 +00001632 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001633 AggValueSlot::IsNotAliased));
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001634 return LV;
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00001635}
1636
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001637void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src,
1638 QualType Ty, bool isVolatile,
Benjamin Kramer1ca66912012-09-30 12:43:37 +00001639 bool isAssignment) {
Chad Rosier615ed1a2012-03-29 17:37:10 +00001640 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
Mike Stump11289f42009-09-09 15:08:12 +00001641
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001642 Address DestPtr = Dest.getAddress();
1643 Address SrcPtr = Src.getAddress();
1644
Richard Smith9c6890a2012-11-01 22:30:59 +00001645 if (getLangOpts().CPlusPlus) {
Chad Rosier615ed1a2012-03-29 17:37:10 +00001646 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1647 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1648 assert((Record->hasTrivialCopyConstructor() ||
1649 Record->hasTrivialCopyAssignment() ||
1650 Record->hasTrivialMoveConstructor() ||
Richard Smith419bd092015-04-29 19:26:57 +00001651 Record->hasTrivialMoveAssignment() ||
1652 Record->isUnion()) &&
Richard Smith16488472012-11-16 00:53:38 +00001653 "Trying to aggregate-copy a type without a trivial copy/move "
Douglas Gregorf22101a2010-05-20 15:39:01 +00001654 "constructor or assignment operator");
Chad Rosier615ed1a2012-03-29 17:37:10 +00001655 // Ignore empty classes in C++.
1656 if (Record->isEmpty())
Anders Carlsson16e94af2010-05-03 01:20:20 +00001657 return;
1658 }
1659 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001660
Chris Lattnerca05dfe2009-02-28 18:31:01 +00001661 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
Chris Lattner3ef668c2009-02-28 18:18:58 +00001662 // C99 6.5.16.1p3, which states "If the value being stored in an object is
1663 // read from another object that overlaps in anyway the storage of the first
1664 // object, then the overlap shall be exact and the two objects shall have
1665 // qualified or unqualified versions of a compatible type."
1666 //
Chris Lattnerca05dfe2009-02-28 18:31:01 +00001667 // memcpy is not defined if the source and destination pointers are exactly
Chris Lattner3ef668c2009-02-28 18:18:58 +00001668 // equal, but other compilers do this optimization, and almost every memcpy
1669 // implementation handles this case safely. If there is a libc that does not
1670 // safely handle this, we can add a target hook.
Chad Rosier615ed1a2012-03-29 17:37:10 +00001671
John McCall7f416cc2015-09-08 08:05:57 +00001672 // Get data size info for this aggregate. If this is an assignment,
1673 // don't copy the tail padding, because we might be assigning into a
1674 // base subobject where the tail padding is claimed. Otherwise,
1675 // copying it is fine.
Benjamin Kramer1ca66912012-09-30 12:43:37 +00001676 std::pair<CharUnits, CharUnits> TypeInfo;
1677 if (isAssignment)
1678 TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
1679 else
1680 TypeInfo = getContext().getTypeInfoInChars(Ty);
Chad Rosier615ed1a2012-03-29 17:37:10 +00001681
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001682 llvm::Value *SizeVal = nullptr;
1683 if (TypeInfo.first.isZero()) {
1684 // But note that getTypeInfo returns 0 for a VLA.
1685 if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
1686 getContext().getAsArrayType(Ty))) {
1687 QualType BaseEltTy;
1688 SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
1689 TypeInfo = getContext().getTypeInfoDataSizeInChars(BaseEltTy);
1690 std::pair<CharUnits, CharUnits> LastElementTypeInfo;
1691 if (!isAssignment)
1692 LastElementTypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
1693 assert(!TypeInfo.first.isZero());
1694 SizeVal = Builder.CreateNUWMul(
1695 SizeVal,
1696 llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
1697 if (!isAssignment) {
1698 SizeVal = Builder.CreateNUWSub(
1699 SizeVal,
1700 llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
1701 SizeVal = Builder.CreateNUWAdd(
1702 SizeVal, llvm::ConstantInt::get(
1703 SizeTy, LastElementTypeInfo.first.getQuantity()));
1704 }
1705 }
1706 }
1707 if (!SizeVal) {
1708 SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity());
1709 }
Chad Rosier615ed1a2012-03-29 17:37:10 +00001710
1711 // FIXME: If we have a volatile struct, the optimizer can remove what might
1712 // appear to be `extra' memory ops:
1713 //
1714 // volatile struct { int i; } a, b;
1715 //
1716 // int main() {
1717 // a = b;
1718 // a = b;
1719 // }
1720 //
1721 // we need to use a different call here. We use isVolatile to indicate when
1722 // either the source or the destination is volatile.
1723
John McCall7f416cc2015-09-08 08:05:57 +00001724 DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1725 SrcPtr = Builder.CreateElementBitCast(SrcPtr, Int8Ty);
Chad Rosier615ed1a2012-03-29 17:37:10 +00001726
1727 // Don't do any of the memmove_collectable tests if GC isn't set.
1728 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1729 // fall through
1730 } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1731 RecordDecl *Record = RecordTy->getDecl();
1732 if (Record->hasObjectMember()) {
Chad Rosier615ed1a2012-03-29 17:37:10 +00001733 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1734 SizeVal);
1735 return;
1736 }
1737 } else if (Ty->isArrayType()) {
1738 QualType BaseType = getContext().getBaseElementType(Ty);
1739 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1740 if (RecordTy->getDecl()->hasObjectMember()) {
Chad Rosier615ed1a2012-03-29 17:37:10 +00001741 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1742 SizeVal);
1743 return;
1744 }
1745 }
1746 }
Dan Gohman22695fc2012-09-28 21:58:29 +00001747
John McCall7f416cc2015-09-08 08:05:57 +00001748 auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
1749
Dan Gohman22695fc2012-09-28 21:58:29 +00001750 // Determine the metadata to describe the position of any padding in this
1751 // memcpy, as well as the TBAA tags for the members of the struct, in case
1752 // the optimizer wishes to expand it in to scalar memory operations.
John McCall7f416cc2015-09-08 08:05:57 +00001753 if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
1754 Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001755
1756 if (CGM.getCodeGenOpts().NewStructPathTBAA) {
1757 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer(
1758 Dest.getTBAAInfo(), Src.getTBAAInfo());
1759 CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo);
1760 }
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00001761}