Coverage Report

Created: 2020-03-31 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGExprAgg.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This contains code to emit Aggregate Expr nodes as LLVM code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGCXXABI.h"
14
#include "CGObjCRuntime.h"
15
#include "CodeGenFunction.h"
16
#include "CodeGenModule.h"
17
#include "ConstantEmitter.h"
18
#include "TargetInfo.h"
19
#include "clang/AST/ASTContext.h"
20
#include "clang/AST/Attr.h"
21
#include "clang/AST/DeclCXX.h"
22
#include "clang/AST/DeclTemplate.h"
23
#include "clang/AST/StmtVisitor.h"
24
#include "llvm/IR/Constants.h"
25
#include "llvm/IR/Function.h"
26
#include "llvm/IR/GlobalVariable.h"
27
#include "llvm/IR/IntrinsicInst.h"
28
#include "llvm/IR/Intrinsics.h"
29
using namespace clang;
30
using namespace CodeGen;
31
32
//===----------------------------------------------------------------------===//
33
//                        Aggregate Expression Emitter
34
//===----------------------------------------------------------------------===//
35
36
namespace  {
37
class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
38
  CodeGenFunction &CGF;
39
  CGBuilderTy &Builder;
40
  AggValueSlot Dest;
41
  bool IsResultUnused;
42
43
64.5k
  AggValueSlot EnsureSlot(QualType T) {
44
64.5k
    if (!Dest.isIgnored()) 
return Dest64.5k
;
45
68
    return CGF.CreateAggTemp(T, "agg.tmp.ensured");
46
68
  }
47
5.91k
  void EnsureDest(QualType T) {
48
5.91k
    if (!Dest.isIgnored()) 
return5.75k
;
49
157
    Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
50
157
  }
51
52
  // Calls `Fn` with a valid return value slot, potentially creating a temporary
53
  // to do so. If a temporary is created, an appropriate copy into `Dest` will
54
  // be emitted, as will lifetime markers.
55
  //
56
  // The given function should take a ReturnValueSlot, and return an RValue that
57
  // points to said slot.
58
  void withReturnValueSlot(const Expr *E,
59
                           llvm::function_ref<RValue(ReturnValueSlot)> Fn);
60
61
public:
62
  AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
63
    : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
64
74.7k
    IsResultUnused(IsResultUnused) { }
65
66
  //===--------------------------------------------------------------------===//
67
  //                               Utilities
68
  //===--------------------------------------------------------------------===//
69
70
  /// EmitAggLoadOfLValue - Given an expression with aggregate type that
71
  /// represents a value lvalue, this method emits the address of the lvalue,
72
  /// then loads the result into DestPtr.
73
  void EmitAggLoadOfLValue(const Expr *E);
74
75
  enum ExprValueKind {
76
    EVK_RValue,
77
    EVK_NonRValue
78
  };
79
80
  /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
81
  /// SrcIsRValue is true if source comes from an RValue.
82
  void EmitFinalDestCopy(QualType type, const LValue &src,
83
                         ExprValueKind SrcValueKind = EVK_NonRValue);
84
  void EmitFinalDestCopy(QualType type, RValue src);
85
  void EmitCopy(QualType type, const AggValueSlot &dest,
86
                const AggValueSlot &src);
87
88
  void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
89
90
  void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
91
                     QualType ArrayQTy, InitListExpr *E);
92
93
3.19k
  AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
94
3.19k
    if (CGF.getLangOpts().getGC() && 
TypeRequiresGCollection(T)24
)
95
20
      return AggValueSlot::NeedsGCBarriers;
96
3.17k
    return AggValueSlot::DoesNotNeedGCBarriers;
97
3.17k
  }
98
99
  bool TypeRequiresGCollection(QualType T);
100
101
  //===--------------------------------------------------------------------===//
102
  //                            Visitor Methods
103
  //===--------------------------------------------------------------------===//
104
105
112k
  void Visit(Expr *E) {
106
112k
    ApplyDebugLocation DL(CGF, E);
107
112k
    StmtVisitor<AggExprEmitter>::Visit(E);
108
112k
  }
109
110
0
  void VisitStmt(Stmt *S) {
111
0
    CGF.ErrorUnsupported(S, "aggregate expression");
112
0
  }
113
85
  void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
114
0
  void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
115
0
    Visit(GE->getResultExpr());
116
0
  }
117
5
  void VisitCoawaitExpr(CoawaitExpr *E) {
118
5
    CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused);
119
5
  }
120
0
  void VisitCoyieldExpr(CoyieldExpr *E) {
121
0
    CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused);
122
0
  }
123
0
  void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); }
124
591
  void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
125
0
  void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
126
0
    return Visit(E->getReplacement());
127
0
  }
128
129
1
  void VisitConstantExpr(ConstantExpr *E) {
130
1
    return Visit(E->getSubExpr());
131
1
  }
132
133
  // l-values.
134
2.17k
  void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); }
135
7
  void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
136
94
  void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
137
19
  void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
138
  void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
139
6
  void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
140
6
    EmitAggLoadOfLValue(E);
141
6
  }
142
0
  void VisitPredefinedExpr(const PredefinedExpr *E) {
143
0
    EmitAggLoadOfLValue(E);
144
0
  }
145
146
  // Operators.
147
  void VisitCastExpr(CastExpr *E);
148
  void VisitCallExpr(const CallExpr *E);
149
  void VisitStmtExpr(const StmtExpr *E);
150
  void VisitBinaryOperator(const BinaryOperator *BO);
151
  void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
152
  void VisitBinAssign(const BinaryOperator *E);
153
  void VisitBinComma(const BinaryOperator *E);
154
  void VisitBinCmp(const BinaryOperator *E);
155
0
  void VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
156
0
    Visit(E->getSemanticForm());
157
0
  }
158
159
  void VisitObjCMessageExpr(ObjCMessageExpr *E);
160
5
  void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
161
5
    EmitAggLoadOfLValue(E);
162
5
  }
163
164
  void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
165
  void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
166
  void VisitChooseExpr(const ChooseExpr *CE);
167
  void VisitInitListExpr(InitListExpr *E);
168
  void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
169
                              llvm::Value *outerBegin = nullptr);
170
  void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
171
0
  void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.
172
396
  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
173
396
    CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
174
396
    Visit(DAE->getExpr());
175
396
  }
176
34
  void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
177
34
    CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
178
34
    Visit(DIE->getExpr());
179
34
  }
180
  void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
181
  void VisitCXXConstructExpr(const CXXConstructExpr *E);
182
  void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
183
  void VisitLambdaExpr(LambdaExpr *E);
184
  void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
185
  void VisitExprWithCleanups(ExprWithCleanups *E);
186
  void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
187
0
  void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
188
  void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
189
  void VisitOpaqueValueExpr(OpaqueValueExpr *E);
190
191
28
  void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
192
28
    if (E->isGLValue()) {
193
0
      LValue LV = CGF.EmitPseudoObjectLValue(E);
194
0
      return EmitFinalDestCopy(E->getType(), LV);
195
0
    }
196
28
197
28
    CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
198
28
  }
199
200
  void VisitVAArgExpr(VAArgExpr *E);
201
202
  void EmitInitializationToLValue(Expr *E, LValue Address);
203
  void EmitNullInitializationToLValue(LValue Address);
204
  //  case Expr::ChooseExprClass:
205
1
  void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
206
15
  void VisitAtomicExpr(AtomicExpr *E) {
207
15
    RValue Res = CGF.EmitAtomicExpr(E);
208
15
    EmitFinalDestCopy(E->getType(), Res);
209
15
  }
210
};
211
}  // end anonymous namespace.
212
213
//===----------------------------------------------------------------------===//
214
//                                Utilities
215
//===----------------------------------------------------------------------===//
216
217
/// EmitAggLoadOfLValue - Given an expression with aggregate type that
218
/// represents a value lvalue, this method emits the address of the lvalue,
219
/// then loads the result into DestPtr.
220
2.32k
void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
221
2.32k
  LValue LV = CGF.EmitLValue(E);
222
2.32k
223
2.32k
  // If the type of the l-value is atomic, then do an atomic load.
224
2.32k
  if (LV.getType()->isAtomicType() || 
CGF.LValueIsSuitableForInlineAtomic(LV)2.31k
) {
225
11
    CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
226
11
    return;
227
11
  }
228
2.31k
229
2.31k
  EmitFinalDestCopy(E->getType(), LV);
230
2.31k
}
231
232
/// True if the given aggregate type requires special GC API calls.
233
24
bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
234
24
  // Only record types have members that might require garbage collection.
235
24
  const RecordType *RecordTy = T->getAs<RecordType>();
236
24
  if (!RecordTy) 
return false0
;
237
24
238
24
  // Don't mess with non-trivial C++ types.
239
24
  RecordDecl *Record = RecordTy->getDecl();
240
24
  if (isa<CXXRecordDecl>(Record) &&
241
24
      
(5
cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor()5
||
242
5
       !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
243
0
    return false;
244
24
245
24
  // Check whether the type has an object member.
246
24
  return Record->hasObjectMember();
247
24
}
248
249
void AggExprEmitter::withReturnValueSlot(
250
6.53k
    const Expr *E, llvm::function_ref<RValue(ReturnValueSlot)> EmitCall) {
251
6.53k
  QualType RetTy = E->getType();
252
6.53k
  bool RequiresDestruction =
253
6.53k
      !Dest.isExternallyDestructed() &&
254
6.53k
      
RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct2.10k
;
255
6.53k
256
6.53k
  // If it makes no observable difference, save a memcpy + temporary.
257
6.53k
  //
258
6.53k
  // We need to always provide our own temporary if destruction is required.
259
6.53k
  // Otherwise, EmitCall will emit its own, notice that it's "unused", and end
260
6.53k
  // its lifetime before we have the chance to emit a proper destructor call.
261
6.53k
  bool UseTemp = Dest.isPotentiallyAliased() || 
Dest.requiresGCollection()6.36k
||
262
6.53k
                 
(6.36k
RequiresDestruction6.36k
&&
!Dest.getAddress().isValid()12
);
263
6.53k
264
6.53k
  Address RetAddr = Address::invalid();
265
6.53k
  Address RetAllocaAddr = Address::invalid();
266
6.53k
267
6.53k
  EHScopeStack::stable_iterator LifetimeEndBlock;
268
6.53k
  llvm::Value *LifetimeSizePtr = nullptr;
269
6.53k
  llvm::IntrinsicInst *LifetimeStartInst = nullptr;
270
6.53k
  if (!UseTemp) {
271
6.34k
    RetAddr = Dest.getAddress();
272
6.34k
  } else {
273
189
    RetAddr = CGF.CreateMemTemp(RetTy, "tmp", &RetAllocaAddr);
274
189
    uint64_t Size =
275
189
        CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy));
276
189
    LifetimeSizePtr = CGF.EmitLifetimeStart(Size, RetAllocaAddr.getPointer());
277
189
    if (LifetimeSizePtr) {
278
12
      LifetimeStartInst =
279
12
          cast<llvm::IntrinsicInst>(std::prev(Builder.GetInsertPoint()));
280
12
      assert(LifetimeStartInst->getIntrinsicID() ==
281
12
                 llvm::Intrinsic::lifetime_start &&
282
12
             "Last insertion wasn't a lifetime.start?");
283
12
284
12
      CGF.pushFullExprCleanup<CodeGenFunction::CallLifetimeEnd>(
285
12
          NormalEHLifetimeMarker, RetAllocaAddr, LifetimeSizePtr);
286
12
      LifetimeEndBlock = CGF.EHStack.stable_begin();
287
12
    }
288
189
  }
289
6.53k
290
6.53k
  RValue Src =
291
6.53k
      EmitCall(ReturnValueSlot(RetAddr, Dest.isVolatile(), IsResultUnused,
292
6.53k
                               Dest.isExternallyDestructed()));
293
6.53k
294
6.53k
  if (!UseTemp)
295
6.34k
    return;
296
189
297
189
  assert(Dest.getPointer() != Src.getAggregatePointer());
298
189
  EmitFinalDestCopy(E->getType(), Src);
299
189
300
189
  if (!RequiresDestruction && 
LifetimeStartInst177
) {
301
10
    // If there's no dtor to run, the copy was the last use of our temporary.
302
10
    // Since we're not guaranteed to be in an ExprWithCleanups, clean up
303
10
    // eagerly.
304
10
    CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst);
305
10
    CGF.EmitLifetimeEnd(LifetimeSizePtr, RetAllocaAddr.getPointer());
306
10
  }
307
189
}
308
309
/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
310
208
void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {
311
208
  assert(src.isAggregate() && "value must be aggregate value!");
312
208
  LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);
313
208
  EmitFinalDestCopy(type, srcLV, EVK_RValue);
314
208
}
315
316
/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
317
void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src,
318
3.29k
                                       ExprValueKind SrcValueKind) {
319
3.29k
  // If Dest is ignored, then we're evaluating an aggregate expression
320
3.29k
  // in a context that doesn't care about the result.  Note that loads
321
3.29k
  // from volatile l-values force the existence of a non-ignored
322
3.29k
  // destination.
323
3.29k
  if (Dest.isIgnored())
324
467
    return;
325
2.83k
326
2.83k
  // Copy non-trivial C structs here.
327
2.83k
  LValue DstLV = CGF.MakeAddrLValue(
328
2.83k
      Dest.getAddress(), Dest.isVolatile() ? 
type.withVolatile()17
:
type2.81k
);
329
2.83k
330
2.83k
  if (SrcValueKind == EVK_RValue) {
331
196
    if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) {
332
8
      if (Dest.isPotentiallyAliased())
333
8
        CGF.callCStructMoveAssignmentOperator(DstLV, src);
334
0
      else
335
0
        CGF.callCStructMoveConstructor(DstLV, src);
336
8
      return;
337
8
    }
338
2.63k
  } else {
339
2.63k
    if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
340
58
      if (Dest.isPotentiallyAliased())
341
14
        CGF.callCStructCopyAssignmentOperator(DstLV, src);
342
44
      else
343
44
        CGF.callCStructCopyConstructor(DstLV, src);
344
58
      return;
345
58
    }
346
2.76k
  }
347
2.76k
348
2.76k
  AggValueSlot srcAgg = AggValueSlot::forLValue(
349
2.76k
      src, CGF, AggValueSlot::IsDestructed, needsGC(type),
350
2.76k
      AggValueSlot::IsAliased, AggValueSlot::MayOverlap);
351
2.76k
  EmitCopy(type, Dest, srcAgg);
352
2.76k
}
353
354
/// Perform a copy from the source into the destination.
355
///
356
/// \param type - the type of the aggregate being copied; qualifiers are
357
///   ignored
358
void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
359
2.76k
                              const AggValueSlot &src) {
360
2.76k
  if (dest.requiresGCollection()) {
361
6
    CharUnits sz = dest.getPreferredSize(CGF.getContext(), type);
362
6
    llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
363
6
    CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
364
6
                                                      dest.getAddress(),
365
6
                                                      src.getAddress(),
366
6
                                                      size);
367
6
    return;
368
6
  }
369
2.76k
370
2.76k
  // If the result of the assignment is used, copy the LHS there also.
371
2.76k
  // It's volatile if either side is.  Use the minimum alignment of
372
2.76k
  // the two sides.
373
2.76k
  LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type);
374
2.76k
  LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type);
375
2.76k
  CGF.EmitAggregateCopy(DestLV, SrcLV, type, dest.mayOverlap(),
376
2.76k
                        dest.isVolatile() || 
src.isVolatile()2.74k
);
377
2.76k
}
378
379
/// Emit the initializer for a std::initializer_list initialized with a
380
/// real initializer list.
381
void
382
161
AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
383
161
  // Emit an array containing the elements.  The array is externally destructed
384
161
  // if the std::initializer_list object is.
385
161
  ASTContext &Ctx = CGF.getContext();
386
161
  LValue Array = CGF.EmitLValue(E->getSubExpr());
387
161
  assert(Array.isSimple() && "initializer_list array not a simple lvalue");
388
161
  Address ArrayPtr = Array.getAddress(CGF);
389
161
390
161
  const ConstantArrayType *ArrayType =
391
161
      Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
392
161
  assert(ArrayType && "std::initializer_list constructed from non-array");
393
161
394
161
  // FIXME: Perform the checks on the field types in SemaInit.
395
161
  RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
396
161
  RecordDecl::field_iterator Field = Record->field_begin();
397
161
  if (Field == Record->field_end()) {
398
1
    CGF.ErrorUnsupported(E, "weird std::initializer_list");
399
1
    return;
400
1
  }
401
160
402
160
  // Start pointer.
403
160
  if (!Field->getType()->isPointerType() ||
404
160
      !Ctx.hasSameType(Field->getType()->getPointeeType(),
405
160
                       ArrayType->getElementType())) {
406
0
    CGF.ErrorUnsupported(E, "weird std::initializer_list");
407
0
    return;
408
0
  }
409
160
410
160
  AggValueSlot Dest = EnsureSlot(E->getType());
411
160
  LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
412
160
  LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
413
160
  llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
414
160
  llvm::Value *IdxStart[] = { Zero, Zero };
415
160
  llvm::Value *ArrayStart =
416
160
      Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxStart, "arraystart");
417
160
  CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
418
160
  ++Field;
419
160
420
160
  if (Field == Record->field_end()) {
421
0
    CGF.ErrorUnsupported(E, "weird std::initializer_list");
422
0
    return;
423
0
  }
424
160
425
160
  llvm::Value *Size = Builder.getInt(ArrayType->getSize());
426
160
  LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
427
160
  if (Field->getType()->isPointerType() &&
428
160
      Ctx.hasSameType(Field->getType()->getPointeeType(),
429
7
                      ArrayType->getElementType())) {
430
7
    // End pointer.
431
7
    llvm::Value *IdxEnd[] = { Zero, Size };
432
7
    llvm::Value *ArrayEnd =
433
7
        Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxEnd, "arrayend");
434
7
    CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
435
153
  } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
436
153
    // Length.
437
153
    CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
438
153
  } else {
439
0
    CGF.ErrorUnsupported(E, "weird std::initializer_list");
440
0
    return;
441
0
  }
442
160
}
443
444
/// Determine if E is a trivial array filler, that is, one that is
445
/// equivalent to zero-initialization.
446
1.56k
static bool isTrivialFiller(Expr *E) {
447
1.56k
  if (!E)
448
1.50k
    return true;
449
64
450
64
  if (isa<ImplicitValueInitExpr>(E))
451
33
    return true;
452
31
453
31
  if (auto *ILE = dyn_cast<InitListExpr>(E)) {
454
5
    if (ILE->getNumInits())
455
4
      return false;
456
1
    return isTrivialFiller(ILE->getArrayFiller());
457
1
  }
458
26
459
26
  if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
460
23
    return Cons->getConstructor()->isDefaultConstructor() &&
461
23
           
Cons->getConstructor()->isTrivial()21
;
462
3
463
3
  // FIXME: Are there other cases where we can avoid emitting an initializer?
464
3
  return false;
465
3
}
466
467
/// Emit initialization of an array from an initializer list.
468
void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
469
1.58k
                                   QualType ArrayQTy, InitListExpr *E) {
470
1.58k
  uint64_t NumInitElements = E->getNumInits();
471
1.58k
472
1.58k
  uint64_t NumArrayElements = AType->getNumElements();
473
1.58k
  assert(NumInitElements <= NumArrayElements);
474
1.58k
475
1.58k
  QualType elementType =
476
1.58k
      CGF.getContext().getAsArrayType(ArrayQTy)->getElementType();
477
1.58k
478
1.58k
  // DestPtr is an array*.  Construct an elementType* by drilling
479
1.58k
  // down a level.
480
1.58k
  llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
481
1.58k
  llvm::Value *indices[] = { zero, zero };
482
1.58k
  llvm::Value *begin =
483
1.58k
    Builder.CreateInBoundsGEP(DestPtr.getPointer(), indices, "arrayinit.begin");
484
1.58k
485
1.58k
  CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
486
1.58k
  CharUnits elementAlign =
487
1.58k
    DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
488
1.58k
489
1.58k
  // Consider initializing the array by copying from a global. For this to be
490
1.58k
  // more efficient than per-element initialization, the size of the elements
491
1.58k
  // with explicit initializers should be large enough.
492
1.58k
  if (NumInitElements * elementSize.getQuantity() > 16 &&
493
1.58k
      
elementType.isTriviallyCopyableType(CGF.getContext())117
) {
494
80
    CodeGen::CodeGenModule &CGM = CGF.CGM;
495
80
    ConstantEmitter Emitter(CGF);
496
80
    LangAS AS = ArrayQTy.getAddressSpace();
497
80
    if (llvm::Constant *C = Emitter.tryEmitForInitializer(E, AS, ArrayQTy)) {
498
24
      auto GV = new llvm::GlobalVariable(
499
24
          CGM.getModule(), C->getType(),
500
24
          CGM.isTypeConstant(ArrayQTy, /* ExcludeCtorDtor= */ true),
501
24
          llvm::GlobalValue::PrivateLinkage, C, "constinit",
502
24
          /* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal,
503
24
          CGM.getContext().getTargetAddressSpace(AS));
504
24
      Emitter.finalize(GV);
505
24
      CharUnits Align = CGM.getContext().getTypeAlignInChars(ArrayQTy);
506
24
      GV->setAlignment(Align.getAsAlign());
507
24
      EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GV, ArrayQTy, Align));
508
24
      return;
509
24
    }
510
1.56k
  }
511
1.56k
512
1.56k
  // Exception safety requires us to destroy all the
513
1.56k
  // already-constructed members if an initializer throws.
514
1.56k
  // For that, we'll need an EH cleanup.
515
1.56k
  QualType::DestructionKind dtorKind = elementType.isDestructedType();
516
1.56k
  Address endOfInit = Address::invalid();
517
1.56k
  EHScopeStack::stable_iterator cleanup;
518
1.56k
  llvm::Instruction *cleanupDominator = nullptr;
519
1.56k
  if (CGF.needsEHCleanup(dtorKind)) {
520
52
    // In principle we could tell the cleanup where we are more
521
52
    // directly, but the control flow can get so varied here that it
522
52
    // would actually be quite complex.  Therefore we go through an
523
52
    // alloca.
524
52
    endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),
525
52
                                     "arrayinit.endOfInit");
526
52
    cleanupDominator = Builder.CreateStore(begin, endOfInit);
527
52
    CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
528
52
                                         elementAlign,
529
52
                                         CGF.getDestroyer(dtorKind));
530
52
    cleanup = CGF.EHStack.stable_begin();
531
52
532
52
  // Otherwise, remember that we didn't need a cleanup.
533
1.51k
  } else {
534
1.51k
    dtorKind = QualType::DK_none;
535
1.51k
  }
536
1.56k
537
1.56k
  llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
538
1.56k
539
1.56k
  // The 'current element to initialize'.  The invariants on this
540
1.56k
  // variable are complicated.  Essentially, after each iteration of
541
1.56k
  // the loop, it points to the last initialized element, except
542
1.56k
  // that it points to the beginning of the array before any
543
1.56k
  // elements have been initialized.
544
1.56k
  llvm::Value *element = begin;
545
1.56k
546
1.56k
  // Emit the explicit initializers.
547
4.75k
  for (uint64_t i = 0; i != NumInitElements; 
++i3.18k
) {
548
3.18k
    // Advance to the next element.
549
3.18k
    if (i > 0) {
550
1.64k
      element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
551
1.64k
552
1.64k
      // Tell the cleanup that it needs to destroy up to this
553
1.64k
      // element.  TODO: some of these stores can be trivially
554
1.64k
      // observed to be unnecessary.
555
1.64k
      if (endOfInit.isValid()) 
Builder.CreateStore(element, endOfInit)80
;
556
1.64k
    }
557
3.18k
558
3.18k
    LValue elementLV =
559
3.18k
      CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
560
3.18k
    EmitInitializationToLValue(E->getInit(i), elementLV);
561
3.18k
  }
562
1.56k
563
1.56k
  // Check whether there's a non-trivial array-fill expression.
564
1.56k
  Expr *filler = E->getArrayFiller();
565
1.56k
  bool hasTrivialFiller = isTrivialFiller(filler);
566
1.56k
567
1.56k
  // Any remaining elements need to be zero-initialized, possibly
568
1.56k
  // using the filler expression.  We can skip this if the we're
569
1.56k
  // emitting to zeroed memory.
570
1.56k
  if (NumInitElements != NumArrayElements &&
571
1.56k
      
!(58
Dest.isZeroed()58
&&
hasTrivialFiller27
&&
572
58
        
CGF.getTypes().isZeroInitializable(elementType)20
)) {
573
38
574
38
    // Use an actual loop.  This is basically
575
38
    //   do { *array++ = filler; } while (array != end);
576
38
577
38
    // Advance to the start of the rest of the array.
578
38
    if (NumInitElements) {
579
19
      element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
580
19
      if (endOfInit.isValid()) 
Builder.CreateStore(element, endOfInit)2
;
581
19
    }
582
38
583
38
    // Compute the end of the array.
584
38
    llvm::Value *end = Builder.CreateInBoundsGEP(begin,
585
38
                      llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
586
38
                                                 "arrayinit.end");
587
38
588
38
    llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
589
38
    llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
590
38
591
38
    // Jump into the body.
592
38
    CGF.EmitBlock(bodyBB);
593
38
    llvm::PHINode *currentElement =
594
38
      Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
595
38
    currentElement->addIncoming(element, entryBB);
596
38
597
38
    // Emit the actual filler expression.
598
38
    {
599
38
      // C++1z [class.temporary]p5:
600
38
      //   when a default constructor is called to initialize an element of
601
38
      //   an array with no corresponding initializer [...] the destruction of
602
38
      //   every temporary created in a default argument is sequenced before
603
38
      //   the construction of the next array element, if any
604
38
      CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
605
38
      LValue elementLV =
606
38
        CGF.MakeAddrLValue(Address(currentElement, elementAlign), elementType);
607
38
      if (filler)
608
38
        EmitInitializationToLValue(filler, elementLV);
609
0
      else
610
0
        EmitNullInitializationToLValue(elementLV);
611
38
    }
612
38
613
38
    // Move on to the next element.
614
38
    llvm::Value *nextElement =
615
38
      Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
616
38
617
38
    // Tell the EH cleanup that we finished with the last element.
618
38
    if (endOfInit.isValid()) 
Builder.CreateStore(nextElement, endOfInit)2
;
619
38
620
38
    // Leave the loop if we're done.
621
38
    llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
622
38
                                             "arrayinit.done");
623
38
    llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
624
38
    Builder.CreateCondBr(done, endBB, bodyBB);
625
38
    currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
626
38
627
38
    CGF.EmitBlock(endBB);
628
38
  }
629
1.56k
630
1.56k
  // Leave the partial-array cleanup if we entered one.
631
1.56k
  if (dtorKind) 
CGF.DeactivateCleanupBlock(cleanup, cleanupDominator)52
;
632
1.56k
}
633
634
//===----------------------------------------------------------------------===//
635
//                            Visitor Methods
636
//===----------------------------------------------------------------------===//
637
638
11.9k
void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
639
11.9k
  Visit(E->getSubExpr());
640
11.9k
}
641
642
20
void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
643
20
  // If this is a unique OVE, just visit its source expression.
644
20
  if (e->isUnique())
645
7
    Visit(e->getSourceExpr());
646
13
  else
647
13
    EmitFinalDestCopy(e->getType(), CGF.getOrCreateOpaqueLValueMapping(e));
648
20
}
649
650
void
651
540
AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
652
540
  if (Dest.isPotentiallyAliased() &&
653
540
      
E->getType().isPODType(CGF.getContext())20
) {
654
20
    // For a POD type, just emit a load of the lvalue + a copy, because our
655
20
    // compound literal might alias the destination.
656
20
    EmitAggLoadOfLValue(E);
657
20
    return;
658
20
  }
659
520
660
520
  AggValueSlot Slot = EnsureSlot(E->getType());
661
520
662
520
  // Block-scope compound literals are destroyed at the end of the enclosing
663
520
  // scope in C.
664
520
  bool Destruct =
665
520
      !CGF.getLangOpts().CPlusPlus && 
!Slot.isExternallyDestructed()220
;
666
520
  if (Destruct)
667
20
    Slot.setExternallyDestructed();
668
520
669
520
  CGF.EmitAggExpr(E->getInitializer(), Slot);
670
520
671
520
  if (Destruct)
672
20
    if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
673
0
      CGF.pushLifetimeExtendedDestroy(
674
0
          CGF.getCleanupKind(DtorKind), Slot.getAddress(), E->getType(),
675
0
          CGF.getDestroyer(DtorKind), DtorKind & EHCleanup);
676
520
}
677
678
/// Attempt to look through various unimportant expressions to find a
679
/// cast of the given kind.
680
9
static Expr *findPeephole(Expr *op, CastKind kind) {
681
9
  while (true) {
682
9
    op = op->IgnoreParens();
683
9
    if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
684
9
      if (castE->getCastKind() == kind)
685
0
        return castE->getSubExpr();
686
9
      if (castE->getCastKind() == CK_NoOp)
687
0
        continue;
688
9
    }
689
9
    return nullptr;
690
9
  }
691
9
}
692
693
12.3k
void AggExprEmitter::VisitCastExpr(CastExpr *E) {
694
12.3k
  if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
695
3.35k
    CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
696
12.3k
  switch (E->getCastKind()) {
697
0
  case CK_Dynamic: {
698
0
    // FIXME: Can this actually happen? We have no test coverage for it.
699
0
    assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
700
0
    LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
701
0
                                      CodeGenFunction::TCK_Load);
702
0
    // FIXME: Do we also need to handle property references here?
703
0
    if (LV.isSimple())
704
0
      CGF.EmitDynamicCast(LV.getAddress(CGF), cast<CXXDynamicCastExpr>(E));
705
0
    else
706
0
      CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
707
0
708
0
    if (!Dest.isIgnored())
709
0
      CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
710
0
    break;
711
0
  }
712
0
713
7
  case CK_ToUnion: {
714
7
    // Evaluate even if the destination is ignored.
715
7
    if (Dest.isIgnored()) {
716
1
      CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
717
1
                      /*ignoreResult=*/true);
718
1
      break;
719
1
    }
720
6
721
6
    // GCC union extension
722
6
    QualType Ty = E->getSubExpr()->getType();
723
6
    Address CastPtr =
724
6
      Builder.CreateElementBitCast(Dest.getAddress(), CGF.ConvertType(Ty));
725
6
    EmitInitializationToLValue(E->getSubExpr(),
726
6
                               CGF.MakeAddrLValue(CastPtr, Ty));
727
6
    break;
728
6
  }
729
6
730
6
  case CK_LValueToRValueBitCast: {
731
4
    if (Dest.isIgnored()) {
732
0
      CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
733
0
                      /*ignoreResult=*/true);
734
0
      break;
735
0
    }
736
4
737
4
    LValue SourceLV = CGF.EmitLValue(E->getSubExpr());
738
4
    Address SourceAddress =
739
4
        Builder.CreateElementBitCast(SourceLV.getAddress(CGF), CGF.Int8Ty);
740
4
    Address DestAddress =
741
4
        Builder.CreateElementBitCast(Dest.getAddress(), CGF.Int8Ty);
742
4
    llvm::Value *SizeVal = llvm::ConstantInt::get(
743
4
        CGF.SizeTy,
744
4
        CGF.getContext().getTypeSizeInChars(E->getType()).getQuantity());
745
4
    Builder.CreateMemCpy(DestAddress, SourceAddress, SizeVal);
746
4
    break;
747
4
  }
748
4
749
4
  case CK_DerivedToBase:
750
0
  case CK_BaseToDerived:
751
0
  case CK_UncheckedDerivedToBase: {
752
0
    llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
753
0
                "should have been unpacked before we got here");
754
0
  }
755
0
756
23
  case CK_NonAtomicToAtomic:
757
23
  case CK_AtomicToNonAtomic: {
758
23
    bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
759
23
760
23
    // Determine the atomic and value types.
761
23
    QualType atomicType = E->getSubExpr()->getType();
762
23
    QualType valueType = E->getType();
763
23
    if (isToAtomic) 
std::swap(atomicType, valueType)15
;
764
23
765
23
    assert(atomicType->isAtomicType());
766
23
    assert(CGF.getContext().hasSameUnqualifiedType(valueType,
767
23
                          atomicType->castAs<AtomicType>()->getValueType()));
768
23
769
23
    // Just recurse normally if we're ignoring the result or the
770
23
    // atomic type doesn't change representation.
771
23
    if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
772
14
      return Visit(E->getSubExpr());
773
14
    }
774
9
775
9
    CastKind peepholeTarget =
776
9
      (isToAtomic ? 
CK_AtomicToNonAtomic5
:
CK_NonAtomicToAtomic4
);
777
9
778
9
    // These two cases are reverses of each other; try to peephole them.
779
9
    if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
780
0
      assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
781
0
                                                     E->getType()) &&
782
0
           "peephole significantly changed types?");
783
0
      return Visit(op);
784
0
    }
785
9
786
9
    // If we're converting an r-value of non-atomic type to an r-value
787
9
    // of atomic type, just emit directly into the relevant sub-object.
788
9
    if (isToAtomic) {
789
5
      AggValueSlot valueDest = Dest;
790
5
      if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
791
5
        // Zero-initialize.  (Strictly speaking, we only need to initialize
792
5
        // the padding at the end, but this is simpler.)
793
5
        if (!Dest.isZeroed())
794
5
          CGF.EmitNullInitialization(Dest.getAddress(), atomicType);
795
5
796
5
        // Build a GEP to refer to the subobject.
797
5
        Address valueAddr =
798
5
            CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0);
799
5
        valueDest = AggValueSlot::forAddr(valueAddr,
800
5
                                          valueDest.getQualifiers(),
801
5
                                          valueDest.isExternallyDestructed(),
802
5
                                          valueDest.requiresGCollection(),
803
5
                                          valueDest.isPotentiallyAliased(),
804
5
                                          AggValueSlot::DoesNotOverlap,
805
5
                                          AggValueSlot::IsZeroed);
806
5
      }
807
5
808
5
      CGF.EmitAggExpr(E->getSubExpr(), valueDest);
809
5
      return;
810
5
    }
811
4
812
4
    // Otherwise, we're converting an atomic type to a non-atomic type.
813
4
    // Make an atomic temporary, emit into that, and then copy the value out.
814
4
    AggValueSlot atomicSlot =
815
4
      CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
816
4
    CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
817
4
818
4
    Address valueAddr = Builder.CreateStructGEP(atomicSlot.getAddress(), 0);
819
4
    RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
820
4
    return EmitFinalDestCopy(valueType, rvalue);
821
4
  }
822
4
  case CK_AddressSpaceConversion:
823
0
     return Visit(E->getSubExpr());
824
4
825
2.45k
  case CK_LValueToRValue:
826
2.45k
    // If we're loading from a volatile type, force the destination
827
2.45k
    // into existence.
828
2.45k
    if (E->getSubExpr()->getType().isVolatileQualified()) {
829
17
      bool Destruct =
830
17
          !Dest.isExternallyDestructed() &&
831
17
          
E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct10
;
832
17
      if (Destruct)
833
2
        Dest.setExternallyDestructed();
834
17
      EnsureDest(E->getType());
835
17
      Visit(E->getSubExpr());
836
17
837
17
      if (Destruct)
838
2
        CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
839
2
                        E->getType());
840
17
841
17
      return;
842
17
    }
843
2.44k
844
2.44k
    LLVM_FALLTHROUGH;
845
2.44k
846
2.44k
847
12.3k
  case CK_NoOp:
848
12.3k
  case CK_UserDefinedConversion:
849
12.3k
  case CK_ConstructorConversion:
850
12.3k
    assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
851
12.3k
                                                   E->getType()) &&
852
12.3k
           "Implicit cast types must be compatible");
853
12.3k
    Visit(E->getSubExpr());
854
12.3k
    break;
855
12.3k
856
12.3k
  case CK_LValueBitCast:
857
0
    llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
858
12.3k
859
12.3k
  case CK_Dependent:
860
0
  case CK_BitCast:
861
0
  case CK_ArrayToPointerDecay:
862
0
  case CK_FunctionToPointerDecay:
863
0
  case CK_NullToPointer:
864
0
  case CK_NullToMemberPointer:
865
0
  case CK_BaseToDerivedMemberPointer:
866
0
  case CK_DerivedToBaseMemberPointer:
867
0
  case CK_MemberPointerToBoolean:
868
0
  case CK_ReinterpretMemberPointer:
869
0
  case CK_IntegralToPointer:
870
0
  case CK_PointerToIntegral:
871
0
  case CK_PointerToBoolean:
872
0
  case CK_ToVoid:
873
0
  case CK_VectorSplat:
874
0
  case CK_IntegralCast:
875
0
  case CK_BooleanToSignedIntegral:
876
0
  case CK_IntegralToBoolean:
877
0
  case CK_IntegralToFloating:
878
0
  case CK_FloatingToIntegral:
879
0
  case CK_FloatingToBoolean:
880
0
  case CK_FloatingCast:
881
0
  case CK_CPointerToObjCPointerCast:
882
0
  case CK_BlockPointerToObjCPointerCast:
883
0
  case CK_AnyPointerToBlockPointerCast:
884
0
  case CK_ObjCObjectLValueCast:
885
0
  case CK_FloatingRealToComplex:
886
0
  case CK_FloatingComplexToReal:
887
0
  case CK_FloatingComplexToBoolean:
888
0
  case CK_FloatingComplexCast:
889
0
  case CK_FloatingComplexToIntegralComplex:
890
0
  case CK_IntegralRealToComplex:
891
0
  case CK_IntegralComplexToReal:
892
0
  case CK_IntegralComplexToBoolean:
893
0
  case CK_IntegralComplexCast:
894
0
  case CK_IntegralComplexToFloatingComplex:
895
0
  case CK_ARCProduceObject:
896
0
  case CK_ARCConsumeObject:
897
0
  case CK_ARCReclaimReturnedObject:
898
0
  case CK_ARCExtendBlockObject:
899
0
  case CK_CopyAndAutoreleaseBlockObject:
900
0
  case CK_BuiltinFnToFnPtr:
901
0
  case CK_ZeroToOCLOpaqueType:
902
0
903
0
  case CK_IntToOCLSampler:
904
0
  case CK_FixedPointCast:
905
0
  case CK_FixedPointToBoolean:
906
0
  case CK_FixedPointToIntegral:
907
0
  case CK_IntegralToFixedPoint:
908
0
    llvm_unreachable("cast kind invalid for aggregate types");
909
12.3k
  }
910
12.3k
}
911
912
6.46k
void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
913
6.46k
  if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
914
0
    EmitAggLoadOfLValue(E);
915
0
    return;
916
0
  }
917
6.46k
918
6.46k
  withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
919
6.46k
    return CGF.EmitCallExpr(E, Slot);
920
6.46k
  });
921
6.46k
}
922
923
69
void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
924
69
  withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
925
69
    return CGF.EmitObjCMessageExpr(E, Slot);
926
69
  });
927
69
}
928
929
43
void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
930
43
  CGF.EmitIgnoredExpr(E->getLHS());
931
43
  Visit(E->getRHS());
932
43
}
933
934
597
void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
935
597
  CodeGenFunction::StmtExprEvaluation eval(CGF);
936
597
  CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
937
597
}
938
939
enum CompareKind {
940
  CK_Less,
941
  CK_Greater,
942
  CK_Equal,
943
};
944
945
static llvm::Value *EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF,
946
                                const BinaryOperator *E, llvm::Value *LHS,
947
                                llvm::Value *RHS, CompareKind Kind,
948
27
                                const char *NameSuffix = "") {
949
27
  QualType ArgTy = E->getLHS()->getType();
950
27
  if (const ComplexType *CT = ArgTy->getAs<ComplexType>())
951
0
    ArgTy = CT->getElementType();
952
27
953
27
  if (const auto *MPT = ArgTy->getAs<MemberPointerType>()) {
954
0
    assert(Kind == CK_Equal &&
955
0
           "member pointers may only be compared for equality");
956
0
    return CGF.CGM.getCXXABI().EmitMemberPointerComparison(
957
0
        CGF, LHS, RHS, MPT, /*IsInequality*/ false);
958
0
  }
959
27
960
27
  // Compute the comparison instructions for the specified comparison kind.
961
27
  struct CmpInstInfo {
962
27
    const char *Name;
963
27
    llvm::CmpInst::Predicate FCmp;
964
27
    llvm::CmpInst::Predicate SCmp;
965
27
    llvm::CmpInst::Predicate UCmp;
966
27
  };
967
27
  CmpInstInfo InstInfo = [&]() -> CmpInstInfo {
968
27
    using FI = llvm::FCmpInst;
969
27
    using II = llvm::ICmpInst;
970
27
    switch (Kind) {
971
13
    case CK_Less:
972
13
      return {"cmp.lt", FI::FCMP_OLT, II::ICMP_SLT, II::ICMP_ULT};
973
1
    case CK_Greater:
974
1
      return {"cmp.gt", FI::FCMP_OGT, II::ICMP_SGT, II::ICMP_UGT};
975
13
    case CK_Equal:
976
13
      return {"cmp.eq", FI::FCMP_OEQ, II::ICMP_EQ, II::ICMP_EQ};
977
0
    }
978
0
    llvm_unreachable("Unrecognised CompareKind enum");
979
0
  }();
980
27
981
27
  if (ArgTy->hasFloatingRepresentation())
982
3
    return Builder.CreateFCmp(InstInfo.FCmp, LHS, RHS,
983
3
                              llvm::Twine(InstInfo.Name) + NameSuffix);
984
24
  if (ArgTy->isIntegralOrEnumerationType() || 
ArgTy->isPointerType()2
) {
985
24
    auto Inst =
986
24
        ArgTy->hasSignedIntegerRepresentation() ? 
InstInfo.SCmp14
:
InstInfo.UCmp10
;
987
24
    return Builder.CreateICmp(Inst, LHS, RHS,
988
24
                              llvm::Twine(InstInfo.Name) + NameSuffix);
989
24
  }
990
0
991
0
  llvm_unreachable("unsupported aggregate binary expression should have "
992
0
                   "already been handled");
993
0
}
994
995
13
void AggExprEmitter::VisitBinCmp(const BinaryOperator *E) {
996
13
  using llvm::BasicBlock;
997
13
  using llvm::PHINode;
998
13
  using llvm::Value;
999
13
  assert(CGF.getContext().hasSameType(E->getLHS()->getType(),
1000
13
                                      E->getRHS()->getType()));
1001
13
  const ComparisonCategoryInfo &CmpInfo =
1002
13
      CGF.getContext().CompCategories.getInfoForType(E->getType());
1003
13
  assert(CmpInfo.Record->isTriviallyCopyable() &&
1004
13
         "cannot copy non-trivially copyable aggregate");
1005
13
1006
13
  QualType ArgTy = E->getLHS()->getType();
1007
13
1008
13
  if (!ArgTy->isIntegralOrEnumerationType() && 
!ArgTy->isRealFloatingType()2
&&
1009
13
      
!ArgTy->isNullPtrType()1
&&
!ArgTy->isPointerType()1
&&
1010
13
      
!ArgTy->isMemberPointerType()0
&&
!ArgTy->isAnyComplexType()0
) {
1011
0
    return CGF.ErrorUnsupported(E, "aggregate three-way comparison");
1012
0
  }
1013
13
  bool IsComplex = ArgTy->isAnyComplexType();
1014
13
1015
13
  // Evaluate the operands to the expression and extract their values.
1016
26
  auto EmitOperand = [&](Expr *E) -> std::pair<Value *, Value *> {
1017
26
    RValue RV = CGF.EmitAnyExpr(E);
1018
26
    if (RV.isScalar())
1019
26
      return {RV.getScalarVal(), nullptr};
1020
0
    if (RV.isAggregate())
1021
0
      return {RV.getAggregatePointer(), nullptr};
1022
0
    assert(RV.isComplex());
1023
0
    return RV.getComplexVal();
1024
0
  };
1025
13
  auto LHSValues = EmitOperand(E->getLHS()),
1026
13
       RHSValues = EmitOperand(E->getRHS());
1027
13
1028
27
  auto EmitCmp = [&](CompareKind K) {
1029
27
    Value *Cmp = EmitCompare(Builder, CGF, E, LHSValues.first, RHSValues.first,
1030
27
                             K, IsComplex ? 
".r"0
: "");
1031
27
    if (!IsComplex)
1032
27
      return Cmp;
1033
0
    assert(K == CompareKind::CK_Equal);
1034
0
    Value *CmpImag = EmitCompare(Builder, CGF, E, LHSValues.second,
1035
0
                                 RHSValues.second, K, ".i");
1036
0
    return Builder.CreateAnd(Cmp, CmpImag, "and.eq");
1037
0
  };
1038
40
  auto EmitCmpRes = [&](const ComparisonCategoryInfo::ValueInfo *VInfo) {
1039
40
    return Builder.getInt(VInfo->getIntValue());
1040
40
  };
1041
13
1042
13
  Value *Select;
1043
13
  if (ArgTy->isNullPtrType()) {
1044
0
    Select = EmitCmpRes(CmpInfo.getEqualOrEquiv());
1045
13
  } else if (!CmpInfo.isPartial()) {
1046
12
    Value *SelectOne =
1047
12
        Builder.CreateSelect(EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()),
1048
12
                             EmitCmpRes(CmpInfo.getGreater()), "sel.lt");
1049
12
    Select = Builder.CreateSelect(EmitCmp(CK_Equal),
1050
12
                                  EmitCmpRes(CmpInfo.getEqualOrEquiv()),
1051
12
                                  SelectOne, "sel.eq");
1052
12
  } else {
1053
1
    Value *SelectEq = Builder.CreateSelect(
1054
1
        EmitCmp(CK_Equal), EmitCmpRes(CmpInfo.getEqualOrEquiv()),
1055
1
        EmitCmpRes(CmpInfo.getUnordered()), "sel.eq");
1056
1
    Value *SelectGT = Builder.CreateSelect(EmitCmp(CK_Greater),
1057
1
                                           EmitCmpRes(CmpInfo.getGreater()),
1058
1
                                           SelectEq, "sel.gt");
1059
1
    Select = Builder.CreateSelect(
1060
1
        EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()), SelectGT, "sel.lt");
1061
1
  }
1062
13
  // Create the return value in the destination slot.
1063
13
  EnsureDest(E->getType());
1064
13
  LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1065
13
1066
13
  // Emit the address of the first (and only) field in the comparison category
1067
13
  // type, and initialize it from the constant integer value selected above.
1068
13
  LValue FieldLV = CGF.EmitLValueForFieldInitialization(
1069
13
      DestLV, *CmpInfo.Record->field_begin());
1070
13
  CGF.EmitStoreThroughLValue(RValue::get(Select), FieldLV, /*IsInit*/ true);
1071
13
1072
13
  // All done! The result is in the Dest slot.
1073
13
}
1074
1075
0
void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
1076
0
  if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
1077
0
    VisitPointerToDataMemberBinaryOperator(E);
1078
0
  else
1079
0
    CGF.ErrorUnsupported(E, "aggregate binary expression");
1080
0
}
1081
1082
void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
1083
0
                                                    const BinaryOperator *E) {
1084
0
  LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
1085
0
  EmitFinalDestCopy(E->getType(), LV);
1086
0
}
1087
1088
/// Is the value of the given expression possibly a reference to or
1089
/// into a __block variable?
1090
674
static bool isBlockVarRef(const Expr *E) {
1091
674
  // Make sure we look through parens.
1092
674
  E = E->IgnoreParens();
1093
674
1094
674
  // Check for a direct reference to a __block variable.
1095
674
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1096
226
    const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
1097
226
    return (var && var->hasAttr<BlocksAttr>());
1098
226
  }
1099
448
1100
448
  // More complicated stuff.
1101
448
1102
448
  // Binary operators.
1103
448
  if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
1104
0
    // For an assignment or pointer-to-member operation, just care
1105
0
    // about the LHS.
1106
0
    if (op->isAssignmentOp() || op->isPtrMemOp())
1107
0
      return isBlockVarRef(op->getLHS());
1108
0
1109
0
    // For a comma, just care about the RHS.
1110
0
    if (op->getOpcode() == BO_Comma)
1111
0
      return isBlockVarRef(op->getRHS());
1112
0
1113
0
    // FIXME: pointer arithmetic?
1114
0
    return false;
1115
0
1116
0
  // Check both sides of a conditional operator.
1117
448
  } else if (const AbstractConditionalOperator *op
1118
0
               = dyn_cast<AbstractConditionalOperator>(E)) {
1119
0
    return isBlockVarRef(op->getTrueExpr())
1120
0
        || isBlockVarRef(op->getFalseExpr());
1121
0
1122
0
  // OVEs are required to support BinaryConditionalOperators.
1123
448
  } else if (const OpaqueValueExpr *op
1124
0
               = dyn_cast<OpaqueValueExpr>(E)) {
1125
0
    if (const Expr *src = op->getSourceExpr())
1126
0
      return isBlockVarRef(src);
1127
448
1128
448
  // Casts are necessary to get things like (*(int*)&var) = foo().
1129
448
  // We don't really care about the kind of cast here, except
1130
448
  // we don't want to look through l2r casts, because it's okay
1131
448
  // to get the *value* in a __block variable.
1132
448
  } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
1133
225
    if (cast->getCastKind() == CK_LValueToRValue)
1134
211
      return false;
1135
14
    return isBlockVarRef(cast->getSubExpr());
1136
14
1137
14
  // Handle unary operators.  Again, just aggressively look through
1138
14
  // it, ignoring the operation.
1139
223
  } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
1140
198
    return isBlockVarRef(uop->getSubExpr());
1141
198
1142
198
  // Look into the base of a field access.
1143
198
  } else 
if (const MemberExpr *25
mem25
= dyn_cast<MemberExpr>(E)) {
1144
5
    return isBlockVarRef(mem->getBase());
1145
5
1146
5
  // Look into the base of a subscript.
1147
20
  } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
1148
13
    return isBlockVarRef(sub->getBase());
1149
13
  }
1150
7
1151
7
  return false;
1152
7
}
1153
1154
444
void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1155
444
  // For an assignment to work, the value on the right has
1156
444
  // to be compatible with the value on the left.
1157
444
  assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
1158
444
                                                 E->getRHS()->getType())
1159
444
         && "Invalid assignment");
1160
444
1161
444
  // If the LHS might be a __block variable, and the RHS can
1162
444
  // potentially cause a block copy, we need to evaluate the RHS first
1163
444
  // so that the assignment goes the right place.
1164
444
  // This is pretty semantically fragile.
1165
444
  if (isBlockVarRef(E->getLHS()) &&
1166
444
      
E->getRHS()->HasSideEffects(CGF.getContext())3
) {
1167
3
    // Ensure that we have a destination, and evaluate the RHS into that.
1168
3
    EnsureDest(E->getRHS()->getType());
1169
3
    Visit(E->getRHS());
1170
3
1171
3
    // Now emit the LHS and copy into it.
1172
3
    LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
1173
3
1174
3
    // That copy is an atomic copy if the LHS is atomic.
1175
3
    if (LHS.getType()->isAtomicType() ||
1176
3
        CGF.LValueIsSuitableForInlineAtomic(LHS)) {
1177
0
      CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1178
0
      return;
1179
0
    }
1180
3
1181
3
    EmitCopy(E->getLHS()->getType(),
1182
3
             AggValueSlot::forLValue(LHS, CGF, AggValueSlot::IsDestructed,
1183
3
                                     needsGC(E->getLHS()->getType()),
1184
3
                                     AggValueSlot::IsAliased,
1185
3
                                     AggValueSlot::MayOverlap),
1186
3
             Dest);
1187
3
    return;
1188
3
  }
1189
441
1190
441
  LValue LHS = CGF.EmitLValue(E->getLHS());
1191
441
1192
441
  // If we have an atomic type, evaluate into the destination and then
1193
441
  // do an atomic copy.
1194
441
  if (LHS.getType()->isAtomicType() ||
1195
441
      
CGF.LValueIsSuitableForInlineAtomic(LHS)434
) {
1196
10
    EnsureDest(E->getRHS()->getType());
1197
10
    Visit(E->getRHS());
1198
10
    CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1199
10
    return;
1200
10
  }
1201
431
1202
431
  // Codegen the RHS so that it stores directly into the LHS.
1203
431
  AggValueSlot LHSSlot = AggValueSlot::forLValue(
1204
431
      LHS, CGF, AggValueSlot::IsDestructed, needsGC(E->getLHS()->getType()),
1205
431
      AggValueSlot::IsAliased, AggValueSlot::MayOverlap);
1206
431
  // A non-volatile aggregate destination might have volatile member.
1207
431
  if (!LHSSlot.isVolatile() &&
1208
431
      
CGF.hasVolatileMember(E->getLHS()->getType())421
)
1209
5
    LHSSlot.setVolatile(true);
1210
431
1211
431
  CGF.EmitAggExpr(E->getRHS(), LHSSlot);
1212
431
1213
431
  // Copy into the destination if the assignment isn't ignored.
1214
431
  EmitFinalDestCopy(E->getType(), LHS);
1215
431
}
1216
1217
void AggExprEmitter::
1218
56
VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1219
56
  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1220
56
  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1221
56
  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1222
56
1223
56
  // Bind the common expression if necessary.
1224
56
  CodeGenFunction::OpaqueValueMapping binding(CGF, E);
1225
56
1226
56
  CodeGenFunction::ConditionalEvaluation eval(CGF);
1227
56
  CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
1228
56
                           CGF.getProfileCount(E));
1229
56
1230
56
  // Save whether the destination's lifetime is externally managed.
1231
56
  bool isExternallyDestructed = Dest.isExternallyDestructed();
1232
56
1233
56
  eval.begin(CGF);
1234
56
  CGF.EmitBlock(LHSBlock);
1235
56
  CGF.incrementProfileCounter(E);
1236
56
  Visit(E->getTrueExpr());
1237
56
  eval.end(CGF);
1238
56
1239
56
  assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
1240
56
  CGF.Builder.CreateBr(ContBlock);
1241
56
1242
56
  // If the result of an agg expression is unused, then the emission
1243
56
  // of the LHS might need to create a destination slot.  That's fine
1244
56
  // with us, and we can safely emit the RHS into the same slot, but
1245
56
  // we shouldn't claim that it's already being destructed.
1246
56
  Dest.setExternallyDestructed(isExternallyDestructed);
1247
56
1248
56
  eval.begin(CGF);
1249
56
  CGF.EmitBlock(RHSBlock);
1250
56
  Visit(E->getFalseExpr());
1251
56
  eval.end(CGF);
1252
56
1253
56
  CGF.EmitBlock(ContBlock);
1254
56
}
1255
1256
0
void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
1257
0
  Visit(CE->getChosenSubExpr());
1258
0
}
1259
1260
306
void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1261
306
  Address ArgValue = Address::invalid();
1262
306
  Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
1263
306
1264
306
  // If EmitVAArg fails, emit an error.
1265
306
  if (!ArgPtr.isValid()) {
1266
0
    CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
1267
0
    return;
1268
0
  }
1269
306
1270
306
  EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
1271
306
}
1272
1273
5.87k
void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1274
5.87k
  // Ensure that we have a slot, but if we already do, remember
1275
5.87k
  // whether it was externally destructed.
1276
5.87k
  bool wasExternallyDestructed = Dest.isExternallyDestructed();
1277
5.87k
  EnsureDest(E->getType());
1278
5.87k
1279
5.87k
  // We're going to push a destructor if there isn't already one.
1280
5.87k
  Dest.setExternallyDestructed();
1281
5.87k
1282
5.87k
  Visit(E->getSubExpr());
1283
5.87k
1284
5.87k
  // Push that destructor we promised.
1285
5.87k
  if (!wasExternallyDestructed)
1286
746
    CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
1287
5.87k
}
1288
1289
void
1290
59.2k
AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
1291
59.2k
  AggValueSlot Slot = EnsureSlot(E->getType());
1292
59.2k
  CGF.EmitCXXConstructExpr(E, Slot);
1293
59.2k
}
1294
1295
void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
1296
200
    const CXXInheritedCtorInitExpr *E) {
1297
200
  AggValueSlot Slot = EnsureSlot(E->getType());
1298
200
  CGF.EmitInheritedCXXConstructorCall(
1299
200
      E->getConstructor(), E->constructsVBase(), Slot.getAddress(),
1300
200
      E->inheritedFromVBase(), E);
1301
200
}
1302
1303
void
1304
1.45k
AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1305
1.45k
  AggValueSlot Slot = EnsureSlot(E->getType());
1306
1.45k
  LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType());
1307
1.45k
1308
1.45k
  // We'll need to enter cleanup scopes in case any of the element
1309
1.45k
  // initializers throws an exception.
1310
1.45k
  SmallVector<EHScopeStack::stable_iterator, 16> Cleanups;
1311
1.45k
  llvm::Instruction *CleanupDominator = nullptr;
1312
1.45k
1313
1.45k
  CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1314
1.45k
  for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
1315
1.45k
                                               e = E->capture_init_end();
1316
3.91k
       i != e; 
++i, ++CurField2.45k
) {
1317
2.45k
    // Emit initialization
1318
2.45k
    LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
1319
2.45k
    if (CurField->hasCapturedVLAType()) {
1320
24
      CGF.EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
1321
24
      continue;
1322
24
    }
1323
2.42k
1324
2.42k
    EmitInitializationToLValue(*i, LV);
1325
2.42k
1326
2.42k
    // Push a destructor if necessary.
1327
2.42k
    if (QualType::DestructionKind DtorKind =
1328
26
            CurField->getType().isDestructedType()) {
1329
26
      assert(LV.isSimple());
1330
26
      if (CGF.needsEHCleanup(DtorKind)) {
1331
19
        if (!CleanupDominator)
1332
18
          CleanupDominator = CGF.Builder.CreateAlignedLoad(
1333
18
              CGF.Int8Ty,
1334
18
              llvm::Constant::getNullValue(CGF.Int8PtrTy),
1335
18
              CharUnits::One()); // placeholder
1336
19
1337
19
        CGF.pushDestroy(EHCleanup, LV.getAddress(CGF), CurField->getType(),
1338
19
                        CGF.getDestroyer(DtorKind), false);
1339
19
        Cleanups.push_back(CGF.EHStack.stable_begin());
1340
19
      }
1341
26
    }
1342
2.42k
  }
1343
1.45k
1344
1.45k
  // Deactivate all the partial cleanups in reverse order, which
1345
1.45k
  // generally means popping them.
1346
1.47k
  for (unsigned i = Cleanups.size(); i != 0; 
--i19
)
1347
19
    CGF.DeactivateCleanupBlock(Cleanups[i-1], CleanupDominator);
1348
1.45k
1349
1.45k
  // Destroy the placeholder if we made one.
1350
1.45k
  if (CleanupDominator)
1351
18
    CleanupDominator->eraseFromParent();
1352
1.45k
}
1353
1354
6.42k
void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1355
6.42k
  CGF.enterFullExpression(E);
1356
6.42k
  CodeGenFunction::RunCleanupsScope cleanups(CGF);
1357
6.42k
  Visit(E->getSubExpr());
1358
6.42k
}
1359
1360
0
void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1361
0
  QualType T = E->getType();
1362
0
  AggValueSlot Slot = EnsureSlot(T);
1363
0
  EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1364
0
}
1365
1366
18
void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
1367
18
  QualType T = E->getType();
1368
18
  AggValueSlot Slot = EnsureSlot(T);
1369
18
  EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1370
18
}
1371
1372
/// isSimpleZero - If emitting this value will obviously just cause a store of
1373
/// zero to memory, return true.  This can return false if uncertain, so it just
1374
/// handles simple cases.
1375
4.34k
static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
1376
4.34k
  E = E->IgnoreParens();
1377
4.34k
1378
4.34k
  // 0
1379
4.34k
  if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1380
264
    return IL->getValue() == 0;
1381
4.07k
  // +0.0
1382
4.07k
  if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1383
80
    return FL->getValue().isPosZero();
1384
3.99k
  // int()
1385
3.99k
  if ((isa<ImplicitValueInitExpr>(E) || 
isa<CXXScalarValueInitExpr>(E)3.88k
) &&
1386
3.99k
      
CGF.getTypes().isZeroInitializable(E->getType())114
)
1387
114
    return true;
1388
3.88k
  // (int*)0 - Null pointer expressions.
1389
3.88k
  if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1390
1.45k
    return ICE->getCastKind() == CK_NullToPointer &&
1391
1.45k
           
CGF.getTypes().isPointerZeroInitializable(E->getType())11
&&
1392
1.45k
           
!E->HasSideEffects(CGF.getContext())11
;
1393
2.42k
  // '\0'
1394
2.42k
  if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1395
1
    return CL->getValue() == 0;
1396
2.42k
1397
2.42k
  // Otherwise, hard case: conservatively return false.
1398
2.42k
  return false;
1399
2.42k
}
1400
1401
1402
void
1403
7.83k
AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
1404
7.83k
  QualType type = LV.getType();
1405
7.83k
  // FIXME: Ignore result?
1406
7.83k
  // FIXME: Are initializers affected by volatile?
1407
7.83k
  if (Dest.isZeroed() && 
isSimpleZero(E, CGF)110
) {
1408
45
    // Storing "i32 0" to a zero'd memory location is a noop.
1409
45
    return;
1410
7.78k
  } else if (isa<ImplicitValueInitExpr>(E) || 
isa<CXXScalarValueInitExpr>(E)7.73k
) {
1411
59
    return EmitNullInitializationToLValue(LV);
1412
7.73k
  } else if (isa<NoInitExpr>(E)) {
1413
14
    // Do nothing.
1414
14
    return;
1415
7.71k
  } else if (type->isReferenceType()) {
1416
2.34k
    RValue RV = CGF.EmitReferenceBindingToExpr(E);
1417
2.34k
    return CGF.EmitStoreThroughLValue(RV, LV);
1418
2.34k
  }
1419
5.37k
1420
5.37k
  switch (CGF.getEvaluationKind(type)) {
1421
8
  case TEK_Complex:
1422
8
    CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1423
8
    return;
1424
3.00k
  case TEK_Aggregate:
1425
3.00k
    CGF.EmitAggExpr(
1426
3.00k
        E, AggValueSlot::forLValue(LV, CGF, AggValueSlot::IsDestructed,
1427
3.00k
                                   AggValueSlot::DoesNotNeedGCBarriers,
1428
3.00k
                                   AggValueSlot::IsNotAliased,
1429
3.00k
                                   AggValueSlot::MayOverlap, Dest.isZeroed()));
1430
3.00k
    return;
1431
2.35k
  case TEK_Scalar:
1432
2.35k
    if (LV.isSimple()) {
1433
2.34k
      CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
1434
2.34k
    } else {
1435
11
      CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1436
11
    }
1437
2.35k
    return;
1438
0
  }
1439
0
  llvm_unreachable("bad evaluation kind");
1440
0
}
1441
1442
77
void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1443
77
  QualType type = lv.getType();
1444
77
1445
77
  // If the destination slot is already zeroed out before the aggregate is
1446
77
  // copied into it, we don't have to emit any zeros here.
1447
77
  if (Dest.isZeroed() && 
CGF.getTypes().isZeroInitializable(type)10
)
1448
10
    return;
1449
67
1450
67
  if (CGF.hasScalarEvaluationKind(type)) {
1451
49
    // For non-aggregates, we can store the appropriate null constant.
1452
49
    llvm::Value *null = CGF.CGM.EmitNullConstant(type);
1453
49
    // Note that the following is not equivalent to
1454
49
    // EmitStoreThroughBitfieldLValue for ARC types.
1455
49
    if (lv.isBitField()) {
1456
1
      CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
1457
48
    } else {
1458
48
      assert(lv.isSimple());
1459
48
      CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1460
48
    }
1461
49
  } else {
1462
18
    // There's a potential optimization opportunity in combining
1463
18
    // memsets; that would be easy for arrays, but relatively
1464
18
    // difficult for structures with the current code.
1465
18
    CGF.EmitNullInitialization(lv.getAddress(CGF), lv.getType());
1466
18
  }
1467
67
}
1468
1469
2.86k
void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1470
#if 0
1471
  // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
1472
  // (Length of globals? Chunks of zeroed-out space?).
1473
  //
1474
  // If we can, prefer a copy from a global; this is a lot less code for long
1475
  // globals, and it's easier for the current optimizers to analyze.
1476
  if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
1477
    llvm::GlobalVariable* GV =
1478
    new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1479
                             llvm::GlobalValue::InternalLinkage, C, "");
1480
    EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
1481
    return;
1482
  }
1483
#endif
1484
2.86k
  if (E->hadArrayRangeDesignator())
1485
0
    CGF.ErrorUnsupported(E, "GNU array range designator extension");
1486
2.86k
1487
2.86k
  if (E->isTransparent())
1488
6
    return Visit(E->getInit(0));
1489
2.85k
1490
2.85k
  AggValueSlot Dest = EnsureSlot(E->getType());
1491
2.85k
1492
2.85k
  LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1493
2.85k
1494
2.85k
  // Handle initialization of an array.
1495
2.85k
  if (E->getType()->isArrayType()) {
1496
1.58k
    auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
1497
1.58k
    EmitArrayInit(Dest.getAddress(), AType, E->getType(), E);
1498
1.58k
    return;
1499
1.58k
  }
1500
1.27k
1501
1.27k
  assert(E->getType()->isRecordType() && "Only support structs/unions here!");
1502
1.27k
1503
1.27k
  // Do struct initialization; this code just sets each individual member
1504
1.27k
  // to the approprate value.  This makes bitfield support automatic;
1505
1.27k
  // the disadvantage is that the generated code is more difficult for
1506
1.27k
  // the optimizer, especially with bitfields.
1507
1.27k
  unsigned NumInitElements = E->getNumInits();
1508
1.27k
  RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
1509
1.27k
1510
1.27k
  // We'll need to enter cleanup scopes in case any of the element
1511
1.27k
  // initializers throws an exception.
1512
1.27k
  SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
1513
1.27k
  llvm::Instruction *cleanupDominator = nullptr;
1514
1.27k
  auto addCleanup = [&](const EHScopeStack::stable_iterator &cleanup) {
1515
16
    cleanups.push_back(cleanup);
1516
16
    if (!cleanupDominator) // create placeholder once needed
1517
8
      cleanupDominator = CGF.Builder.CreateAlignedLoad(
1518
8
          CGF.Int8Ty, llvm::Constant::getNullValue(CGF.Int8PtrTy),
1519
8
          CharUnits::One());
1520
16
  };
1521
1.27k
1522
1.27k
  unsigned curInitIndex = 0;
1523
1.27k
1524
1.27k
  // Emit initialization of base classes.
1525
1.27k
  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
1526
836
    assert(E->getNumInits() >= CXXRD->getNumBases() &&
1527
836
           "missing initializer for base class");
1528
836
    for (auto &Base : CXXRD->bases()) {
1529
14
      assert(!Base.isVirtual() && "should not see vbases here");
1530
14
      auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
1531
14
      Address V = CGF.GetAddressOfDirectBaseInCompleteClass(
1532
14
          Dest.getAddress(), CXXRD, BaseRD,
1533
14
          /*isBaseVirtual*/ false);
1534
14
      AggValueSlot AggSlot = AggValueSlot::forAddr(
1535
14
          V, Qualifiers(),
1536
14
          AggValueSlot::IsDestructed,
1537
14
          AggValueSlot::DoesNotNeedGCBarriers,
1538
14
          AggValueSlot::IsNotAliased,
1539
14
          CGF.getOverlapForBaseInit(CXXRD, BaseRD, Base.isVirtual()));
1540
14
      CGF.EmitAggExpr(E->getInit(curInitIndex++), AggSlot);
1541
14
1542
14
      if (QualType::DestructionKind dtorKind =
1543
8
              Base.getType().isDestructedType()) {
1544
8
        CGF.pushDestroy(dtorKind, V, Base.getType());
1545
8
        addCleanup(CGF.EHStack.stable_begin());
1546
8
      }
1547
14
    }
1548
836
  }
1549
1.27k
1550
1.27k
  // Prepare a 'this' for CXXDefaultInitExprs.
1551
1.27k
  CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
1552
1.27k
1553
1.27k
  if (record->isUnion()) {
1554
47
    // Only initialize one field of a union. The field itself is
1555
47
    // specified by the initializer list.
1556
47
    if (!E->getInitializedFieldInUnion()) {
1557
12
      // Empty union; we have nothing to do.
1558
12
1559
12
#ifndef NDEBUG
1560
12
      // Make sure that it's really an empty and not a failure of
1561
12
      // semantic analysis.
1562
12
      for (const auto *Field : record->fields())
1563
12
        assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1564
12
#endif
1565
12
      return;
1566
12
    }
1567
35
1568
35
    // FIXME: volatility
1569
35
    FieldDecl *Field = E->getInitializedFieldInUnion();
1570
35
1571
35
    LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
1572
35
    if (NumInitElements) {
1573
35
      // Store the initializer into the field
1574
35
      EmitInitializationToLValue(E->getInit(0), FieldLoc);
1575
35
    } else {
1576
0
      // Default-initialize to null.
1577
0
      EmitNullInitializationToLValue(FieldLoc);
1578
0
    }
1579
35
1580
35
    return;
1581
35
  }
1582
1.22k
1583
1.22k
  // Here we iterate over the fields; this makes it simpler to both
1584
1.22k
  // default-initialize fields and skip over unnamed fields.
1585
2.13k
  
for (const auto *field : record->fields())1.22k
{
1586
2.13k
    // We're done once we hit the flexible array member.
1587
2.13k
    if (field->getType()->isIncompleteArrayType())
1588
0
      break;
1589
2.13k
1590
2.13k
    // Always skip anonymous bitfields.
1591
2.13k
    if (field->isUnnamedBitfield())
1592
24
      continue;
1593
2.10k
1594
2.10k
    // We're done if we reach the end of the explicit initializers, we
1595
2.10k
    // have a zeroed object, and the rest of the fields are
1596
2.10k
    // zero-initializable.
1597
2.10k
    if (curInitIndex == NumInitElements && 
Dest.isZeroed()0
&&
1598
2.10k
        
CGF.getTypes().isZeroInitializable(E->getType())0
)
1599
0
      break;
1600
2.10k
1601
2.10k
1602
2.10k
    LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
1603
2.10k
    // We never generate write-barries for initialized fields.
1604
2.10k
    LV.setNonGC(true);
1605
2.10k
1606
2.10k
    if (curInitIndex < NumInitElements) {
1607
2.10k
      // Store the initializer into the field.
1608
2.10k
      EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
1609
2.10k
    } else {
1610
0
      // We're out of initializers; default-initialize to null
1611
0
      EmitNullInitializationToLValue(LV);
1612
0
    }
1613
2.10k
1614
2.10k
    // Push a destructor if necessary.
1615
2.10k
    // FIXME: if we have an array of structures, all explicitly
1616
2.10k
    // initialized, we can end up pushing a linear number of cleanups.
1617
2.10k
    bool pushedCleanup = false;
1618
2.10k
    if (QualType::DestructionKind dtorKind
1619
56
          = field->getType().isDestructedType()) {
1620
56
      assert(LV.isSimple());
1621
56
      if (CGF.needsEHCleanup(dtorKind)) {
1622
8
        CGF.pushDestroy(EHCleanup, LV.getAddress(CGF), field->getType(),
1623
8
                        CGF.getDestroyer(dtorKind), false);
1624
8
        addCleanup(CGF.EHStack.stable_begin());
1625
8
        pushedCleanup = true;
1626
8
      }
1627
56
    }
1628
2.10k
1629
2.10k
    // If the GEP didn't get used because of a dead zero init or something
1630
2.10k
    // else, clean it up for -O0 builds and general tidiness.
1631
2.10k
    if (!pushedCleanup && 
LV.isSimple()2.10k
)
1632
2.08k
      if (llvm::GetElementPtrInst *GEP =
1633
2.00k
              dyn_cast<llvm::GetElementPtrInst>(LV.getPointer(CGF)))
1634
2.00k
        if (GEP->use_empty())
1635
85
          GEP->eraseFromParent();
1636
2.10k
  }
1637
1.22k
1638
1.22k
  // Deactivate all the partial cleanups in reverse order, which
1639
1.22k
  // generally means popping them.
1640
1.22k
  assert((cleanupDominator || cleanups.empty()) &&
1641
1.22k
         "Missing cleanupDominator before deactivating cleanup blocks");
1642
1.23k
  for (unsigned i = cleanups.size(); i != 0; 
--i16
)
1643
16
    CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1644
1.22k
1645
1.22k
  // Destroy the placeholder if we made one.
1646
1.22k
  if (cleanupDominator)
1647
8
    cleanupDominator->eraseFromParent();
1648
1.22k
}
1649
1650
void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
1651
28
                                            llvm::Value *outerBegin) {
1652
28
  // Emit the common subexpression.
1653
28
  CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
1654
28
1655
28
  Address destPtr = EnsureSlot(E->getType()).getAddress();
1656
28
  uint64_t numElements = E->getArraySize().getZExtValue();
1657
28
1658
28
  if (!numElements)
1659
0
    return;
1660
28
1661
28
  // destPtr is an array*. Construct an elementType* by drilling down a level.
1662
28
  llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1663
28
  llvm::Value *indices[] = {zero, zero};
1664
28
  llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getPointer(), indices,
1665
28
                                                 "arrayinit.begin");
1666
28
1667
28
  // Prepare to special-case multidimensional array initialization: we avoid
1668
28
  // emitting multiple destructor loops in that case.
1669
28
  if (!outerBegin)
1670
21
    outerBegin = begin;
1671
28
  ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
1672
28
1673
28
  QualType elementType =
1674
28
      CGF.getContext().getAsArrayType(E->getType())->getElementType();
1675
28
  CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1676
28
  CharUnits elementAlign =
1677
28
      destPtr.getAlignment().alignmentOfArrayElement(elementSize);
1678
28
1679
28
  llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1680
28
  llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
1681
28
1682
28
  // Jump into the body.
1683
28
  CGF.EmitBlock(bodyBB);
1684
28
  llvm::PHINode *index =
1685
28
      Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
1686
28
  index->addIncoming(zero, entryBB);
1687
28
  llvm::Value *element = Builder.CreateInBoundsGEP(begin, index);
1688
28
1689
28
  // Prepare for a cleanup.
1690
28
  QualType::DestructionKind dtorKind = elementType.isDestructedType();
1691
28
  EHScopeStack::stable_iterator cleanup;
1692
28
  if (CGF.needsEHCleanup(dtorKind) && 
!InnerLoop6
) {
1693
5
    if (outerBegin->getType() != element->getType())
1694
1
      outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
1695
5
    CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
1696
5
                                       elementAlign,
1697
5
                                       CGF.getDestroyer(dtorKind));
1698
5
    cleanup = CGF.EHStack.stable_begin();
1699
23
  } else {
1700
23
    dtorKind = QualType::DK_none;
1701
23
  }
1702
28
1703
28
  // Emit the actual filler expression.
1704
28
  {
1705
28
    // Temporaries created in an array initialization loop are destroyed
1706
28
    // at the end of each iteration.
1707
28
    CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
1708
28
    CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
1709
28
    LValue elementLV =
1710
28
        CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
1711
28
1712
28
    if (InnerLoop) {
1713
7
      // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
1714
7
      auto elementSlot = AggValueSlot::forLValue(
1715
7
          elementLV, CGF, AggValueSlot::IsDestructed,
1716
7
          AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
1717
7
          AggValueSlot::DoesNotOverlap);
1718
7
      AggExprEmitter(CGF, elementSlot, false)
1719
7
          .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
1720
7
    } else
1721
21
      EmitInitializationToLValue(E->getSubExpr(), elementLV);
1722
28
  }
1723
28
1724
28
  // Move on to the next element.
1725
28
  llvm::Value *nextIndex = Builder.CreateNUWAdd(
1726
28
      index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
1727
28
  index->addIncoming(nextIndex, Builder.GetInsertBlock());
1728
28
1729
28
  // Leave the loop if we're done.
1730
28
  llvm::Value *done = Builder.CreateICmpEQ(
1731
28
      nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
1732
28
      "arrayinit.done");
1733
28
  llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
1734
28
  Builder.CreateCondBr(done, endBB, bodyBB);
1735
28
1736
28
  CGF.EmitBlock(endBB);
1737
28
1738
28
  // Leave the partial-array cleanup if we entered one.
1739
28
  if (dtorKind)
1740
5
    CGF.DeactivateCleanupBlock(cleanup, index);
1741
28
}
1742
1743
8
void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
1744
8
  AggValueSlot Dest = EnsureSlot(E->getType());
1745
8
1746
8
  LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1747
8
  EmitInitializationToLValue(E->getBase(), DestLV);
1748
8
  VisitInitListExpr(E->getUpdater());
1749
8
}
1750
1751
//===----------------------------------------------------------------------===//
1752
//                        Entry Points into this File
1753
//===----------------------------------------------------------------------===//
1754
1755
/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1756
/// non-zero bytes that will be stored when outputting the initializer for the
1757
/// specified initializer expression.
1758
4.23k
static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
1759
4.23k
  E = E->IgnoreParens();
1760
4.23k
1761
4.23k
  // 0 and 0.0 won't require any non-zero stores!
1762
4.23k
  if (isSimpleZero(E, CGF)) 
return CharUnits::Zero()94
;
1763
4.13k
1764
4.13k
  // If this is an initlist expr, sum up the size of sizes of the (present)
1765
4.13k
  // elements.  If this is something weird, assume the whole thing is non-zero.
1766
4.13k
  const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
1767
4.13k
  while (ILE && 
ILE->isTransparent()206
)
1768
2
    ILE = dyn_cast<InitListExpr>(ILE->getInit(0));
1769
4.13k
  if (!ILE || 
!CGF.getTypes().isZeroInitializable(ILE->getType())204
)
1770
3.93k
    return CGF.getContext().getTypeSizeInChars(E->getType());
1771
204
1772
204
  // InitListExprs for structs have to be handled carefully.  If there are
1773
204
  // reference members, we need to consider the size of the reference, not the
1774
204
  // referencee.  InitListExprs for unions and arrays can't have references.
1775
204
  if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1776
98
    if (!RT->isUnionType()) {
1777
95
      RecordDecl *SD = RT->getDecl();
1778
95
      CharUnits NumNonZeroBytes = CharUnits::Zero();
1779
95
1780
95
      unsigned ILEElement = 0;
1781
95
      if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))
1782
61
        while (ILEElement != CXXRD->getNumBases())
1783
0
          NumNonZeroBytes +=
1784
0
              GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);
1785
384
      for (const auto *Field : SD->fields()) {
1786
384
        // We're done once we hit the flexible array member or run out of
1787
384
        // InitListExpr elements.
1788
384
        if (Field->getType()->isIncompleteArrayType() ||
1789
384
            ILEElement == ILE->getNumInits())
1790
0
          break;
1791
384
        if (Field->isUnnamedBitfield())
1792
0
          continue;
1793
384
1794
384
        const Expr *E = ILE->getInit(ILEElement++);
1795
384
1796
384
        // Reference values are always non-null and have the width of a pointer.
1797
384
        if (Field->getType()->isReferenceType())
1798
4
          NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1799
4
              CGF.getTarget().getPointerWidth(0));
1800
380
        else
1801
380
          NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1802
384
      }
1803
95
1804
95
      return NumNonZeroBytes;
1805
95
    }
1806
109
  }
1807
109
1808
109
1809
109
  CharUnits NumNonZeroBytes = CharUnits::Zero();
1810
461
  for (unsigned i = 0, e = ILE->getNumInits(); i != e; 
++i352
)
1811
352
    NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1812
109
  return NumNonZeroBytes;
1813
109
}
1814
1815
/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1816
/// zeros in it, emit a memset and avoid storing the individual zeros.
1817
///
1818
static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1819
74.7k
                                     CodeGenFunction &CGF) {
1820
74.7k
  // If the slot is already known to be zeroed, nothing to do.  Don't mess with
1821
74.7k
  // volatile stores.
1822
74.7k
  if (Slot.isZeroed() || 
Slot.isVolatile()74.7k
||
!Slot.getAddress().isValid()74.7k
)
1823
1.50k
    return;
1824
73.2k
1825
73.2k
  // C++ objects with a user-declared constructor don't need zero'ing.
1826
73.2k
  if (CGF.getLangOpts().CPlusPlus)
1827
68.5k
    if (const RecordType *RT = CGF.getContext()
1828
68.3k
                       .getBaseElementType(E->getType())->getAs<RecordType>()) {
1829
68.3k
      const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1830
68.3k
      if (RD->hasUserDeclaredConstructor())
1831
47.1k
        return;
1832
26.1k
    }
1833
26.1k
1834
26.1k
  // If the type is 16-bytes or smaller, prefer individual stores over memset.
1835
26.1k
  CharUnits Size = Slot.getPreferredSize(CGF.getContext(), E->getType());
1836
26.1k
  if (Size <= CharUnits::fromQuantity(16))
1837
22.6k
    return;
1838
3.49k
1839
3.49k
  // Check to see if over 3/4 of the initializer are known to be zero.  If so,
1840
3.49k
  // we prefer to emit memset + individual stores for the rest.
1841
3.49k
  CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1842
3.49k
  if (NumNonZeroBytes*4 > Size)
1843
3.45k
    return;
1844
42
1845
42
  // Okay, it seems like a good idea to use an initial memset, emit the call.
1846
42
  llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
1847
42
1848
42
  Address Loc = Slot.getAddress();
1849
42
  Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty);
1850
42
  CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
1851
42
1852
42
  // Tell the AggExprEmitter that the slot is known zero.
1853
42
  Slot.setZeroed();
1854
42
}
1855
1856
1857
1858
1859
/// EmitAggExpr - Emit the computation of the specified expression of aggregate
1860
/// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
1861
/// the value of the aggregate expression is not needed.  If VolatileDest is
1862
/// true, DestPtr cannot be 0.
1863
74.7k
void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
1864
74.7k
  assert(E && hasAggregateEvaluationKind(E->getType()) &&
1865
74.7k
         "Invalid aggregate expression to emit");
1866
74.7k
  assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
1867
74.7k
         "slot has bits but no address");
1868
74.7k
1869
74.7k
  // Optimize the slot if possible.
1870
74.7k
  CheckAggExprForMemSetUse(Slot, E, *this);
1871
74.7k
1872
74.7k
  AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
1873
74.7k
}
1874
1875
79
LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1876
79
  assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
1877
79
  Address Temp = CreateMemTemp(E->getType());
1878
79
  LValue LV = MakeAddrLValue(Temp, E->getType());
1879
79
  EmitAggExpr(E, AggValueSlot::forLValue(
1880
79
                     LV, *this, AggValueSlot::IsNotDestructed,
1881
79
                     AggValueSlot::DoesNotNeedGCBarriers,
1882
79
                     AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap));
1883
79
  return LV;
1884
79
}
1885
1886
AggValueSlot::Overlap_t
1887
4.22k
CodeGenFunction::getOverlapForFieldInit(const FieldDecl *FD) {
1888
4.22k
  if (!FD->hasAttr<NoUniqueAddressAttr>() || 
!FD->getType()->isRecordType()3
)
1889
4.21k
    return AggValueSlot::DoesNotOverlap;
1890
3
1891
3
  // If the field lies entirely within the enclosing class's nvsize, its tail
1892
3
  // padding cannot overlap any already-initialized object. (The only subobjects
1893
3
  // with greater addresses that might already be initialized are vbases.)
1894
3
  const RecordDecl *ClassRD = FD->getParent();
1895
3
  const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassRD);
1896
3
  if (Layout.getFieldOffset(FD->getFieldIndex()) +
1897
3
          getContext().getTypeSize(FD->getType()) <=
1898
3
      (uint64_t)getContext().toBits(Layout.getNonVirtualSize()))
1899
1
    return AggValueSlot::DoesNotOverlap;
1900
2
1901
2
  // The tail padding may contain values we need to preserve.
1902
2
  return AggValueSlot::MayOverlap;
1903
2
}
1904
1905
AggValueSlot::Overlap_t CodeGenFunction::getOverlapForBaseInit(
1906
9.39k
    const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual) {
1907
9.39k
  // If the most-derived object is a field declared with [[no_unique_address]],
1908
9.39k
  // the tail padding of any virtual base could be reused for other subobjects
1909
9.39k
  // of that field's class.
1910
9.39k
  if (IsVirtual)
1911
779
    return AggValueSlot::MayOverlap;
1912
8.62k
1913
8.62k
  // If the base class is laid out entirely within the nvsize of the derived
1914
8.62k
  // class, its tail padding cannot yet be initialized, so we can issue
1915
8.62k
  // stores at the full width of the base class.
1916
8.62k
  const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1917
8.62k
  if (Layout.getBaseClassOffset(BaseRD) +
1918
8.62k
          getContext().getASTRecordLayout(BaseRD).getSize() <=
1919
8.62k
      Layout.getNonVirtualSize())
1920
8.32k
    return AggValueSlot::DoesNotOverlap;
1921
292
1922
292
  // The tail padding may contain values we need to preserve.
1923
292
  return AggValueSlot::MayOverlap;
1924
292
}
1925
1926
void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty,
1927
                                        AggValueSlot::Overlap_t MayOverlap,
1928
12.9k
                                        bool isVolatile) {
1929
12.9k
  assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
1930
12.9k
1931
12.9k
  Address DestPtr = Dest.getAddress(*this);
1932
12.9k
  Address SrcPtr = Src.getAddress(*this);
1933
12.9k
1934
12.9k
  if (getLangOpts().CPlusPlus) {
1935
10.4k
    if (const RecordType *RT = Ty->getAs<RecordType>()) {
1936
9.43k
      CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1937
9.43k
      assert((Record->hasTrivialCopyConstructor() ||
1938
9.43k
              Record->hasTrivialCopyAssignment() ||
1939
9.43k
              Record->hasTrivialMoveConstructor() ||
1940
9.43k
              Record->hasTrivialMoveAssignment() ||
1941
9.43k
              Record->isUnion()) &&
1942
9.43k
             "Trying to aggregate-copy a type without a trivial copy/move "
1943
9.43k
             "constructor or assignment operator");
1944
9.43k
      // Ignore empty classes in C++.
1945
9.43k
      if (Record->isEmpty())
1946
3.50k
        return;
1947
9.44k
    }
1948
10.4k
  }
1949
9.44k
1950
9.44k
  if (getLangOpts().CUDAIsDevice) {
1951
3
    if (Ty->isCUDADeviceBuiltinSurfaceType()) {
1952
1
      if (getTargetHooks().emitCUDADeviceBuiltinSurfaceDeviceCopy(*this, Dest,
1953
1
                                                                  Src))
1954
1
        return;
1955
2
    } else if (Ty->isCUDADeviceBuiltinTextureType()) {
1956
2
      if (getTargetHooks().emitCUDADeviceBuiltinTextureDeviceCopy(*this, Dest,
1957
2
                                                                  Src))
1958
2
        return;
1959
9.44k
    }
1960
3
  }
1961
9.44k
1962
9.44k
  // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
1963
9.44k
  // C99 6.5.16.1p3, which states "If the value being stored in an object is
1964
9.44k
  // read from another object that overlaps in anyway the storage of the first
1965
9.44k
  // object, then the overlap shall be exact and the two objects shall have
1966
9.44k
  // qualified or unqualified versions of a compatible type."
1967
9.44k
  //
1968
9.44k
  // memcpy is not defined if the source and destination pointers are exactly
1969
9.44k
  // equal, but other compilers do this optimization, and almost every memcpy
1970
9.44k
  // implementation handles this case safely.  If there is a libc that does not
1971
9.44k
  // safely handle this, we can add a target hook.
1972
9.44k
1973
9.44k
  // Get data size info for this aggregate. Don't copy the tail padding if this
1974
9.44k
  // might be a potentially-overlapping subobject, since the tail padding might
1975
9.44k
  // be occupied by a different object. Otherwise, copying it is fine.
1976
9.44k
  std::pair<CharUnits, CharUnits> TypeInfo;
1977
9.44k
  if (MayOverlap)
1978
4.09k
    TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
1979
5.35k
  else
1980
5.35k
    TypeInfo = getContext().getTypeInfoInChars(Ty);
1981
9.44k
1982
9.44k
  llvm::Value *SizeVal = nullptr;
1983
9.44k
  if (TypeInfo.first.isZero()) {
1984
94
    // But note that getTypeInfo returns 0 for a VLA.
1985
94
    if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
1986
40
            getContext().getAsArrayType(Ty))) {
1987
40
      QualType BaseEltTy;
1988
40
      SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
1989
40
      TypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
1990
40
      assert(!TypeInfo.first.isZero());
1991
40
      SizeVal = Builder.CreateNUWMul(
1992
40
          SizeVal,
1993
40
          llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
1994
40
    }
1995
94
  }
1996
9.44k
  if (!SizeVal) {
1997
9.40k
    SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity());
1998
9.40k
  }
1999
9.44k
2000
9.44k
  // FIXME: If we have a volatile struct, the optimizer can remove what might
2001
9.44k
  // appear to be `extra' memory ops:
2002
9.44k
  //
2003
9.44k
  // volatile struct { int i; } a, b;
2004
9.44k
  //
2005
9.44k
  // int main() {
2006
9.44k
  //   a = b;
2007
9.44k
  //   a = b;
2008
9.44k
  // }
2009
9.44k
  //
2010
9.44k
  // we need to use a different call here.  We use isVolatile to indicate when
2011
9.44k
  // either the source or the destination is volatile.
2012
9.44k
2013
9.44k
  DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
2014
9.44k
  SrcPtr = Builder.CreateElementBitCast(SrcPtr, Int8Ty);
2015
9.44k
2016
9.44k
  // Don't do any of the memmove_collectable tests if GC isn't set.
2017
9.44k
  if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
2018
9.41k
    // fall through
2019
9.41k
  } else 
if (const RecordType *30
RecordTy30
= Ty->getAs<RecordType>()) {
2020
28
    RecordDecl *Record = RecordTy->getDecl();
2021
28
    if (Record->hasObjectMember()) {
2022
23
      CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
2023
23
                                                    SizeVal);
2024
23
      return;
2025
23
    }
2026
2
  } else if (Ty->isArrayType()) {
2027
2
    QualType BaseType = getContext().getBaseElementType(Ty);
2028
2
    if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
2029
1
      if (RecordTy->getDecl()->hasObjectMember()) {
2030
1
        CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
2031
1
                                                      SizeVal);
2032
1
        return;
2033
1
      }
2034
9.41k
    }
2035
2
  }
2036
9.41k
2037
9.41k
  auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
2038
9.41k
2039
9.41k
  // Determine the metadata to describe the position of any padding in this
2040
9.41k
  // memcpy, as well as the TBAA tags for the members of the struct, in case
2041
9.41k
  // the optimizer wishes to expand it in to scalar memory operations.
2042
9.41k
  if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
2043
261
    Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
2044
9.41k
2045
9.41k
  if (CGM.getCodeGenOpts().NewStructPathTBAA) {
2046
7
    TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer(
2047
7
        Dest.getTBAAInfo(), Src.getTBAAInfo());
2048
7
    CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo);
2049
7
  }
2050
9.41k
}