Coverage Report

Created: 2021-08-24 07:12

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