Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Sema/SemaInit.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
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 file implements semantic analysis for initializers.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTContext.h"
14
#include "clang/AST/DeclObjC.h"
15
#include "clang/AST/ExprCXX.h"
16
#include "clang/AST/ExprObjC.h"
17
#include "clang/AST/ExprOpenMP.h"
18
#include "clang/AST/TypeLoc.h"
19
#include "clang/Basic/TargetInfo.h"
20
#include "clang/Sema/Designator.h"
21
#include "clang/Sema/Initialization.h"
22
#include "clang/Sema/Lookup.h"
23
#include "clang/Sema/SemaInternal.h"
24
#include "llvm/ADT/APInt.h"
25
#include "llvm/ADT/SmallString.h"
26
#include "llvm/Support/ErrorHandling.h"
27
#include "llvm/Support/raw_ostream.h"
28
29
using namespace clang;
30
31
//===----------------------------------------------------------------------===//
32
// Sema Initialization Checking
33
//===----------------------------------------------------------------------===//
34
35
/// Check whether T is compatible with a wide character type (wchar_t,
36
/// char16_t or char32_t).
37
892
static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38
892
  if (Context.typesAreCompatible(Context.getWideCharType(), T))
39
34
    return true;
40
858
  if (Context.getLangOpts().CPlusPlus || 
Context.getLangOpts().C11326
) {
41
838
    return Context.typesAreCompatible(Context.Char16Ty, T) ||
42
838
           
Context.typesAreCompatible(Context.Char32Ty, T)828
;
43
838
  }
44
20
  return false;
45
20
}
46
47
enum StringInitFailureKind {
48
  SIF_None,
49
  SIF_NarrowStringIntoWideChar,
50
  SIF_WideStringIntoChar,
51
  SIF_IncompatWideStringIntoWideChar,
52
  SIF_UTF8StringIntoPlainChar,
53
  SIF_PlainStringIntoUTF8Char,
54
  SIF_Other
55
};
56
57
/// Check whether the array of type AT can be initialized by the Init
58
/// expression by means of string initialization. Returns SIF_None if so,
59
/// otherwise returns a StringInitFailureKind that describes why the
60
/// initialization would not work.
61
static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
62
90.7k
                                          ASTContext &Context) {
63
90.7k
  if (!isa<ConstantArrayType>(AT) && 
!isa<IncompleteArrayType>(AT)31.8k
)
64
16
    return SIF_Other;
65
90.6k
66
90.6k
  // See if this is a string literal or @encode.
67
90.6k
  Init = Init->IgnoreParens();
68
90.6k
69
90.6k
  // Handle @encode, which is a narrow string.
70
90.6k
  if (isa<ObjCEncodeExpr>(Init) && 
AT->getElementType()->isCharType()41
)
71
41
    return SIF_None;
72
90.6k
73
90.6k
  // Otherwise we can only handle string literals.
74
90.6k
  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
75
90.6k
  if (!SL)
76
87.3k
    return SIF_Other;
77
3.32k
78
3.32k
  const QualType ElemTy =
79
3.32k
      Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
80
3.32k
81
3.32k
  switch (SL->getKind()) {
82
3.32k
  case StringLiteral::UTF8:
83
18
    // char8_t array can be initialized with a UTF-8 string.
84
18
    if (ElemTy->isChar8Type())
85
2
      return SIF_None;
86
16
    LLVM_FALLTHROUGH;
87
3.23k
  case StringLiteral::Ascii:
88
3.23k
    // char array can be initialized with a narrow string.
89
3.23k
    // Only allow char x[] = "foo";  not char x[] = L"foo";
90
3.23k
    if (ElemTy->isCharType())
91
2.64k
      return (SL->getKind() == StringLiteral::UTF8 &&
92
2.64k
              
Context.getLangOpts().Char87
)
93
2.64k
                 ? 
SIF_UTF8StringIntoPlainChar3
94
2.64k
                 : 
SIF_None2.64k
;
95
589
    if (ElemTy->isChar8Type())
96
2
      return SIF_PlainStringIntoUTF8Char;
97
587
    if (IsWideCharCompatible(ElemTy, Context))
98
31
      return SIF_NarrowStringIntoWideChar;
99
556
    return SIF_Other;
100
556
  // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
101
556
  // "An array with element type compatible with a qualified or unqualified
102
556
  // version of wchar_t, char16_t, or char32_t may be initialized by a wide
103
556
  // string literal with the corresponding encoding prefix (L, u, or U,
104
556
  // respectively), optionally enclosed in braces.
105
556
  case StringLiteral::UTF16:
106
16
    if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
107
7
      return SIF_None;
108
9
    if (ElemTy->isCharType() || 
ElemTy->isChar8Type()7
)
109
2
      return SIF_WideStringIntoChar;
110
7
    if (IsWideCharCompatible(ElemTy, Context))
111
5
      return SIF_IncompatWideStringIntoWideChar;
112
2
    return SIF_Other;
113
12
  case StringLiteral::UTF32:
114
12
    if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
115
3
      return SIF_None;
116
9
    if (ElemTy->isCharType() || 
ElemTy->isChar8Type()7
)
117
2
      return SIF_WideStringIntoChar;
118
7
    if (IsWideCharCompatible(ElemTy, Context))
119
5
      return SIF_IncompatWideStringIntoWideChar;
120
2
    return SIF_Other;
121
54
  case StringLiteral::Wide:
122
54
    if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
123
41
      return SIF_None;
124
13
    if (ElemTy->isCharType() || 
ElemTy->isChar8Type()9
)
125
4
      return SIF_WideStringIntoChar;
126
9
    if (IsWideCharCompatible(ElemTy, Context))
127
4
      return SIF_IncompatWideStringIntoWideChar;
128
5
    return SIF_Other;
129
0
  }
130
0
131
0
  llvm_unreachable("missed a StringLiteral kind?");
132
0
}
133
134
static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
135
5.83k
                                          ASTContext &Context) {
136
5.83k
  const ArrayType *arrayType = Context.getAsArrayType(declType);
137
5.83k
  if (!arrayType)
138
3.78k
    return SIF_Other;
139
2.05k
  return IsStringInit(init, arrayType, Context);
140
2.05k
}
141
142
/// Update the type of a string literal, including any surrounding parentheses,
143
/// to match the type of the object which it is initializing.
144
2.27k
static void updateStringLiteralType(Expr *E, QualType Ty) {
145
2.28k
  while (true) {
146
2.28k
    E->setType(Ty);
147
2.28k
    E->setValueKind(VK_RValue);
148
2.28k
    if (isa<StringLiteral>(E) || 
isa<ObjCEncodeExpr>(E)54
) {
149
2.27k
      break;
150
2.27k
    } else 
if (ParenExpr *16
PE16
= dyn_cast<ParenExpr>(E)) {
151
10
      E = PE->getSubExpr();
152
10
    } else 
if (UnaryOperator *6
UO6
= dyn_cast<UnaryOperator>(E)) {
153
4
      assert(UO->getOpcode() == UO_Extension);
154
4
      E = UO->getSubExpr();
155
4
    } else 
if (GenericSelectionExpr *2
GSE2
= dyn_cast<GenericSelectionExpr>(E)) {
156
2
      E = GSE->getResultExpr();
157
2
    } else 
if (ChooseExpr *0
CE0
= dyn_cast<ChooseExpr>(E)) {
158
0
      E = CE->getChosenSubExpr();
159
0
    } else {
160
0
      llvm_unreachable("unexpected expr in string literal init");
161
0
    }
162
2.28k
  }
163
2.27k
}
164
165
/// Fix a compound literal initializing an array so it's correctly marked
166
/// as an rvalue.
167
17
static void updateGNUCompoundLiteralRValue(Expr *E) {
168
23
  while (true) {
169
23
    E->setValueKind(VK_RValue);
170
23
    if (isa<CompoundLiteralExpr>(E)) {
171
17
      break;
172
17
    } else 
if (ParenExpr *6
PE6
= dyn_cast<ParenExpr>(E)) {
173
3
      E = PE->getSubExpr();
174
3
    } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
175
1
      assert(UO->getOpcode() == UO_Extension);
176
1
      E = UO->getSubExpr();
177
2
    } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
178
1
      E = GSE->getResultExpr();
179
1
    } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
180
1
      E = CE->getChosenSubExpr();
181
1
    } else {
182
0
      llvm_unreachable("unexpected expr in array compound literal init");
183
0
    }
184
23
  }
185
17
}
186
187
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
188
2.27k
                            Sema &S) {
189
2.27k
  // Get the length of the string as parsed.
190
2.27k
  auto *ConstantArrayTy =
191
2.27k
      cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
192
2.27k
  uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
193
2.27k
194
2.27k
  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
195
1.50k
    // C99 6.7.8p14. We have an array of character type with unknown size
196
1.50k
    // being initialized to a string literal.
197
1.50k
    llvm::APInt ConstVal(32, StrLength);
198
1.50k
    // Return a new array type (C99 6.7.8p22).
199
1.50k
    DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
200
1.50k
                                           ConstVal,
201
1.50k
                                           ArrayType::Normal, 0);
202
1.50k
    updateStringLiteralType(Str, DeclT);
203
1.50k
    return;
204
1.50k
  }
205
773
206
773
  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
207
773
208
773
  // We have an array of character type with known size.  However,
209
773
  // the size may be smaller or larger than the string we are initializing.
210
773
  // FIXME: Avoid truncation for 64-bit length strings.
211
773
  if (S.getLangOpts().CPlusPlus) {
212
342
    if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
213
342
      // For Pascal strings it's OK to strip off the terminating null character,
214
342
      // so the example below is valid:
215
342
      //
216
342
      // unsigned char a[2] = "\pa";
217
342
      if (SL->isPascal())
218
5
        StrLength--;
219
342
    }
220
342
221
342
    // [dcl.init.string]p2
222
342
    if (StrLength > CAT->getSize().getZExtValue())
223
4
      S.Diag(Str->getBeginLoc(),
224
4
             diag::err_initializer_string_for_char_array_too_long)
225
4
          << Str->getSourceRange();
226
431
  } else {
227
431
    // C99 6.7.8p14.
228
431
    if (StrLength-1 > CAT->getSize().getZExtValue())
229
16
      S.Diag(Str->getBeginLoc(),
230
16
             diag::ext_initializer_string_for_char_array_too_long)
231
16
          << Str->getSourceRange();
232
431
  }
233
773
234
773
  // Set the type to the actual size that we are initializing.  If we have
235
773
  // something like:
236
773
  //   char x[1] = "foo";
237
773
  // then this will set the string literal's type to char[1].
238
773
  updateStringLiteralType(Str, DeclT);
239
773
}
240
241
//===----------------------------------------------------------------------===//
242
// Semantic checking for initializer lists.
243
//===----------------------------------------------------------------------===//
244
245
namespace {
246
247
/// Semantic checking for initializer lists.
248
///
249
/// The InitListChecker class contains a set of routines that each
250
/// handle the initialization of a certain kind of entity, e.g.,
251
/// arrays, vectors, struct/union types, scalars, etc. The
252
/// InitListChecker itself performs a recursive walk of the subobject
253
/// structure of the type to be initialized, while stepping through
254
/// the initializer list one element at a time. The IList and Index
255
/// parameters to each of the Check* routines contain the active
256
/// (syntactic) initializer list and the index into that initializer
257
/// list that represents the current initializer. Each routine is
258
/// responsible for moving that Index forward as it consumes elements.
259
///
260
/// Each Check* routine also has a StructuredList/StructuredIndex
261
/// arguments, which contains the current "structured" (semantic)
262
/// initializer list and the index into that initializer list where we
263
/// are copying initializers as we map them over to the semantic
264
/// list. Once we have completed our recursive walk of the subobject
265
/// structure, we will have constructed a full semantic initializer
266
/// list.
267
///
268
/// C99 designators cause changes in the initializer list traversal,
269
/// because they make the initialization "jump" into a specific
270
/// subobject and then continue the initialization from that
271
/// point. CheckDesignatedInitializer() recursively steps into the
272
/// designated subobject and manages backing out the recursion to
273
/// initialize the subobjects after the one designated.
274
class InitListChecker {
275
  Sema &SemaRef;
276
  bool hadError;
277
  bool VerifyOnly; // no diagnostics, no structure building
278
  bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
279
  llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
280
  InitListExpr *FullyStructuredList;
281
282
  void CheckImplicitInitList(const InitializedEntity &Entity,
283
                             InitListExpr *ParentIList, QualType T,
284
                             unsigned &Index, InitListExpr *StructuredList,
285
                             unsigned &StructuredIndex);
286
  void CheckExplicitInitList(const InitializedEntity &Entity,
287
                             InitListExpr *IList, QualType &T,
288
                             InitListExpr *StructuredList,
289
                             bool TopLevelObject = false);
290
  void CheckListElementTypes(const InitializedEntity &Entity,
291
                             InitListExpr *IList, QualType &DeclType,
292
                             bool SubobjectIsDesignatorContext,
293
                             unsigned &Index,
294
                             InitListExpr *StructuredList,
295
                             unsigned &StructuredIndex,
296
                             bool TopLevelObject = false);
297
  void CheckSubElementType(const InitializedEntity &Entity,
298
                           InitListExpr *IList, QualType ElemType,
299
                           unsigned &Index,
300
                           InitListExpr *StructuredList,
301
                           unsigned &StructuredIndex);
302
  void CheckComplexType(const InitializedEntity &Entity,
303
                        InitListExpr *IList, QualType DeclType,
304
                        unsigned &Index,
305
                        InitListExpr *StructuredList,
306
                        unsigned &StructuredIndex);
307
  void CheckScalarType(const InitializedEntity &Entity,
308
                       InitListExpr *IList, QualType DeclType,
309
                       unsigned &Index,
310
                       InitListExpr *StructuredList,
311
                       unsigned &StructuredIndex);
312
  void CheckReferenceType(const InitializedEntity &Entity,
313
                          InitListExpr *IList, QualType DeclType,
314
                          unsigned &Index,
315
                          InitListExpr *StructuredList,
316
                          unsigned &StructuredIndex);
317
  void CheckVectorType(const InitializedEntity &Entity,
318
                       InitListExpr *IList, QualType DeclType, unsigned &Index,
319
                       InitListExpr *StructuredList,
320
                       unsigned &StructuredIndex);
321
  void CheckStructUnionTypes(const InitializedEntity &Entity,
322
                             InitListExpr *IList, QualType DeclType,
323
                             CXXRecordDecl::base_class_range Bases,
324
                             RecordDecl::field_iterator Field,
325
                             bool SubobjectIsDesignatorContext, unsigned &Index,
326
                             InitListExpr *StructuredList,
327
                             unsigned &StructuredIndex,
328
                             bool TopLevelObject = false);
329
  void CheckArrayType(const InitializedEntity &Entity,
330
                      InitListExpr *IList, QualType &DeclType,
331
                      llvm::APSInt elementIndex,
332
                      bool SubobjectIsDesignatorContext, unsigned &Index,
333
                      InitListExpr *StructuredList,
334
                      unsigned &StructuredIndex);
335
  bool CheckDesignatedInitializer(const InitializedEntity &Entity,
336
                                  InitListExpr *IList, DesignatedInitExpr *DIE,
337
                                  unsigned DesigIdx,
338
                                  QualType &CurrentObjectType,
339
                                  RecordDecl::field_iterator *NextField,
340
                                  llvm::APSInt *NextElementIndex,
341
                                  unsigned &Index,
342
                                  InitListExpr *StructuredList,
343
                                  unsigned &StructuredIndex,
344
                                  bool FinishSubobjectInit,
345
                                  bool TopLevelObject);
346
  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
347
                                           QualType CurrentObjectType,
348
                                           InitListExpr *StructuredList,
349
                                           unsigned StructuredIndex,
350
                                           SourceRange InitRange,
351
                                           bool IsFullyOverwritten = false);
352
  void UpdateStructuredListElement(InitListExpr *StructuredList,
353
                                   unsigned &StructuredIndex,
354
                                   Expr *expr);
355
  int numArrayElements(QualType DeclType);
356
  int numStructUnionElements(QualType DeclType);
357
358
  static ExprResult PerformEmptyInit(Sema &SemaRef,
359
                                     SourceLocation Loc,
360
                                     const InitializedEntity &Entity,
361
                                     bool VerifyOnly,
362
                                     bool TreatUnavailableAsInvalid);
363
364
  // Explanation on the "FillWithNoInit" mode:
365
  //
366
  // Assume we have the following definitions (Case#1):
367
  // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
368
  // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
369
  //
370
  // l.lp.x[1][0..1] should not be filled with implicit initializers because the
371
  // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
372
  //
373
  // But if we have (Case#2):
374
  // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
375
  //
376
  // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
377
  // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
378
  //
379
  // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
380
  // in the InitListExpr, the "holes" in Case#1 are filled not with empty
381
  // initializers but with special "NoInitExpr" place holders, which tells the
382
  // CodeGen not to generate any initializers for these parts.
383
  void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
384
                              const InitializedEntity &ParentEntity,
385
                              InitListExpr *ILE, bool &RequiresSecondPass,
386
                              bool FillWithNoInit);
387
  void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
388
                               const InitializedEntity &ParentEntity,
389
                               InitListExpr *ILE, bool &RequiresSecondPass,
390
                               bool FillWithNoInit = false);
391
  void FillInEmptyInitializations(const InitializedEntity &Entity,
392
                                  InitListExpr *ILE, bool &RequiresSecondPass,
393
                                  InitListExpr *OuterILE, unsigned OuterIndex,
394
                                  bool FillWithNoInit = false);
395
  bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
396
                              Expr *InitExpr, FieldDecl *Field,
397
                              bool TopLevelObject);
398
  void CheckEmptyInitializable(const InitializedEntity &Entity,
399
                               SourceLocation Loc);
400
401
public:
402
  InitListChecker(Sema &S, const InitializedEntity &Entity,
403
                  InitListExpr *IL, QualType &T, bool VerifyOnly,
404
                  bool TreatUnavailableAsInvalid);
405
205k
  bool HadError() { return hadError; }
406
407
  // Retrieves the fully-structured initializer list used for
408
  // semantic analysis and code generation.
409
96.4k
  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
410
};
411
412
} // end anonymous namespace
413
414
ExprResult InitListChecker::PerformEmptyInit(Sema &SemaRef,
415
                                             SourceLocation Loc,
416
                                             const InitializedEntity &Entity,
417
                                             bool VerifyOnly,
418
31.1k
                                             bool TreatUnavailableAsInvalid) {
419
31.1k
  InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
420
31.1k
                                                            true);
421
31.1k
  MultiExprArg SubInit;
422
31.1k
  Expr *InitExpr;
423
31.1k
  InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
424
31.1k
425
31.1k
  // C++ [dcl.init.aggr]p7:
426
31.1k
  //   If there are fewer initializer-clauses in the list than there are
427
31.1k
  //   members in the aggregate, then each member not explicitly initialized
428
31.1k
  //   ...
429
31.1k
  bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
430
31.1k
      
Entity.getType()->getBaseElementTypeUnsafe()->isRecordType()17.8k
;
431
31.1k
  if (EmptyInitList) {
432
1.04k
    // C++1y / DR1070:
433
1.04k
    //   shall be initialized [...] from an empty initializer list.
434
1.04k
    //
435
1.04k
    // We apply the resolution of this DR to C++11 but not C++98, since C++98
436
1.04k
    // does not have useful semantics for initialization from an init list.
437
1.04k
    // We treat this as copy-initialization, because aggregate initialization
438
1.04k
    // always performs copy-initialization on its elements.
439
1.04k
    //
440
1.04k
    // Only do this if we're initializing a class type, to avoid filling in
441
1.04k
    // the initializer list where possible.
442
1.04k
    InitExpr = VerifyOnly ? 
&DummyInitList578
: new (SemaRef.Context)
443
463
                   InitListExpr(SemaRef.Context, Loc, None, Loc);
444
1.04k
    InitExpr->setType(SemaRef.Context.VoidTy);
445
1.04k
    SubInit = InitExpr;
446
1.04k
    Kind = InitializationKind::CreateCopy(Loc, Loc);
447
30.1k
  } else {
448
30.1k
    // C++03:
449
30.1k
    //   shall be value-initialized.
450
30.1k
  }
451
31.1k
452
31.1k
  InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
453
31.1k
  // libstdc++4.6 marks the vector default constructor as explicit in
454
31.1k
  // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
455
31.1k
  // stlport does so too. Look for std::__debug for libstdc++, and for
456
31.1k
  // std:: for stlport.  This is effectively a compiler-side implementation of
457
31.1k
  // LWG2193.
458
31.1k
  if (!InitSeq && 
EmptyInitList77
&& InitSeq.getFailureKind() ==
459
66
          InitializationSequence::FK_ExplicitConstructor) {
460
5
    OverloadCandidateSet::iterator Best;
461
5
    OverloadingResult O =
462
5
        InitSeq.getFailedCandidateSet()
463
5
            .BestViableFunction(SemaRef, Kind.getLocation(), Best);
464
5
    (void)O;
465
5
    assert(O == OR_Success && "Inconsistent overload resolution");
466
5
    CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
467
5
    CXXRecordDecl *R = CtorDecl->getParent();
468
5
469
5
    if (CtorDecl->getMinRequiredArguments() == 0 &&
470
5
        CtorDecl->isExplicit() && R->getDeclName() &&
471
5
        SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
472
5
      bool IsInStd = false;
473
5
      for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
474
15
           ND && 
!IsInStd10
;
ND = dyn_cast<NamespaceDecl>(ND->getParent())10
) {
475
10
        if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
476
5
          IsInStd = true;
477
10
      }
478
5
479
5
      if (IsInStd && llvm::StringSwitch<bool>(R->getName())
480
5
              .Cases("basic_string", "deque", "forward_list", true)
481
5
              .Cases("list", "map", "multimap", "multiset", true)
482
5
              .Cases("priority_queue", "queue", "set", "stack", true)
483
5
              .Cases("unordered_map", "unordered_set", "vector", true)
484
5
              .Default(false)) {
485
5
        InitSeq.InitializeFrom(
486
5
            SemaRef, Entity,
487
5
            InitializationKind::CreateValue(Loc, Loc, Loc, true),
488
5
            MultiExprArg(), /*TopLevelOfInitList=*/false,
489
5
            TreatUnavailableAsInvalid);
490
5
        // Emit a warning for this.  System header warnings aren't shown
491
5
        // by default, but people working on system headers should see it.
492
5
        if (!VerifyOnly) {
493
2
          SemaRef.Diag(CtorDecl->getLocation(),
494
2
                       diag::warn_invalid_initializer_from_system_header);
495
2
          if (Entity.getKind() == InitializedEntity::EK_Member)
496
1
            SemaRef.Diag(Entity.getDecl()->getLocation(),
497
1
                         diag::note_used_in_initialization_here);
498
1
          else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
499
1
            SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
500
2
        }
501
5
      }
502
5
    }
503
5
  }
504
31.1k
  if (!InitSeq) {
505
72
    if (!VerifyOnly) {
506
31
      InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
507
31
      if (Entity.getKind() == InitializedEntity::EK_Member)
508
12
        SemaRef.Diag(Entity.getDecl()->getLocation(),
509
12
                     diag::note_in_omitted_aggregate_initializer)
510
12
          << /*field*/1 << Entity.getDecl();
511
19
      else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
512
17
        bool IsTrailingArrayNewMember =
513
17
            Entity.getParent() &&
514
17
            Entity.getParent()->isVariableLengthArrayNew();
515
17
        SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
516
17
          << (IsTrailingArrayNewMember ? 
24
: /*array element*/
013
)
517
17
          << Entity.getElementIndex();
518
17
      }
519
31
    }
520
72
    return ExprError();
521
72
  }
522
31.1k
523
31.1k
  return VerifyOnly ? 
ExprResult(static_cast<Expr *>(nullptr))13.2k
524
31.1k
                    : 
InitSeq.Perform(SemaRef, Entity, Kind, SubInit)17.8k
;
525
31.1k
}
526
527
void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
528
13.2k
                                              SourceLocation Loc) {
529
13.2k
  assert(VerifyOnly &&
530
13.2k
         "CheckEmptyInitializable is only inteded for verification mode.");
531
13.2k
  if (PerformEmptyInit(SemaRef, Loc, Entity, /*VerifyOnly*/true,
532
13.2k
                       TreatUnavailableAsInvalid).isInvalid())
533
41
    hadError = true;
534
13.2k
}
535
536
void InitListChecker::FillInEmptyInitForBase(
537
    unsigned Init, const CXXBaseSpecifier &Base,
538
    const InitializedEntity &ParentEntity, InitListExpr *ILE,
539
168
    bool &RequiresSecondPass, bool FillWithNoInit) {
540
168
  assert(Init < ILE->getNumInits() && "should have been expanded");
541
168
542
168
  InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
543
168
      SemaRef.Context, &Base, false, &ParentEntity);
544
168
545
168
  if (!ILE->getInit(Init)) {
546
68
    ExprResult BaseInit =
547
68
        FillWithNoInit
548
68
            ? 
new (SemaRef.Context) NoInitExpr(Base.getType())0
549
68
            : PerformEmptyInit(SemaRef, ILE->getEndLoc(), BaseEntity,
550
68
                               /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
551
68
    if (BaseInit.isInvalid()) {
552
2
      hadError = true;
553
2
      return;
554
2
    }
555
66
556
66
    ILE->setInit(Init, BaseInit.getAs<Expr>());
557
100
  } else if (InitListExpr *InnerILE =
558
67
                 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
559
67
    FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
560
67
                               ILE, Init, FillWithNoInit);
561
67
  } else 
if (DesignatedInitUpdateExpr *33
InnerDIUE33
=
562
0
               dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
563
0
    FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
564
0
                               RequiresSecondPass, ILE, Init,
565
0
                               /*FillWithNoInit =*/true);
566
0
  }
567
168
}
568
569
void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
570
                                        const InitializedEntity &ParentEntity,
571
                                              InitListExpr *ILE,
572
                                              bool &RequiresSecondPass,
573
143k
                                              bool FillWithNoInit) {
574
143k
  SourceLocation Loc = ILE->getEndLoc();
575
143k
  unsigned NumInits = ILE->getNumInits();
576
143k
  InitializedEntity MemberEntity
577
143k
    = InitializedEntity::InitializeMember(Field, &ParentEntity);
578
143k
579
143k
  if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
580
143k
    if (!RType->getDecl()->isUnion())
581
143k
      assert(Init < NumInits && "This ILE should have been expanded");
582
143k
583
143k
  if (Init >= NumInits || 
!ILE->getInit(Init)142k
) {
584
4.09k
    if (FillWithNoInit) {
585
31
      Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
586
31
      if (Init < NumInits)
587
31
        ILE->setInit(Init, Filler);
588
0
      else
589
0
        ILE->updateInit(SemaRef.Context, Init, Filler);
590
31
      return;
591
31
    }
592
4.06k
    // C++1y [dcl.init.aggr]p7:
593
4.06k
    //   If there are fewer initializer-clauses in the list than there are
594
4.06k
    //   members in the aggregate, then each member not explicitly initialized
595
4.06k
    //   shall be initialized from its brace-or-equal-initializer [...]
596
4.06k
    if (Field->hasInClassInitializer()) {
597
189
      ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
598
189
      if (DIE.isInvalid()) {
599
7
        hadError = true;
600
7
        return;
601
7
      }
602
182
      SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
603
182
      if (Init < NumInits)
604
177
        ILE->setInit(Init, DIE.get());
605
5
      else {
606
5
        ILE->updateInit(SemaRef.Context, Init, DIE.get());
607
5
        RequiresSecondPass = true;
608
5
      }
609
182
      return;
610
182
    }
611
3.87k
612
3.87k
    if (Field->getType()->isReferenceType()) {
613
4
      // C++ [dcl.init.aggr]p9:
614
4
      //   If an incomplete or empty initializer-list leaves a
615
4
      //   member of reference type uninitialized, the program is
616
4
      //   ill-formed.
617
4
      SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
618
4
        << Field->getType()
619
4
        << ILE->getSyntacticForm()->getSourceRange();
620
4
      SemaRef.Diag(Field->getLocation(),
621
4
                   diag::note_uninit_reference_member);
622
4
      hadError = true;
623
4
      return;
624
4
    }
625
3.87k
626
3.87k
    ExprResult MemberInit = PerformEmptyInit(SemaRef, Loc, MemberEntity,
627
3.87k
                                             /*VerifyOnly*/false,
628
3.87k
                                             TreatUnavailableAsInvalid);
629
3.87k
    if (MemberInit.isInvalid()) {
630
12
      hadError = true;
631
12
      return;
632
12
    }
633
3.86k
634
3.86k
    if (hadError) {
635
0
      // Do nothing
636
3.86k
    } else if (Init < NumInits) {
637
3.72k
      ILE->setInit(Init, MemberInit.getAs<Expr>());
638
3.72k
    } else 
if (138
!isa<ImplicitValueInitExpr>(MemberInit.get())138
) {
639
5
      // Empty initialization requires a constructor call, so
640
5
      // extend the initializer list to include the constructor
641
5
      // call and make a note that we'll need to take another pass
642
5
      // through the initializer list.
643
5
      ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
644
5
      RequiresSecondPass = true;
645
5
    }
646
138k
  } else if (InitListExpr *InnerILE
647
7.50k
               = dyn_cast<InitListExpr>(ILE->getInit(Init)))
648
7.50k
    FillInEmptyInitializations(MemberEntity, InnerILE,
649
7.50k
                               RequiresSecondPass, ILE, Init, FillWithNoInit);
650
131k
  else if (DesignatedInitUpdateExpr *InnerDIUE
651
45
               = dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init)))
652
45
    FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
653
45
                               RequiresSecondPass, ILE, Init,
654
45
                               /*FillWithNoInit =*/true);
655
143k
}
656
657
/// Recursively replaces NULL values within the given initializer list
658
/// with expressions that perform value-initialization of the
659
/// appropriate type, and finish off the InitListExpr formation.
660
void
661
InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
662
                                            InitListExpr *ILE,
663
                                            bool &RequiresSecondPass,
664
                                            InitListExpr *OuterILE,
665
                                            unsigned OuterIndex,
666
172k
                                            bool FillWithNoInit) {
667
172k
  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
668
172k
         "Should not have void type");
669
172k
670
172k
  // If this is a nested initializer list, we might have changed its contents
671
172k
  // (and therefore some of its properties, such as instantiation-dependence)
672
172k
  // while filling it in. Inform the outer initializer list so that its state
673
172k
  // can be updated to match.
674
172k
  // FIXME: We should fully build the inner initializers before constructing
675
172k
  // the outer InitListExpr instead of mutating AST nodes after they have
676
172k
  // been used as subexpressions of other nodes.
677
172k
  struct UpdateOuterILEWithUpdatedInit {
678
172k
    InitListExpr *Outer;
679
172k
    unsigned OuterIndex;
680
172k
    ~UpdateOuterILEWithUpdatedInit() {
681
172k
      if (Outer)
682
75.9k
        Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
683
172k
    }
684
172k
  } UpdateOuterRAII = {OuterILE, OuterIndex};
685
172k
686
172k
  // A transparent ILE is not performing aggregate initialization and should
687
172k
  // not be filled in.
688
172k
  if (ILE->isTransparent())
689
3.58k
    return;
690
168k
691
168k
  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
692
60.7k
    const RecordDecl *RDecl = RType->getDecl();
693
60.7k
    if (RDecl->isUnion() && 
ILE->getInitializedFieldInUnion()4.37k
)
694
4.34k
      FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
695
4.34k
                              Entity, ILE, RequiresSecondPass, FillWithNoInit);
696
56.4k
    else if (RDecl->isUnion() && 
isa<CXXRecordDecl>(RDecl)34
&&
697
56.4k
             
cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()8
) {
698
0
      for (auto *Field : RDecl->fields()) {
699
0
        if (Field->hasInClassInitializer()) {
700
0
          FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
701
0
                                  FillWithNoInit);
702
0
          break;
703
0
        }
704
0
      }
705
56.4k
    } else {
706
56.4k
      // The fields beyond ILE->getNumInits() are default initialized, so in
707
56.4k
      // order to leave them uninitialized, the ILE is expanded and the extra
708
56.4k
      // fields are then filled with NoInitExpr.
709
56.4k
      unsigned NumElems = numStructUnionElements(ILE->getType());
710
56.4k
      if (RDecl->hasFlexibleArrayMember())
711
58
        ++NumElems;
712
56.4k
      if (ILE->getNumInits() < NumElems)
713
1.76k
        ILE->resizeInits(SemaRef.Context, NumElems);
714
56.4k
715
56.4k
      unsigned Init = 0;
716
56.4k
717
56.4k
      if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
718
32.1k
        for (auto &Base : CXXRD->bases()) {
719
168
          if (hadError)
720
0
            return;
721
168
722
168
          FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
723
168
                                 FillWithNoInit);
724
168
          ++Init;
725
168
        }
726
32.1k
      }
727
56.4k
728
138k
      
for (auto *Field : RDecl->fields())56.4k
{
729
138k
        if (Field->isUnnamedBitfield())
730
113
          continue;
731
138k
732
138k
        if (hadError)
733
0
          return;
734
138k
735
138k
        FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
736
138k
                                FillWithNoInit);
737
138k
        if (hadError)
738
23
          return;
739
138k
740
138k
        ++Init;
741
138k
742
138k
        // Only look at the first initialization of a union.
743
138k
        if (RDecl->isUnion())
744
0
          break;
745
138k
      }
746
56.4k
    }
747
60.7k
748
60.7k
    
return60.7k
;
749
108k
  }
750
108k
751
108k
  QualType ElementType;
752
108k
753
108k
  InitializedEntity ElementEntity = Entity;
754
108k
  unsigned NumInits = ILE->getNumInits();
755
108k
  unsigned NumElements = NumInits;
756
108k
  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
757
67.8k
    ElementType = AType->getElementType();
758
67.8k
    if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
759
67.8k
      NumElements = CAType->getSize().getZExtValue();
760
67.8k
    // For an array new with an unknown bound, ask for one additional element
761
67.8k
    // in order to populate the array filler.
762
67.8k
    if (Entity.isVariableLengthArrayNew())
763
23
      ++NumElements;
764
67.8k
    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
765
67.8k
                                                         0, Entity);
766
67.8k
  } else 
if (const VectorType *40.1k
VType40.1k
= ILE->getType()->getAs<VectorType>()) {
767
39.1k
    ElementType = VType->getElementType();
768
39.1k
    NumElements = VType->getNumElements();
769
39.1k
    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
770
39.1k
                                                         0, Entity);
771
39.1k
  } else
772
1.04k
    ElementType = ILE->getType();
773
108k
774
1.29M
  for (unsigned Init = 0; Init != NumElements; 
++Init1.18M
) {
775
1.19M
    if (hadError)
776
3
      return;
777
1.19M
778
1.19M
    if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
779
1.19M
        
ElementEntity.getKind() == InitializedEntity::EK_VectorElement309k
)
780
1.19M
      ElementEntity.setElementIndex(Init);
781
1.19M
782
1.19M
    if (Init >= NumInits && 
ILE->hasArrayFiller()15.5k
)
783
1.72k
      return;
784
1.19M
785
1.19M
    Expr *InitExpr = (Init < NumInits ? 
ILE->getInit(Init)1.17M
:
nullptr13.8k
);
786
1.19M
    if (!InitExpr && 
Init < NumInits13.9k
&&
ILE->hasArrayFiller()149
)
787
1
      ILE->setInit(Init, ILE->getArrayFiller());
788
1.19M
    else if (!InitExpr && 
!ILE->hasArrayFiller()13.9k
) {
789
13.9k
      Expr *Filler = nullptr;
790
13.9k
791
13.9k
      if (FillWithNoInit)
792
28
        Filler = new (SemaRef.Context) NoInitExpr(ElementType);
793
13.9k
      else {
794
13.9k
        ExprResult ElementInit =
795
13.9k
            PerformEmptyInit(SemaRef, ILE->getEndLoc(), ElementEntity,
796
13.9k
                             /*VerifyOnly*/ false, TreatUnavailableAsInvalid);
797
13.9k
        if (ElementInit.isInvalid()) {
798
17
          hadError = true;
799
17
          return;
800
17
        }
801
13.9k
802
13.9k
        Filler = ElementInit.getAs<Expr>();
803
13.9k
      }
804
13.9k
805
13.9k
      
if (13.9k
hadError13.9k
) {
806
0
        // Do nothing
807
13.9k
      } else if (Init < NumInits) {
808
147
        // For arrays, just set the expression used for value-initialization
809
147
        // of the "holes" in the array.
810
147
        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
811
147
          ILE->setArrayFiller(Filler);
812
0
        else
813
0
          ILE->setInit(Init, Filler);
814
13.8k
      } else {
815
13.8k
        // For arrays, just set the expression used for value-initialization
816
13.8k
        // of the rest of elements and exit.
817
13.8k
        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
818
7.12k
          ILE->setArrayFiller(Filler);
819
7.12k
          return;
820
7.12k
        }
821
6.69k
822
6.69k
        if (!isa<ImplicitValueInitExpr>(Filler) && 
!isa<NoInitExpr>(Filler)0
) {
823
0
          // Empty initialization requires a constructor call, so
824
0
          // extend the initializer list to include the constructor
825
0
          // call and make a note that we'll need to take another pass
826
0
          // through the initializer list.
827
0
          ILE->updateInit(SemaRef.Context, Init, Filler);
828
0
          RequiresSecondPass = true;
829
0
        }
830
6.69k
      }
831
1.17M
    } else if (InitListExpr *InnerILE
832
45.2k
                 = dyn_cast_or_null<InitListExpr>(InitExpr))
833
45.2k
      FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
834
45.2k
                                 ILE, Init, FillWithNoInit);
835
1.13M
    else if (DesignatedInitUpdateExpr *InnerDIUE
836
4
                 = dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr))
837
4
      FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
838
4
                                 RequiresSecondPass, ILE, Init,
839
4
                                 /*FillWithNoInit =*/true);
840
1.19M
  }
841
108k
}
842
843
InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
844
                                 InitListExpr *IL, QualType &T,
845
                                 bool VerifyOnly,
846
                                 bool TreatUnavailableAsInvalid)
847
  : SemaRef(S), VerifyOnly(VerifyOnly),
848
206k
    TreatUnavailableAsInvalid(TreatUnavailableAsInvalid) {
849
206k
  // FIXME: Check that IL isn't already the semantic form of some other
850
206k
  // InitListExpr. If it is, we'd create a broken AST.
851
206k
852
206k
  hadError = false;
853
206k
854
206k
  FullyStructuredList =
855
206k
      getStructuredSubobjectInit(IL, 0, T, nullptr, 0, IL->getSourceRange());
856
206k
  CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
857
206k
                        /*TopLevelObject=*/true);
858
206k
859
206k
  if (!hadError && 
!VerifyOnly205k
) {
860
96.4k
    bool RequiresSecondPass = false;
861
96.4k
    FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
862
96.4k
                               /*OuterILE=*/nullptr, /*OuterIndex=*/0);
863
96.4k
    if (RequiresSecondPass && 
!hadError10
)
864
10
      FillInEmptyInitializations(Entity, FullyStructuredList,
865
10
                                 RequiresSecondPass, nullptr, 0);
866
96.4k
  }
867
206k
}
868
869
600
int InitListChecker::numArrayElements(QualType DeclType) {
870
600
  // FIXME: use a proper constant
871
600
  int maxElements = 0x7FFFFFFF;
872
600
  if (const ConstantArrayType *CAT =
873
584
        SemaRef.Context.getAsConstantArrayType(DeclType)) {
874
584
    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
875
584
  }
876
600
  return maxElements;
877
600
}
878
879
58.5k
int InitListChecker::numStructUnionElements(QualType DeclType) {
880
58.5k
  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
881
58.5k
  int InitializableMembers = 0;
882
58.5k
  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
883
32.6k
    InitializableMembers += CXXRD->getNumBases();
884
58.5k
  for (const auto *Field : structDecl->fields())
885
143k
    if (!Field->isUnnamedBitfield())
886
143k
      ++InitializableMembers;
887
58.5k
888
58.5k
  if (structDecl->isUnion())
889
100
    return std::min(InitializableMembers, 1);
890
58.4k
  return InitializableMembers - structDecl->hasFlexibleArrayMember();
891
58.4k
}
892
893
/// Determine whether Entity is an entity for which it is idiomatic to elide
894
/// the braces in aggregate initialization.
895
1.24k
static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
896
1.24k
  // Recursive initialization of the one and only field within an aggregate
897
1.24k
  // class is considered idiomatic. This case arises in particular for
898
1.24k
  // initialization of std::array, where the C++ standard suggests the idiom of
899
1.24k
  //
900
1.24k
  //   std::array<T, N> arr = {1, 2, 3};
901
1.24k
  //
902
1.24k
  // (where std::array is an aggregate struct containing a single array field.
903
1.24k
904
1.24k
  // FIXME: Should aggregate initialization of a struct with a single
905
1.24k
  // base class and no members also suppress the warning?
906
1.24k
  if (Entity.getKind() != InitializedEntity::EK_Member || 
!Entity.getParent()173
)
907
1.07k
    return false;
908
173
909
173
  auto *ParentRD =
910
173
      Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
911
173
  if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD))
912
111
    if (CXXRD->getNumBases())
913
1
      return false;
914
172
915
172
  auto FieldIt = ParentRD->field_begin();
916
172
  assert(FieldIt != ParentRD->field_end() &&
917
172
         "no fields but have initializer for member?");
918
172
  return ++FieldIt == ParentRD->field_end();
919
172
}
920
921
/// Check whether the range of the initializer \p ParentIList from element
922
/// \p Index onwards can be used to initialize an object of type \p T. Update
923
/// \p Index to indicate how many elements of the list were consumed.
924
///
925
/// This also fills in \p StructuredList, from element \p StructuredIndex
926
/// onwards, with the fully-braced, desugared form of the initialization.
927
void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
928
                                            InitListExpr *ParentIList,
929
                                            QualType T, unsigned &Index,
930
                                            InitListExpr *StructuredList,
931
2.68k
                                            unsigned &StructuredIndex) {
932
2.68k
  int maxElements = 0;
933
2.68k
934
2.68k
  if (T->isArrayType())
935
600
    maxElements = numArrayElements(T);
936
2.08k
  else if (T->isRecordType())
937
2.06k
    maxElements = numStructUnionElements(T);
938
16
  else if (T->isVectorType())
939
16
    maxElements = T->getAs<VectorType>()->getNumElements();
940
16
  else
941
16
    
llvm_unreachable0
("CheckImplicitInitList(): Illegal type");
942
2.68k
943
2.68k
  if (maxElements == 0) {
944
24
    if (!VerifyOnly)
945
12
      SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
946
12
                   diag::err_implicit_empty_initializer);
947
24
    ++Index;
948
24
    hadError = true;
949
24
    return;
950
24
  }
951
2.65k
952
2.65k
  // Build a structured initializer list corresponding to this subobject.
953
2.65k
  InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
954
2.65k
      ParentIList, Index, T, StructuredList, StructuredIndex,
955
2.65k
      SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
956
2.65k
                  ParentIList->getSourceRange().getEnd()));
957
2.65k
  unsigned StructuredSubobjectInitIndex = 0;
958
2.65k
959
2.65k
  // Check the element types and build the structural subobject.
960
2.65k
  unsigned StartIndex = Index;
961
2.65k
  CheckListElementTypes(Entity, ParentIList, T,
962
2.65k
                        /*SubobjectIsDesignatorContext=*/false, Index,
963
2.65k
                        StructuredSubobjectInitList,
964
2.65k
                        StructuredSubobjectInitIndex);
965
2.65k
966
2.65k
  if (!VerifyOnly) {
967
1.30k
    StructuredSubobjectInitList->setType(T);
968
1.30k
969
1.30k
    unsigned EndIndex = (Index == StartIndex? 
StartIndex0
: Index - 1);
970
1.30k
    // Update the structured sub-object initializer so that it's ending
971
1.30k
    // range corresponds with the end of the last initializer it used.
972
1.30k
    if (EndIndex < ParentIList->getNumInits() &&
973
1.30k
        ParentIList->getInit(EndIndex)) {
974
1.30k
      SourceLocation EndLoc
975
1.30k
        = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
976
1.30k
      StructuredSubobjectInitList->setRBraceLoc(EndLoc);
977
1.30k
    }
978
1.30k
979
1.30k
    // Complain about missing braces.
980
1.30k
    if ((T->isArrayType() || 
T->isRecordType()1.01k
) &&
981
1.30k
        
!ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts())1.29k
&&
982
1.30k
        
!isIdiomaticBraceElisionEntity(Entity)1.24k
) {
983
1.19k
      SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
984
1.19k
                   diag::warn_missing_braces)
985
1.19k
          << StructuredSubobjectInitList->getSourceRange()
986
1.19k
          << FixItHint::CreateInsertion(
987
1.19k
                 StructuredSubobjectInitList->getBeginLoc(), "{")
988
1.19k
          << FixItHint::CreateInsertion(
989
1.19k
                 SemaRef.getLocForEndOfToken(
990
1.19k
                     StructuredSubobjectInitList->getEndLoc()),
991
1.19k
                 "}");
992
1.19k
    }
993
1.30k
994
1.30k
    // Warn if this type won't be an aggregate in future versions of C++.
995
1.30k
    auto *CXXRD = T->getAsCXXRecordDecl();
996
1.30k
    if (CXXRD && 
CXXRD->hasUserDeclaredConstructor()232
) {
997
3
      SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
998
3
                   diag::warn_cxx2a_compat_aggregate_init_with_ctors)
999
3
          << StructuredSubobjectInitList->getSourceRange() << T;
1000
3
    }
1001
1.30k
  }
1002
2.65k
}
1003
1004
/// Warn that \p Entity was of scalar type and was initialized by a
1005
/// single-element braced initializer list.
1006
static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1007
3.50k
                                 SourceRange Braces) {
1008
3.50k
  // Don't warn during template instantiation. If the initialization was
1009
3.50k
  // non-dependent, we warned during the initial parse; otherwise, the
1010
3.50k
  // type might not be scalar in some uses of the template.
1011
3.50k
  if (S.inTemplateInstantiation())
1012
1.71k
    return;
1013
1.79k
1014
1.79k
  unsigned DiagID = 0;
1015
1.79k
1016
1.79k
  switch (Entity.getKind()) {
1017
1.79k
  case InitializedEntity::EK_VectorElement:
1018
29
  case InitializedEntity::EK_ComplexElement:
1019
29
  case InitializedEntity::EK_ArrayElement:
1020
29
  case InitializedEntity::EK_Parameter:
1021
29
  case InitializedEntity::EK_Parameter_CF_Audited:
1022
29
  case InitializedEntity::EK_Result:
1023
29
    // Extra braces here are suspicious.
1024
29
    DiagID = diag::warn_braces_around_scalar_init;
1025
29
    break;
1026
29
1027
1.37k
  case InitializedEntity::EK_Member:
1028
1.37k
    // Warn on aggregate initialization but not on ctor init list or
1029
1.37k
    // default member initializer.
1030
1.37k
    if (Entity.getParent())
1031
11
      DiagID = diag::warn_braces_around_scalar_init;
1032
1.37k
    break;
1033
29
1034
242
  case InitializedEntity::EK_Variable:
1035
242
  case InitializedEntity::EK_LambdaCapture:
1036
242
    // No warning, might be direct-list-initialization.
1037
242
    // FIXME: Should we warn for copy-list-initialization in these cases?
1038
242
    break;
1039
242
1040
242
  case InitializedEntity::EK_New:
1041
153
  case InitializedEntity::EK_Temporary:
1042
153
  case InitializedEntity::EK_CompoundLiteralInit:
1043
153
    // No warning, braces are part of the syntax of the underlying construct.
1044
153
    break;
1045
153
1046
153
  case InitializedEntity::EK_RelatedResult:
1047
0
    // No warning, we already warned when initializing the result.
1048
0
    break;
1049
153
1050
153
  case InitializedEntity::EK_Exception:
1051
0
  case InitializedEntity::EK_Base:
1052
0
  case InitializedEntity::EK_Delegating:
1053
0
  case InitializedEntity::EK_BlockElement:
1054
0
  case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1055
0
  case InitializedEntity::EK_Binding:
1056
0
  case InitializedEntity::EK_StmtExprResult:
1057
0
    llvm_unreachable("unexpected braced scalar init");
1058
1.79k
  }
1059
1.79k
1060
1.79k
  if (DiagID) {
1061
40
    S.Diag(Braces.getBegin(), DiagID)
1062
40
      << Braces
1063
40
      << FixItHint::CreateRemoval(Braces.getBegin())
1064
40
      << FixItHint::CreateRemoval(Braces.getEnd());
1065
40
  }
1066
1.79k
}
1067
1068
/// Check whether the initializer \p IList (that was written with explicit
1069
/// braces) can be used to initialize an object of type \p T.
1070
///
1071
/// This also fills in \p StructuredList with the fully-braced, desugared
1072
/// form of the initialization.
1073
void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1074
                                            InitListExpr *IList, QualType &T,
1075
                                            InitListExpr *StructuredList,
1076
252k
                                            bool TopLevelObject) {
1077
252k
  if (!VerifyOnly) {
1078
120k
    SyntacticToSemantic[IList] = StructuredList;
1079
120k
    StructuredList->setSyntacticForm(IList);
1080
120k
  }
1081
252k
1082
252k
  unsigned Index = 0, StructuredIndex = 0;
1083
252k
  CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1084
252k
                        Index, StructuredList, StructuredIndex, TopLevelObject);
1085
252k
  if (!VerifyOnly) {
1086
120k
    QualType ExprTy = T;
1087
120k
    if (!ExprTy->isArrayType())
1088
83.4k
      ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1089
120k
    IList->setType(ExprTy);
1090
120k
    StructuredList->setType(ExprTy);
1091
120k
  }
1092
252k
  if (hadError)
1093
845
    return;
1094
251k
1095
251k
  if (Index < IList->getNumInits()) {
1096
157
    // We have leftover initializers
1097
157
    if (VerifyOnly) {
1098
87
      if (SemaRef.getLangOpts().CPlusPlus ||
1099
87
          
(43
SemaRef.getLangOpts().OpenCL43
&&
1100
45
           
IList->getType()->isVectorType()3
)) {
1101
45
        hadError = true;
1102
45
      }
1103
87
      return;
1104
87
    }
1105
70
1106
70
    if (StructuredIndex == 1 &&
1107
70
        IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1108
29
            SIF_None) {
1109
4
      unsigned DK = diag::ext_excess_initializers_in_char_array_initializer;
1110
4
      if (SemaRef.getLangOpts().CPlusPlus) {
1111
0
        DK = diag::err_excess_initializers_in_char_array_initializer;
1112
0
        hadError = true;
1113
0
      }
1114
4
      // Special-case
1115
4
      SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1116
4
          << IList->getInit(Index)->getSourceRange();
1117
66
    } else if (!T->isIncompleteType()) {
1118
66
      // Don't complain for incomplete types, since we'll get an error
1119
66
      // elsewhere
1120
66
      QualType CurrentObjectType = StructuredList->getType();
1121
66
      int initKind =
1122
66
        CurrentObjectType->isArrayType()? 
025
:
1123
66
        
CurrentObjectType->isVectorType()41
?
16
:
1124
41
        
CurrentObjectType->isScalarType()35
?
28
:
1125
35
        
CurrentObjectType->isUnionType()27
?
34
:
1126
27
        
423
;
1127
66
1128
66
      unsigned DK = diag::ext_excess_initializers;
1129
66
      if (SemaRef.getLangOpts().CPlusPlus) {
1130
27
        DK = diag::err_excess_initializers;
1131
27
        hadError = true;
1132
27
      }
1133
66
      if (SemaRef.getLangOpts().OpenCL && 
initKind == 13
) {
1134
1
        DK = diag::err_excess_initializers;
1135
1
        hadError = true;
1136
1
      }
1137
66
1138
66
      SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1139
66
          << initKind << IList->getInit(Index)->getSourceRange();
1140
66
    }
1141
70
  }
1142
251k
1143
251k
  
if (251k
!VerifyOnly251k
) {
1144
119k
    if (T->isScalarType() && 
IList->getNumInits() == 14.50k
&&
1145
119k
        
!isa<InitListExpr>(IList->getInit(0))3.51k
)
1146
3.50k
      warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1147
119k
1148
119k
    // Warn if this is a class type that won't be an aggregate in future
1149
119k
    // versions of C++.
1150
119k
    auto *CXXRD = T->getAsCXXRecordDecl();
1151
119k
    if (CXXRD && 
CXXRD->hasUserDeclaredConstructor()23.8k
) {
1152
24
      // Don't warn if there's an equivalent default constructor that would be
1153
24
      // used instead.
1154
24
      bool HasEquivCtor = false;
1155
24
      if (IList->getNumInits() == 0) {
1156
19
        auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1157
19
        HasEquivCtor = CD && !CD->isDeleted();
1158
19
      }
1159
24
1160
24
      if (!HasEquivCtor) {
1161
8
        SemaRef.Diag(IList->getBeginLoc(),
1162
8
                     diag::warn_cxx2a_compat_aggregate_init_with_ctors)
1163
8
            << IList->getSourceRange() << T;
1164
8
      }
1165
24
    }
1166
119k
  }
1167
251k
}
1168
1169
void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1170
                                            InitListExpr *IList,
1171
                                            QualType &DeclType,
1172
                                            bool SubobjectIsDesignatorContext,
1173
                                            unsigned &Index,
1174
                                            InitListExpr *StructuredList,
1175
                                            unsigned &StructuredIndex,
1176
255k
                                            bool TopLevelObject) {
1177
255k
  if (DeclType->isAnyComplexType() && 
SubobjectIsDesignatorContext142
) {
1178
142
    // Explicitly braced initializer for complex type can be real+imaginary
1179
142
    // parts.
1180
142
    CheckComplexType(Entity, IList, DeclType, Index,
1181
142
                     StructuredList, StructuredIndex);
1182
254k
  } else if (DeclType->isScalarType()) {
1183
9.27k
    CheckScalarType(Entity, IList, DeclType, Index,
1184
9.27k
                    StructuredList, StructuredIndex);
1185
245k
  } else if (DeclType->isVectorType()) {
1186
78.3k
    CheckVectorType(Entity, IList, DeclType, Index,
1187
78.3k
                    StructuredList, StructuredIndex);
1188
167k
  } else if (DeclType->isRecordType()) {
1189
90.1k
    assert(DeclType->isAggregateType() &&
1190
90.1k
           "non-aggregate records should be handed in CheckSubElementType");
1191
90.1k
    RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1192
90.1k
    auto Bases =
1193
90.1k
        CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1194
90.1k
                                        CXXRecordDecl::base_class_iterator());
1195
90.1k
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1196
57.3k
      Bases = CXXRD->bases();
1197
90.1k
    CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1198
90.1k
                          SubobjectIsDesignatorContext, Index, StructuredList,
1199
90.1k
                          StructuredIndex, TopLevelObject);
1200
90.1k
  } else 
if (77.1k
DeclType->isArrayType()77.1k
) {
1201
77.1k
    llvm::APSInt Zero(
1202
77.1k
                    SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1203
77.1k
                    false);
1204
77.1k
    CheckArrayType(Entity, IList, DeclType, Zero,
1205
77.1k
                   SubobjectIsDesignatorContext, Index,
1206
77.1k
                   StructuredList, StructuredIndex);
1207
77.1k
  } else 
if (96
DeclType->isVoidType()96
||
DeclType->isFunctionType()94
) {
1208
4
    // This type is invalid, issue a diagnostic.
1209
4
    ++Index;
1210
4
    if (!VerifyOnly)
1211
2
      SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1212
2
          << DeclType;
1213
4
    hadError = true;
1214
92
  } else if (DeclType->isReferenceType()) {
1215
0
    CheckReferenceType(Entity, IList, DeclType, Index,
1216
0
                       StructuredList, StructuredIndex);
1217
92
  } else if (DeclType->isObjCObjectType()) {
1218
2
    if (!VerifyOnly)
1219
1
      SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1220
2
    hadError = true;
1221
90
  } else if (DeclType->isOCLIntelSubgroupAVCType()) {
1222
76
    // Checks for scalar type are sufficient for these types too.
1223
76
    CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1224
76
                    StructuredIndex);
1225
76
  } else {
1226
14
    if (!VerifyOnly)
1227
6
      SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1228
6
          << DeclType;
1229
14
    hadError = true;
1230
14
  }
1231
255k
}
1232
1233
void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1234
                                          InitListExpr *IList,
1235
                                          QualType ElemType,
1236
                                          unsigned &Index,
1237
                                          InitListExpr *StructuredList,
1238
2.24M
                                          unsigned &StructuredIndex) {
1239
2.24M
  Expr *expr = IList->getInit(Index);
1240
2.24M
1241
2.24M
  if (ElemType->isReferenceType())
1242
639
    return CheckReferenceType(Entity, IList, ElemType, Index,
1243
639
                              StructuredList, StructuredIndex);
1244
2.24M
1245
2.24M
  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1246
69.9k
    if (SubInitList->getNumInits() == 1 &&
1247
69.9k
        IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1248
5.80k
        SIF_None) {
1249
56
      expr = SubInitList->getInit(0);
1250
69.8k
    } else if (!SemaRef.getLangOpts().CPlusPlus) {
1251
46.2k
      InitListExpr *InnerStructuredList
1252
46.2k
        = getStructuredSubobjectInit(IList, Index, ElemType,
1253
46.2k
                                     StructuredList, StructuredIndex,
1254
46.2k
                                     SubInitList->getSourceRange(), true);
1255
46.2k
      CheckExplicitInitList(Entity, SubInitList, ElemType,
1256
46.2k
                            InnerStructuredList);
1257
46.2k
1258
46.2k
      if (!hadError && 
!VerifyOnly46.2k
) {
1259
23.1k
        bool RequiresSecondPass = false;
1260
23.1k
        FillInEmptyInitializations(Entity, InnerStructuredList,
1261
23.1k
                                   RequiresSecondPass, StructuredList,
1262
23.1k
                                   StructuredIndex);
1263
23.1k
        if (RequiresSecondPass && 
!hadError0
)
1264
0
          FillInEmptyInitializations(Entity, InnerStructuredList,
1265
0
                                     RequiresSecondPass, StructuredList,
1266
0
                                     StructuredIndex);
1267
23.1k
      }
1268
46.2k
      ++StructuredIndex;
1269
46.2k
      ++Index;
1270
46.2k
      return;
1271
46.2k
    }
1272
2.17M
    // C++ initialization is handled later.
1273
2.17M
  } else if (isa<ImplicitValueInitExpr>(expr)) {
1274
0
    // This happens during template instantiation when we see an InitListExpr
1275
0
    // that we've already checked once.
1276
0
    assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1277
0
           "found implicit initialization for the wrong type");
1278
0
    if (!VerifyOnly)
1279
0
      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1280
0
    ++Index;
1281
0
    return;
1282
0
  }
1283
2.20M
1284
2.20M
  if (SemaRef.getLangOpts().CPlusPlus) {
1285
737k
    // C++ [dcl.init.aggr]p2:
1286
737k
    //   Each member is copy-initialized from the corresponding
1287
737k
    //   initializer-clause.
1288
737k
1289
737k
    // FIXME: Better EqualLoc?
1290
737k
    InitializationKind Kind =
1291
737k
        InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1292
737k
    InitializationSequence Seq(SemaRef, Entity, Kind, expr,
1293
737k
                               /*TopLevelOfInitList*/ true);
1294
737k
1295
737k
    // C++14 [dcl.init.aggr]p13:
1296
737k
    //   If the assignment-expression can initialize a member, the member is
1297
737k
    //   initialized. Otherwise [...] brace elision is assumed
1298
737k
    //
1299
737k
    // Brace elision is never performed if the element is not an
1300
737k
    // assignment-expression.
1301
737k
    if (Seq || 
isa<InitListExpr>(expr)1.00k
) {
1302
736k
      if (!VerifyOnly) {
1303
353k
        ExprResult Result =
1304
353k
          Seq.Perform(SemaRef, Entity, Kind, expr);
1305
353k
        if (Result.isInvalid())
1306
39
          hadError = true;
1307
353k
1308
353k
        UpdateStructuredListElement(StructuredList, StructuredIndex,
1309
353k
                                    Result.getAs<Expr>());
1310
382k
      } else if (!Seq)
1311
56
        hadError = true;
1312
736k
      ++Index;
1313
736k
      return;
1314
736k
    }
1315
1.46M
1316
1.46M
    // Fall through for subaggregate initialization
1317
1.46M
  } else if (ElemType->isScalarType() || 
ElemType->isAtomicType()2.62k
) {
1318
1.46M
    // FIXME: Need to handle atomic aggregate types with implicit init lists.
1319
1.46M
    return CheckScalarType(Entity, IList, ElemType, Index,
1320
1.46M
                           StructuredList, StructuredIndex);
1321
1.46M
  } else 
if (const ArrayType *2.61k
arrayType2.61k
=
1322
820
                 SemaRef.Context.getAsArrayType(ElemType)) {
1323
820
    // arrayType can be incomplete if we're initializing a flexible
1324
820
    // array member.  There's nothing we can do with the completed
1325
820
    // type here, though.
1326
820
1327
820
    if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1328
494
      if (!VerifyOnly) {
1329
247
        CheckStringInit(expr, ElemType, arrayType, SemaRef);
1330
247
        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1331
247
      }
1332
494
      ++Index;
1333
494
      return;
1334
494
    }
1335
1.79k
1336
1.79k
    // Fall through for subaggregate initialization.
1337
1.79k
1338
1.79k
  } else {
1339
1.79k
    assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1340
1.79k
            ElemType->isOpenCLSpecificType()) && "Unexpected type");
1341
1.79k
1342
1.79k
    // C99 6.7.8p13:
1343
1.79k
    //
1344
1.79k
    //   The initializer for a structure or union object that has
1345
1.79k
    //   automatic storage duration shall be either an initializer
1346
1.79k
    //   list as described below, or a single expression that has
1347
1.79k
    //   compatible structure or union type. In the latter case, the
1348
1.79k
    //   initial value of the object, including unnamed members, is
1349
1.79k
    //   that of the expression.
1350
1.79k
    ExprResult ExprRes = expr;
1351
1.79k
    if (SemaRef.CheckSingleAssignmentConstraints(
1352
1.79k
            ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1353
220
      if (ExprRes.isInvalid())
1354
0
        hadError = true;
1355
220
      else {
1356
220
        ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1357
220
          if (ExprRes.isInvalid())
1358
0
            hadError = true;
1359
220
      }
1360
220
      UpdateStructuredListElement(StructuredList, StructuredIndex,
1361
220
                                  ExprRes.getAs<Expr>());
1362
220
      ++Index;
1363
220
      return;
1364
220
    }
1365
1.57k
    ExprRes.get();
1366
1.57k
    // Fall through for subaggregate initialization
1367
1.57k
  }
1368
2.20M
1369
2.20M
  // C++ [dcl.init.aggr]p12:
1370
2.20M
  //
1371
2.20M
  //   [...] Otherwise, if the member is itself a non-empty
1372
2.20M
  //   subaggregate, brace elision is assumed and the initializer is
1373
2.20M
  //   considered for the initialization of the first member of
1374
2.20M
  //   the subaggregate.
1375
2.20M
  // OpenCL vector initializer is handled elsewhere.
1376
2.20M
  
if (2.81k
(2.81k
!SemaRef.getLangOpts().OpenCL2.81k
&&
ElemType->isVectorType()2.79k
) ||
1377
2.81k
      
ElemType->isAggregateType()2.80k
) {
1378
2.67k
    CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1379
2.67k
                          StructuredIndex);
1380
2.67k
    ++StructuredIndex;
1381
2.67k
  } else {
1382
148
    if (!VerifyOnly) {
1383
72
      // We cannot initialize this element, so let
1384
72
      // PerformCopyInitialization produce the appropriate diagnostic.
1385
72
      SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1386
72
                                        /*TopLevelOfInitList=*/true);
1387
72
    }
1388
148
    hadError = true;
1389
148
    ++Index;
1390
148
    ++StructuredIndex;
1391
148
  }
1392
2.81k
}
1393
1394
void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1395
                                       InitListExpr *IList, QualType DeclType,
1396
                                       unsigned &Index,
1397
                                       InitListExpr *StructuredList,
1398
142
                                       unsigned &StructuredIndex) {
1399
142
  assert(Index == 0 && "Index in explicit init list must be zero");
1400
142
1401
142
  // As an extension, clang supports complex initializers, which initialize
1402
142
  // a complex number component-wise.  When an explicit initializer list for
1403
142
  // a complex number contains two two initializers, this extension kicks in:
1404
142
  // it exepcts the initializer list to contain two elements convertible to
1405
142
  // the element type of the complex type. The first element initializes
1406
142
  // the real part, and the second element intitializes the imaginary part.
1407
142
1408
142
  if (IList->getNumInits() != 2)
1409
48
    return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1410
48
                           StructuredIndex);
1411
94
1412
94
  // This is an extension in C.  (The builtin _Complex type does not exist
1413
94
  // in the C++ standard.)
1414
94
  if (!SemaRef.getLangOpts().CPlusPlus && 
!VerifyOnly42
)
1415
21
    SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1416
21
        << IList->getSourceRange();
1417
94
1418
94
  // Initialize the complex number.
1419
94
  QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
1420
94
  InitializedEntity ElementEntity =
1421
94
    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1422
94
1423
282
  for (unsigned i = 0; i < 2; 
++i188
) {
1424
188
    ElementEntity.setElementIndex(Index);
1425
188
    CheckSubElementType(ElementEntity, IList, elementType, Index,
1426
188
                        StructuredList, StructuredIndex);
1427
188
  }
1428
94
}
1429
1430
void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1431
                                      InitListExpr *IList, QualType DeclType,
1432
                                      unsigned &Index,
1433
                                      InitListExpr *StructuredList,
1434
1.47M
                                      unsigned &StructuredIndex) {
1435
1.47M
  if (Index >= IList->getNumInits()) {
1436
1.89k
    if (!VerifyOnly)
1437
943
      SemaRef.Diag(IList->getBeginLoc(),
1438
943
                   SemaRef.getLangOpts().CPlusPlus11
1439
943
                       ? 
diag::warn_cxx98_compat_empty_scalar_initializer938
1440
943
                       : 
diag::err_empty_scalar_initializer5
)
1441
943
          << IList->getSourceRange();
1442
1.89k
    hadError = !SemaRef.getLangOpts().CPlusPlus11;
1443
1.89k
    ++Index;
1444
1.89k
    ++StructuredIndex;
1445
1.89k
    return;
1446
1.89k
  }
1447
1.46M
1448
1.46M
  Expr *expr = IList->getInit(Index);
1449
1.46M
  if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1450
22
    // FIXME: This is invalid, and accepting it causes overload resolution
1451
22
    // to pick the wrong overload in some corner cases.
1452
22
    if (!VerifyOnly)
1453
10
      SemaRef.Diag(SubIList->getBeginLoc(),
1454
10
                   diag::ext_many_braces_around_scalar_init)
1455
10
          << SubIList->getSourceRange();
1456
22
1457
22
    CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1458
22
                    StructuredIndex);
1459
22
    return;
1460
1.46M
  } else if (isa<DesignatedInitExpr>(expr)) {
1461
2
    if (!VerifyOnly)
1462
1
      SemaRef.Diag(expr->getBeginLoc(), diag::err_designator_for_scalar_init)
1463
1
          << DeclType << expr->getSourceRange();
1464
2
    hadError = true;
1465
2
    ++Index;
1466
2
    ++StructuredIndex;
1467
2
    return;
1468
2
  }
1469
1.46M
1470
1.46M
  if (VerifyOnly) {
1471
734k
    if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1472
190
      hadError = true;
1473
734k
    ++Index;
1474
734k
    return;
1475
734k
  }
1476
734k
1477
734k
  ExprResult Result =
1478
734k
      SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1479
734k
                                        /*TopLevelOfInitList=*/true);
1480
734k
1481
734k
  Expr *ResultExpr = nullptr;
1482
734k
1483
734k
  if (Result.isInvalid())
1484
181
    hadError = true; // types weren't compatible.
1485
734k
  else {
1486
734k
    ResultExpr = Result.getAs<Expr>();
1487
734k
1488
734k
    if (ResultExpr != expr) {
1489
664k
      // The type was promoted, update initializer list.
1490
664k
      IList->setInit(Index, ResultExpr);
1491
664k
    }
1492
734k
  }
1493
734k
  if (hadError)
1494
207
    ++StructuredIndex;
1495
734k
  else
1496
734k
    UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1497
734k
  ++Index;
1498
734k
}
1499
1500
void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1501
                                         InitListExpr *IList, QualType DeclType,
1502
                                         unsigned &Index,
1503
                                         InitListExpr *StructuredList,
1504
639
                                         unsigned &StructuredIndex) {
1505
639
  if (Index >= IList->getNumInits()) {
1506
0
    // FIXME: It would be wonderful if we could point at the actual member. In
1507
0
    // general, it would be useful to pass location information down the stack,
1508
0
    // so that we know the location (or decl) of the "current object" being
1509
0
    // initialized.
1510
0
    if (!VerifyOnly)
1511
0
      SemaRef.Diag(IList->getBeginLoc(),
1512
0
                   diag::err_init_reference_member_uninitialized)
1513
0
          << DeclType << IList->getSourceRange();
1514
0
    hadError = true;
1515
0
    ++Index;
1516
0
    ++StructuredIndex;
1517
0
    return;
1518
0
  }
1519
639
1520
639
  Expr *expr = IList->getInit(Index);
1521
639
  if (isa<InitListExpr>(expr) && 
!SemaRef.getLangOpts().CPlusPlus11105
) {
1522
0
    if (!VerifyOnly)
1523
0
      SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1524
0
          << DeclType << IList->getSourceRange();
1525
0
    hadError = true;
1526
0
    ++Index;
1527
0
    ++StructuredIndex;
1528
0
    return;
1529
0
  }
1530
639
1531
639
  if (VerifyOnly) {
1532
341
    if (!SemaRef.CanPerformCopyInitialization(Entity,expr))
1533
8
      hadError = true;
1534
341
    ++Index;
1535
341
    return;
1536
341
  }
1537
298
1538
298
  ExprResult Result =
1539
298
      SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1540
298
                                        /*TopLevelOfInitList=*/true);
1541
298
1542
298
  if (Result.isInvalid())
1543
8
    hadError = true;
1544
298
1545
298
  expr = Result.getAs<Expr>();
1546
298
  IList->setInit(Index, expr);
1547
298
1548
298
  if (hadError)
1549
8
    ++StructuredIndex;
1550
290
  else
1551
290
    UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1552
298
  ++Index;
1553
298
}
1554
1555
void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1556
                                      InitListExpr *IList, QualType DeclType,
1557
                                      unsigned &Index,
1558
                                      InitListExpr *StructuredList,
1559
78.3k
                                      unsigned &StructuredIndex) {
1560
78.3k
  const VectorType *VT = DeclType->getAs<VectorType>();
1561
78.3k
  unsigned maxElements = VT->getNumElements();
1562
78.3k
  unsigned numEltsInit = 0;
1563
78.3k
  QualType elementType = VT->getElementType();
1564
78.3k
1565
78.3k
  if (Index >= IList->getNumInits()) {
1566
126
    // Make sure the element type can be value-initialized.
1567
126
    if (VerifyOnly)
1568
63
      CheckEmptyInitializable(
1569
63
          InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1570
63
          IList->getEndLoc());
1571
126
    return;
1572
126
  }
1573
78.1k
1574
78.1k
  if (!SemaRef.getLangOpts().OpenCL) {
1575
77.8k
    // If the initializing element is a vector, try to copy-initialize
1576
77.8k
    // instead of breaking it apart (which is doomed to failure anyway).
1577
77.8k
    Expr *Init = IList->getInit(Index);
1578
77.8k
    if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1579
11
      if (VerifyOnly) {
1580
6
        if (!SemaRef.CanPerformCopyInitialization(Entity, Init))
1581
1
          hadError = true;
1582
6
        ++Index;
1583
6
        return;
1584
6
      }
1585
5
1586
5
      ExprResult Result =
1587
5
          SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1588
5
                                            /*TopLevelOfInitList=*/true);
1589
5
1590
5
      Expr *ResultExpr = nullptr;
1591
5
      if (Result.isInvalid())
1592
3
        hadError = true; // types weren't compatible.
1593
2
      else {
1594
2
        ResultExpr = Result.getAs<Expr>();
1595
2
1596
2
        if (ResultExpr != Init) {
1597
2
          // The type was promoted, update initializer list.
1598
2
          IList->setInit(Index, ResultExpr);
1599
2
        }
1600
2
      }
1601
5
      if (hadError)
1602
3
        ++StructuredIndex;
1603
2
      else
1604
2
        UpdateStructuredListElement(StructuredList, StructuredIndex,
1605
2
                                    ResultExpr);
1606
5
      ++Index;
1607
5
      return;
1608
5
    }
1609
77.8k
1610
77.8k
    InitializedEntity ElementEntity =
1611
77.8k
      InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1612
77.8k
1613
682k
    for (unsigned i = 0; i < maxElements; 
++i, ++numEltsInit604k
) {
1614
606k
      // Don't attempt to go past the end of the init list
1615
606k
      if (Index >= IList->getNumInits()) {
1616
1.59k
        if (VerifyOnly)
1617
799
          CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1618
1.59k
        break;
1619
1.59k
      }
1620
604k
1621
604k
      ElementEntity.setElementIndex(Index);
1622
604k
      CheckSubElementType(ElementEntity, IList, elementType, Index,
1623
604k
                          StructuredList, StructuredIndex);
1624
604k
    }
1625
77.8k
1626
77.8k
    if (VerifyOnly)
1627
38.9k
      return;
1628
38.9k
1629
38.9k
    bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1630
38.9k
    const VectorType *T = Entity.getType()->getAs<VectorType>();
1631
38.9k
    if (isBigEndian && 
(7.58k
T->getVectorKind() == VectorType::NeonVector7.58k
||
1632
7.58k
                        
T->getVectorKind() == VectorType::NeonPolyVector6.21k
)) {
1633
1.49k
      // The ability to use vector initializer lists is a GNU vector extension
1634
1.49k
      // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1635
1.49k
      // endian machines it works fine, however on big endian machines it
1636
1.49k
      // exhibits surprising behaviour:
1637
1.49k
      //
1638
1.49k
      //   uint32x2_t x = {42, 64};
1639
1.49k
      //   return vget_lane_u32(x, 0); // Will return 64.
1640
1.49k
      //
1641
1.49k
      // Because of this, explicitly call out that it is non-portable.
1642
1.49k
      //
1643
1.49k
      SemaRef.Diag(IList->getBeginLoc(),
1644
1.49k
                   diag::warn_neon_vector_initializer_non_portable);
1645
1.49k
1646
1.49k
      const char *typeCode;
1647
1.49k
      unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1648
1.49k
1649
1.49k
      if (elementType->isFloatingType())
1650
262
        typeCode = "f";
1651
1.23k
      else if (elementType->isSignedIntegerType())
1652
674
        typeCode = "s";
1653
560
      else if (elementType->isUnsignedIntegerType())
1654
560
        typeCode = "u";
1655
560
      else
1656
560
        
llvm_unreachable0
("Invalid element type!");
1657
1.49k
1658
1.49k
      SemaRef.Diag(IList->getBeginLoc(),
1659
1.49k
                   SemaRef.Context.getTypeSize(VT) > 64
1660
1.49k
                       ? 
diag::note_neon_vector_initializer_non_portable_q565
1661
1.49k
                       : 
diag::note_neon_vector_initializer_non_portable931
)
1662
1.49k
          << typeCode << typeSize;
1663
1.49k
    }
1664
38.9k
1665
38.9k
    return;
1666
298
  }
1667
298
1668
298
  InitializedEntity ElementEntity =
1669
298
    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1670
298
1671
298
  // OpenCL initializers allows vectors to be constructed from vectors.
1672
1.21k
  for (unsigned i = 0; i < maxElements; 
++i912
) {
1673
978
    // Don't attempt to go past the end of the init list
1674
978
    if (Index >= IList->getNumInits())
1675
66
      break;
1676
912
1677
912
    ElementEntity.setElementIndex(Index);
1678
912
1679
912
    QualType IType = IList->getInit(Index)->getType();
1680
912
    if (!IType->isVectorType()) {
1681
830
      CheckSubElementType(ElementEntity, IList, elementType, Index,
1682
830
                          StructuredList, StructuredIndex);
1683
830
      ++numEltsInit;
1684
830
    } else {
1685
82
      QualType VecType;
1686
82
      const VectorType *IVT = IType->getAs<VectorType>();
1687
82
      unsigned numIElts = IVT->getNumElements();
1688
82
1689
82
      if (IType->isExtVectorType())
1690
78
        VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1691
4
      else
1692
4
        VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1693
4
                                                IVT->getVectorKind());
1694
82
      CheckSubElementType(ElementEntity, IList, VecType, Index,
1695
82
                          StructuredList, StructuredIndex);
1696
82
      numEltsInit += numIElts;
1697
82
    }
1698
912
  }
1699
298
1700
298
  // OpenCL requires all elements to be initialized.
1701
298
  if (numEltsInit != maxElements) {
1702
2
    if (!VerifyOnly)
1703
1
      SemaRef.Diag(IList->getBeginLoc(),
1704
1
                   diag::err_vector_incorrect_num_initializers)
1705
1
          << (numEltsInit < maxElements) << maxElements << numEltsInit;
1706
2
    hadError = true;
1707
2
  }
1708
298
}
1709
1710
/// Check if the type of a class element has an accessible destructor, and marks
1711
/// it referenced. Returns true if we shouldn't form a reference to the
1712
/// destructor.
1713
///
1714
/// Aggregate initialization requires a class element's destructor be
1715
/// accessible per 11.6.1 [dcl.init.aggr]:
1716
///
1717
/// The destructor for each element of class type is potentially invoked
1718
/// (15.4 [class.dtor]) from the context where the aggregate initialization
1719
/// occurs.
1720
static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1721
140k
                                     Sema &SemaRef) {
1722
140k
  auto *CXXRD = ElementType->getAsCXXRecordDecl();
1723
140k
  if (!CXXRD)
1724
126k
    return false;
1725
14.3k
1726
14.3k
  CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1727
14.3k
  SemaRef.CheckDestructorAccess(Loc, Destructor,
1728
14.3k
                                SemaRef.PDiag(diag::err_access_dtor_temp)
1729
14.3k
                                << ElementType);
1730
14.3k
  SemaRef.MarkFunctionReferenced(Loc, Destructor);
1731
14.3k
  return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1732
14.3k
}
1733
1734
void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1735
                                     InitListExpr *IList, QualType &DeclType,
1736
                                     llvm::APSInt elementIndex,
1737
                                     bool SubobjectIsDesignatorContext,
1738
                                     unsigned &Index,
1739
                                     InitListExpr *StructuredList,
1740
77.2k
                                     unsigned &StructuredIndex) {
1741
77.2k
  const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1742
77.2k
1743
77.2k
  if (!VerifyOnly) {
1744
36.9k
    if (checkDestructorReference(arrayType->getElementType(),
1745
36.9k
                                 IList->getEndLoc(), SemaRef)) {
1746
0
      hadError = true;
1747
0
      return;
1748
0
    }
1749
77.2k
  }
1750
77.2k
1751
77.2k
  // Check for the special-case of initializing an array with a string.
1752
77.2k
  if (Index < IList->getNumInits()) {
1753
74.2k
    if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1754
74.2k
        SIF_None) {
1755
74
      // We place the string literal directly into the resulting
1756
74
      // initializer list. This is the only place where the structure
1757
74
      // of the structured initializer list doesn't match exactly,
1758
74
      // because doing so would involve allocating one character
1759
74
      // constant for each string.
1760
74
      if (!VerifyOnly) {
1761
37
        CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1762
37
        UpdateStructuredListElement(StructuredList, StructuredIndex,
1763
37
                                    IList->getInit(Index));
1764
37
        StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1765
37
      }
1766
74
      ++Index;
1767
74
      return;
1768
74
    }
1769
77.1k
  }
1770
77.1k
  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1771
16
    // Check for VLAs; in standard C it would be possible to check this
1772
16
    // earlier, but I don't know where clang accepts VLAs (gcc accepts
1773
16
    // them in all sorts of strange places).
1774
16
    if (!VerifyOnly)
1775
8
      SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1776
8
                   diag::err_variable_object_no_init)
1777
8
          << VAT->getSizeExpr()->getSourceRange();
1778
16
    hadError = true;
1779
16
    ++Index;
1780
16
    ++StructuredIndex;
1781
16
    return;
1782
16
  }
1783
77.1k
1784
77.1k
  // We might know the maximum number of elements in advance.
1785
77.1k
  llvm::APSInt maxElements(elementIndex.getBitWidth(),
1786
77.1k
                           elementIndex.isUnsigned());
1787
77.1k
  bool maxElementsKnown = false;
1788
77.1k
  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1789
52.8k
    maxElements = CAT->getSize();
1790
52.8k
    elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1791
52.8k
    elementIndex.setIsUnsigned(maxElements.isUnsigned());
1792
52.8k
    maxElementsKnown = true;
1793
52.8k
  }
1794
77.1k
1795
77.1k
  QualType elementType = arrayType->getElementType();
1796
1.52M
  while (Index < IList->getNumInits()) {
1797
1.44M
    Expr *Init = IList->getInit(Index);
1798
1.44M
    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1799
486
      // If we're not the subobject that matches up with the '{' for
1800
486
      // the designator, we shouldn't be handling the
1801
486
      // designator. Return immediately.
1802
486
      if (!SubobjectIsDesignatorContext)
1803
32
        return;
1804
454
1805
454
      // Handle this designated initializer. elementIndex will be
1806
454
      // updated to be the next array element we'll initialize.
1807
454
      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1808
454
                                     DeclType, nullptr, &elementIndex, Index,
1809
454
                                     StructuredList, StructuredIndex, true,
1810
454
                                     false)) {
1811
24
        hadError = true;
1812
24
        continue;
1813
24
      }
1814
430
1815
430
      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1816
0
        maxElements = maxElements.extend(elementIndex.getBitWidth());
1817
430
      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1818
84
        elementIndex = elementIndex.extend(maxElements.getBitWidth());
1819
430
      elementIndex.setIsUnsigned(maxElements.isUnsigned());
1820
430
1821
430
      // If the array is of incomplete type, keep track of the number of
1822
430
      // elements in the initializer.
1823
430
      if (!maxElementsKnown && 
elementIndex > maxElements96
)
1824
54
        maxElements = elementIndex;
1825
430
1826
430
      continue;
1827
430
    }
1828
1.44M
1829
1.44M
    // If we know the maximum number of elements, and we've already
1830
1.44M
    // hit it, stop consuming elements in the initializer list.
1831
1.44M
    if (maxElementsKnown && 
elementIndex == maxElements386k
)
1832
268
      break;
1833
1.44M
1834
1.44M
    InitializedEntity ElementEntity =
1835
1.44M
      InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1836
1.44M
                                           Entity);
1837
1.44M
    // Check this element.
1838
1.44M
    CheckSubElementType(ElementEntity, IList, elementType, Index,
1839
1.44M
                        StructuredList, StructuredIndex);
1840
1.44M
    ++elementIndex;
1841
1.44M
1842
1.44M
    // If the array is of incomplete type, keep track of the number of
1843
1.44M
    // elements in the initializer.
1844
1.44M
    if (!maxElementsKnown && 
elementIndex > maxElements1.05M
)
1845
1.05M
      maxElements = elementIndex;
1846
1.44M
  }
1847
77.1k
  
if (77.1k
!hadError77.1k
&&
DeclType->isIncompleteArrayType()76.9k
&&
!VerifyOnly24.2k
) {
1848
12.1k
    // If this is an incomplete array type, the actual type needs to
1849
12.1k
    // be calculated here.
1850
12.1k
    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1851
12.1k
    if (maxElements == Zero && 
!Entity.isVariableLengthArrayNew()37
) {
1852
31
      // Sizing an array implicitly to zero is not allowed by ISO C,
1853
31
      // but is supported by GNU.
1854
31
      SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
1855
31
    }
1856
12.1k
1857
12.1k
    DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1858
12.1k
                                                     ArrayType::Normal, 0);
1859
12.1k
  }
1860
77.1k
  if (!hadError && 
VerifyOnly76.9k
) {
1861
40.1k
    // If there are any members of the array that get value-initialized, check
1862
40.1k
    // that is possible. That happens if we know the bound and don't have
1863
40.1k
    // enough elements, or if we're performing an array new with an unknown
1864
40.1k
    // bound.
1865
40.1k
    // FIXME: This needs to detect holes left by designated initializers too.
1866
40.1k
    if ((maxElementsKnown && 
elementIndex < maxElements28.0k
) ||
1867
40.1k
        
Entity.isVariableLengthArrayNew()32.3k
)
1868
7.80k
      CheckEmptyInitializable(
1869
7.80k
          InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1870
7.80k
          IList->getEndLoc());
1871
40.1k
  }
1872
77.1k
}
1873
1874
bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1875
                                             Expr *InitExpr,
1876
                                             FieldDecl *Field,
1877
68
                                             bool TopLevelObject) {
1878
68
  // Handle GNU flexible array initializers.
1879
68
  unsigned FlexArrayDiag;
1880
68
  if (isa<InitListExpr>(InitExpr) &&
1881
68
      
cast<InitListExpr>(InitExpr)->getNumInits() == 052
) {
1882
6
    // Empty flexible array init always allowed as an extension
1883
6
    FlexArrayDiag = diag::ext_flexible_array_init;
1884
62
  } else if (SemaRef.getLangOpts().CPlusPlus) {
1885
0
    // Disallow flexible array init in C++; it is not required for gcc
1886
0
    // compatibility, and it needs work to IRGen correctly in general.
1887
0
    FlexArrayDiag = diag::err_flexible_array_init;
1888
62
  } else if (!TopLevelObject) {
1889
6
    // Disallow flexible array init on non-top-level object
1890
6
    FlexArrayDiag = diag::err_flexible_array_init;
1891
56
  } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1892
2
    // Disallow flexible array init on anything which is not a variable.
1893
2
    FlexArrayDiag = diag::err_flexible_array_init;
1894
54
  } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1895
8
    // Disallow flexible array init on local variables.
1896
8
    FlexArrayDiag = diag::err_flexible_array_init;
1897
46
  } else {
1898
46
    // Allow other cases.
1899
46
    FlexArrayDiag = diag::ext_flexible_array_init;
1900
46
  }
1901
68
1902
68
  if (!VerifyOnly) {
1903
34
    SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
1904
34
        << InitExpr->getBeginLoc();
1905
34
    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1906
34
      << Field;
1907
34
  }
1908
68
1909
68
  return FlexArrayDiag != diag::ext_flexible_array_init;
1910
68
}
1911
1912
void InitListChecker::CheckStructUnionTypes(
1913
    const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
1914
    CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
1915
    bool SubobjectIsDesignatorContext, unsigned &Index,
1916
    InitListExpr *StructuredList, unsigned &StructuredIndex,
1917
90.5k
    bool TopLevelObject) {
1918
90.5k
  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
1919
90.5k
1920
90.5k
  // If the record is invalid, some of it's members are invalid. To avoid
1921
90.5k
  // confusion, we forgo checking the intializer for the entire record.
1922
90.5k
  if (structDecl->isInvalidDecl()) {
1923
26
    // Assume it was supposed to consume a single initializer.
1924
26
    ++Index;
1925
26
    hadError = true;
1926
26
    return;
1927
26
  }
1928
90.4k
1929
90.4k
  if (DeclType->isUnionType() && 
IList->getNumInits() == 06.04k
) {
1930
381
    RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1931
381
1932
381
    if (!VerifyOnly)
1933
281
      
for (FieldDecl *FD : RD->fields())159
{
1934
281
        QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
1935
281
        if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
1936
0
          hadError = true;
1937
0
          return;
1938
0
        }
1939
281
      }
1940
381
1941
381
    // If there's a default initializer, use it.
1942
381
    if (isa<CXXRecordDecl>(RD) && 
cast<CXXRecordDecl>(RD)->hasInClassInitializer()259
) {
1943
13
      if (VerifyOnly)
1944
8
        return;
1945
5
      for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1946
10
           Field != FieldEnd; 
++Field5
) {
1947
10
        if (Field->hasInClassInitializer()) {
1948
5
          StructuredList->setInitializedFieldInUnion(*Field);
1949
5
          // FIXME: Actually build a CXXDefaultInitExpr?
1950
5
          return;
1951
5
        }
1952
10
      }
1953
5
    }
1954
381
1955
381
    // Value-initialize the first member of the union that isn't an unnamed
1956
381
    // bitfield.
1957
381
    for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1958
368
         Field != FieldEnd; 
++Field0
) {
1959
325
      if (!Field->isUnnamedBitfield()) {
1960
325
        if (VerifyOnly)
1961
192
          CheckEmptyInitializable(
1962
192
              InitializedEntity::InitializeMember(*Field, &Entity),
1963
192
              IList->getEndLoc());
1964
133
        else
1965
133
          StructuredList->setInitializedFieldInUnion(*Field);
1966
325
        break;
1967
325
      }
1968
325
    }
1969
368
    return;
1970
90.1k
  }
1971
90.1k
1972
90.1k
  bool InitializedSomething = false;
1973
90.1k
1974
90.1k
  // If we have any base classes, they are initialized prior to the fields.
1975
90.1k
  for (auto &Base : Bases) {
1976
370
    Expr *Init = Index < IList->getNumInits() ? 
IList->getInit(Index)198
:
nullptr172
;
1977
370
1978
370
    // Designated inits always initialize fields, so if we see one, all
1979
370
    // remaining base classes have no explicit initializer.
1980
370
    if (Init && 
isa<DesignatedInitExpr>(Init)198
)
1981
0
      Init = nullptr;
1982
370
1983
370
    SourceLocation InitLoc = Init ? 
Init->getBeginLoc()198
:
IList->getEndLoc()172
;
1984
370
    InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
1985
370
        SemaRef.Context, &Base, false, &Entity);
1986
370
    if (Init) {
1987
198
      CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
1988
198
                          StructuredList, StructuredIndex);
1989
198
      InitializedSomething = true;
1990
198
    } else 
if (172
VerifyOnly172
) {
1991
104
      CheckEmptyInitializable(BaseEntity, InitLoc);
1992
104
    }
1993
370
1994
370
    if (!VerifyOnly)
1995
163
      if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
1996
1
        hadError = true;
1997
1
        return;
1998
1
      }
1999
370
  }
2000
90.1k
2001
90.1k
  // If structDecl is a forward declaration, this loop won't do
2002
90.1k
  // anything except look at designated initializers; That's okay,
2003
90.1k
  // because an error should get printed out elsewhere. It might be
2004
90.1k
  // worthwhile to skip over the rest of the initializer, though.
2005
90.1k
  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
2006
90.1k
  RecordDecl::field_iterator FieldEnd = RD->field_end();
2007
90.1k
  bool CheckForMissingFields =
2008
90.1k
    !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
2009
90.1k
  bool HasDesignatedInit = false;
2010
90.1k
2011
288k
  while (Index < IList->getNumInits()) {
2012
200k
    Expr *Init = IList->getInit(Index);
2013
200k
    SourceLocation InitLoc = Init->getBeginLoc();
2014
200k
2015
200k
    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2016
5.17k
      // If we're not the subobject that matches up with the '{' for
2017
5.17k
      // the designator, we shouldn't be handling the
2018
5.17k
      // designator. Return immediately.
2019
5.17k
      if (!SubobjectIsDesignatorContext)
2020
164
        return;
2021
5.01k
2022
5.01k
      HasDesignatedInit = true;
2023
5.01k
2024
5.01k
      // Handle this designated initializer. Field will be updated to
2025
5.01k
      // the next field that we'll be initializing.
2026
5.01k
      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2027
5.01k
                                     DeclType, &Field, nullptr, Index,
2028
5.01k
                                     StructuredList, StructuredIndex,
2029
5.01k
                                     true, TopLevelObject))
2030
38
        hadError = true;
2031
4.97k
      else if (!VerifyOnly) {
2032
2.47k
        // Find the field named by the designated initializer.
2033
2.47k
        RecordDecl::field_iterator F = RD->field_begin();
2034
3.74k
        while (std::next(F) != Field)
2035
1.27k
          ++F;
2036
2.47k
        QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2037
2.47k
        if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2038
0
          hadError = true;
2039
0
          return;
2040
0
        }
2041
5.01k
      }
2042
5.01k
2043
5.01k
      InitializedSomething = true;
2044
5.01k
2045
5.01k
      // Disable check for missing fields when designators are used.
2046
5.01k
      // This matches gcc behaviour.
2047
5.01k
      CheckForMissingFields = false;
2048
5.01k
      continue;
2049
5.01k
    }
2050
195k
2051
195k
    if (Field == FieldEnd) {
2052
1.75k
      // We've run out of fields. We're done.
2053
1.75k
      break;
2054
1.75k
    }
2055
193k
2056
193k
    // We've already initialized a member of a union. We're done.
2057
193k
    if (InitializedSomething && 
DeclType->isUnionType()123k
)
2058
40
      break;
2059
193k
2060
193k
    // If we've hit the flexible array member at the end, we're done.
2061
193k
    if (Field->getType()->isIncompleteArrayType())
2062
56
      break;
2063
193k
2064
193k
    if (Field->isUnnamedBitfield()) {
2065
132
      // Don't initialize unnamed bitfields, e.g. "int : 20;"
2066
132
      ++Field;
2067
132
      continue;
2068
132
    }
2069
193k
2070
193k
    // Make sure we can use this declaration.
2071
193k
    bool InvalidUse;
2072
193k
    if (VerifyOnly)
2073
107k
      InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2074
86.0k
    else
2075
86.0k
      InvalidUse = SemaRef.DiagnoseUseOfDecl(
2076
86.0k
          *Field, IList->getInit(Index)->getBeginLoc());
2077
193k
    if (InvalidUse) {
2078
0
      ++Index;
2079
0
      ++Field;
2080
0
      hadError = true;
2081
0
      continue;
2082
0
    }
2083
193k
2084
193k
    if (!VerifyOnly) {
2085
86.0k
      QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2086
86.0k
      if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2087
6
        hadError = true;
2088
6
        return;
2089
6
      }
2090
193k
    }
2091
193k
2092
193k
    InitializedEntity MemberEntity =
2093
193k
      InitializedEntity::InitializeMember(*Field, &Entity);
2094
193k
    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2095
193k
                        StructuredList, StructuredIndex);
2096
193k
    InitializedSomething = true;
2097
193k
2098
193k
    if (DeclType->isUnionType() && 
!VerifyOnly1.58k
) {
2099
790
      // Initialize the first field within the union.
2100
790
      StructuredList->setInitializedFieldInUnion(*Field);
2101
790
    }
2102
193k
2103
193k
    ++Field;
2104
193k
  }
2105
90.1k
2106
90.1k
  // Emit warnings for missing struct field initializers.
2107
90.1k
  
if (89.9k
!VerifyOnly89.9k
&&
InitializedSomething40.4k
&&
CheckForMissingFields33.0k
&&
2108
89.9k
      
Field != FieldEnd30.5k
&&
!Field->getType()->isIncompleteArrayType()1.15k
&&
2109
89.9k
      
!DeclType->isUnionType()1.11k
) {
2110
392
    // It is possible we have one or more unnamed bitfields remaining.
2111
392
    // Find first (if any) named field and emit warning.
2112
392
    for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2113
433
         it != end; 
++it41
) {
2114
401
      if (!it->isUnnamedBitfield() && 
!it->hasInClassInitializer()381
) {
2115
360
        SemaRef.Diag(IList->getSourceRange().getEnd(),
2116
360
                     diag::warn_missing_field_initializers) << *it;
2117
360
        break;
2118
360
      }
2119
401
    }
2120
392
  }
2121
89.9k
2122
89.9k
  // Check that any remaining fields can be value-initialized.
2123
89.9k
  if (VerifyOnly && 
Field != FieldEnd49.4k
&&
!DeclType->isUnionType()3.93k
&&
2124
89.9k
      
!Field->getType()->isIncompleteArrayType()2.21k
) {
2125
2.16k
    // FIXME: Should check for holes left by designated initializers too.
2126
6.71k
    for (; Field != FieldEnd && 
!hadError4.58k
;
++Field4.55k
) {
2127
4.55k
      if (!Field->isUnnamedBitfield() && 
!Field->hasInClassInitializer()4.50k
)
2128
4.31k
        CheckEmptyInitializable(
2129
4.31k
            InitializedEntity::InitializeMember(*Field, &Entity),
2130
4.31k
            IList->getEndLoc());
2131
4.55k
    }
2132
2.16k
  }
2133
89.9k
2134
89.9k
  // Check that the types of the remaining fields have accessible destructors.
2135
89.9k
  if (!VerifyOnly) {
2136
40.4k
    // If the initializer expression has a designated initializer, check the
2137
40.4k
    // elements for which a designated initializer is not provided too.
2138
40.4k
    RecordDecl::field_iterator I = HasDesignatedInit ? 
RD->field_begin()2.34k
2139
40.4k
                                                     : 
Field38.1k
;
2140
49.7k
    for (RecordDecl::field_iterator E = RD->field_end(); I != E; 
++I9.26k
) {
2141
9.26k
      QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2142
9.26k
      if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2143
3
        hadError = true;
2144
3
        return;
2145
3
      }
2146
9.26k
    }
2147
40.4k
  }
2148
89.9k
2149
89.9k
  
if (89.9k
Field == FieldEnd89.9k
||
!Field->getType()->isIncompleteArrayType()5.28k
||
2150
89.9k
      
Index >= IList->getNumInits()100
)
2151
89.8k
    return;
2152
56
2153
56
  if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2154
56
                             TopLevelObject)) {
2155
10
    hadError = true;
2156
10
    ++Index;
2157
10
    return;
2158
10
  }
2159
46
2160
46
  InitializedEntity MemberEntity =
2161
46
    InitializedEntity::InitializeMember(*Field, &Entity);
2162
46
2163
46
  if (isa<InitListExpr>(IList->getInit(Index)))
2164
34
    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2165
34
                        StructuredList, StructuredIndex);
2166
12
  else
2167
12
    CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2168
12
                          StructuredList, StructuredIndex);
2169
46
}
2170
2171
/// Expand a field designator that refers to a member of an
2172
/// anonymous struct or union into a series of field designators that
2173
/// refers to the field within the appropriate subobject.
2174
///
2175
static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2176
                                           DesignatedInitExpr *DIE,
2177
                                           unsigned DesigIdx,
2178
30
                                           IndirectFieldDecl *IndirectField) {
2179
30
  typedef DesignatedInitExpr::Designator Designator;
2180
30
2181
30
  // Build the replacement designators.
2182
30
  SmallVector<Designator, 4> Replacements;
2183
30
  for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2184
101
       PE = IndirectField->chain_end(); PI != PE; 
++PI71
) {
2185
71
    if (PI + 1 == PE)
2186
30
      Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2187
30
                                    DIE->getDesignator(DesigIdx)->getDotLoc(),
2188
30
                                DIE->getDesignator(DesigIdx)->getFieldLoc()));
2189
41
    else
2190
41
      Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2191
41
                                        SourceLocation(), SourceLocation()));
2192
71
    assert(isa<FieldDecl>(*PI));
2193
71
    Replacements.back().setField(cast<FieldDecl>(*PI));
2194
71
  }
2195
30
2196
30
  // Expand the current designator into the set of replacement
2197
30
  // designators, so we have a full subobject path down to where the
2198
30
  // member of the anonymous struct/union is actually stored.
2199
30
  DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2200
30
                        &Replacements[0] + Replacements.size());
2201
30
}
2202
2203
static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2204
30
                                                   DesignatedInitExpr *DIE) {
2205
30
  unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2206
30
  SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2207
30
  for (unsigned I = 0; I < NumIndexExprs; 
++I0
)
2208
0
    IndexExprs[I] = DIE->getSubExpr(I + 1);
2209
30
  return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2210
30
                                    IndexExprs,
2211
30
                                    DIE->getEqualOrColonLoc(),
2212
30
                                    DIE->usesGNUSyntax(), DIE->getInit());
2213
30
}
2214
2215
namespace {
2216
2217
// Callback to only accept typo corrections that are for field members of
2218
// the given struct or union.
2219
class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2220
 public:
2221
  explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2222
18
      : Record(RD) {}
2223
2224
8
  bool ValidateCandidate(const TypoCorrection &candidate) override {
2225
8
    FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2226
8
    return FD && 
FD->getDeclContext()->getRedeclContext()->Equals(Record)7
;
2227
8
  }
2228
2229
12
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
2230
12
    return llvm::make_unique<FieldInitializerValidatorCCC>(*this);
2231
12
  }
2232
2233
 private:
2234
  RecordDecl *Record;
2235
};
2236
2237
} // end anonymous namespace
2238
2239
/// Check the well-formedness of a C99 designated initializer.
2240
///
2241
/// Determines whether the designated initializer @p DIE, which
2242
/// resides at the given @p Index within the initializer list @p
2243
/// IList, is well-formed for a current object of type @p DeclType
2244
/// (C99 6.7.8). The actual subobject that this designator refers to
2245
/// within the current subobject is returned in either
2246
/// @p NextField or @p NextElementIndex (whichever is appropriate).
2247
///
2248
/// @param IList  The initializer list in which this designated
2249
/// initializer occurs.
2250
///
2251
/// @param DIE The designated initializer expression.
2252
///
2253
/// @param DesigIdx  The index of the current designator.
2254
///
2255
/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2256
/// into which the designation in @p DIE should refer.
2257
///
2258
/// @param NextField  If non-NULL and the first designator in @p DIE is
2259
/// a field, this will be set to the field declaration corresponding
2260
/// to the field named by the designator.
2261
///
2262
/// @param NextElementIndex  If non-NULL and the first designator in @p
2263
/// DIE is an array designator or GNU array-range designator, this
2264
/// will be set to the last index initialized by this designator.
2265
///
2266
/// @param Index  Index into @p IList where the designated initializer
2267
/// @p DIE occurs.
2268
///
2269
/// @param StructuredList  The initializer list expression that
2270
/// describes all of the subobject initializers in the order they'll
2271
/// actually be initialized.
2272
///
2273
/// @returns true if there was an error, false otherwise.
2274
bool
2275
InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2276
                                            InitListExpr *IList,
2277
                                            DesignatedInitExpr *DIE,
2278
                                            unsigned DesigIdx,
2279
                                            QualType &CurrentObjectType,
2280
                                          RecordDecl::field_iterator *NextField,
2281
                                            llvm::APSInt *NextElementIndex,
2282
                                            unsigned &Index,
2283
                                            InitListExpr *StructuredList,
2284
                                            unsigned &StructuredIndex,
2285
                                            bool FinishSubobjectInit,
2286
11.5k
                                            bool TopLevelObject) {
2287
11.5k
  if (DesigIdx == DIE->size()) {
2288
5.47k
    // Check the actual initialization for the designated object type.
2289
5.47k
    bool prevHadError = hadError;
2290
5.47k
2291
5.47k
    // Temporarily remove the designator expression from the
2292
5.47k
    // initializer list that the child calls see, so that we don't try
2293
5.47k
    // to re-process the designator.
2294
5.47k
    unsigned OldIndex = Index;
2295
5.47k
    IList->setInit(OldIndex, DIE->getInit());
2296
5.47k
2297
5.47k
    CheckSubElementType(Entity, IList, CurrentObjectType, Index,
2298
5.47k
                        StructuredList, StructuredIndex);
2299
5.47k
2300
5.47k
    // Restore the designated initializer expression in the syntactic
2301
5.47k
    // form of the initializer list.
2302
5.47k
    if (IList->getInit(OldIndex) != DIE->getInit())
2303
2.10k
      DIE->setInit(IList->getInit(OldIndex));
2304
5.47k
    IList->setInit(OldIndex, DIE);
2305
5.47k
2306
5.47k
    return hadError && 
!prevHadError40
;
2307
5.47k
  }
2308
6.04k
2309
6.04k
  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2310
6.04k
  bool IsFirstDesignator = (DesigIdx == 0);
2311
6.04k
  if (!VerifyOnly) {
2312
3.00k
    assert((IsFirstDesignator || StructuredList) &&
2313
3.00k
           "Need a non-designated initializer list to start from");
2314
3.00k
2315
3.00k
    // Determine the structural initializer list that corresponds to the
2316
3.00k
    // current subobject.
2317
3.00k
    if (IsFirstDesignator)
2318
2.71k
      StructuredList = SyntacticToSemantic.lookup(IList);
2319
293
    else {
2320
293
      Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2321
293
          StructuredList->getInit(StructuredIndex) : 
nullptr0
;
2322
293
      if (!ExistingInit && 
StructuredList->hasArrayFiller()175
)
2323
1
        ExistingInit = StructuredList->getArrayFiller();
2324
293
2325
293
      if (!ExistingInit)
2326
174
        StructuredList = getStructuredSubobjectInit(
2327
174
            IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2328
174
            SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2329
119
      else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2330
58
        StructuredList = Result;
2331
61
      else {
2332
61
        if (DesignatedInitUpdateExpr *E =
2333
12
                dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2334
12
          StructuredList = E->getUpdater();
2335
49
        else {
2336
49
          DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2337
49
              DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2338
49
                                       ExistingInit, DIE->getEndLoc());
2339
49
          StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2340
49
          StructuredList = DIUE->getUpdater();
2341
49
        }
2342
61
2343
61
        // We need to check on source range validity because the previous
2344
61
        // initializer does not have to be an explicit initializer. e.g.,
2345
61
        //
2346
61
        // struct P { int a, b; };
2347
61
        // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2348
61
        //
2349
61
        // There is an overwrite taking place because the first braced initializer
2350
61
        // list "{ .a = 2 }" already provides value for .p.b (which is zero).
2351
61
        if (ExistingInit->getSourceRange().isValid()) {
2352
59
          // We are creating an initializer list that initializes the
2353
59
          // subobjects of the current object, but there was already an
2354
59
          // initialization that completely initialized the current
2355
59
          // subobject, e.g., by a compound literal:
2356
59
          //
2357
59
          // struct X { int a, b; };
2358
59
          // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2359
59
          //
2360
59
          // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2361
59
          // designated initializer re-initializes the whole
2362
59
          // subobject [0], overwriting previous initializers.
2363
59
          SemaRef.Diag(D->getBeginLoc(),
2364
59
                       diag::warn_subobject_initializer_overrides)
2365
59
              << SourceRange(D->getBeginLoc(), DIE->getEndLoc());
2366
59
2367
59
          SemaRef.Diag(ExistingInit->getBeginLoc(),
2368
59
                       diag::note_previous_initializer)
2369
59
              << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
2370
59
        }
2371
61
      }
2372
293
    }
2373
3.00k
    assert(StructuredList && "Expected a structured initializer list");
2374
3.00k
  }
2375
6.04k
2376
6.04k
  if (D->isFieldDesignator()) {
2377
5.45k
    // C99 6.7.8p7:
2378
5.45k
    //
2379
5.45k
    //   If a designator has the form
2380
5.45k
    //
2381
5.45k
    //      . identifier
2382
5.45k
    //
2383
5.45k
    //   then the current object (defined below) shall have
2384
5.45k
    //   structure or union type and the identifier shall be the
2385
5.45k
    //   name of a member of that type.
2386
5.45k
    const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2387
5.45k
    if (!RT) {
2388
2
      SourceLocation Loc = D->getDotLoc();
2389
2
      if (Loc.isInvalid())
2390
0
        Loc = D->getFieldLoc();
2391
2
      if (!VerifyOnly)
2392
1
        SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2393
1
          << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2394
2
      ++Index;
2395
2
      return true;
2396
2
    }
2397
5.45k
2398
5.45k
    FieldDecl *KnownField = D->getField();
2399
5.45k
    if (!KnownField) {
2400
5.33k
      IdentifierInfo *FieldName = D->getFieldName();
2401
5.33k
      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2402
5.33k
      for (NamedDecl *ND : Lookup) {
2403
5.30k
        if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2404
5.27k
          KnownField = FD;
2405
5.27k
          break;
2406
5.27k
        }
2407
30
        if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2408
30
          // In verify mode, don't modify the original.
2409
30
          if (VerifyOnly)
2410
30
            DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2411
30
          ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2412
30
          D = DIE->getDesignator(DesigIdx);
2413
30
          KnownField = cast<FieldDecl>(*IFD->chain_begin());
2414
30
          break;
2415
30
        }
2416
30
      }
2417
5.33k
      if (!KnownField) {
2418
33
        if (VerifyOnly) {
2419
15
          ++Index;
2420
15
          return true;  // No typo correction when just trying this out.
2421
15
        }
2422
18
2423
18
        // Name lookup found something, but it wasn't a field.
2424
18
        if (!Lookup.empty()) {
2425
0
          SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2426
0
            << FieldName;
2427
0
          SemaRef.Diag(Lookup.front()->getLocation(),
2428
0
                       diag::note_field_designator_found);
2429
0
          ++Index;
2430
0
          return true;
2431
0
        }
2432
18
2433
18
        // Name lookup didn't find anything.
2434
18
        // Determine whether this was a typo for another field name.
2435
18
        FieldInitializerValidatorCCC CCC(RT->getDecl());
2436
18
        if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2437
7
                DeclarationNameInfo(FieldName, D->getFieldLoc()),
2438
7
                Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2439
7
                Sema::CTK_ErrorRecovery, RT->getDecl())) {
2440
7
          SemaRef.diagnoseTypo(
2441
7
              Corrected,
2442
7
              SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2443
7
                << FieldName << CurrentObjectType);
2444
7
          KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2445
7
          hadError = true;
2446
11
        } else {
2447
11
          // Typo correction didn't find anything.
2448
11
          SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2449
11
            << FieldName << CurrentObjectType;
2450
11
          ++Index;
2451
11
          return true;
2452
11
        }
2453
5.42k
      }
2454
5.33k
    }
2455
5.42k
2456
5.42k
    unsigned FieldIndex = 0;
2457
5.42k
2458
5.42k
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2459
527
      FieldIndex = CXXRD->getNumBases();
2460
5.42k
2461
8.22k
    for (auto *FI : RT->getDecl()->fields()) {
2462
8.22k
      if (FI->isUnnamedBitfield())
2463
2
        continue;
2464
8.22k
      if (declaresSameEntity(KnownField, FI)) {
2465
5.42k
        KnownField = FI;
2466
5.42k
        break;
2467
5.42k
      }
2468
2.79k
      ++FieldIndex;
2469
2.79k
    }
2470
5.42k
2471
5.42k
    RecordDecl::field_iterator Field =
2472
5.42k
        RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2473
5.42k
2474
5.42k
    // All of the fields of a union are located at the same place in
2475
5.42k
    // the initializer list.
2476
5.42k
    if (RT->getDecl()->isUnion()) {
2477
4.16k
      FieldIndex = 0;
2478
4.16k
      if (!VerifyOnly) {
2479
2.06k
        FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2480
2.06k
        if (CurrentField && 
!declaresSameEntity(CurrentField, *Field)24
) {
2481
19
          assert(StructuredList->getNumInits() == 1
2482
19
                 && "A union should never have more than one initializer!");
2483
19
2484
19
          Expr *ExistingInit = StructuredList->getInit(0);
2485
19
          if (ExistingInit) {
2486
18
            // We're about to throw away an initializer, emit warning.
2487
18
            SemaRef.Diag(D->getFieldLoc(),
2488
18
                         diag::warn_initializer_overrides)
2489
18
              << D->getSourceRange();
2490
18
            SemaRef.Diag(ExistingInit->getBeginLoc(),
2491
18
                         diag::note_previous_initializer)
2492
18
                << /*FIXME:has side effects=*/0
2493
18
                << ExistingInit->getSourceRange();
2494
18
          }
2495
19
2496
19
          // remove existing initializer
2497
19
          StructuredList->resizeInits(SemaRef.Context, 0);
2498
19
          StructuredList->setInitializedFieldInUnion(nullptr);
2499
19
        }
2500
2.06k
2501
2.06k
        StructuredList->setInitializedFieldInUnion(*Field);
2502
2.06k
      }
2503
4.16k
    }
2504
5.42k
2505
5.42k
    // Make sure we can use this declaration.
2506
5.42k
    bool InvalidUse;
2507
5.42k
    if (VerifyOnly)
2508
2.72k
      InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2509
2.70k
    else
2510
2.70k
      InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2511
5.42k
    if (InvalidUse) {
2512
0
      ++Index;
2513
0
      return true;
2514
0
    }
2515
5.42k
2516
5.42k
    if (!VerifyOnly) {
2517
2.70k
      // Update the designator with the field declaration.
2518
2.70k
      D->setField(*Field);
2519
2.70k
2520
2.70k
      // Make sure that our non-designated initializer list has space
2521
2.70k
      // for a subobject corresponding to this field.
2522
2.70k
      if (FieldIndex >= StructuredList->getNumInits())
2523
2.56k
        StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2524
2.70k
    }
2525
5.42k
2526
5.42k
    // This designator names a flexible array member.
2527
5.42k
    if (Field->getType()->isIncompleteArrayType()) {
2528
16
      bool Invalid = false;
2529
16
      if ((DesigIdx + 1) != DIE->size()) {
2530
2
        // We can't designate an object within the flexible array
2531
2
        // member (because GCC doesn't allow it).
2532
2
        if (!VerifyOnly) {
2533
1
          DesignatedInitExpr::Designator *NextD
2534
1
            = DIE->getDesignator(DesigIdx + 1);
2535
1
          SemaRef.Diag(NextD->getBeginLoc(),
2536
1
                       diag::err_designator_into_flexible_array_member)
2537
1
              << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2538
1
          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2539
1
            << *Field;
2540
1
        }
2541
2
        Invalid = true;
2542
2
      }
2543
16
2544
16
      if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2545
16
          
!isa<StringLiteral>(DIE->getInit())6
) {
2546
2
        // The initializer is not an initializer list.
2547
2
        if (!VerifyOnly) {
2548
1
          SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2549
1
                       diag::err_flexible_array_init_needs_braces)
2550
1
              << DIE->getInit()->getSourceRange();
2551
1
          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2552
1
            << *Field;
2553
1
        }
2554
2
        Invalid = true;
2555
2
      }
2556
16
2557
16
      // Check GNU flexible array initializer.
2558
16
      if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2559
12
                                             TopLevelObject))
2560
6
        Invalid = true;
2561
16
2562
16
      if (Invalid) {
2563
10
        ++Index;
2564
10
        return true;
2565
10
      }
2566
6
2567
6
      // Initialize the array.
2568
6
      bool prevHadError = hadError;
2569
6
      unsigned newStructuredIndex = FieldIndex;
2570
6
      unsigned OldIndex = Index;
2571
6
      IList->setInit(Index, DIE->getInit());
2572
6
2573
6
      InitializedEntity MemberEntity =
2574
6
        InitializedEntity::InitializeMember(*Field, &Entity);
2575
6
      CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2576
6
                          StructuredList, newStructuredIndex);
2577
6
2578
6
      IList->setInit(OldIndex, DIE);
2579
6
      if (hadError && 
!prevHadError0
) {
2580
0
        ++Field;
2581
0
        ++FieldIndex;
2582
0
        if (NextField)
2583
0
          *NextField = Field;
2584
0
        StructuredIndex = FieldIndex;
2585
0
        return true;
2586
0
      }
2587
5.41k
    } else {
2588
5.41k
      // Recurse to check later designated subobjects.
2589
5.41k
      QualType FieldType = Field->getType();
2590
5.41k
      unsigned newStructuredIndex = FieldIndex;
2591
5.41k
2592
5.41k
      InitializedEntity MemberEntity =
2593
5.41k
        InitializedEntity::InitializeMember(*Field, &Entity);
2594
5.41k
      if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2595
5.41k
                                     FieldType, nullptr, nullptr, Index,
2596
5.41k
                                     StructuredList, newStructuredIndex,
2597
5.41k
                                     FinishSubobjectInit, false))
2598
6
        return true;
2599
5.41k
    }
2600
5.41k
2601
5.41k
    // Find the position of the next field to be initialized in this
2602
5.41k
    // subobject.
2603
5.41k
    ++Field;
2604
5.41k
    ++FieldIndex;
2605
5.41k
2606
5.41k
    // If this the first designator, our caller will continue checking
2607
5.41k
    // the rest of this struct/class/union subobject.
2608
5.41k
    if (IsFirstDesignator) {
2609
4.97k
      if (NextField)
2610
4.97k
        *NextField = Field;
2611
4.97k
      StructuredIndex = FieldIndex;
2612
4.97k
      return false;
2613
4.97k
    }
2614
438
2615
438
    if (!FinishSubobjectInit)
2616
4
      return false;
2617
434
2618
434
    // We've already initialized something in the union; we're done.
2619
434
    if (RT->getDecl()->isUnion())
2620
46
      return hadError;
2621
388
2622
388
    // Check the remaining fields within this class/struct/union subobject.
2623
388
    bool prevHadError = hadError;
2624
388
2625
388
    auto NoBases =
2626
388
        CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2627
388
                                        CXXRecordDecl::base_class_iterator());
2628
388
    CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2629
388
                          false, Index, StructuredList, FieldIndex);
2630
388
    return hadError && 
!prevHadError10
;
2631
388
  }
2632
590
2633
590
  // C99 6.7.8p6:
2634
590
  //
2635
590
  //   If a designator has the form
2636
590
  //
2637
590
  //      [ constant-expression ]
2638
590
  //
2639
590
  //   then the current object (defined below) shall have array
2640
590
  //   type and the expression shall be an integer constant
2641
590
  //   expression. If the array is of unknown size, any
2642
590
  //   nonnegative value is valid.
2643
590
  //
2644
590
  // Additionally, cope with the GNU extension that permits
2645
590
  // designators of the form
2646
590
  //
2647
590
  //      [ constant-expression ... constant-expression ]
2648
590
  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2649
590
  if (!AT) {
2650
2
    if (!VerifyOnly)
2651
1
      SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2652
1
        << CurrentObjectType;
2653
2
    ++Index;
2654
2
    return true;
2655
2
  }
2656
588
2657
588
  Expr *IndexExpr = nullptr;
2658
588
  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2659
588
  if (D->isArrayDesignator()) {
2660
544
    IndexExpr = DIE->getArrayIndex(*D);
2661
544
    DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2662
544
    DesignatedEndIndex = DesignatedStartIndex;
2663
544
  } else {
2664
44
    assert(D->isArrayRangeDesignator() && "Need array-range designator");
2665
44
2666
44
    DesignatedStartIndex =
2667
44
      DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2668
44
    DesignatedEndIndex =
2669
44
      DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2670
44
    IndexExpr = DIE->getArrayRangeEnd(*D);
2671
44
2672
44
    // Codegen can't handle evaluating array range designators that have side
2673
44
    // effects, because we replicate the AST value for each initialized element.
2674
44
    // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2675
44
    // elements with something that has a side effect, so codegen can emit an
2676
44
    // "error unsupported" error instead of miscompiling the app.
2677
44
    if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2678
44
        DIE->getInit()->HasSideEffects(SemaRef.Context) && 
!VerifyOnly0
)
2679
0
      FullyStructuredList->sawArrayRangeDesignator();
2680
44
  }
2681
588
2682
588
  if (isa<ConstantArrayType>(AT)) {
2683
492
    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2684
492
    DesignatedStartIndex
2685
492
      = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2686
492
    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2687
492
    DesignatedEndIndex
2688
492
      = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2689
492
    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2690
492
    if (DesignatedEndIndex >= MaxElements) {
2691
18
      if (!VerifyOnly)
2692
9
        SemaRef.Diag(IndexExpr->getBeginLoc(),
2693
9
                     diag::err_array_designator_too_large)
2694
9
            << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2695
9
            << IndexExpr->getSourceRange();
2696
18
      ++Index;
2697
18
      return true;
2698
18
    }
2699
96
  } else {
2700
96
    unsigned DesignatedIndexBitWidth =
2701
96
      ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2702
96
    DesignatedStartIndex =
2703
96
      DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2704
96
    DesignatedEndIndex =
2705
96
      DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2706
96
    DesignatedStartIndex.setIsUnsigned(true);
2707
96
    DesignatedEndIndex.setIsUnsigned(true);
2708
96
  }
2709
588
2710
588
  
if (570
!VerifyOnly570
&&
StructuredList->isStringLiteralInit()285
) {
2711
0
    // We're modifying a string literal init; we have to decompose the string
2712
0
    // so we can modify the individual characters.
2713
0
    ASTContext &Context = SemaRef.Context;
2714
0
    Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2715
0
2716
0
    // Compute the character type
2717
0
    QualType CharTy = AT->getElementType();
2718
0
2719
0
    // Compute the type of the integer literals.
2720
0
    QualType PromotedCharTy = CharTy;
2721
0
    if (CharTy->isPromotableIntegerType())
2722
0
      PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2723
0
    unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2724
0
2725
0
    if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2726
0
      // Get the length of the string.
2727
0
      uint64_t StrLen = SL->getLength();
2728
0
      if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2729
0
        StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2730
0
      StructuredList->resizeInits(Context, StrLen);
2731
0
2732
0
      // Build a literal for each character in the string, and put them into
2733
0
      // the init list.
2734
0
      for (unsigned i = 0, e = StrLen; i != e; ++i) {
2735
0
        llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2736
0
        Expr *Init = new (Context) IntegerLiteral(
2737
0
            Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2738
0
        if (CharTy != PromotedCharTy)
2739
0
          Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2740
0
                                          Init, nullptr, VK_RValue);
2741
0
        StructuredList->updateInit(Context, i, Init);
2742
0
      }
2743
0
    } else {
2744
0
      ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2745
0
      std::string Str;
2746
0
      Context.getObjCEncodingForType(E->getEncodedType(), Str);
2747
0
2748
0
      // Get the length of the string.
2749
0
      uint64_t StrLen = Str.size();
2750
0
      if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2751
0
        StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2752
0
      StructuredList->resizeInits(Context, StrLen);
2753
0
2754
0
      // Build a literal for each character in the string, and put them into
2755
0
      // the init list.
2756
0
      for (unsigned i = 0, e = StrLen; i != e; ++i) {
2757
0
        llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2758
0
        Expr *Init = new (Context) IntegerLiteral(
2759
0
            Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2760
0
        if (CharTy != PromotedCharTy)
2761
0
          Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2762
0
                                          Init, nullptr, VK_RValue);
2763
0
        StructuredList->updateInit(Context, i, Init);
2764
0
      }
2765
0
    }
2766
0
  }
2767
570
2768
570
  // Make sure that our non-designated initializer list has space
2769
570
  // for a subobject corresponding to this array element.
2770
570
  if (!VerifyOnly &&
2771
570
      
DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()285
)
2772
227
    StructuredList->resizeInits(SemaRef.Context,
2773
227
                                DesignatedEndIndex.getZExtValue() + 1);
2774
570
2775
570
  // Repeatedly perform subobject initializations in the range
2776
570
  // [DesignatedStartIndex, DesignatedEndIndex].
2777
570
2778
570
  // Move to the next designator
2779
570
  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2780
570
  unsigned OldIndex = Index;
2781
570
2782
570
  InitializedEntity ElementEntity =
2783
570
    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2784
570
2785
1.21k
  while (DesignatedStartIndex <= DesignatedEndIndex) {
2786
644
    // Recurse to check later designated subobjects.
2787
644
    QualType ElementType = AT->getElementType();
2788
644
    Index = OldIndex;
2789
644
2790
644
    ElementEntity.setElementIndex(ElementIndex);
2791
644
    if (CheckDesignatedInitializer(
2792
644
            ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
2793
644
            nullptr, Index, StructuredList, ElementIndex,
2794
644
            FinishSubobjectInit && 
(DesignatedStartIndex == DesignatedEndIndex)636
,
2795
644
            false))
2796
4
      return true;
2797
640
2798
640
    // Move to the next index in the array that we'll be initializing.
2799
640
    ++DesignatedStartIndex;
2800
640
    ElementIndex = DesignatedStartIndex.getZExtValue();
2801
640
  }
2802
570
2803
570
  // If this the first designator, our caller will continue checking
2804
570
  // the rest of this array subobject.
2805
570
  
if (566
IsFirstDesignator566
) {
2806
430
    if (NextElementIndex)
2807
430
      *NextElementIndex = DesignatedStartIndex;
2808
430
    StructuredIndex = ElementIndex;
2809
430
    return false;
2810
430
  }
2811
136
2812
136
  if (!FinishSubobjectInit)
2813
4
    return false;
2814
132
2815
132
  // Check the remaining elements within this array subobject.
2816
132
  bool prevHadError = hadError;
2817
132
  CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2818
132
                 /*SubobjectIsDesignatorContext=*/false, Index,
2819
132
                 StructuredList, ElementIndex);
2820
132
  return hadError && 
!prevHadError0
;
2821
132
}
2822
2823
// Get the structured initializer list for a subobject of type
2824
// @p CurrentObjectType.
2825
InitListExpr *
2826
InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2827
                                            QualType CurrentObjectType,
2828
                                            InitListExpr *StructuredList,
2829
                                            unsigned StructuredIndex,
2830
                                            SourceRange InitRange,
2831
255k
                                            bool IsFullyOverwritten) {
2832
255k
  if (VerifyOnly)
2833
133k
    return nullptr; // No structured list in verification-only mode.
2834
121k
  Expr *ExistingInit = nullptr;
2835
121k
  if (!StructuredList)
2836
96.8k
    ExistingInit = SyntacticToSemantic.lookup(IList);
2837
24.6k
  else if (StructuredIndex < StructuredList->getNumInits())
2838
231
    ExistingInit = StructuredList->getInit(StructuredIndex);
2839
121k
2840
121k
  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2841
6
    // There might have already been initializers for subobjects of the current
2842
6
    // object, but a subsequent initializer list will overwrite the entirety
2843
6
    // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
2844
6
    //
2845
6
    // struct P { char x[6]; };
2846
6
    // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
2847
6
    //
2848
6
    // The first designated initializer is ignored, and l.x is just "f".
2849
6
    if (!IsFullyOverwritten)
2850
1
      return Result;
2851
121k
2852
121k
  if (ExistingInit) {
2853
10
    // We are creating an initializer list that initializes the
2854
10
    // subobjects of the current object, but there was already an
2855
10
    // initialization that completely initialized the current
2856
10
    // subobject, e.g., by a compound literal:
2857
10
    //
2858
10
    // struct X { int a, b; };
2859
10
    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2860
10
    //
2861
10
    // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2862
10
    // designated initializer re-initializes the whole
2863
10
    // subobject [0], overwriting previous initializers.
2864
10
    SemaRef.Diag(InitRange.getBegin(),
2865
10
                 diag::warn_subobject_initializer_overrides)
2866
10
      << InitRange;
2867
10
    SemaRef.Diag(ExistingInit->getBeginLoc(), diag::note_previous_initializer)
2868
10
        << /*FIXME:has side effects=*/0 << ExistingInit->getSourceRange();
2869
10
  }
2870
121k
2871
121k
  InitListExpr *Result
2872
121k
    = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2873
121k
                                         InitRange.getBegin(), None,
2874
121k
                                         InitRange.getEnd());
2875
121k
2876
121k
  QualType ResultType = CurrentObjectType;
2877
121k
  if (!ResultType->isArrayType())
2878
84.5k
    ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2879
121k
  Result->setType(ResultType);
2880
121k
2881
121k
  // Pre-allocate storage for the structured initializer list.
2882
121k
  unsigned NumElements = 0;
2883
121k
  unsigned NumInits = 0;
2884
121k
  bool GotNumInits = false;
2885
121k
  if (!StructuredList) {
2886
96.8k
    NumInits = IList->getNumInits();
2887
96.8k
    GotNumInits = true;
2888
96.8k
  } else 
if (24.6k
Index < IList->getNumInits()24.6k
) {
2889
24.6k
    if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2890
23.1k
      NumInits = SubList->getNumInits();
2891
23.1k
      GotNumInits = true;
2892
23.1k
    }
2893
24.6k
  }
2894
121k
2895
121k
  if (const ArrayType *AType
2896
36.9k
      = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2897
36.9k
    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2898
24.7k
      NumElements = CAType->getSize().getZExtValue();
2899
24.7k
      // Simple heuristic so that we don't allocate a very large
2900
24.7k
      // initializer with many empty entries at the end.
2901
24.7k
      if (GotNumInits && 
NumElements > NumInits24.4k
)
2902
7.15k
        NumElements = 0;
2903
24.7k
    }
2904
84.5k
  } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2905
39.1k
    NumElements = VType->getNumElements();
2906
45.3k
  else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2907
40.6k
    RecordDecl *RDecl = RType->getDecl();
2908
40.6k
    if (RDecl->isUnion())
2909
2.98k
      NumElements = 1;
2910
37.6k
    else
2911
37.6k
      NumElements = std::distance(RDecl->field_begin(), RDecl->field_end());
2912
40.6k
  }
2913
121k
2914
121k
  Result->reserveInits(SemaRef.Context, NumElements);
2915
121k
2916
121k
  // Link this new initializer list into the structured initializer
2917
121k
  // lists.
2918
121k
  if (StructuredList)
2919
24.6k
    StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2920
96.8k
  else {
2921
96.8k
    Result->setSyntacticForm(IList);
2922
96.8k
    SyntacticToSemantic[IList] = Result;
2923
96.8k
  }
2924
121k
2925
121k
  return Result;
2926
121k
}
2927
2928
/// Update the initializer at index @p StructuredIndex within the
2929
/// structured initializer list to the value @p expr.
2930
void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2931
                                                  unsigned &StructuredIndex,
2932
1.08M
                                                  Expr *expr) {
2933
1.08M
  // No structured initializer list to update
2934
1.08M
  if (!StructuredList)
2935
110
    return;
2936
1.08M
2937
1.08M
  if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2938
20
                                                  StructuredIndex, expr)) {
2939
20
    // This initializer overwrites a previous initializer. Warn.
2940
20
    // We need to check on source range validity because the previous
2941
20
    // initializer does not have to be an explicit initializer.
2942
20
    // struct P { int a, b; };
2943
20
    // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
2944
20
    // There is an overwrite taking place because the first braced initializer
2945
20
    // list "{ .a = 2 }' already provides value for .p.b (which is zero).
2946
20
    if (PrevInit->getSourceRange().isValid()) {
2947
17
      SemaRef.Diag(expr->getBeginLoc(), diag::warn_initializer_overrides)
2948
17
          << expr->getSourceRange();
2949
17
2950
17
      SemaRef.Diag(PrevInit->getBeginLoc(), diag::note_previous_initializer)
2951
17
          << /*FIXME:has side effects=*/0 << PrevInit->getSourceRange();
2952
17
    }
2953
20
  }
2954
1.08M
2955
1.08M
  ++StructuredIndex;
2956
1.08M
}
2957
2958
/// Check that the given Index expression is a valid array designator
2959
/// value. This is essentially just a wrapper around
2960
/// VerifyIntegerConstantExpression that also checks for negative values
2961
/// and produces a reasonable diagnostic if there is a
2962
/// failure. Returns the index expression, possibly with an implicit cast
2963
/// added, on success.  If everything went okay, Value will receive the
2964
/// value of the constant expression.
2965
static ExprResult
2966
334
CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2967
334
  SourceLocation Loc = Index->getBeginLoc();
2968
334
2969
334
  // Make sure this is an integer constant expression.
2970
334
  ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2971
334
  if (Result.isInvalid())
2972
6
    return Result;
2973
328
2974
328
  if (Value.isSigned() && 
Value.isNegative()317
)
2975
1
    return S.Diag(Loc, diag::err_array_designator_negative)
2976
1
      << Value.toString(10) << Index->getSourceRange();
2977
327
2978
327
  Value.setIsUnsigned(true);
2979
327
  return Result;
2980
327
}
2981
2982
ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2983
                                            SourceLocation Loc,
2984
                                            bool GNUSyntax,
2985
2.75k
                                            ExprResult Init) {
2986
2.75k
  typedef DesignatedInitExpr::Designator ASTDesignator;
2987
2.75k
2988
2.75k
  bool Invalid = false;
2989
2.75k
  SmallVector<ASTDesignator, 32> Designators;
2990
2.75k
  SmallVector<Expr *, 32> InitExpressions;
2991
2.75k
2992
2.75k
  // Build designators and check array designator expressions.
2993
5.76k
  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); 
++Idx3.00k
) {
2994
3.00k
    const Designator &D = Desig.getDesignator(Idx);
2995
3.00k
    switch (D.getKind()) {
2996
3.00k
    case Designator::FieldDesignator:
2997
2.68k
      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2998
2.68k
                                          D.getFieldLoc()));
2999
2.68k
      break;
3000
3.00k
3001
3.00k
    case Designator::ArrayDesignator: {
3002
293
      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3003
293
      llvm::APSInt IndexValue;
3004
293
      if (!Index->isTypeDependent() && !Index->isValueDependent())
3005
286
        Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3006
293
      if (!Index)
3007
7
        Invalid = true;
3008
286
      else {
3009
286
        Designators.push_back(ASTDesignator(InitExpressions.size(),
3010
286
                                            D.getLBracketLoc(),
3011
286
                                            D.getRBracketLoc()));
3012
286
        InitExpressions.push_back(Index);
3013
286
      }
3014
293
      break;
3015
3.00k
    }
3016
3.00k
3017
3.00k
    case Designator::ArrayRangeDesignator: {
3018
27
      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3019
27
      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3020
27
      llvm::APSInt StartValue;
3021
27
      llvm::APSInt EndValue;
3022
27
      bool StartDependent = StartIndex->isTypeDependent() ||
3023
27
                            StartIndex->isValueDependent();
3024
27
      bool EndDependent = EndIndex->isTypeDependent() ||
3025
27
                          EndIndex->isValueDependent();
3026
27
      if (!StartDependent)
3027
24
        StartIndex =
3028
24
            CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3029
27
      if (!EndDependent)
3030
24
        EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3031
27
3032
27
      if (!StartIndex || !EndIndex)
3033
0
        Invalid = true;
3034
27
      else {
3035
27
        // Make sure we're comparing values with the same bit width.
3036
27
        if (StartDependent || 
EndDependent24
) {
3037
3
          // Nothing to compute.
3038
24
        } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3039
0
          EndValue = EndValue.extend(StartValue.getBitWidth());
3040
24
        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3041
1
          StartValue = StartValue.extend(EndValue.getBitWidth());
3042
27
3043
27
        if (!StartDependent && 
!EndDependent24
&&
EndValue < StartValue24
) {
3044
1
          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3045
1
            << StartValue.toString(10) << EndValue.toString(10)
3046
1
            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3047
1
          Invalid = true;
3048
26
        } else {
3049
26
          Designators.push_back(ASTDesignator(InitExpressions.size(),
3050
26
                                              D.getLBracketLoc(),
3051
26
                                              D.getEllipsisLoc(),
3052
26
                                              D.getRBracketLoc()));
3053
26
          InitExpressions.push_back(StartIndex);
3054
26
          InitExpressions.push_back(EndIndex);
3055
26
        }
3056
27
      }
3057
27
      break;
3058
3.00k
    }
3059
3.00k
    }
3060
3.00k
  }
3061
2.75k
3062
2.75k
  if (Invalid || 
Init.isInvalid()2.74k
)
3063
9
    return ExprError();
3064
2.74k
3065
2.74k
  // Clear out the expressions within the designation.
3066
2.74k
  Desig.ClearExprs(*this);
3067
2.74k
3068
2.74k
  DesignatedInitExpr *DIE
3069
2.74k
    = DesignatedInitExpr::Create(Context,
3070
2.74k
                                 Designators,
3071
2.74k
                                 InitExpressions, Loc, GNUSyntax,
3072
2.74k
                                 Init.getAs<Expr>());
3073
2.74k
3074
2.74k
  if (!getLangOpts().C99)
3075
305
    Diag(DIE->getBeginLoc(), diag::ext_designated_init)
3076
305
        << DIE->getSourceRange();
3077
2.74k
3078
2.74k
  return DIE;
3079
2.74k
}
3080
3081
//===----------------------------------------------------------------------===//
3082
// Initialization entity
3083
//===----------------------------------------------------------------------===//
3084
3085
InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3086
                                     const InitializedEntity &Parent)
3087
  : Parent(&Parent), Index(Index)
3088
1.63M
{
3089
1.63M
  if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3090
1.52M
    Kind = EK_ArrayElement;
3091
1.52M
    Type = AT->getElementType();
3092
1.52M
  } else 
if (const VectorType *117k
VT117k
= Parent.getType()->getAs<VectorType>()) {
3093
117k
    Kind = EK_VectorElement;
3094
117k
    Type = VT->getElementType();
3095
117k
  } else {
3096
94
    const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3097
94
    assert(CT && "Unexpected type");
3098
94
    Kind = EK_ComplexElement;
3099
94
    Type = CT->getElementType();
3100
94
  }
3101
1.63M
}
3102
3103
InitializedEntity
3104
InitializedEntity::InitializeBase(ASTContext &Context,
3105
                                  const CXXBaseSpecifier *Base,
3106
                                  bool IsInheritedVirtualBase,
3107
61.9k
                                  const InitializedEntity *Parent) {
3108
61.9k
  InitializedEntity Result;
3109
61.9k
  Result.Kind = EK_Base;
3110
61.9k
  Result.Parent = Parent;
3111
61.9k
  Result.Base = reinterpret_cast<uintptr_t>(Base);
3112
61.9k
  if (IsInheritedVirtualBase)
3113
2.00k
    Result.Base |= 0x01;
3114
61.9k
3115
61.9k
  Result.Type = Base->getType();
3116
61.9k
  return Result;
3117
61.9k
}
3118
3119
9
DeclarationName InitializedEntity::getName() const {
3120
9
  switch (getKind()) {
3121
9
  case EK_Parameter:
3122
0
  case EK_Parameter_CF_Audited: {
3123
0
    ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3124
0
    return (D ? D->getDeclName() : DeclarationName());
3125
0
  }
3126
0
3127
9
  case EK_Variable:
3128
9
  case EK_Member:
3129
9
  case EK_Binding:
3130
9
    return Variable.VariableOrMember->getDeclName();
3131
9
3132
9
  case EK_LambdaCapture:
3133
0
    return DeclarationName(Capture.VarID);
3134
9
3135
9
  case EK_Result:
3136
0
  case EK_StmtExprResult:
3137
0
  case EK_Exception:
3138
0
  case EK_New:
3139
0
  case EK_Temporary:
3140
0
  case EK_Base:
3141
0
  case EK_Delegating:
3142
0
  case EK_ArrayElement:
3143
0
  case EK_VectorElement:
3144
0
  case EK_ComplexElement:
3145
0
  case EK_BlockElement:
3146
0
  case EK_LambdaToBlockConversionBlockElement:
3147
0
  case EK_CompoundLiteralInit:
3148
0
  case EK_RelatedResult:
3149
0
    return DeclarationName();
3150
0
  }
3151
0
3152
0
  llvm_unreachable("Invalid EntityKind!");
3153
0
}
3154
3155
16.4M
ValueDecl *InitializedEntity::getDecl() const {
3156
16.4M
  switch (getKind()) {
3157
16.4M
  case EK_Variable:
3158
3.81M
  case EK_Member:
3159
3.81M
  case EK_Binding:
3160
3.81M
    return Variable.VariableOrMember;
3161
3.81M
3162
12.5M
  case EK_Parameter:
3163
12.5M
  case EK_Parameter_CF_Audited:
3164
12.5M
    return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
3165
12.5M
3166
12.5M
  case EK_Result:
3167
37.2k
  case EK_StmtExprResult:
3168
37.2k
  case EK_Exception:
3169
37.2k
  case EK_New:
3170
37.2k
  case EK_Temporary:
3171
37.2k
  case EK_Base:
3172
37.2k
  case EK_Delegating:
3173
37.2k
  case EK_ArrayElement:
3174
37.2k
  case EK_VectorElement:
3175
37.2k
  case EK_ComplexElement:
3176
37.2k
  case EK_BlockElement:
3177
37.2k
  case EK_LambdaToBlockConversionBlockElement:
3178
37.2k
  case EK_LambdaCapture:
3179
37.2k
  case EK_CompoundLiteralInit:
3180
37.2k
  case EK_RelatedResult:
3181
37.2k
    return nullptr;
3182
0
  }
3183
0
3184
0
  llvm_unreachable("Invalid EntityKind!");
3185
0
}
3186
3187
339k
bool InitializedEntity::allowsNRVO() const {
3188
339k
  switch (getKind()) {
3189
339k
  case EK_Result:
3190
46.6k
  case EK_Exception:
3191
46.6k
    return LocAndNRVO.NRVO;
3192
46.6k
3193
292k
  case EK_StmtExprResult:
3194
292k
  case EK_Variable:
3195
292k
  case EK_Parameter:
3196
292k
  case EK_Parameter_CF_Audited:
3197
292k
  case EK_Member:
3198
292k
  case EK_Binding:
3199
292k
  case EK_New:
3200
292k
  case EK_Temporary:
3201
292k
  case EK_CompoundLiteralInit:
3202
292k
  case EK_Base:
3203
292k
  case EK_Delegating:
3204
292k
  case EK_ArrayElement:
3205
292k
  case EK_VectorElement:
3206
292k
  case EK_ComplexElement:
3207
292k
  case EK_BlockElement:
3208
292k
  case EK_LambdaToBlockConversionBlockElement:
3209
292k
  case EK_LambdaCapture:
3210
292k
  case EK_RelatedResult:
3211
292k
    break;
3212
292k
  }
3213
292k
3214
292k
  return false;
3215
292k
}
3216
3217
0
unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3218
0
  assert(getParent() != this);
3219
0
  unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3220
0
  for (unsigned I = 0; I != Depth; ++I)
3221
0
    OS << "`-";
3222
0
3223
0
  switch (getKind()) {
3224
0
  case EK_Variable: OS << "Variable"; break;
3225
0
  case EK_Parameter: OS << "Parameter"; break;
3226
0
  case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3227
0
    break;
3228
0
  case EK_Result: OS << "Result"; break;
3229
0
  case EK_StmtExprResult: OS << "StmtExprResult"; break;
3230
0
  case EK_Exception: OS << "Exception"; break;
3231
0
  case EK_Member: OS << "Member"; break;
3232
0
  case EK_Binding: OS << "Binding"; break;
3233
0
  case EK_New: OS << "New"; break;
3234
0
  case EK_Temporary: OS << "Temporary"; break;
3235
0
  case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3236
0
  case EK_RelatedResult: OS << "RelatedResult"; break;
3237
0
  case EK_Base: OS << "Base"; break;
3238
0
  case EK_Delegating: OS << "Delegating"; break;
3239
0
  case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3240
0
  case EK_VectorElement: OS << "VectorElement " << Index; break;
3241
0
  case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3242
0
  case EK_BlockElement: OS << "Block"; break;
3243
0
  case EK_LambdaToBlockConversionBlockElement:
3244
0
    OS << "Block (lambda)";
3245
0
    break;
3246
0
  case EK_LambdaCapture:
3247
0
    OS << "LambdaCapture ";
3248
0
    OS << DeclarationName(Capture.VarID);
3249
0
    break;
3250
0
  }
3251
0
3252
0
  if (auto *D = getDecl()) {
3253
0
    OS << " ";
3254
0
    D->printQualifiedName(OS);
3255
0
  }
3256
0
3257
0
  OS << " '" << getType().getAsString() << "'\n";
3258
0
3259
0
  return Depth + 1;
3260
0
}
3261
3262
0
LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3263
0
  dumpImpl(llvm::errs());
3264
0
}
3265
3266
//===----------------------------------------------------------------------===//
3267
// Initialization sequence
3268
//===----------------------------------------------------------------------===//
3269
3270
14.4M
void InitializationSequence::Step::Destroy() {
3271
14.4M
  switch (Kind) {
3272
14.4M
  case SK_ResolveAddressOfOverloadedFunction:
3273
7.53M
  case SK_CastDerivedToBaseRValue:
3274
7.53M
  case SK_CastDerivedToBaseXValue:
3275
7.53M
  case SK_CastDerivedToBaseLValue:
3276
7.53M
  case SK_BindReference:
3277
7.53M
  case SK_BindReferenceToTemporary:
3278
7.53M
  case SK_FinalCopy:
3279
7.53M
  case SK_ExtraneousCopyToTemporary:
3280
7.53M
  case SK_UserConversion:
3281
7.53M
  case SK_QualificationConversionRValue:
3282
7.53M
  case SK_QualificationConversionXValue:
3283
7.53M
  case SK_QualificationConversionLValue:
3284
7.53M
  case SK_AtomicConversion:
3285
7.53M
  case SK_ListInitialization:
3286
7.53M
  case SK_UnwrapInitList:
3287
7.53M
  case SK_RewrapInitList:
3288
7.53M
  case SK_ConstructorInitialization:
3289
7.53M
  case SK_ConstructorInitializationFromList:
3290
7.53M
  case SK_ZeroInitialization:
3291
7.53M
  case SK_CAssignment:
3292
7.53M
  case SK_StringInit:
3293
7.53M
  case SK_ObjCObjectConversion:
3294
7.53M
  case SK_ArrayLoopIndex:
3295
7.53M
  case SK_ArrayLoopInit:
3296
7.53M
  case SK_ArrayInit:
3297
7.53M
  case SK_GNUArrayInit:
3298
7.53M
  case SK_ParenthesizedArrayInit:
3299
7.53M
  case SK_PassByIndirectCopyRestore:
3300
7.53M
  case SK_PassByIndirectRestore:
3301
7.53M
  case SK_ProduceObjCObject:
3302
7.53M
  case SK_StdInitializerList:
3303
7.53M
  case SK_StdInitializerListConstructorCall:
3304
7.53M
  case SK_OCLSamplerInit:
3305
7.53M
  case SK_OCLZeroOpaqueType:
3306
7.53M
    break;
3307
7.53M
3308
7.53M
  case SK_ConversionSequence:
3309
6.89M
  case SK_ConversionSequenceNoNarrowing:
3310
6.89M
    delete ICS;
3311
14.4M
  }
3312
14.4M
}
3313
3314
608
bool InitializationSequence::isDirectReferenceBinding() const {
3315
608
  // There can be some lvalue adjustments after the SK_BindReference step.
3316
622
  for (auto I = Steps.rbegin(); I != Steps.rend(); 
++I14
) {
3317
485
    if (I->Kind == SK_BindReference)
3318
413
      return true;
3319
72
    if (I->Kind == SK_BindReferenceToTemporary)
3320
58
      return false;
3321
72
  }
3322
608
  
return false137
;
3323
608
}
3324
3325
412
bool InitializationSequence::isAmbiguous() const {
3326
412
  if (!Failed())
3327
101
    return false;
3328
311
3329
311
  switch (getFailureKind()) {
3330
311
  case FK_TooManyInitsForReference:
3331
138
  case FK_ParenthesizedListInitForReference:
3332
138
  case FK_ArrayNeedsInitList:
3333
138
  case FK_ArrayNeedsInitListOrStringLiteral:
3334
138
  case FK_ArrayNeedsInitListOrWideStringLiteral:
3335
138
  case FK_NarrowStringIntoWideCharArray:
3336
138
  case FK_WideStringIntoCharArray:
3337
138
  case FK_IncompatWideStringIntoWideChar:
3338
138
  case FK_PlainStringIntoUTF8Char:
3339
138
  case FK_UTF8StringIntoPlainChar:
3340
138
  case FK_AddressOfOverloadFailed: // FIXME: Could do better
3341
138
  case FK_NonConstLValueReferenceBindingToTemporary:
3342
138
  case FK_NonConstLValueReferenceBindingToBitfield:
3343
138
  case FK_NonConstLValueReferenceBindingToVectorElement:
3344
138
  case FK_NonConstLValueReferenceBindingToUnrelated:
3345
138
  case FK_RValueReferenceBindingToLValue:
3346
138
  case FK_ReferenceAddrspaceMismatchTemporary:
3347
138
  case FK_ReferenceInitDropsQualifiers:
3348
138
  case FK_ReferenceInitFailed:
3349
138
  case FK_ConversionFailed:
3350
138
  case FK_ConversionFromPropertyFailed:
3351
138
  case FK_TooManyInitsForScalar:
3352
138
  case FK_ParenthesizedListInitForScalar:
3353
138
  case FK_ReferenceBindingToInitList:
3354
138
  case FK_InitListBadDestinationType:
3355
138
  case FK_DefaultInitOfConst:
3356
138
  case FK_Incomplete:
3357
138
  case FK_ArrayTypeMismatch:
3358
138
  case FK_NonConstantArrayInit:
3359
138
  case FK_ListInitializationFailed:
3360
138
  case FK_VariableLengthArrayHasInitializer:
3361
138
  case FK_PlaceholderType:
3362
138
  case FK_ExplicitConstructor:
3363
138
  case FK_AddressOfUnaddressableFunction:
3364
138
    return false;
3365
138
3366
173
  case FK_ReferenceInitOverloadFailed:
3367
173
  case FK_UserConversionOverloadFailed:
3368
173
  case FK_ConstructorOverloadFailed:
3369
173
  case FK_ListConstructorOverloadFailed:
3370
173
    return FailedOverloadResult == OR_Ambiguous;
3371
0
  }
3372
0
3373
0
  llvm_unreachable("Invalid EntityKind!");
3374
0
}
3375
3376
7.36M
bool InitializationSequence::isConstructorInitialization() const {
3377
7.36M
  return !Steps.empty() && 
Steps.back().Kind == SK_ConstructorInitialization7.36M
;
3378
7.36M
}
3379
3380
void
3381
InitializationSequence
3382
::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3383
                                   DeclAccessPair Found,
3384
81
                                   bool HadMultipleCandidates) {
3385
81
  Step S;
3386
81
  S.Kind = SK_ResolveAddressOfOverloadedFunction;
3387
81
  S.Type = Function->getType();
3388
81
  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3389
81
  S.Function.Function = Function;
3390
81
  S.Function.FoundDecl = Found;
3391
81
  Steps.push_back(S);
3392
81
}
3393
3394
void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3395
28.6k
                                                      ExprValueKind VK) {
3396
28.6k
  Step S;
3397
28.6k
  switch (VK) {
3398
28.6k
  
case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break0
;
3399
28.6k
  
case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break4.56k
;
3400
28.6k
  
case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break24.1k
;
3401
28.6k
  }
3402
28.6k
  S.Type = BaseType;
3403
28.6k
  Steps.push_back(S);
3404
28.6k
}
3405
3406
void InitializationSequence::AddReferenceBindingStep(QualType T,
3407
699k
                                                     bool BindingTemporary) {
3408
699k
  Step S;
3409
699k
  S.Kind = BindingTemporary? 
SK_BindReferenceToTemporary178k
:
SK_BindReference521k
;
3410
699k
  S.Type = T;
3411
699k
  Steps.push_back(S);
3412
699k
}
3413
3414
12.2k
void InitializationSequence::AddFinalCopy(QualType T) {
3415
12.2k
  Step S;
3416
12.2k
  S.Kind = SK_FinalCopy;
3417
12.2k
  S.Type = T;
3418
12.2k
  Steps.push_back(S);
3419
12.2k
}
3420
3421
24.3k
void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3422
24.3k
  Step S;
3423
24.3k
  S.Kind = SK_ExtraneousCopyToTemporary;
3424
24.3k
  S.Type = T;
3425
24.3k
  Steps.push_back(S);
3426
24.3k
}
3427
3428
void
3429
InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3430
                                              DeclAccessPair FoundDecl,
3431
                                              QualType T,
3432
15.6k
                                              bool HadMultipleCandidates) {
3433
15.6k
  Step S;
3434
15.6k
  S.Kind = SK_UserConversion;
3435
15.6k
  S.Type = T;
3436
15.6k
  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3437
15.6k
  S.Function.Function = Function;
3438
15.6k
  S.Function.FoundDecl = FoundDecl;
3439
15.6k
  Steps.push_back(S);
3440
15.6k
}
3441
3442
void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3443
142k
                                                            ExprValueKind VK) {
3444
142k
  Step S;
3445
142k
  S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
3446
142k
  switch (VK) {
3447
142k
  case VK_RValue:
3448
55.7k
    S.Kind = SK_QualificationConversionRValue;
3449
55.7k
    break;
3450
142k
  case VK_XValue:
3451
2.14k
    S.Kind = SK_QualificationConversionXValue;
3452
2.14k
    break;
3453
142k
  case VK_LValue:
3454
84.6k
    S.Kind = SK_QualificationConversionLValue;
3455
84.6k
    break;
3456
142k
  }
3457
142k
  S.Type = Ty;
3458
142k
  Steps.push_back(S);
3459
142k
}
3460
3461
30
void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3462
30
  Step S;
3463
30
  S.Kind = SK_AtomicConversion;
3464
30
  S.Type = Ty;
3465
30
  Steps.push_back(S);
3466
30
}
3467
3468
void InitializationSequence::AddConversionSequenceStep(
3469
    const ImplicitConversionSequence &ICS, QualType T,
3470
6.89M
    bool TopLevelOfInitList) {
3471
6.89M
  Step S;
3472
6.89M
  S.Kind = TopLevelOfInitList ? 
SK_ConversionSequenceNoNarrowing711k
3473
6.89M
                              : 
SK_ConversionSequence6.18M
;
3474
6.89M
  S.Type = T;
3475
6.89M
  S.ICS = new ImplicitConversionSequence(ICS);
3476
6.89M
  Steps.push_back(S);
3477
6.89M
}
3478
3479
108k
void InitializationSequence::AddListInitializationStep(QualType T) {
3480
108k
  Step S;
3481
108k
  S.Kind = SK_ListInitialization;
3482
108k
  S.Type = T;
3483
108k
  Steps.push_back(S);
3484
108k
}
3485
3486
void InitializationSequence::AddConstructorInitializationStep(
3487
    DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3488
403k
    bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3489
403k
  Step S;
3490
403k
  S.Kind = FromInitList ? 
AsInitList 2.98k
?
SK_StdInitializerListConstructorCall292
3491
2.98k
                                     : 
SK_ConstructorInitializationFromList2.69k
3492
403k
                        : 
SK_ConstructorInitialization400k
;
3493
403k
  S.Type = T;
3494
403k
  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3495
403k
  S.Function.Function = Constructor;
3496
403k
  S.Function.FoundDecl = FoundDecl;
3497
403k
  Steps.push_back(S);
3498
403k
}
3499
3500
80.4k
void InitializationSequence::AddZeroInitializationStep(QualType T) {
3501
80.4k
  Step S;
3502
80.4k
  S.Kind = SK_ZeroInitialization;
3503
80.4k
  S.Type = T;
3504
80.4k
  Steps.push_back(S);
3505
80.4k
}
3506
3507
6.01M
void InitializationSequence::AddCAssignmentStep(QualType T) {
3508
6.01M
  Step S;
3509
6.01M
  S.Kind = SK_CAssignment;
3510
6.01M
  S.Type = T;
3511
6.01M
  Steps.push_back(S);
3512
6.01M
}
3513
3514
2.04k
void InitializationSequence::AddStringInitStep(QualType T) {
3515
2.04k
  Step S;
3516
2.04k
  S.Kind = SK_StringInit;
3517
2.04k
  S.Type = T;
3518
2.04k
  Steps.push_back(S);
3519
2.04k
}
3520
3521
15
void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3522
15
  Step S;
3523
15
  S.Kind = SK_ObjCObjectConversion;
3524
15
  S.Type = T;
3525
15
  Steps.push_back(S);
3526
15
}
3527
3528
19
void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3529
19
  Step S;
3530
19
  S.Kind = IsGNUExtension ? 
SK_GNUArrayInit17
:
SK_ArrayInit2
;
3531
19
  S.Type = T;
3532
19
  Steps.push_back(S);
3533
19
}
3534
3535
1.08k
void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3536
1.08k
  Step S;
3537
1.08k
  S.Kind = SK_ArrayLoopIndex;
3538
1.08k
  S.Type = EltT;
3539
1.08k
  Steps.insert(Steps.begin(), S);
3540
1.08k
3541
1.08k
  S.Kind = SK_ArrayLoopInit;
3542
1.08k
  S.Type = T;
3543
1.08k
  Steps.push_back(S);
3544
1.08k
}
3545
3546
1
void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3547
1
  Step S;
3548
1
  S.Kind = SK_ParenthesizedArrayInit;
3549
1
  S.Type = T;
3550
1
  Steps.push_back(S);
3551
1
}
3552
3553
void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3554
69
                                                              bool shouldCopy) {
3555
69
  Step s;
3556
69
  s.Kind = (shouldCopy ? 
SK_PassByIndirectCopyRestore65
3557
69
                       : 
SK_PassByIndirectRestore4
);
3558
69
  s.Type = type;
3559
69
  Steps.push_back(s);
3560
69
}
3561
3562
648
void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3563
648
  Step S;
3564
648
  S.Kind = SK_ProduceObjCObject;
3565
648
  S.Type = T;
3566
648
  Steps.push_back(S);
3567
648
}
3568
3569
746
void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3570
746
  Step S;
3571
746
  S.Kind = SK_StdInitializerList;
3572
746
  S.Type = T;
3573
746
  Steps.push_back(S);
3574
746
}
3575
3576
123
void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3577
123
  Step S;
3578
123
  S.Kind = SK_OCLSamplerInit;
3579
123
  S.Type = T;
3580
123
  Steps.push_back(S);
3581
123
}
3582
3583
102
void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
3584
102
  Step S;
3585
102
  S.Kind = SK_OCLZeroOpaqueType;
3586
102
  S.Type = T;
3587
102
  Steps.push_back(S);
3588
102
}
3589
3590
void InitializationSequence::RewrapReferenceInitList(QualType T,
3591
278
                                                     InitListExpr *Syntactic) {
3592
278
  assert(Syntactic->getNumInits() == 1 &&
3593
278
         "Can only rewrap trivial init lists.");
3594
278
  Step S;
3595
278
  S.Kind = SK_UnwrapInitList;
3596
278
  S.Type = Syntactic->getInit(0)->getType();
3597
278
  Steps.insert(Steps.begin(), S);
3598
278
3599
278
  S.Kind = SK_RewrapInitList;
3600
278
  S.Type = T;
3601
278
  S.WrappingSyntacticList = Syntactic;
3602
278
  Steps.push_back(S);
3603
278
}
3604
3605
void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3606
5.66k
                                                OverloadingResult Result) {
3607
5.66k
  setSequenceKind(FailedSequence);
3608
5.66k
  this->Failure = Failure;
3609
5.66k
  this->FailedOverloadResult = Result;
3610
5.66k
}
3611
3612
//===----------------------------------------------------------------------===//
3613
// Attempt initialization
3614
//===----------------------------------------------------------------------===//
3615
3616
/// Tries to add a zero initializer. Returns true if that worked.
3617
static bool
3618
maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3619
75
                                   const InitializedEntity &Entity) {
3620
75
  if (Entity.getKind() != InitializedEntity::EK_Variable)
3621
4
    return false;
3622
71
3623
71
  VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3624
71
  if (VD->getInit() || VD->getEndLoc().isMacroID())
3625
0
    return false;
3626
71
3627
71
  QualType VariableTy = VD->getType().getCanonicalType();
3628
71
  SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
3629
71
  std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3630
71
  if (!Init.empty()) {
3631
68
    Sequence.AddZeroInitializationStep(Entity.getType());
3632
68
    Sequence.SetZeroInitializationFixit(Init, Loc);
3633
68
    return true;
3634
68
  }
3635
3
  return false;
3636
3
}
3637
3638
static void MaybeProduceObjCObject(Sema &S,
3639
                                   InitializationSequence &Sequence,
3640
12.8M
                                   const InitializedEntity &Entity) {
3641
12.8M
  if (!S.getLangOpts().ObjCAutoRefCount) 
return12.8M
;
3642
6.21k
3643
6.21k
  /// When initializing a parameter, produce the value if it's marked
3644
6.21k
  /// __attribute__((ns_consumed)).
3645
6.21k
  if (Entity.isParameterKind()) {
3646
2.79k
    if (!Entity.isParameterConsumed())
3647
2.76k
      return;
3648
30
3649
30
    assert(Entity.getType()->isObjCRetainableType() &&
3650
30
           "consuming an object of unretainable type?");
3651
30
    Sequence.AddProduceObjCObjectStep(Entity.getType());
3652
30
3653
30
  /// When initializing a return value, if the return type is a
3654
30
  /// retainable type, then returns need to immediately retain the
3655
30
  /// object.  If an autorelease is required, it will be done at the
3656
30
  /// last instant.
3657
3.42k
  } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3658
3.42k
             
Entity.getKind() == InitializedEntity::EK_StmtExprResult2.44k
) {
3659
1.00k
    if (!Entity.getType()->isObjCRetainableType())
3660
388
      return;
3661
618
3662
618
    Sequence.AddProduceObjCObjectStep(Entity.getType());
3663
618
  }
3664
6.21k
}
3665
3666
static void TryListInitialization(Sema &S,
3667
                                  const InitializedEntity &Entity,
3668
                                  const InitializationKind &Kind,
3669
                                  InitListExpr *InitList,
3670
                                  InitializationSequence &Sequence,
3671
                                  bool TreatUnavailableAsInvalid);
3672
3673
/// When initializing from init list via constructor, handle
3674
/// initialization of an object of type std::initializer_list<T>.
3675
///
3676
/// \return true if we have handled initialization of an object of type
3677
/// std::initializer_list<T>, false otherwise.
3678
static bool TryInitializerListConstruction(Sema &S,
3679
                                           InitListExpr *List,
3680
                                           QualType DestType,
3681
                                           InitializationSequence &Sequence,
3682
2.99k
                                           bool TreatUnavailableAsInvalid) {
3683
2.99k
  QualType E;
3684
2.99k
  if (!S.isStdInitializerList(DestType, &E))
3685
2.24k
    return false;
3686
751
3687
751
  if (!S.isCompleteType(List->getExprLoc(), E)) {
3688
0
    Sequence.setIncompleteTypeFailure(E);
3689
0
    return true;
3690
0
  }
3691
751
3692
751
  // Try initializing a temporary array from the init list.
3693
751
  QualType ArrayType = S.Context.getConstantArrayType(
3694
751
      E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3695
751
                                 List->getNumInits()),
3696
751
      clang::ArrayType::Normal, 0);
3697
751
  InitializedEntity HiddenArray =
3698
751
      InitializedEntity::InitializeTemporary(ArrayType);
3699
751
  InitializationKind Kind = InitializationKind::CreateDirectList(
3700
751
      List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
3701
751
  TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3702
751
                        TreatUnavailableAsInvalid);
3703
751
  if (Sequence)
3704
746
    Sequence.AddStdInitializerListConstructionStep(DestType);
3705
751
  return true;
3706
751
}
3707
3708
/// Determine if the constructor has the signature of a copy or move
3709
/// constructor for the type T of the class in which it was found. That is,
3710
/// determine if its first parameter is of type T or reference to (possibly
3711
/// cv-qualified) T.
3712
static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3713
548k
                                   const ConstructorInfo &Info) {
3714
548k
  if (Info.Constructor->getNumParams() == 0)
3715
83.5k
    return false;
3716
465k
3717
465k
  QualType ParmT =
3718
465k
      Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3719
465k
  QualType ClassT =
3720
465k
      Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3721
465k
3722
465k
  return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3723
465k
}
3724
3725
static OverloadingResult
3726
ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3727
                           MultiExprArg Args,
3728
                           OverloadCandidateSet &CandidateSet,
3729
                           QualType DestType,
3730
                           DeclContext::lookup_result Ctors,
3731
                           OverloadCandidateSet::iterator &Best,
3732
                           bool CopyInitializing, bool AllowExplicit,
3733
                           bool OnlyListConstructors, bool IsListInit,
3734
440k
                           bool SecondStepOfCopyInit = false) {
3735
440k
  CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
3736
440k
  CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
3737
440k
3738
1.94M
  for (NamedDecl *D : Ctors) {
3739
1.94M
    auto Info = getConstructorInfo(D);
3740
1.94M
    if (!Info.Constructor || 
Info.Constructor->isInvalidDecl()1.94M
)
3741
495
      continue;
3742
1.94M
3743
1.94M
    if (!AllowExplicit && 
Info.Constructor->isExplicit()603k
)
3744
74.0k
      continue;
3745
1.87M
3746
1.87M
    if (OnlyListConstructors && 
!S.isInitListConstructor(Info.Constructor)10.2k
)
3747
9.94k
      continue;
3748
1.86M
3749
1.86M
    // C++11 [over.best.ics]p4:
3750
1.86M
    //   ... and the constructor or user-defined conversion function is a
3751
1.86M
    //   candidate by
3752
1.86M
    //   - 13.3.1.3, when the argument is the temporary in the second step
3753
1.86M
    //     of a class copy-initialization, or
3754
1.86M
    //   - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3755
1.86M
    //   - the second phase of 13.3.1.7 when the initializer list has exactly
3756
1.86M
    //     one element that is itself an initializer list, and the target is
3757
1.86M
    //     the first parameter of a constructor of class X, and the conversion
3758
1.86M
    //     is to X or reference to (possibly cv-qualified X),
3759
1.86M
    //   user-defined conversion sequences are not considered.
3760
1.86M
    bool SuppressUserConversions =
3761
1.86M
        SecondStepOfCopyInit ||
3762
1.86M
        
(1.72M
IsListInit1.72M
&&
Args.size() == 112.7k
&&
isa<InitListExpr>(Args[0])4.10k
&&
3763
1.72M
         
hasCopyOrMoveCtorParam(S.Context, Info)443
);
3764
1.86M
3765
1.86M
    if (Info.ConstructorTmpl)
3766
352k
      S.AddTemplateOverloadCandidate(
3767
352k
          Info.ConstructorTmpl, Info.FoundDecl,
3768
352k
          /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
3769
352k
          /*PartialOverloading=*/false, AllowExplicit);
3770
1.50M
    else {
3771
1.50M
      // C++ [over.match.copy]p1:
3772
1.50M
      //   - When initializing a temporary to be bound to the first parameter
3773
1.50M
      //     of a constructor [for type T] that takes a reference to possibly
3774
1.50M
      //     cv-qualified T as its first argument, called with a single
3775
1.50M
      //     argument in the context of direct-initialization, explicit
3776
1.50M
      //     conversion functions are also considered.
3777
1.50M
      // FIXME: What if a constructor template instantiates to such a signature?
3778
1.50M
      bool AllowExplicitConv = AllowExplicit && 
!CopyInitializing1.08M
&&
3779
1.50M
                               
Args.size() == 11.07M
&&
3780
1.50M
                               
hasCopyOrMoveCtorParam(S.Context, Info)456k
;
3781
1.50M
      S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
3782
1.50M
                             CandidateSet, SuppressUserConversions,
3783
1.50M
                             /*PartialOverloading=*/false, AllowExplicit,
3784
1.50M
                             AllowExplicitConv);
3785
1.50M
    }
3786
1.86M
  }
3787
440k
3788
440k
  // FIXME: Work around a bug in C++17 guaranteed copy elision.
3789
440k
  //
3790
440k
  // When initializing an object of class type T by constructor
3791
440k
  // ([over.match.ctor]) or by list-initialization ([over.match.list])
3792
440k
  // from a single expression of class type U, conversion functions of
3793
440k
  // U that convert to the non-reference type cv T are candidates.
3794
440k
  // Explicit conversion functions are only candidates during
3795
440k
  // direct-initialization.
3796
440k
  //
3797
440k
  // Note: SecondStepOfCopyInit is only ever true in this case when
3798
440k
  // evaluating whether to produce a C++98 compatibility warning.
3799
440k
  if (S.getLangOpts().CPlusPlus17 && 
Args.size() == 16.59k
&&
3800
440k
      
!SecondStepOfCopyInit2.38k
) {
3801
2.35k
    Expr *Initializer = Args[0];
3802
2.35k
    auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
3803
2.35k
    if (SourceRD && 
S.isCompleteType(DeclLoc, Initializer->getType())1.44k
) {
3804
1.44k
      const auto &Conversions = SourceRD->getVisibleConversionFunctions();
3805
1.74k
      for (auto I = Conversions.begin(), E = Conversions.end(); I != E; 
++I301
) {
3806
301
        NamedDecl *D = *I;
3807
301
        CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3808
301
        D = D->getUnderlyingDecl();
3809
301
3810
301
        FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3811
301
        CXXConversionDecl *Conv;
3812
301
        if (ConvTemplate)
3813
16
          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3814
285
        else
3815
285
          Conv = cast<CXXConversionDecl>(D);
3816
301
3817
301
        if (AllowExplicit || 
!Conv->isExplicit()238
) {
3818
299
          if (ConvTemplate)
3819
16
            S.AddTemplateConversionCandidate(
3820
16
                ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
3821
16
                CandidateSet, AllowExplicit, AllowExplicit,
3822
16
                /*AllowResultConversion*/ false);
3823
283
          else
3824
283
            S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
3825
283
                                     DestType, CandidateSet, AllowExplicit,
3826
283
                                     AllowExplicit,
3827
283
                                     /*AllowResultConversion*/ false);
3828
299
        }
3829
301
      }
3830
1.44k
    }
3831
2.35k
  }
3832
440k
3833
440k
  // Perform overload resolution and return the result.
3834
440k
  return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3835
440k
}
3836
3837
/// Attempt initialization by constructor (C++ [dcl.init]), which
3838
/// enumerates the constructors of the initialized entity and performs overload
3839
/// resolution to select the best.
3840
/// \param DestType       The destination class type.
3841
/// \param DestArrayType  The destination type, which is either DestType or
3842
///                       a (possibly multidimensional) array of DestType.
3843
/// \param IsListInit     Is this list-initialization?
3844
/// \param IsInitListCopy Is this non-list-initialization resulting from a
3845
///                       list-initialization from {x} where x is the same
3846
///                       type as the entity?
3847
static void TryConstructorInitialization(Sema &S,
3848
                                         const InitializedEntity &Entity,
3849
                                         const InitializationKind &Kind,
3850
                                         MultiExprArg Args, QualType DestType,
3851
                                         QualType DestArrayType,
3852
                                         InitializationSequence &Sequence,
3853
                                         bool IsListInit = false,
3854
406k
                                         bool IsInitListCopy = false) {
3855
406k
  assert(((!IsListInit && !IsInitListCopy) ||
3856
406k
          (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3857
406k
         "IsListInit/IsInitListCopy must come with a single initializer list "
3858
406k
         "argument.");
3859
406k
  InitListExpr *ILE =
3860
406k
      (IsListInit || 
IsInitListCopy403k
) ?
cast<InitListExpr>(Args[0])3.27k
:
nullptr403k
;
3861
406k
  MultiExprArg UnwrappedArgs =
3862
406k
      ILE ? 
MultiExprArg(ILE->getInits(), ILE->getNumInits())3.27k
:
Args403k
;
3863
406k
3864
406k
  // The type we're constructing needs to be complete.
3865
406k
  if (!S.isCompleteType(Kind.getLocation(), DestType)) {
3866
37
    Sequence.setIncompleteTypeFailure(DestType);
3867
37
    return;
3868
37
  }
3869
406k
3870
406k
  // C++17 [dcl.init]p17:
3871
406k
  //     - If the initializer expression is a prvalue and the cv-unqualified
3872
406k
  //       version of the source type is the same class as the class of the
3873
406k
  //       destination, the initializer expression is used to initialize the
3874
406k
  //       destination object.
3875
406k
  // Per DR (no number yet), this does not apply when initializing a base
3876
406k
  // class or delegating to another constructor from a mem-initializer.
3877
406k
  // ObjC++: Lambda captured by the block in the lambda to block conversion
3878
406k
  // should avoid copy elision.
3879
406k
  if (S.getLangOpts().CPlusPlus17 &&
3880
406k
      
Entity.getKind() != InitializedEntity::EK_Base8.48k
&&
3881
406k
      
Entity.getKind() != InitializedEntity::EK_Delegating7.96k
&&
3882
406k
      Entity.getKind() !=
3883
7.95k
          InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
3884
406k
      
UnwrappedArgs.size() == 17.95k
&&
UnwrappedArgs[0]->isRValue()4.15k
&&
3885
406k
      
S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)2.74k
) {
3886
2.10k
    // Convert qualifications if necessary.
3887
2.10k
    Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3888
2.10k
    if (ILE)
3889
19
      Sequence.RewrapReferenceInitList(DestType, ILE);
3890
2.10k
    return;
3891
2.10k
  }
3892
404k
3893
404k
  const RecordType *DestRecordType = DestType->getAs<RecordType>();
3894
404k
  assert(DestRecordType && "Constructor initialization requires record type");
3895
404k
  CXXRecordDecl *DestRecordDecl
3896
404k
    = cast<CXXRecordDecl>(DestRecordType->getDecl());
3897
404k
3898
404k
  // Build the candidate set directly in the initialization sequence
3899
404k
  // structure, so that it will persist if we fail.
3900
404k
  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3901
404k
3902
404k
  // Determine whether we are allowed to call explicit constructors or
3903
404k
  // explicit conversion operators.
3904
404k
  bool AllowExplicit = Kind.AllowExplicit() || 
IsListInit121k
;
3905
404k
  bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3906
404k
3907
404k
  //   - Otherwise, if T is a class type, constructors are considered. The
3908
404k
  //     applicable constructors are enumerated, and the best one is chosen
3909
404k
  //     through overload resolution.
3910
404k
  DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
3911
404k
3912
404k
  OverloadingResult Result = OR_No_Viable_Function;
3913
404k
  OverloadCandidateSet::iterator Best;
3914
404k
  bool AsInitializerList = false;
3915
404k
3916
404k
  // C++11 [over.match.list]p1, per DR1467:
3917
404k
  //   When objects of non-aggregate type T are list-initialized, such that
3918
404k
  //   8.5.4 [dcl.init.list] specifies that overload resolution is performed
3919
404k
  //   according to the rules in this section, overload resolution selects
3920
404k
  //   the constructor in two phases:
3921
404k
  //
3922
404k
  //   - Initially, the candidate functions are the initializer-list
3923
404k
  //     constructors of the class T and the argument list consists of the
3924
404k
  //     initializer list as a single argument.
3925
404k
  if (IsListInit) {
3926
3.18k
    AsInitializerList = true;
3927
3.18k
3928
3.18k
    // If the initializer list has no elements and T has a default constructor,
3929
3.18k
    // the first phase is omitted.
3930
3.18k
    if (!(UnwrappedArgs.empty() && 
DestRecordDecl->hasDefaultConstructor()1.02k
))
3931
2.24k
      Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3932
2.24k
                                          CandidateSet, DestType, Ctors, Best,
3933
2.24k
                                          CopyInitialization, AllowExplicit,
3934
2.24k
                                          /*OnlyListConstructors=*/true,
3935
2.24k
                                          IsListInit);
3936
3.18k
  }
3937
404k
3938
404k
  // C++11 [over.match.list]p1:
3939
404k
  //   - If no viable initializer-list constructor is found, overload resolution
3940
404k
  //     is performed again, where the candidate functions are all the
3941
404k
  //     constructors of the class T and the argument list consists of the
3942
404k
  //     elements of the initializer list.
3943
404k
  if (Result == OR_No_Viable_Function) {
3944
404k
    AsInitializerList = false;
3945
404k
    Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
3946
404k
                                        CandidateSet, DestType, Ctors, Best,
3947
404k
                                        CopyInitialization, AllowExplicit,
3948
404k
                                        /*OnlyListConstructors=*/false,
3949
404k
                                        IsListInit);
3950
404k
  }
3951
404k
  if (Result) {
3952
1.48k
    Sequence.SetOverloadFailure(IsListInit ?
3953
197
                      InitializationSequence::FK_ListConstructorOverloadFailed :
3954
1.48k
                      
InitializationSequence::FK_ConstructorOverloadFailed1.28k
,
3955
1.48k
                                Result);
3956
1.48k
    return;
3957
1.48k
  }
3958
403k
3959
403k
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3960
403k
3961
403k
  // In C++17, ResolveConstructorOverload can select a conversion function
3962
403k
  // instead of a constructor.
3963
403k
  if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
3964
22
    // Add the user-defined conversion step that calls the conversion function.
3965
22
    QualType ConvType = CD->getConversionType();
3966
22
    assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
3967
22
           "should not have selected this conversion function");
3968
22
    Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
3969
22
                                   HadMultipleCandidates);
3970
22
    if (!S.Context.hasSameType(ConvType, DestType))
3971
4
      Sequence.AddQualificationConversionStep(DestType, VK_RValue);
3972
22
    if (IsListInit)
3973
8
      Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
3974
22
    return;
3975
22
  }
3976
403k
3977
403k
  // C++11 [dcl.init]p6:
3978
403k
  //   If a program calls for the default initialization of an object
3979
403k
  //   of a const-qualified type T, T shall be a class type with a
3980
403k
  //   user-provided default constructor.
3981
403k
  // C++ core issue 253 proposal:
3982
403k
  //   If the implicit default constructor initializes all subobjects, no
3983
403k
  //   initializer should be required.
3984
403k
  // The 253 proposal is for example needed to process libstdc++ headers in 5.x.
3985
403k
  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3986
403k
  if (Kind.getKind() == InitializationKind::IK_Default &&
3987
403k
      
Entity.getType().isConstQualified()104k
) {
3988
1.93k
    if (!CtorDecl->getParent()->allowConstDefaultInit()) {
3989
26
      if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
3990
2
        Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3991
26
      return;
3992
26
    }
3993
403k
  }
3994
403k
3995
403k
  // C++11 [over.match.list]p1:
3996
403k
  //   In copy-list-initialization, if an explicit constructor is chosen, the
3997
403k
  //   initializer is ill-formed.
3998
403k
  if (IsListInit && 
!Kind.AllowExplicit()2.97k
&&
CtorDecl->isExplicit()2.05k
) {
3999
72
    Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4000
72
    return;
4001
72
  }
4002
403k
4003
403k
  // Add the constructor initialization step. Any cv-qualification conversion is
4004
403k
  // subsumed by the initialization.
4005
403k
  Sequence.AddConstructorInitializationStep(
4006
403k
      Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4007
403k
      IsListInit | IsInitListCopy, AsInitializerList);
4008
403k
}
4009
4010
static bool
4011
ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4012
                                             Expr *Initializer,
4013
                                             QualType &SourceType,
4014
                                             QualType &UnqualifiedSourceType,
4015
                                             QualType UnqualifiedTargetType,
4016
700k
                                             InitializationSequence &Sequence) {
4017
700k
  if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4018
700k
        S.Context.OverloadTy) {
4019
93
    DeclAccessPair Found;
4020
93
    bool HadMultipleCandidates = false;
4021
93
    if (FunctionDecl *Fn
4022
81
        = S.ResolveAddressOfOverloadedFunction(Initializer,
4023
81
                                               UnqualifiedTargetType,
4024
81
                                               false, Found,
4025
81
                                               &HadMultipleCandidates)) {
4026
81
      Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4027
81
                                                HadMultipleCandidates);
4028
81
      SourceType = Fn->getType();
4029
81
      UnqualifiedSourceType = SourceType.getUnqualifiedType();
4030
81
    } else 
if (12
!UnqualifiedTargetType->isRecordType()12
) {
4031
12
      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4032
12
      return true;
4033
12
    }
4034
700k
  }
4035
700k
  return false;
4036
700k
}
4037
4038
static void TryReferenceInitializationCore(Sema &S,
4039
                                           const InitializedEntity &Entity,
4040
                                           const InitializationKind &Kind,
4041
                                           Expr *Initializer,
4042
                                           QualType cv1T1, QualType T1,
4043
                                           Qualifiers T1Quals,
4044
                                           QualType cv2T2, QualType T2,
4045
                                           Qualifiers T2Quals,
4046
                                           InitializationSequence &Sequence);
4047
4048
static void TryValueInitialization(Sema &S,
4049
                                   const InitializedEntity &Entity,
4050
                                   const InitializationKind &Kind,
4051
                                   InitializationSequence &Sequence,
4052
                                   InitListExpr *InitList = nullptr);
4053
4054
/// Attempt list initialization of a reference.
4055
static void TryReferenceListInitialization(Sema &S,
4056
                                           const InitializedEntity &Entity,
4057
                                           const InitializationKind &Kind,
4058
                                           InitListExpr *InitList,
4059
                                           InitializationSequence &Sequence,
4060
674
                                           bool TreatUnavailableAsInvalid) {
4061
674
  // First, catch C++03 where this isn't possible.
4062
674
  if (!S.getLangOpts().CPlusPlus11) {
4063
0
    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4064
0
    return;
4065
0
  }
4066
674
  // Can't reference initialize a compound literal.
4067
674
  if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4068
1
    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4069
1
    return;
4070
1
  }
4071
673
4072
673
  QualType DestType = Entity.getType();
4073
673
  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4074
673
  Qualifiers T1Quals;
4075
673
  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4076
673
4077
673
  // Reference initialization via an initializer list works thus:
4078
673
  // If the initializer list consists of a single element that is
4079
673
  // reference-related to the referenced type, bind directly to that element
4080
673
  // (possibly creating temporaries).
4081
673
  // Otherwise, initialize a temporary with the initializer list and
4082
673
  // bind to that.
4083
673
  if (InitList->getNumInits() == 1) {
4084
260
    Expr *Initializer = InitList->getInit(0);
4085
260
    QualType cv2T2 = Initializer->getType();
4086
260
    Qualifiers T2Quals;
4087
260
    QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4088
260
4089
260
    // If this fails, creating a temporary wouldn't work either.
4090
260
    if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4091
260
                                                     T1, Sequence))
4092
4
      return;
4093
256
4094
256
    SourceLocation DeclLoc = Initializer->getBeginLoc();
4095
256
    bool dummy1, dummy2, dummy3;
4096
256
    Sema::ReferenceCompareResult RefRelationship
4097
256
      = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
4098
256
                                       dummy2, dummy3);
4099
256
    if (RefRelationship >= Sema::Ref_Related) {
4100
70
      // Try to bind the reference here.
4101
70
      TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4102
70
                                     T1Quals, cv2T2, T2, T2Quals, Sequence);
4103
70
      if (Sequence)
4104
61
        Sequence.RewrapReferenceInitList(cv1T1, InitList);
4105
70
      return;
4106
70
    }
4107
186
4108
186
    // Update the initializer if we've resolved an overloaded function.
4109
186
    if (Sequence.step_begin() != Sequence.step_end())
4110
1
      Sequence.RewrapReferenceInitList(cv1T1, InitList);
4111
186
  }
4112
673
4113
673
  // Not reference-related. Create a temporary and bind to that.
4114
673
  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
4115
599
4116
599
  TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4117
599
                        TreatUnavailableAsInvalid);
4118
599
  if (Sequence) {
4119
555
    if (DestType->isRValueReferenceType() ||
4120
555
        
(299
T1Quals.hasConst()299
&&
!T1Quals.hasVolatile()292
))
4121
548
      Sequence.AddReferenceBindingStep(cv1T1, /*BindingTemporary=*/true);
4122
7
    else
4123
7
      Sequence.SetFailed(
4124
7
          InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4125
555
  }
4126
599
}
4127
4128
/// Attempt list initialization (C++0x [dcl.init.list])
4129
static void TryListInitialization(Sema &S,
4130
                                  const InitializedEntity &Entity,
4131
                                  const InitializationKind &Kind,
4132
                                  InitListExpr *InitList,
4133
                                  InitializationSequence &Sequence,
4134
114k
                                  bool TreatUnavailableAsInvalid) {
4135
114k
  QualType DestType = Entity.getType();
4136
114k
4137
114k
  // C++ doesn't allow scalar initialization with more than one argument.
4138
114k
  // But C99 complex numbers are scalars and it makes sense there.
4139
114k
  if (S.getLangOpts().CPlusPlus && 
DestType->isScalarType()68.8k
&&
4140
114k
      
!DestType->isAnyComplexType()4.84k
&&
InitList->getNumInits() > 14.79k
) {
4141
26
    Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4142
26
    return;
4143
26
  }
4144
114k
  if (DestType->isReferenceType()) {
4145
674
    TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4146
674
                                   TreatUnavailableAsInvalid);
4147
674
    return;
4148
674
  }
4149
113k
4150
113k
  if (DestType->isRecordType() &&
4151
113k
      
!S.isCompleteType(InitList->getBeginLoc(), DestType)41.9k
) {
4152
1
    Sequence.setIncompleteTypeFailure(DestType);
4153
1
    return;
4154
1
  }
4155
113k
4156
113k
  // C++11 [dcl.init.list]p3, per DR1467:
4157
113k
  // - If T is a class type and the initializer list has a single element of
4158
113k
  //   type cv U, where U is T or a class derived from T, the object is
4159
113k
  //   initialized from that element (by copy-initialization for
4160
113k
  //   copy-list-initialization, or by direct-initialization for
4161
113k
  //   direct-list-initialization).
4162
113k
  // - Otherwise, if T is a character array and the initializer list has a
4163
113k
  //   single element that is an appropriately-typed string literal
4164
113k
  //   (8.5.2 [dcl.init.string]), initialization is performed as described
4165
113k
  //   in that section.
4166
113k
  // - Otherwise, if T is an aggregate, [...] (continue below).
4167
113k
  if (S.getLangOpts().CPlusPlus11 && 
InitList->getNumInits() == 165.5k
) {
4168
19.5k
    if (DestType->isRecordType()) {
4169
5.38k
      QualType InitType = InitList->getInit(0)->getType();
4170
5.38k
      if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4171
5.38k
          
S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)5.29k
) {
4172
95
        Expr *InitListAsExpr = InitList;
4173
95
        TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4174
95
                                     DestType, Sequence,
4175
95
                                     /*InitListSyntax*/false,
4176
95
                                     /*IsInitListCopy*/true);
4177
95
        return;
4178
95
      }
4179
19.4k
    }
4180
19.4k
    if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4181
10.0k
      Expr *SubInit[1] = {InitList->getInit(0)};
4182
10.0k
      if (!isa<VariableArrayType>(DestAT) &&
4183
10.0k
          IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4184
62
        InitializationKind SubKind =
4185
62
            Kind.getKind() == InitializationKind::IK_DirectList
4186
62
                ? InitializationKind::CreateDirect(Kind.getLocation(),
4187
15
                                                   InitList->getLBraceLoc(),
4188
15
                                                   InitList->getRBraceLoc())
4189
62
                : 
Kind47
;
4190
62
        Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4191
62
                                /*TopLevelOfInitList*/ true,
4192
62
                                TreatUnavailableAsInvalid);
4193
62
4194
62
        // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4195
62
        // the element is not an appropriately-typed string literal, in which
4196
62
        // case we should proceed as in C++11 (below).
4197
62
        if (Sequence) {
4198
62
          Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4199
62
          return;
4200
62
        }
4201
113k
      }
4202
10.0k
    }
4203
19.4k
  }
4204
113k
4205
113k
  // C++11 [dcl.init.list]p3:
4206
113k
  //   - If T is an aggregate, aggregate initialization is performed.
4207
113k
  if ((DestType->isRecordType() && 
!DestType->isAggregateType()41.8k
) ||
4208
113k
      
(109k
S.getLangOpts().CPlusPlus11109k
&&
4209
109k
       
S.isStdInitializerList(DestType, nullptr)61.4k
)) {
4210
3.94k
    if (S.getLangOpts().CPlusPlus11) {
4211
3.93k
      //   - Otherwise, if the initializer list has no elements and T is a
4212
3.93k
      //     class type with a default constructor, the object is
4213
3.93k
      //     value-initialized.
4214
3.93k
      if (InitList->getNumInits() == 0) {
4215
1.05k
        CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4216
1.05k
        if (RD->hasDefaultConstructor()) {
4217
937
          TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4218
937
          return;
4219
937
        }
4220
2.99k
      }
4221
2.99k
4222
2.99k
      //   - Otherwise, if T is a specialization of std::initializer_list<E>,
4223
2.99k
      //     an initializer_list object constructed [...]
4224
2.99k
      if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4225
2.99k
                                         TreatUnavailableAsInvalid))
4226
751
        return;
4227
2.24k
4228
2.24k
      //   - Otherwise, if T is a class type, constructors are considered.
4229
2.24k
      Expr *InitListAsExpr = InitList;
4230
2.24k
      TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4231
2.24k
                                   DestType, Sequence, /*InitListSyntax*/true);
4232
2.24k
    } else
4233
5
      Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4234
3.94k
    
return2.25k
;
4235
109k
  }
4236
109k
4237
109k
  if (S.getLangOpts().CPlusPlus && 
!DestType->isAggregateType()64.0k
&&
4238
109k
      
InitList->getNumInits() == 18.67k
) {
4239
4.08k
    Expr *E = InitList->getInit(0);
4240
4.08k
4241
4.08k
    //   - Otherwise, if T is an enumeration with a fixed underlying type,
4242
4.08k
    //     the initializer-list has a single element v, and the initialization
4243
4.08k
    //     is direct-list-initialization, the object is initialized with the
4244
4.08k
    //     value T(v); if a narrowing conversion is required to convert v to
4245
4.08k
    //     the underlying type of T, the program is ill-formed.
4246
4.08k
    auto *ET = DestType->getAs<EnumType>();
4247
4.08k
    if (S.getLangOpts().CPlusPlus17 &&
4248
4.08k
        
Kind.getKind() == InitializationKind::IK_DirectList239
&&
4249
4.08k
        
ET168
&&
ET->getDecl()->isFixed()71
&&
4250
4.08k
        
!S.Context.hasSameUnqualifiedType(E->getType(), DestType)63
&&
4251
4.08k
        
(63
E->getType()->isIntegralOrEnumerationType()63
||
4252
63
         
E->getType()->isFloatingType()1
)) {
4253
63
      // There are two ways that T(v) can work when T is an enumeration type.
4254
63
      // If there is either an implicit conversion sequence from v to T or
4255
63
      // a conversion function that can convert from v to T, then we use that.
4256
63
      // Otherwise, if v is of integral, enumeration, or floating-point type,
4257
63
      // it is converted to the enumeration type via its underlying type.
4258
63
      // There is no overlap possible between these two cases (except when the
4259
63
      // source value is already of the destination type), and the first
4260
63
      // case is handled by the general case for single-element lists below.
4261
63
      ImplicitConversionSequence ICS;
4262
63
      ICS.setStandard();
4263
63
      ICS.Standard.setAsIdentityConversion();
4264
63
      if (!E->isRValue())
4265
8
        ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4266
63
      // If E is of a floating-point type, then the conversion is ill-formed
4267
63
      // due to narrowing, but go through the motions in order to produce the
4268
63
      // right diagnostic.
4269
63
      ICS.Standard.Second = E->getType()->isFloatingType()
4270
63
                                ? 
ICK_Floating_Integral1
4271
63
                                : 
ICK_Integral_Conversion62
;
4272
63
      ICS.Standard.setFromType(E->getType());
4273
63
      ICS.Standard.setToType(0, E->getType());
4274
63
      ICS.Standard.setToType(1, DestType);
4275
63
      ICS.Standard.setToType(2, DestType);
4276
63
      Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4277
63
                                         /*TopLevelOfInitList*/true);
4278
63
      Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4279
63
      return;
4280
63
    }
4281
4.02k
4282
4.02k
    //   - Otherwise, if the initializer list has a single element of type E
4283
4.02k
    //     [...references are handled above...], the object or reference is
4284
4.02k
    //     initialized from that element (by copy-initialization for
4285
4.02k
    //     copy-list-initialization, or by direct-initialization for
4286
4.02k
    //     direct-list-initialization); if a narrowing conversion is required
4287
4.02k
    //     to convert the element to T, the program is ill-formed.
4288
4.02k
    //
4289
4.02k
    // Per core-24034, this is direct-initialization if we were performing
4290
4.02k
    // direct-list-initialization and copy-initialization otherwise.
4291
4.02k
    // We can't use InitListChecker for this, because it always performs
4292
4.02k
    // copy-initialization. This only matters if we might use an 'explicit'
4293
4.02k
    // conversion operator, so we only need to handle the cases where the source
4294
4.02k
    // is of record type.
4295
4.02k
    if (InitList->getInit(0)->getType()->isRecordType()) {
4296
94
      InitializationKind SubKind =
4297
94
          Kind.getKind() == InitializationKind::IK_DirectList
4298
94
              ? InitializationKind::CreateDirect(Kind.getLocation(),
4299
48
                                                 InitList->getLBraceLoc(),
4300
48
                                                 InitList->getRBraceLoc())
4301
94
              : 
Kind46
;
4302
94
      Expr *SubInit[1] = { InitList->getInit(0) };
4303
94
      Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4304
94
                              /*TopLevelOfInitList*/true,
4305
94
                              TreatUnavailableAsInvalid);
4306
94
      if (Sequence)
4307
64
        Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4308
94
      return;
4309
94
    }
4310
109k
  }
4311
109k
4312
109k
  InitListChecker CheckInitList(S, Entity, InitList,
4313
109k
          DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4314
109k
  if (CheckInitList.HadError()) {
4315
481
    Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4316
481
    return;
4317
481
  }
4318
108k
4319
108k
  // Add the list initialization step with the built init list.
4320
108k
  Sequence.AddListInitializationStep(DestType);
4321
108k
}
4322
4323
/// Try a reference initialization that involves calling a conversion
4324
/// function.
4325
static OverloadingResult TryRefInitWithConversionFunction(
4326
    Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4327
    Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4328
2.13k
    InitializationSequence &Sequence) {
4329
2.13k
  QualType DestType = Entity.getType();
4330
2.13k
  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4331
2.13k
  QualType T1 = cv1T1.getUnqualifiedType();
4332
2.13k
  QualType cv2T2 = Initializer->getType();
4333
2.13k
  QualType T2 = cv2T2.getUnqualifiedType();
4334
2.13k
4335
2.13k
  bool DerivedToBase;
4336
2.13k
  bool ObjCConversion;
4337
2.13k
  bool ObjCLifetimeConversion;
4338
2.13k
  assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2,
4339
2.13k
                                         DerivedToBase, ObjCConversion,
4340
2.13k
                                         ObjCLifetimeConversion) &&
4341
2.13k
         "Must have incompatible references when binding via conversion");
4342
2.13k
  (void)DerivedToBase;
4343
2.13k
  (void)ObjCConversion;
4344
2.13k
  (void)ObjCLifetimeConversion;
4345
2.13k
4346
2.13k
  // Build the candidate set directly in the initialization sequence
4347
2.13k
  // structure, so that it will persist if we fail.
4348
2.13k
  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4349
2.13k
  CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4350
2.13k
4351
2.13k
  // Determine whether we are allowed to call explicit conversion operators.
4352
2.13k
  // Note that none of [over.match.copy], [over.match.conv], nor
4353
2.13k
  // [over.match.ref] permit an explicit constructor to be chosen when
4354
2.13k
  // initializing a reference, not even for direct-initialization.
4355
2.13k
  bool AllowExplicitCtors = false;
4356
2.13k
  bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4357
2.13k
4358
2.13k
  const RecordType *T1RecordType = nullptr;
4359
2.13k
  if (AllowRValues && 
(T1RecordType = T1->getAs<RecordType>())992
&&
4360
2.13k
      
S.isCompleteType(Kind.getLocation(), T1)885
) {
4361
883
    // The type we're converting to is a class type. Enumerate its constructors
4362
883
    // to see if there is a suitable conversion.
4363
883
    CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4364
883
4365
7.45k
    for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4366
7.45k
      auto Info = getConstructorInfo(D);
4367
7.45k
      if (!Info.Constructor)
4368
3
        continue;
4369
7.44k
4370
7.44k
      if (!Info.Constructor->isInvalidDecl() &&
4371
7.44k
          Info.Constructor->isConvertingConstructor(AllowExplicitCtors)) {
4372
6.04k
        if (Info.ConstructorTmpl)
4373
241
          S.AddTemplateOverloadCandidate(
4374
241
              Info.ConstructorTmpl, Info.FoundDecl,
4375
241
              /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4376
241
              /*SuppressUserConversions=*/true,
4377
241
              /*PartialOverloading*/ false, AllowExplicitCtors);
4378
5.80k
        else
4379
5.80k
          S.AddOverloadCandidate(
4380
5.80k
              Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4381
5.80k
              /*SuppressUserConversions=*/true,
4382
5.80k
              /*PartialOverloading*/ false, AllowExplicitCtors);
4383
6.04k
      }
4384
7.44k
    }
4385
883
  }
4386
2.13k
  if (T1RecordType && 
T1RecordType->getDecl()->isInvalidDecl()885
)
4387
0
    return OR_No_Viable_Function;
4388
2.13k
4389
2.13k
  const RecordType *T2RecordType = nullptr;
4390
2.13k
  if ((T2RecordType = T2->getAs<RecordType>()) &&
4391
2.13k
      S.isCompleteType(Kind.getLocation(), T2)) {
4392
2.13k
    // The type we're converting from is a class type, enumerate its conversion
4393
2.13k
    // functions.
4394
2.13k
    CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4395
2.13k
4396
2.13k
    const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4397
3.26k
    for (auto I = Conversions.begin(), E = Conversions.end(); I != E; 
++I1.12k
) {
4398
1.12k
      NamedDecl *D = *I;
4399
1.12k
      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4400
1.12k
      if (isa<UsingShadowDecl>(D))
4401
0
        D = cast<UsingShadowDecl>(D)->getTargetDecl();
4402
1.12k
4403
1.12k
      FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4404
1.12k
      CXXConversionDecl *Conv;
4405
1.12k
      if (ConvTemplate)
4406
138
        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4407
990
      else
4408
990
        Conv = cast<CXXConversionDecl>(D);
4409
1.12k
4410
1.12k
      // If the conversion function doesn't return a reference type,
4411
1.12k
      // it can't be considered for this conversion unless we're allowed to
4412
1.12k
      // consider rvalues.
4413
1.12k
      // FIXME: Do we need to make sure that we only consider conversion
4414
1.12k
      // candidates with reference-compatible results? That might be needed to
4415
1.12k
      // break recursion.
4416
1.12k
      if ((AllowExplicitConvs || 
!Conv->isExplicit()602
) &&
4417
1.12k
          
(1.07k
AllowRValues1.07k
||
4418
1.07k
           
Conv->getConversionType()->isLValueReferenceType()611
)) {
4419
675
        if (ConvTemplate)
4420
100
          S.AddTemplateConversionCandidate(
4421
100
              ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4422
100
              CandidateSet,
4423
100
              /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4424
575
        else
4425
575
          S.AddConversionCandidate(
4426
575
              Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4427
575
              /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4428
675
      }
4429
1.12k
    }
4430
2.13k
  }
4431
2.13k
  if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4432
2
    return OR_No_Viable_Function;
4433
2.13k
4434
2.13k
  SourceLocation DeclLoc = Initializer->getBeginLoc();
4435
2.13k
4436
2.13k
  // Perform overload resolution. If it fails, return the failed result.
4437
2.13k
  OverloadCandidateSet::iterator Best;
4438
2.13k
  if (OverloadingResult Result
4439
1.05k
        = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4440
1.05k
    return Result;
4441
1.08k
4442
1.08k
  FunctionDecl *Function = Best->Function;
4443
1.08k
  // This is the overload that will be used for this initialization step if we
4444
1.08k
  // use this initialization. Mark it as referenced.
4445
1.08k
  Function->setReferenced();
4446
1.08k
4447
1.08k
  // Compute the returned type and value kind of the conversion.
4448
1.08k
  QualType cv3T3;
4449
1.08k
  if (isa<CXXConversionDecl>(Function))
4450
451
    cv3T3 = Function->getReturnType();
4451
633
  else
4452
633
    cv3T3 = T1;
4453
1.08k
4454
1.08k
  ExprValueKind VK = VK_RValue;
4455
1.08k
  if (cv3T3->isLValueReferenceType())
4456
166
    VK = VK_LValue;
4457
918
  else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4458
25
    VK = RRef->getPointeeType()->isFunctionType() ? 
VK_LValue0
: VK_XValue;
4459
1.08k
  cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4460
1.08k
4461
1.08k
  // Add the user-defined conversion step.
4462
1.08k
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4463
1.08k
  Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4464
1.08k
                                 HadMultipleCandidates);
4465
1.08k
4466
1.08k
  // Determine whether we'll need to perform derived-to-base adjustments or
4467
1.08k
  // other conversions.
4468
1.08k
  bool NewDerivedToBase = false;
4469
1.08k
  bool NewObjCConversion = false;
4470
1.08k
  bool NewObjCLifetimeConversion = false;
4471
1.08k
  Sema::ReferenceCompareResult NewRefRelationship
4472
1.08k
    = S.CompareReferenceRelationship(DeclLoc, T1, cv3T3,
4473
1.08k
                                     NewDerivedToBase, NewObjCConversion,
4474
1.08k
                                     NewObjCLifetimeConversion);
4475
1.08k
4476
1.08k
  // Add the final conversion sequence, if necessary.
4477
1.08k
  if (NewRefRelationship == Sema::Ref_Incompatible) {
4478
16
    assert(!isa<CXXConstructorDecl>(Function) &&
4479
16
           "should not have conversion after constructor");
4480
16
4481
16
    ImplicitConversionSequence ICS;
4482
16
    ICS.setStandard();
4483
16
    ICS.Standard = Best->FinalConversion;
4484
16
    Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4485
16
4486
16
    // Every implicit conversion results in a prvalue, except for a glvalue
4487
16
    // derived-to-base conversion, which we handle below.
4488
16
    cv3T3 = ICS.Standard.getToType(2);
4489
16
    VK = VK_RValue;
4490
16
  }
4491
1.08k
4492
1.08k
  //   If the converted initializer is a prvalue, its type T4 is adjusted to
4493
1.08k
  //   type "cv1 T4" and the temporary materialization conversion is applied.
4494
1.08k
  //
4495
1.08k
  // We adjust the cv-qualifications to match the reference regardless of
4496
1.08k
  // whether we have a prvalue so that the AST records the change. In this
4497
1.08k
  // case, T4 is "cv3 T3".
4498
1.08k
  QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4499
1.08k
  if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4500
828
    Sequence.AddQualificationConversionStep(cv1T4, VK);
4501
1.08k
  Sequence.AddReferenceBindingStep(cv1T4, VK == VK_RValue);
4502
1.08k
  VK = IsLValueRef ? 
VK_LValue966
:
VK_XValue118
;
4503
1.08k
4504
1.08k
  if (NewDerivedToBase)
4505
32
    Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4506
1.05k
  else if (NewObjCConversion)
4507
5
    Sequence.AddObjCObjectConversionStep(cv1T1);
4508
1.08k
4509
1.08k
  return OR_Success;
4510
1.08k
}
4511
4512
static void CheckCXX98CompatAccessibleCopy(Sema &S,
4513
                                           const InitializedEntity &Entity,
4514
                                           Expr *CurInitExpr);
4515
4516
/// Attempt reference initialization (C++0x [dcl.init.ref])
4517
static void TryReferenceInitialization(Sema &S,
4518
                                       const InitializedEntity &Entity,
4519
                                       const InitializationKind &Kind,
4520
                                       Expr *Initializer,
4521
700k
                                       InitializationSequence &Sequence) {
4522
700k
  QualType DestType = Entity.getType();
4523
700k
  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
4524
700k
  Qualifiers T1Quals;
4525
700k
  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4526
700k
  QualType cv2T2 = Initializer->getType();
4527
700k
  Qualifiers T2Quals;
4528
700k
  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4529
700k
4530
700k
  // If the initializer is the address of an overloaded function, try
4531
700k
  // to resolve the overloaded function. If all goes well, T2 is the
4532
700k
  // type of the resulting function.
4533
700k
  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4534
700k
                                                   T1, Sequence))
4535
8
    return;
4536
700k
4537
700k
  // Delegate everything else to a subfunction.
4538
700k
  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4539
700k
                                 T1Quals, cv2T2, T2, T2Quals, Sequence);
4540
700k
}
4541
4542
/// Determine whether an expression is a non-referenceable glvalue (one to
4543
/// which a reference can never bind). Attempting to bind a reference to
4544
/// such a glvalue will always create a temporary.
4545
523k
static bool isNonReferenceableGLValue(Expr *E) {
4546
523k
  return E->refersToBitField() || 
E->refersToVectorElement()523k
;
4547
523k
}
4548
4549
/// Reference initialization without resolving overloaded functions.
4550
static void TryReferenceInitializationCore(Sema &S,
4551
                                           const InitializedEntity &Entity,
4552
                                           const InitializationKind &Kind,
4553
                                           Expr *Initializer,
4554
                                           QualType cv1T1, QualType T1,
4555
                                           Qualifiers T1Quals,
4556
                                           QualType cv2T2, QualType T2,
4557
                                           Qualifiers T2Quals,
4558
700k
                                           InitializationSequence &Sequence) {
4559
700k
  QualType DestType = Entity.getType();
4560
700k
  SourceLocation DeclLoc = Initializer->getBeginLoc();
4561
700k
  // Compute some basic properties of the types and the initializer.
4562
700k
  bool isLValueRef = DestType->isLValueReferenceType();
4563
700k
  bool isRValueRef = !isLValueRef;
4564
700k
  bool DerivedToBase = false;
4565
700k
  bool ObjCConversion = false;
4566
700k
  bool ObjCLifetimeConversion = false;
4567
700k
  Expr::Classification InitCategory = Initializer->Classify(S.Context);
4568
700k
  Sema::ReferenceCompareResult RefRelationship
4569
700k
    = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
4570
700k
                                     ObjCConversion, ObjCLifetimeConversion);
4571
700k
4572
700k
  // C++0x [dcl.init.ref]p5:
4573
700k
  //   A reference to type "cv1 T1" is initialized by an expression of type
4574
700k
  //   "cv2 T2" as follows:
4575
700k
  //
4576
700k
  //     - If the reference is an lvalue reference and the initializer
4577
700k
  //       expression
4578
700k
  // Note the analogous bullet points for rvalue refs to functions. Because
4579
700k
  // there are no function rvalues in C++, rvalue refs to functions are treated
4580
700k
  // like lvalue refs.
4581
700k
  OverloadingResult ConvOvlResult = OR_Success;
4582
700k
  bool T1Function = T1->isFunctionType();
4583
700k
  if (isLValueRef || 
T1Function126k
) {
4584
574k
    if (InitCategory.isLValue() && 
!isNonReferenceableGLValue(Initializer)468k
&&
4585
574k
        
(468k
RefRelationship == Sema::Ref_Compatible468k
||
4586
468k
         
(2.39k
Kind.isCStyleOrFunctionalCast()2.39k
&&
4587
466k
          
RefRelationship == Sema::Ref_Related569
))) {
4588
466k
      //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
4589
466k
      //     reference-compatible with "cv2 T2," or
4590
466k
      if (T1Quals != T2Quals)
4591
84.5k
        // Convert to cv1 T2. This should only add qualifiers unless this is a
4592
84.5k
        // c-style cast. The removal of qualifiers in that case notionally
4593
84.5k
        // happens after the reference binding, but that doesn't matter.
4594
84.5k
        Sequence.AddQualificationConversionStep(
4595
84.5k
            S.Context.getQualifiedType(T2, T1Quals),
4596
84.5k
            Initializer->getValueKind());
4597
466k
      if (DerivedToBase)
4598
23.4k
        Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4599
443k
      else if (ObjCConversion)
4600
10
        Sequence.AddObjCObjectConversionStep(cv1T1);
4601
466k
4602
466k
      // We only create a temporary here when binding a reference to a
4603
466k
      // bit-field or vector element. Those cases are't supposed to be
4604
466k
      // handled by this bullet, but the outcome is the same either way.
4605
466k
      Sequence.AddReferenceBindingStep(cv1T1, false);
4606
466k
      return;
4607
466k
    }
4608
107k
4609
107k
    //     - has a class type (i.e., T2 is a class type), where T1 is not
4610
107k
    //       reference-related to T2, and can be implicitly converted to an
4611
107k
    //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4612
107k
    //       with "cv3 T3" (this conversion is selected by enumerating the
4613
107k
    //       applicable conversion functions (13.3.1.6) and choosing the best
4614
107k
    //       one through overload resolution (13.3)),
4615
107k
    // If we have an rvalue ref to function type here, the rhs must be
4616
107k
    // an rvalue. DR1287 removed the "implicitly" here.
4617
107k
    if (RefRelationship == Sema::Ref_Incompatible && 
T2->isRecordType()8.73k
&&
4618
107k
        
(1.15k
isLValueRef1.15k
||
InitCategory.isRValue()6
)) {
4619
1.15k
      ConvOvlResult = TryRefInitWithConversionFunction(
4620
1.15k
          S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4621
1.15k
          /*IsLValueRef*/ isLValueRef, Sequence);
4622
1.15k
      if (ConvOvlResult == OR_Success)
4623
166
        return;
4624
985
      if (ConvOvlResult != OR_No_Viable_Function)
4625
6
        Sequence.SetOverloadFailure(
4626
6
            InitializationSequence::FK_ReferenceInitOverloadFailed,
4627
6
            ConvOvlResult);
4628
985
    }
4629
107k
  }
4630
700k
4631
700k
  //     - Otherwise, the reference shall be an lvalue reference to a
4632
700k
  //       non-volatile const type (i.e., cv1 shall be const), or the reference
4633
700k
  //       shall be an rvalue reference.
4634
700k
  //       For address spaces, we interpret this to mean that an addr space
4635
700k
  //       of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
4636
700k
  
if (233k
isLValueRef233k
&&
!(107k
T1Quals.hasConst()107k
&&
!T1Quals.hasVolatile()106k
&&
4637
107k
                       
T1Quals.isAddressSpaceSupersetOf(T2Quals)106k
)) {
4638
961
    if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4639
0
      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4640
961
    else if (ConvOvlResult && 
!Sequence.getFailedCandidateSet().empty()130
)
4641
11
      Sequence.SetOverloadFailure(
4642
11
                        InitializationSequence::FK_ReferenceInitOverloadFailed,
4643
11
                                  ConvOvlResult);
4644
950
    else if (!InitCategory.isLValue())
4645
135
      Sequence.SetFailed(
4646
135
          T1Quals.isAddressSpaceSupersetOf(T2Quals)
4647
135
              ? InitializationSequence::
4648
134
                    FK_NonConstLValueReferenceBindingToTemporary
4649
135
              : 
InitializationSequence::FK_ReferenceInitDropsQualifiers1
);
4650
815
    else {
4651
815
      InitializationSequence::FailureKind FK;
4652
815
      switch (RefRelationship) {
4653
815
      case Sema::Ref_Compatible:
4654
44
        if (Initializer->refersToBitField())
4655
40
          FK = InitializationSequence::
4656
40
              FK_NonConstLValueReferenceBindingToBitfield;
4657
4
        else if (Initializer->refersToVectorElement())
4658
4
          FK = InitializationSequence::
4659
4
              FK_NonConstLValueReferenceBindingToVectorElement;
4660
4
        else
4661
4
          
llvm_unreachable0
("unexpected kind of compatible initializer");
4662
44
        break;
4663
80
      case Sema::Ref_Related:
4664
80
        FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4665
80
        break;
4666
691
      case Sema::Ref_Incompatible:
4667
691
        FK = InitializationSequence::
4668
691
            FK_NonConstLValueReferenceBindingToUnrelated;
4669
691
        break;
4670
815
      }
4671
815
      Sequence.SetFailed(FK);
4672
815
    }
4673
961
    return;
4674
232k
  }
4675
232k
4676
232k
  //    - If the initializer expression
4677
232k
  //      - is an
4678
232k
  // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4679
232k
  // [1z]   rvalue (but not a bit-field) or
4680
232k
  //        function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4681
232k
  //
4682
232k
  // Note: functions are handled above and below rather than here...
4683
232k
  if (!T1Function &&
4684
232k
      
(232k
RefRelationship == Sema::Ref_Compatible232k
||
4685
232k
       
(9.66k
Kind.isCStyleOrFunctionalCast()9.66k
&&
4686
9.66k
        
RefRelationship == Sema::Ref_Related27
)) &&
4687
232k
      
(222k
(222k
InitCategory.isXValue()222k
&&
!isNonReferenceableGLValue(Initializer)54.6k
) ||
4688
222k
       
(168k
InitCategory.isPRValue()168k
&&
4689
168k
        
(168k
S.getLangOpts().CPlusPlus17168k
||
T2->isRecordType()167k
||
4690
175k
         
T2->isArrayType()47.0k
)))) {
4691
175k
    ExprValueKind ValueKind = InitCategory.isXValue() ? 
VK_XValue54.6k
:
VK_RValue120k
;
4692
175k
    if (InitCategory.isPRValue() && 
T2->isRecordType()120k
) {
4693
120k
      // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4694
120k
      // compiler the freedom to perform a copy here or bind to the
4695
120k
      // object, while C++0x requires that we bind directly to the
4696
120k
      // object. Hence, we always bind to the object without making an
4697
120k
      // extra copy. However, in C++03 requires that we check for the
4698
120k
      // presence of a suitable copy constructor:
4699
120k
      //
4700
120k
      //   The constructor that would be used to make the copy shall
4701
120k
      //   be callable whether or not the copy is actually done.
4702
120k
      if (!S.getLangOpts().CPlusPlus11 && 
!S.getLangOpts().MicrosoftExt24.3k
)
4703
24.3k
        Sequence.AddExtraneousCopyToTemporary(cv2T2);
4704
96.4k
      else if (S.getLangOpts().CPlusPlus11)
4705
96.4k
        CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4706
120k
    }
4707
175k
4708
175k
    // C++1z [dcl.init.ref]/5.2.1.2:
4709
175k
    //   If the converted initializer is a prvalue, its type T4 is adjusted
4710
175k
    //   to type "cv1 T4" and the temporary materialization conversion is
4711
175k
    //   applied.
4712
175k
    // Postpone address space conversions to after the temporary materialization
4713
175k
    // conversion to allow creating temporaries in the alloca address space.
4714
175k
    auto T1QualsIgnoreAS = T1Quals;
4715
175k
    auto T2QualsIgnoreAS = T2Quals;
4716
175k
    if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4717
2
      T1QualsIgnoreAS.removeAddressSpace();
4718
2
      T2QualsIgnoreAS.removeAddressSpace();
4719
2
    }
4720
175k
    QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
4721
175k
    if (T1QualsIgnoreAS != T2QualsIgnoreAS)
4722
54.9k
      Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4723
175k
    Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_RValue);
4724
175k
    ValueKind = isLValueRef ? 
VK_LValue55.3k
:
VK_XValue120k
;
4725
175k
    // Add addr space conversion if required.
4726
175k
    if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4727
2
      auto T4Quals = cv1T4.getQualifiers();
4728
2
      T4Quals.addAddressSpace(T1Quals.getAddressSpace());
4729
2
      QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
4730
2
      Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
4731
2
    }
4732
175k
4733
175k
    //   In any case, the reference is bound to the resulting glvalue (or to
4734
175k
    //   an appropriate base class subobject).
4735
175k
    if (DerivedToBase)
4736
5.21k
      Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
4737
170k
    else if (ObjCConversion)
4738
0
      Sequence.AddObjCObjectConversionStep(cv1T1);
4739
175k
    return;
4740
175k
  }
4741
56.9k
4742
56.9k
  //       - has a class type (i.e., T2 is a class type), where T1 is not
4743
56.9k
  //         reference-related to T2, and can be implicitly converted to an
4744
56.9k
  //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
4745
56.9k
  //         where "cv1 T1" is reference-compatible with "cv3 T3",
4746
56.9k
  //
4747
56.9k
  // DR1287 removes the "implicitly" here.
4748
56.9k
  if (T2->isRecordType()) {
4749
1.14k
    if (RefRelationship == Sema::Ref_Incompatible) {
4750
986
      ConvOvlResult = TryRefInitWithConversionFunction(
4751
986
          S, Entity, Kind, Initializer, /*AllowRValues*/ true,
4752
986
          /*IsLValueRef*/ isLValueRef, Sequence);
4753
986
      if (ConvOvlResult)
4754
68
        Sequence.SetOverloadFailure(
4755
68
            InitializationSequence::FK_ReferenceInitOverloadFailed,
4756
68
            ConvOvlResult);
4757
986
4758
986
      return;
4759
986
    }
4760
154
4761
154
    if (RefRelationship == Sema::Ref_Compatible &&
4762
154
        
isRValueRef141
&&
InitCategory.isLValue()141
) {
4763
141
      Sequence.SetFailed(
4764
141
        InitializationSequence::FK_RValueReferenceBindingToLValue);
4765
141
      return;
4766
141
    }
4767
13
4768
13
    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4769
13
    return;
4770
13
  }
4771
55.7k
4772
55.7k
  //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
4773
55.7k
  //        from the initializer expression using the rules for a non-reference
4774
55.7k
  //        copy-initialization (8.5). The reference is then bound to the
4775
55.7k
  //        temporary. [...]
4776
55.7k
4777
55.7k
  // Ignore address space of reference type at this point and perform address
4778
55.7k
  // space conversion after the reference binding step.
4779
55.7k
  QualType cv1T1IgnoreAS =
4780
55.7k
      T1Quals.hasAddressSpace()
4781
55.7k
          ? 
S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())2
4782
55.7k
          : 
cv1T155.7k
;
4783
55.7k
4784
55.7k
  InitializedEntity TempEntity =
4785
55.7k
      InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
4786
55.7k
4787
55.7k
  // FIXME: Why do we use an implicit conversion here rather than trying
4788
55.7k
  // copy-initialization?
4789
55.7k
  ImplicitConversionSequence ICS
4790
55.7k
    = S.TryImplicitConversion(Initializer, TempEntity.getType(),
4791
55.7k
                              /*SuppressUserConversions=*/false,
4792
55.7k
                              /*AllowExplicit=*/false,
4793
55.7k
                              /*FIXME:InOverloadResolution=*/false,
4794
55.7k
                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4795
55.7k
                              /*AllowObjCWritebackConversion=*/false);
4796
55.7k
4797
55.7k
  if (ICS.isBad()) {
4798
34
    // FIXME: Use the conversion function set stored in ICS to turn
4799
34
    // this into an overloading ambiguity diagnostic. However, we need
4800
34
    // to keep that set as an OverloadCandidateSet rather than as some
4801
34
    // other kind of set.
4802
34
    if (ConvOvlResult && 
!Sequence.getFailedCandidateSet().empty()0
)
4803
0
      Sequence.SetOverloadFailure(
4804
0
                        InitializationSequence::FK_ReferenceInitOverloadFailed,
4805
0
                                  ConvOvlResult);
4806
34
    else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4807
0
      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4808
34
    else
4809
34
      Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
4810
34
    return;
4811
55.7k
  } else {
4812
55.7k
    Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
4813
55.7k
  }
4814
55.7k
4815
55.7k
  //        [...] If T1 is reference-related to T2, cv1 must be the
4816
55.7k
  //        same cv-qualification as, or greater cv-qualification
4817
55.7k
  //        than, cv2; otherwise, the program is ill-formed.
4818
55.7k
  unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
4819
55.7k
  unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
4820
55.7k
  if ((RefRelationship == Sema::Ref_Related &&
4821
55.7k
       
(T1CVRQuals | T2CVRQuals) != T1CVRQuals16
) ||
4822
55.7k
      
!T1Quals.isAddressSpaceSupersetOf(T2Quals)55.7k
) {
4823
13
    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
4824
13
    return;
4825
13
  }
4826
55.7k
4827
55.7k
  //   [...] If T1 is reference-related to T2 and the reference is an rvalue
4828
55.7k
  //   reference, the initializer expression shall not be an lvalue.
4829
55.7k
  if (RefRelationship >= Sema::Ref_Related && 
!isLValueRef47.1k
&&
4830
55.7k
      
InitCategory.isLValue()4.03k
) {
4831
12
    Sequence.SetFailed(
4832
12
                    InitializationSequence::FK_RValueReferenceBindingToLValue);
4833
12
    return;
4834
12
  }
4835
55.7k
4836
55.7k
  Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
4837
55.7k
4838
55.7k
  if (T1Quals.hasAddressSpace()) {
4839
2
    if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
4840
2
                                              LangAS::Default)) {
4841
1
      Sequence.SetFailed(
4842
1
          InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
4843
1
      return;
4844
1
    }
4845
1
    Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
4846
1
                                                               : 
VK_XValue0
);
4847
1
  }
4848
55.7k
}
4849
4850
/// Attempt character array initialization from a string literal
4851
/// (C++ [dcl.init.string], C99 6.7.8).
4852
static void TryStringLiteralInitialization(Sema &S,
4853
                                           const InitializedEntity &Entity,
4854
                                           const InitializationKind &Kind,
4855
                                           Expr *Initializer,
4856
2.04k
                                       InitializationSequence &Sequence) {
4857
2.04k
  Sequence.AddStringInitStep(Entity.getType());
4858
2.04k
}
4859
4860
/// Attempt value initialization (C++ [dcl.init]p7).
4861
static void TryValueInitialization(Sema &S,
4862
                                   const InitializedEntity &Entity,
4863
                                   const InitializationKind &Kind,
4864
                                   InitializationSequence &Sequence,
4865
90.3k
                                   InitListExpr *InitList) {
4866
90.3k
  assert((!InitList || InitList->getNumInits() == 0) &&
4867
90.3k
         "Shouldn't use value-init for non-empty init lists");
4868
90.3k
4869
90.3k
  // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
4870
90.3k
  //
4871
90.3k
  //   To value-initialize an object of type T means:
4872
90.3k
  QualType T = Entity.getType();
4873
90.3k
4874
90.3k
  //     -- if T is an array type, then each element is value-initialized;
4875
90.3k
  T = S.Context.getBaseElementType(T);
4876
90.3k
4877
90.3k
  if (const RecordType *RT = T->getAs<RecordType>()) {
4878
49.4k
    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
4879
49.3k
      bool NeedZeroInitialization = true;
4880
49.3k
      // C++98:
4881
49.3k
      // -- if T is a class type (clause 9) with a user-declared constructor
4882
49.3k
      //    (12.1), then the default constructor for T is called (and the
4883
49.3k
      //    initialization is ill-formed if T has no accessible default
4884
49.3k
      //    constructor);
4885
49.3k
      // C++11:
4886
49.3k
      // -- if T is a class type (clause 9) with either no default constructor
4887
49.3k
      //    (12.1 [class.ctor]) or a default constructor that is user-provided
4888
49.3k
      //    or deleted, then the object is default-initialized;
4889
49.3k
      //
4890
49.3k
      // Note that the C++11 rule is the same as the C++98 rule if there are no
4891
49.3k
      // defaulted or deleted constructors, so we just use it unconditionally.
4892
49.3k
      CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
4893
49.3k
      if (!CD || 
!CD->getCanonicalDecl()->isDefaulted()48.8k
||
CD->isDeleted()38.7k
)
4894
10.6k
        NeedZeroInitialization = false;
4895
49.3k
4896
49.3k
      // -- if T is a (possibly cv-qualified) non-union class type without a
4897
49.3k
      //    user-provided or deleted default constructor, then the object is
4898
49.3k
      //    zero-initialized and, if T has a non-trivial default constructor,
4899
49.3k
      //    default-initialized;
4900
49.3k
      // The 'non-union' here was removed by DR1502. The 'non-trivial default
4901
49.3k
      // constructor' part was removed by DR1507.
4902
49.3k
      if (NeedZeroInitialization)
4903
38.6k
        Sequence.AddZeroInitializationStep(Entity.getType());
4904
49.3k
4905
49.3k
      // C++03:
4906
49.3k
      // -- if T is a non-union class type without a user-declared constructor,
4907
49.3k
      //    then every non-static data member and base class component of T is
4908
49.3k
      //    value-initialized;
4909
49.3k
      // [...] A program that calls for [...] value-initialization of an
4910
49.3k
      // entity of reference type is ill-formed.
4911
49.3k
      //
4912
49.3k
      // C++11 doesn't need this handling, because value-initialization does not
4913
49.3k
      // occur recursively there, and the implicit default constructor is
4914
49.3k
      // defined as deleted in the problematic cases.
4915
49.3k
      if (!S.getLangOpts().CPlusPlus11 &&
4916
49.3k
          
ClassDecl->hasUninitializedReferenceMember()1.04k
) {
4917
4
        Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
4918
4
        return;
4919
4
      }
4920
49.3k
4921
49.3k
      // If this is list-value-initialization, pass the empty init list on when
4922
49.3k
      // building the constructor call. This affects the semantics of a few
4923
49.3k
      // things (such as whether an explicit default constructor can be called).
4924
49.3k
      Expr *InitListAsExpr = InitList;
4925
49.3k
      MultiExprArg Args(&InitListAsExpr, InitList ? 
1937
:
048.3k
);
4926
49.3k
      bool InitListSyntax = InitList;
4927
49.3k
4928
49.3k
      // FIXME: Instead of creating a CXXConstructExpr of array type here,
4929
49.3k
      // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
4930
49.3k
      return TryConstructorInitialization(
4931
49.3k
          S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
4932
49.3k
    }
4933
49.4k
  }
4934
41.0k
4935
41.0k
  Sequence.AddZeroInitializationStep(Entity.getType());
4936
41.0k
}
4937
4938
/// Attempt default initialization (C++ [dcl.init]p6).
4939
static void TryDefaultInitialization(Sema &S,
4940
                                     const InitializedEntity &Entity,
4941
                                     const InitializationKind &Kind,
4942
562k
                                     InitializationSequence &Sequence) {
4943
562k
  assert(Kind.getKind() == InitializationKind::IK_Default);
4944
562k
4945
562k
  // C++ [dcl.init]p6:
4946
562k
  //   To default-initialize an object of type T means:
4947
562k
  //     - if T is an array type, each element is default-initialized;
4948
562k
  QualType DestType = S.Context.getBaseElementType(Entity.getType());
4949
562k
4950
562k
  //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
4951
562k
  //       constructor for T is called (and the initialization is ill-formed if
4952
562k
  //       T has no accessible default constructor);
4953
562k
  if (DestType->isRecordType() && 
S.getLangOpts().CPlusPlus121k
) {
4954
105k
    TryConstructorInitialization(S, Entity, Kind, None, DestType,
4955
105k
                                 Entity.getType(), Sequence);
4956
105k
    return;
4957
105k
  }
4958
457k
4959
457k
  //     - otherwise, no initialization is performed.
4960
457k
4961
457k
  //   If a program calls for the default initialization of an object of
4962
457k
  //   a const-qualified type T, T shall be a class type with a user-provided
4963
457k
  //   default constructor.
4964
457k
  if (DestType.isConstQualified() && 
S.getLangOpts().CPlusPlus84
) {
4965
49
    if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4966
5
      Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4967
49
    return;
4968
49
  }
4969
457k
4970
457k
  // If the destination type has a lifetime property, zero-initialize it.
4971
457k
  if (DestType.getQualifiers().hasObjCLifetime()) {
4972
649
    Sequence.AddZeroInitializationStep(Entity.getType());
4973
649
    return;
4974
649
  }
4975
457k
}
4976
4977
/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
4978
/// which enumerates all conversion functions and performs overload resolution
4979
/// to select the best.
4980
static void TryUserDefinedConversion(Sema &S,
4981
                                     QualType DestType,
4982
                                     const InitializationKind &Kind,
4983
                                     Expr *Initializer,