Coverage Report

Created: 2021-08-24 07:12

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