Coverage Report

Created: 2024-01-17 10:31

/src/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/IgnoreExpr.h"
19
#include "clang/AST/TypeLoc.h"
20
#include "clang/Basic/CharInfo.h"
21
#include "clang/Basic/SourceManager.h"
22
#include "clang/Basic/Specifiers.h"
23
#include "clang/Basic/TargetInfo.h"
24
#include "clang/Sema/Designator.h"
25
#include "clang/Sema/EnterExpressionEvaluationContext.h"
26
#include "clang/Sema/Initialization.h"
27
#include "clang/Sema/Lookup.h"
28
#include "clang/Sema/Ownership.h"
29
#include "clang/Sema/SemaInternal.h"
30
#include "llvm/ADT/APInt.h"
31
#include "llvm/ADT/FoldingSet.h"
32
#include "llvm/ADT/PointerIntPair.h"
33
#include "llvm/ADT/SmallString.h"
34
#include "llvm/ADT/SmallVector.h"
35
#include "llvm/ADT/StringExtras.h"
36
#include "llvm/Support/ErrorHandling.h"
37
#include "llvm/Support/raw_ostream.h"
38
39
using namespace clang;
40
41
//===----------------------------------------------------------------------===//
42
// Sema Initialization Checking
43
//===----------------------------------------------------------------------===//
44
45
/// Check whether T is compatible with a wide character type (wchar_t,
46
/// char16_t or char32_t).
47
0
static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
48
0
  if (Context.typesAreCompatible(Context.getWideCharType(), T))
49
0
    return true;
50
0
  if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
51
0
    return Context.typesAreCompatible(Context.Char16Ty, T) ||
52
0
           Context.typesAreCompatible(Context.Char32Ty, T);
53
0
  }
54
0
  return false;
55
0
}
56
57
enum StringInitFailureKind {
58
  SIF_None,
59
  SIF_NarrowStringIntoWideChar,
60
  SIF_WideStringIntoChar,
61
  SIF_IncompatWideStringIntoWideChar,
62
  SIF_UTF8StringIntoPlainChar,
63
  SIF_PlainStringIntoUTF8Char,
64
  SIF_Other
65
};
66
67
/// Check whether the array of type AT can be initialized by the Init
68
/// expression by means of string initialization. Returns SIF_None if so,
69
/// otherwise returns a StringInitFailureKind that describes why the
70
/// initialization would not work.
71
static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
72
0
                                          ASTContext &Context) {
73
0
  if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
74
0
    return SIF_Other;
75
76
  // See if this is a string literal or @encode.
77
0
  Init = Init->IgnoreParens();
78
79
  // Handle @encode, which is a narrow string.
80
0
  if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
81
0
    return SIF_None;
82
83
  // Otherwise we can only handle string literals.
84
0
  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
85
0
  if (!SL)
86
0
    return SIF_Other;
87
88
0
  const QualType ElemTy =
89
0
      Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
90
91
0
  auto IsCharOrUnsignedChar = [](const QualType &T) {
92
0
    const BuiltinType *BT = dyn_cast<BuiltinType>(T.getTypePtr());
93
0
    return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar;
94
0
  };
95
96
0
  switch (SL->getKind()) {
97
0
  case StringLiteralKind::UTF8:
98
    // char8_t array can be initialized with a UTF-8 string.
99
    // - C++20 [dcl.init.string] (DR)
100
    //   Additionally, an array of char or unsigned char may be initialized
101
    //   by a UTF-8 string literal.
102
0
    if (ElemTy->isChar8Type() ||
103
0
        (Context.getLangOpts().Char8 &&
104
0
         IsCharOrUnsignedChar(ElemTy.getCanonicalType())))
105
0
      return SIF_None;
106
0
    [[fallthrough]];
107
0
  case StringLiteralKind::Ordinary:
108
    // char array can be initialized with a narrow string.
109
    // Only allow char x[] = "foo";  not char x[] = L"foo";
110
0
    if (ElemTy->isCharType())
111
0
      return (SL->getKind() == StringLiteralKind::UTF8 &&
112
0
              Context.getLangOpts().Char8)
113
0
                 ? SIF_UTF8StringIntoPlainChar
114
0
                 : SIF_None;
115
0
    if (ElemTy->isChar8Type())
116
0
      return SIF_PlainStringIntoUTF8Char;
117
0
    if (IsWideCharCompatible(ElemTy, Context))
118
0
      return SIF_NarrowStringIntoWideChar;
119
0
    return SIF_Other;
120
  // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
121
  // "An array with element type compatible with a qualified or unqualified
122
  // version of wchar_t, char16_t, or char32_t may be initialized by a wide
123
  // string literal with the corresponding encoding prefix (L, u, or U,
124
  // respectively), optionally enclosed in braces.
125
0
  case StringLiteralKind::UTF16:
126
0
    if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
127
0
      return SIF_None;
128
0
    if (ElemTy->isCharType() || ElemTy->isChar8Type())
129
0
      return SIF_WideStringIntoChar;
130
0
    if (IsWideCharCompatible(ElemTy, Context))
131
0
      return SIF_IncompatWideStringIntoWideChar;
132
0
    return SIF_Other;
133
0
  case StringLiteralKind::UTF32:
134
0
    if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
135
0
      return SIF_None;
136
0
    if (ElemTy->isCharType() || ElemTy->isChar8Type())
137
0
      return SIF_WideStringIntoChar;
138
0
    if (IsWideCharCompatible(ElemTy, Context))
139
0
      return SIF_IncompatWideStringIntoWideChar;
140
0
    return SIF_Other;
141
0
  case StringLiteralKind::Wide:
142
0
    if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
143
0
      return SIF_None;
144
0
    if (ElemTy->isCharType() || ElemTy->isChar8Type())
145
0
      return SIF_WideStringIntoChar;
146
0
    if (IsWideCharCompatible(ElemTy, Context))
147
0
      return SIF_IncompatWideStringIntoWideChar;
148
0
    return SIF_Other;
149
0
  case StringLiteralKind::Unevaluated:
150
0
    assert(false && "Unevaluated string literal in initialization");
151
0
    break;
152
0
  }
153
154
0
  llvm_unreachable("missed a StringLiteral kind?");
155
0
}
156
157
static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
158
0
                                          ASTContext &Context) {
159
0
  const ArrayType *arrayType = Context.getAsArrayType(declType);
160
0
  if (!arrayType)
161
0
    return SIF_Other;
162
0
  return IsStringInit(init, arrayType, Context);
163
0
}
164
165
0
bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
166
0
  return ::IsStringInit(Init, AT, Context) == SIF_None;
167
0
}
168
169
/// Update the type of a string literal, including any surrounding parentheses,
170
/// to match the type of the object which it is initializing.
171
0
static void updateStringLiteralType(Expr *E, QualType Ty) {
172
0
  while (true) {
173
0
    E->setType(Ty);
174
0
    E->setValueKind(VK_PRValue);
175
0
    if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
176
0
      break;
177
0
    E = IgnoreParensSingleStep(E);
178
0
  }
179
0
}
180
181
/// Fix a compound literal initializing an array so it's correctly marked
182
/// as an rvalue.
183
0
static void updateGNUCompoundLiteralRValue(Expr *E) {
184
0
  while (true) {
185
0
    E->setValueKind(VK_PRValue);
186
0
    if (isa<CompoundLiteralExpr>(E))
187
0
      break;
188
0
    E = IgnoreParensSingleStep(E);
189
0
  }
190
0
}
191
192
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
193
0
                            Sema &S) {
194
  // Get the length of the string as parsed.
195
0
  auto *ConstantArrayTy =
196
0
      cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
197
0
  uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
198
199
0
  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
200
    // C99 6.7.8p14. We have an array of character type with unknown size
201
    // being initialized to a string literal.
202
0
    llvm::APInt ConstVal(32, StrLength);
203
    // Return a new array type (C99 6.7.8p22).
204
0
    DeclT = S.Context.getConstantArrayType(
205
0
        IAT->getElementType(), ConstVal, nullptr, ArraySizeModifier::Normal, 0);
206
0
    updateStringLiteralType(Str, DeclT);
207
0
    return;
208
0
  }
209
210
0
  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
211
212
  // We have an array of character type with known size.  However,
213
  // the size may be smaller or larger than the string we are initializing.
214
  // FIXME: Avoid truncation for 64-bit length strings.
215
0
  if (S.getLangOpts().CPlusPlus) {
216
0
    if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
217
      // For Pascal strings it's OK to strip off the terminating null character,
218
      // so the example below is valid:
219
      //
220
      // unsigned char a[2] = "\pa";
221
0
      if (SL->isPascal())
222
0
        StrLength--;
223
0
    }
224
225
    // [dcl.init.string]p2
226
0
    if (StrLength > CAT->getSize().getZExtValue())
227
0
      S.Diag(Str->getBeginLoc(),
228
0
             diag::err_initializer_string_for_char_array_too_long)
229
0
          << CAT->getSize().getZExtValue() << StrLength
230
0
          << Str->getSourceRange();
231
0
  } else {
232
    // C99 6.7.8p14.
233
0
    if (StrLength-1 > CAT->getSize().getZExtValue())
234
0
      S.Diag(Str->getBeginLoc(),
235
0
             diag::ext_initializer_string_for_char_array_too_long)
236
0
          << Str->getSourceRange();
237
0
  }
238
239
  // Set the type to the actual size that we are initializing.  If we have
240
  // something like:
241
  //   char x[1] = "foo";
242
  // then this will set the string literal's type to char[1].
243
0
  updateStringLiteralType(Str, DeclT);
244
0
}
245
246
//===----------------------------------------------------------------------===//
247
// Semantic checking for initializer lists.
248
//===----------------------------------------------------------------------===//
249
250
namespace {
251
252
/// Semantic checking for initializer lists.
253
///
254
/// The InitListChecker class contains a set of routines that each
255
/// handle the initialization of a certain kind of entity, e.g.,
256
/// arrays, vectors, struct/union types, scalars, etc. The
257
/// InitListChecker itself performs a recursive walk of the subobject
258
/// structure of the type to be initialized, while stepping through
259
/// the initializer list one element at a time. The IList and Index
260
/// parameters to each of the Check* routines contain the active
261
/// (syntactic) initializer list and the index into that initializer
262
/// list that represents the current initializer. Each routine is
263
/// responsible for moving that Index forward as it consumes elements.
264
///
265
/// Each Check* routine also has a StructuredList/StructuredIndex
266
/// arguments, which contains the current "structured" (semantic)
267
/// initializer list and the index into that initializer list where we
268
/// are copying initializers as we map them over to the semantic
269
/// list. Once we have completed our recursive walk of the subobject
270
/// structure, we will have constructed a full semantic initializer
271
/// list.
272
///
273
/// C99 designators cause changes in the initializer list traversal,
274
/// because they make the initialization "jump" into a specific
275
/// subobject and then continue the initialization from that
276
/// point. CheckDesignatedInitializer() recursively steps into the
277
/// designated subobject and manages backing out the recursion to
278
/// initialize the subobjects after the one designated.
279
///
280
/// If an initializer list contains any designators, we build a placeholder
281
/// structured list even in 'verify only' mode, so that we can track which
282
/// elements need 'empty' initializtion.
283
class InitListChecker {
284
  Sema &SemaRef;
285
  bool hadError = false;
286
  bool VerifyOnly; // No diagnostics.
287
  bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
288
  bool InOverloadResolution;
289
  InitListExpr *FullyStructuredList = nullptr;
290
  NoInitExpr *DummyExpr = nullptr;
291
  SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr;
292
293
0
  NoInitExpr *getDummyInit() {
294
0
    if (!DummyExpr)
295
0
      DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
296
0
    return DummyExpr;
297
0
  }
298
299
  void CheckImplicitInitList(const InitializedEntity &Entity,
300
                             InitListExpr *ParentIList, QualType T,
301
                             unsigned &Index, InitListExpr *StructuredList,
302
                             unsigned &StructuredIndex);
303
  void CheckExplicitInitList(const InitializedEntity &Entity,
304
                             InitListExpr *IList, QualType &T,
305
                             InitListExpr *StructuredList,
306
                             bool TopLevelObject = false);
307
  void CheckListElementTypes(const InitializedEntity &Entity,
308
                             InitListExpr *IList, QualType &DeclType,
309
                             bool SubobjectIsDesignatorContext,
310
                             unsigned &Index,
311
                             InitListExpr *StructuredList,
312
                             unsigned &StructuredIndex,
313
                             bool TopLevelObject = false);
314
  void CheckSubElementType(const InitializedEntity &Entity,
315
                           InitListExpr *IList, QualType ElemType,
316
                           unsigned &Index,
317
                           InitListExpr *StructuredList,
318
                           unsigned &StructuredIndex,
319
                           bool DirectlyDesignated = false);
320
  void CheckComplexType(const InitializedEntity &Entity,
321
                        InitListExpr *IList, QualType DeclType,
322
                        unsigned &Index,
323
                        InitListExpr *StructuredList,
324
                        unsigned &StructuredIndex);
325
  void CheckScalarType(const InitializedEntity &Entity,
326
                       InitListExpr *IList, QualType DeclType,
327
                       unsigned &Index,
328
                       InitListExpr *StructuredList,
329
                       unsigned &StructuredIndex);
330
  void CheckReferenceType(const InitializedEntity &Entity,
331
                          InitListExpr *IList, QualType DeclType,
332
                          unsigned &Index,
333
                          InitListExpr *StructuredList,
334
                          unsigned &StructuredIndex);
335
  void CheckVectorType(const InitializedEntity &Entity,
336
                       InitListExpr *IList, QualType DeclType, unsigned &Index,
337
                       InitListExpr *StructuredList,
338
                       unsigned &StructuredIndex);
339
  void CheckStructUnionTypes(const InitializedEntity &Entity,
340
                             InitListExpr *IList, QualType DeclType,
341
                             CXXRecordDecl::base_class_const_range Bases,
342
                             RecordDecl::field_iterator Field,
343
                             bool SubobjectIsDesignatorContext, unsigned &Index,
344
                             InitListExpr *StructuredList,
345
                             unsigned &StructuredIndex,
346
                             bool TopLevelObject = false);
347
  void CheckArrayType(const InitializedEntity &Entity,
348
                      InitListExpr *IList, QualType &DeclType,
349
                      llvm::APSInt elementIndex,
350
                      bool SubobjectIsDesignatorContext, unsigned &Index,
351
                      InitListExpr *StructuredList,
352
                      unsigned &StructuredIndex);
353
  bool CheckDesignatedInitializer(const InitializedEntity &Entity,
354
                                  InitListExpr *IList, DesignatedInitExpr *DIE,
355
                                  unsigned DesigIdx,
356
                                  QualType &CurrentObjectType,
357
                                  RecordDecl::field_iterator *NextField,
358
                                  llvm::APSInt *NextElementIndex,
359
                                  unsigned &Index,
360
                                  InitListExpr *StructuredList,
361
                                  unsigned &StructuredIndex,
362
                                  bool FinishSubobjectInit,
363
                                  bool TopLevelObject);
364
  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
365
                                           QualType CurrentObjectType,
366
                                           InitListExpr *StructuredList,
367
                                           unsigned StructuredIndex,
368
                                           SourceRange InitRange,
369
                                           bool IsFullyOverwritten = false);
370
  void UpdateStructuredListElement(InitListExpr *StructuredList,
371
                                   unsigned &StructuredIndex,
372
                                   Expr *expr);
373
  InitListExpr *createInitListExpr(QualType CurrentObjectType,
374
                                   SourceRange InitRange,
375
                                   unsigned ExpectedNumInits);
376
  int numArrayElements(QualType DeclType);
377
  int numStructUnionElements(QualType DeclType);
378
  static RecordDecl *getRecordDecl(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
                            bool UnionOverride = false,
386
0
                            bool FullyOverwritten = true) {
387
    // Overriding an initializer via a designator is valid with C99 designated
388
    // initializers, but ill-formed with C++20 designated initializers.
389
0
    unsigned DiagID =
390
0
        SemaRef.getLangOpts().CPlusPlus
391
0
            ? (UnionOverride ? diag::ext_initializer_union_overrides
392
0
                             : diag::ext_initializer_overrides)
393
0
            : diag::warn_initializer_overrides;
394
395
0
    if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) {
396
      // In overload resolution, we have to strictly enforce the rules, and so
397
      // don't allow any overriding of prior initializers. This matters for a
398
      // case such as:
399
      //
400
      //   union U { int a, b; };
401
      //   struct S { int a, b; };
402
      //   void f(U), f(S);
403
      //
404
      // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
405
      // consistency, we disallow all overriding of prior initializers in
406
      // overload resolution, not only overriding of union members.
407
0
      hadError = true;
408
0
    } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) {
409
      // If we'll be keeping around the old initializer but overwriting part of
410
      // the object it initialized, and that object is not trivially
411
      // destructible, this can leak. Don't allow that, not even as an
412
      // extension.
413
      //
414
      // FIXME: It might be reasonable to allow this in cases where the part of
415
      // the initializer that we're overriding has trivial destruction.
416
0
      DiagID = diag::err_initializer_overrides_destructed;
417
0
    } else if (!OldInit->getSourceRange().isValid()) {
418
      // We need to check on source range validity because the previous
419
      // initializer does not have to be an explicit initializer. e.g.,
420
      //
421
      // struct P { int a, b; };
422
      // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
423
      //
424
      // There is an overwrite taking place because the first braced initializer
425
      // list "{ .a = 2 }" already provides value for .p.b (which is zero).
426
      //
427
      // Such overwrites are harmless, so we don't diagnose them. (Note that in
428
      // C++, this cannot be reached unless we've already seen and diagnosed a
429
      // different conformance issue, such as a mixture of designated and
430
      // non-designated initializers or a multi-level designator.)
431
0
      return;
432
0
    }
433
434
0
    if (!VerifyOnly) {
435
0
      SemaRef.Diag(NewInitRange.getBegin(), DiagID)
436
0
          << NewInitRange << FullyOverwritten << OldInit->getType();
437
0
      SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
438
0
          << (OldInit->HasSideEffects(SemaRef.Context) && FullyOverwritten)
439
0
          << OldInit->getSourceRange();
440
0
    }
441
0
  }
442
443
  // Explanation on the "FillWithNoInit" mode:
444
  //
445
  // Assume we have the following definitions (Case#1):
446
  // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
447
  // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
448
  //
449
  // l.lp.x[1][0..1] should not be filled with implicit initializers because the
450
  // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
451
  //
452
  // But if we have (Case#2):
453
  // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
454
  //
455
  // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
456
  // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
457
  //
458
  // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
459
  // in the InitListExpr, the "holes" in Case#1 are filled not with empty
460
  // initializers but with special "NoInitExpr" place holders, which tells the
461
  // CodeGen not to generate any initializers for these parts.
462
  void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
463
                              const InitializedEntity &ParentEntity,
464
                              InitListExpr *ILE, bool &RequiresSecondPass,
465
                              bool FillWithNoInit);
466
  void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
467
                               const InitializedEntity &ParentEntity,
468
                               InitListExpr *ILE, bool &RequiresSecondPass,
469
                               bool FillWithNoInit = false);
470
  void FillInEmptyInitializations(const InitializedEntity &Entity,
471
                                  InitListExpr *ILE, bool &RequiresSecondPass,
472
                                  InitListExpr *OuterILE, unsigned OuterIndex,
473
                                  bool FillWithNoInit = false);
474
  bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
475
                              Expr *InitExpr, FieldDecl *Field,
476
                              bool TopLevelObject);
477
  void CheckEmptyInitializable(const InitializedEntity &Entity,
478
                               SourceLocation Loc);
479
480
public:
481
  InitListChecker(
482
      Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
483
      bool VerifyOnly, bool TreatUnavailableAsInvalid,
484
      bool InOverloadResolution = false,
485
      SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr);
486
  InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
487
                  QualType &T,
488
                  SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes)
489
      : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true,
490
                        /*TreatUnavailableAsInvalid=*/false,
491
                        /*InOverloadResolution=*/false,
492
0
                        &AggrDeductionCandidateParamTypes){};
493
494
0
  bool HadError() { return hadError; }
495
496
  // Retrieves the fully-structured initializer list used for
497
  // semantic analysis and code generation.
498
0
  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
499
};
500
501
} // end anonymous namespace
502
503
ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
504
0
                                             const InitializedEntity &Entity) {
505
0
  InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
506
0
                                                            true);
507
0
  MultiExprArg SubInit;
508
0
  Expr *InitExpr;
509
0
  InitListExpr DummyInitList(SemaRef.Context, Loc, std::nullopt, Loc);
510
511
  // C++ [dcl.init.aggr]p7:
512
  //   If there are fewer initializer-clauses in the list than there are
513
  //   members in the aggregate, then each member not explicitly initialized
514
  //   ...
515
0
  bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
516
0
      Entity.getType()->getBaseElementTypeUnsafe()->isRecordType();
517
0
  if (EmptyInitList) {
518
    // C++1y / DR1070:
519
    //   shall be initialized [...] from an empty initializer list.
520
    //
521
    // We apply the resolution of this DR to C++11 but not C++98, since C++98
522
    // does not have useful semantics for initialization from an init list.
523
    // We treat this as copy-initialization, because aggregate initialization
524
    // always performs copy-initialization on its elements.
525
    //
526
    // Only do this if we're initializing a class type, to avoid filling in
527
    // the initializer list where possible.
528
0
    InitExpr = VerifyOnly
529
0
                   ? &DummyInitList
530
0
                   : new (SemaRef.Context)
531
0
                         InitListExpr(SemaRef.Context, Loc, std::nullopt, Loc);
532
0
    InitExpr->setType(SemaRef.Context.VoidTy);
533
0
    SubInit = InitExpr;
534
0
    Kind = InitializationKind::CreateCopy(Loc, Loc);
535
0
  } else {
536
    // C++03:
537
    //   shall be value-initialized.
538
0
  }
539
540
0
  InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
541
  // libstdc++4.6 marks the vector default constructor as explicit in
542
  // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
543
  // stlport does so too. Look for std::__debug for libstdc++, and for
544
  // std:: for stlport.  This is effectively a compiler-side implementation of
545
  // LWG2193.
546
0
  if (!InitSeq && EmptyInitList && InitSeq.getFailureKind() ==
547
0
          InitializationSequence::FK_ExplicitConstructor) {
548
0
    OverloadCandidateSet::iterator Best;
549
0
    OverloadingResult O =
550
0
        InitSeq.getFailedCandidateSet()
551
0
            .BestViableFunction(SemaRef, Kind.getLocation(), Best);
552
0
    (void)O;
553
0
    assert(O == OR_Success && "Inconsistent overload resolution");
554
0
    CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
555
0
    CXXRecordDecl *R = CtorDecl->getParent();
556
557
0
    if (CtorDecl->getMinRequiredArguments() == 0 &&
558
0
        CtorDecl->isExplicit() && R->getDeclName() &&
559
0
        SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
560
0
      bool IsInStd = false;
561
0
      for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
562
0
           ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(ND->getParent())) {
563
0
        if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
564
0
          IsInStd = true;
565
0
      }
566
567
0
      if (IsInStd && llvm::StringSwitch<bool>(R->getName())
568
0
              .Cases("basic_string", "deque", "forward_list", true)
569
0
              .Cases("list", "map", "multimap", "multiset", true)
570
0
              .Cases("priority_queue", "queue", "set", "stack", true)
571
0
              .Cases("unordered_map", "unordered_set", "vector", true)
572
0
              .Default(false)) {
573
0
        InitSeq.InitializeFrom(
574
0
            SemaRef, Entity,
575
0
            InitializationKind::CreateValue(Loc, Loc, Loc, true),
576
0
            MultiExprArg(), /*TopLevelOfInitList=*/false,
577
0
            TreatUnavailableAsInvalid);
578
        // Emit a warning for this.  System header warnings aren't shown
579
        // by default, but people working on system headers should see it.
580
0
        if (!VerifyOnly) {
581
0
          SemaRef.Diag(CtorDecl->getLocation(),
582
0
                       diag::warn_invalid_initializer_from_system_header);
583
0
          if (Entity.getKind() == InitializedEntity::EK_Member)
584
0
            SemaRef.Diag(Entity.getDecl()->getLocation(),
585
0
                         diag::note_used_in_initialization_here);
586
0
          else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
587
0
            SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
588
0
        }
589
0
      }
590
0
    }
591
0
  }
592
0
  if (!InitSeq) {
593
0
    if (!VerifyOnly) {
594
0
      InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
595
0
      if (Entity.getKind() == InitializedEntity::EK_Member)
596
0
        SemaRef.Diag(Entity.getDecl()->getLocation(),
597
0
                     diag::note_in_omitted_aggregate_initializer)
598
0
          << /*field*/1 << Entity.getDecl();
599
0
      else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
600
0
        bool IsTrailingArrayNewMember =
601
0
            Entity.getParent() &&
602
0
            Entity.getParent()->isVariableLengthArrayNew();
603
0
        SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
604
0
          << (IsTrailingArrayNewMember ? 2 : /*array element*/0)
605
0
          << Entity.getElementIndex();
606
0
      }
607
0
    }
608
0
    hadError = true;
609
0
    return ExprError();
610
0
  }
611
612
0
  return VerifyOnly ? ExprResult()
613
0
                    : InitSeq.Perform(SemaRef, Entity, Kind, SubInit);
614
0
}
615
616
void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
617
0
                                              SourceLocation Loc) {
618
  // If we're building a fully-structured list, we'll check this at the end
619
  // once we know which elements are actually initialized. Otherwise, we know
620
  // that there are no designators so we can just check now.
621
0
  if (FullyStructuredList)
622
0
    return;
623
0
  PerformEmptyInit(Loc, Entity);
624
0
}
625
626
void InitListChecker::FillInEmptyInitForBase(
627
    unsigned Init, const CXXBaseSpecifier &Base,
628
    const InitializedEntity &ParentEntity, InitListExpr *ILE,
629
0
    bool &RequiresSecondPass, bool FillWithNoInit) {
630
0
  InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
631
0
      SemaRef.Context, &Base, false, &ParentEntity);
632
633
0
  if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
634
0
    ExprResult BaseInit = FillWithNoInit
635
0
                              ? new (SemaRef.Context) NoInitExpr(Base.getType())
636
0
                              : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
637
0
    if (BaseInit.isInvalid()) {
638
0
      hadError = true;
639
0
      return;
640
0
    }
641
642
0
    if (!VerifyOnly) {
643
0
      assert(Init < ILE->getNumInits() && "should have been expanded");
644
0
      ILE->setInit(Init, BaseInit.getAs<Expr>());
645
0
    }
646
0
  } else if (InitListExpr *InnerILE =
647
0
                 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
648
0
    FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
649
0
                               ILE, Init, FillWithNoInit);
650
0
  } else if (DesignatedInitUpdateExpr *InnerDIUE =
651
0
               dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
652
0
    FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
653
0
                               RequiresSecondPass, ILE, Init,
654
0
                               /*FillWithNoInit =*/true);
655
0
  }
656
0
}
657
658
void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
659
                                        const InitializedEntity &ParentEntity,
660
                                              InitListExpr *ILE,
661
                                              bool &RequiresSecondPass,
662
0
                                              bool FillWithNoInit) {
663
0
  SourceLocation Loc = ILE->getEndLoc();
664
0
  unsigned NumInits = ILE->getNumInits();
665
0
  InitializedEntity MemberEntity
666
0
    = InitializedEntity::InitializeMember(Field, &ParentEntity);
667
668
0
  if (Init >= NumInits || !ILE->getInit(Init)) {
669
0
    if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
670
0
      if (!RType->getDecl()->isUnion())
671
0
        assert((Init < NumInits || VerifyOnly) &&
672
0
               "This ILE should have been expanded");
673
674
0
    if (FillWithNoInit) {
675
0
      assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
676
0
      Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
677
0
      if (Init < NumInits)
678
0
        ILE->setInit(Init, Filler);
679
0
      else
680
0
        ILE->updateInit(SemaRef.Context, Init, Filler);
681
0
      return;
682
0
    }
683
    // C++1y [dcl.init.aggr]p7:
684
    //   If there are fewer initializer-clauses in the list than there are
685
    //   members in the aggregate, then each member not explicitly initialized
686
    //   shall be initialized from its brace-or-equal-initializer [...]
687
0
    if (Field->hasInClassInitializer()) {
688
0
      if (VerifyOnly)
689
0
        return;
690
691
0
      ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
692
0
      if (DIE.isInvalid()) {
693
0
        hadError = true;
694
0
        return;
695
0
      }
696
0
      SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
697
0
      if (Init < NumInits)
698
0
        ILE->setInit(Init, DIE.get());
699
0
      else {
700
0
        ILE->updateInit(SemaRef.Context, Init, DIE.get());
701
0
        RequiresSecondPass = true;
702
0
      }
703
0
      return;
704
0
    }
705
706
0
    if (Field->getType()->isReferenceType()) {
707
0
      if (!VerifyOnly) {
708
        // C++ [dcl.init.aggr]p9:
709
        //   If an incomplete or empty initializer-list leaves a
710
        //   member of reference type uninitialized, the program is
711
        //   ill-formed.
712
0
        SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
713
0
            << Field->getType()
714
0
            << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm())
715
0
                   ->getSourceRange();
716
0
        SemaRef.Diag(Field->getLocation(), diag::note_uninit_reference_member);
717
0
      }
718
0
      hadError = true;
719
0
      return;
720
0
    }
721
722
0
    ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
723
0
    if (MemberInit.isInvalid()) {
724
0
      hadError = true;
725
0
      return;
726
0
    }
727
728
0
    if (hadError || VerifyOnly) {
729
      // Do nothing
730
0
    } else if (Init < NumInits) {
731
0
      ILE->setInit(Init, MemberInit.getAs<Expr>());
732
0
    } else if (!isa<ImplicitValueInitExpr>(MemberInit.get())) {
733
      // Empty initialization requires a constructor call, so
734
      // extend the initializer list to include the constructor
735
      // call and make a note that we'll need to take another pass
736
      // through the initializer list.
737
0
      ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
738
0
      RequiresSecondPass = true;
739
0
    }
740
0
  } else if (InitListExpr *InnerILE
741
0
               = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
742
0
    FillInEmptyInitializations(MemberEntity, InnerILE,
743
0
                               RequiresSecondPass, ILE, Init, FillWithNoInit);
744
0
  } else if (DesignatedInitUpdateExpr *InnerDIUE =
745
0
                 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
746
0
    FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
747
0
                               RequiresSecondPass, ILE, Init,
748
0
                               /*FillWithNoInit =*/true);
749
0
  }
750
0
}
751
752
/// Recursively replaces NULL values within the given initializer list
753
/// with expressions that perform value-initialization of the
754
/// appropriate type, and finish off the InitListExpr formation.
755
void
756
InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
757
                                            InitListExpr *ILE,
758
                                            bool &RequiresSecondPass,
759
                                            InitListExpr *OuterILE,
760
                                            unsigned OuterIndex,
761
0
                                            bool FillWithNoInit) {
762
0
  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
763
0
         "Should not have void type");
764
765
  // We don't need to do any checks when just filling NoInitExprs; that can't
766
  // fail.
767
0
  if (FillWithNoInit && VerifyOnly)
768
0
    return;
769
770
  // If this is a nested initializer list, we might have changed its contents
771
  // (and therefore some of its properties, such as instantiation-dependence)
772
  // while filling it in. Inform the outer initializer list so that its state
773
  // can be updated to match.
774
  // FIXME: We should fully build the inner initializers before constructing
775
  // the outer InitListExpr instead of mutating AST nodes after they have
776
  // been used as subexpressions of other nodes.
777
0
  struct UpdateOuterILEWithUpdatedInit {
778
0
    InitListExpr *Outer;
779
0
    unsigned OuterIndex;
780
0
    ~UpdateOuterILEWithUpdatedInit() {
781
0
      if (Outer)
782
0
        Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
783
0
    }
784
0
  } UpdateOuterRAII = {OuterILE, OuterIndex};
785
786
  // A transparent ILE is not performing aggregate initialization and should
787
  // not be filled in.
788
0
  if (ILE->isTransparent())
789
0
    return;
790
791
0
  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
792
0
    const RecordDecl *RDecl = RType->getDecl();
793
0
    if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
794
0
      FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
795
0
                              Entity, ILE, RequiresSecondPass, FillWithNoInit);
796
0
    else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
797
0
             cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
798
0
      for (auto *Field : RDecl->fields()) {
799
0
        if (Field->hasInClassInitializer()) {
800
0
          FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
801
0
                                  FillWithNoInit);
802
0
          break;
803
0
        }
804
0
      }
805
0
    } else {
806
      // The fields beyond ILE->getNumInits() are default initialized, so in
807
      // order to leave them uninitialized, the ILE is expanded and the extra
808
      // fields are then filled with NoInitExpr.
809
0
      unsigned NumElems = numStructUnionElements(ILE->getType());
810
0
      if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember())
811
0
        ++NumElems;
812
0
      if (!VerifyOnly && ILE->getNumInits() < NumElems)
813
0
        ILE->resizeInits(SemaRef.Context, NumElems);
814
815
0
      unsigned Init = 0;
816
817
0
      if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
818
0
        for (auto &Base : CXXRD->bases()) {
819
0
          if (hadError)
820
0
            return;
821
822
0
          FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
823
0
                                 FillWithNoInit);
824
0
          ++Init;
825
0
        }
826
0
      }
827
828
0
      for (auto *Field : RDecl->fields()) {
829
0
        if (Field->isUnnamedBitfield())
830
0
          continue;
831
832
0
        if (hadError)
833
0
          return;
834
835
0
        FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
836
0
                                FillWithNoInit);
837
0
        if (hadError)
838
0
          return;
839
840
0
        ++Init;
841
842
        // Only look at the first initialization of a union.
843
0
        if (RDecl->isUnion())
844
0
          break;
845
0
      }
846
0
    }
847
848
0
    return;
849
0
  }
850
851
0
  QualType ElementType;
852
853
0
  InitializedEntity ElementEntity = Entity;
854
0
  unsigned NumInits = ILE->getNumInits();
855
0
  unsigned NumElements = NumInits;
856
0
  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
857
0
    ElementType = AType->getElementType();
858
0
    if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
859
0
      NumElements = CAType->getSize().getZExtValue();
860
    // For an array new with an unknown bound, ask for one additional element
861
    // in order to populate the array filler.
862
0
    if (Entity.isVariableLengthArrayNew())
863
0
      ++NumElements;
864
0
    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
865
0
                                                         0, Entity);
866
0
  } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
867
0
    ElementType = VType->getElementType();
868
0
    NumElements = VType->getNumElements();
869
0
    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
870
0
                                                         0, Entity);
871
0
  } else
872
0
    ElementType = ILE->getType();
873
874
0
  bool SkipEmptyInitChecks = false;
875
0
  for (unsigned Init = 0; Init != NumElements; ++Init) {
876
0
    if (hadError)
877
0
      return;
878
879
0
    if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
880
0
        ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
881
0
      ElementEntity.setElementIndex(Init);
882
883
0
    if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks))
884
0
      return;
885
886
0
    Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr);
887
0
    if (!InitExpr && Init < NumInits && ILE->hasArrayFiller())
888
0
      ILE->setInit(Init, ILE->getArrayFiller());
889
0
    else if (!InitExpr && !ILE->hasArrayFiller()) {
890
      // In VerifyOnly mode, there's no point performing empty initialization
891
      // more than once.
892
0
      if (SkipEmptyInitChecks)
893
0
        continue;
894
895
0
      Expr *Filler = nullptr;
896
897
0
      if (FillWithNoInit)
898
0
        Filler = new (SemaRef.Context) NoInitExpr(ElementType);
899
0
      else {
900
0
        ExprResult ElementInit =
901
0
            PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
902
0
        if (ElementInit.isInvalid()) {
903
0
          hadError = true;
904
0
          return;
905
0
        }
906
907
0
        Filler = ElementInit.getAs<Expr>();
908
0
      }
909
910
0
      if (hadError) {
911
        // Do nothing
912
0
      } else if (VerifyOnly) {
913
0
        SkipEmptyInitChecks = true;
914
0
      } else if (Init < NumInits) {
915
        // For arrays, just set the expression used for value-initialization
916
        // of the "holes" in the array.
917
0
        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
918
0
          ILE->setArrayFiller(Filler);
919
0
        else
920
0
          ILE->setInit(Init, Filler);
921
0
      } else {
922
        // For arrays, just set the expression used for value-initialization
923
        // of the rest of elements and exit.
924
0
        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
925
0
          ILE->setArrayFiller(Filler);
926
0
          return;
927
0
        }
928
929
0
        if (!isa<ImplicitValueInitExpr>(Filler) && !isa<NoInitExpr>(Filler)) {
930
          // Empty initialization requires a constructor call, so
931
          // extend the initializer list to include the constructor
932
          // call and make a note that we'll need to take another pass
933
          // through the initializer list.
934
0
          ILE->updateInit(SemaRef.Context, Init, Filler);
935
0
          RequiresSecondPass = true;
936
0
        }
937
0
      }
938
0
    } else if (InitListExpr *InnerILE
939
0
                 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
940
0
      FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
941
0
                                 ILE, Init, FillWithNoInit);
942
0
    } else if (DesignatedInitUpdateExpr *InnerDIUE =
943
0
                   dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
944
0
      FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
945
0
                                 RequiresSecondPass, ILE, Init,
946
0
                                 /*FillWithNoInit =*/true);
947
0
    }
948
0
  }
949
0
}
950
951
0
static bool hasAnyDesignatedInits(const InitListExpr *IL) {
952
0
  for (const Stmt *Init : *IL)
953
0
    if (isa_and_nonnull<DesignatedInitExpr>(Init))
954
0
      return true;
955
0
  return false;
956
0
}
957
958
InitListChecker::InitListChecker(
959
    Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T,
960
    bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution,
961
    SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes)
962
    : SemaRef(S), VerifyOnly(VerifyOnly),
963
      TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
964
      InOverloadResolution(InOverloadResolution),
965
0
      AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) {
966
0
  if (!VerifyOnly || hasAnyDesignatedInits(IL)) {
967
0
    FullyStructuredList =
968
0
        createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
969
970
    // FIXME: Check that IL isn't already the semantic form of some other
971
    // InitListExpr. If it is, we'd create a broken AST.
972
0
    if (!VerifyOnly)
973
0
      FullyStructuredList->setSyntacticForm(IL);
974
0
  }
975
976
0
  CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
977
0
                        /*TopLevelObject=*/true);
978
979
0
  if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) {
980
0
    bool RequiresSecondPass = false;
981
0
    FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
982
0
                               /*OuterILE=*/nullptr, /*OuterIndex=*/0);
983
0
    if (RequiresSecondPass && !hadError)
984
0
      FillInEmptyInitializations(Entity, FullyStructuredList,
985
0
                                 RequiresSecondPass, nullptr, 0);
986
0
  }
987
0
  if (hadError && FullyStructuredList)
988
0
    FullyStructuredList->markError();
989
0
}
990
991
0
int InitListChecker::numArrayElements(QualType DeclType) {
992
  // FIXME: use a proper constant
993
0
  int maxElements = 0x7FFFFFFF;
994
0
  if (const ConstantArrayType *CAT =
995
0
        SemaRef.Context.getAsConstantArrayType(DeclType)) {
996
0
    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
997
0
  }
998
0
  return maxElements;
999
0
}
1000
1001
0
int InitListChecker::numStructUnionElements(QualType DeclType) {
1002
0
  RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
1003
0
  int InitializableMembers = 0;
1004
0
  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
1005
0
    InitializableMembers += CXXRD->getNumBases();
1006
0
  for (const auto *Field : structDecl->fields())
1007
0
    if (!Field->isUnnamedBitfield())
1008
0
      ++InitializableMembers;
1009
1010
0
  if (structDecl->isUnion())
1011
0
    return std::min(InitializableMembers, 1);
1012
0
  return InitializableMembers - structDecl->hasFlexibleArrayMember();
1013
0
}
1014
1015
0
RecordDecl *InitListChecker::getRecordDecl(QualType DeclType) {
1016
0
  if (const auto *RT = DeclType->getAs<RecordType>())
1017
0
    return RT->getDecl();
1018
0
  if (const auto *Inject = DeclType->getAs<InjectedClassNameType>())
1019
0
    return Inject->getDecl();
1020
0
  return nullptr;
1021
0
}
1022
1023
/// Determine whether Entity is an entity for which it is idiomatic to elide
1024
/// the braces in aggregate initialization.
1025
0
static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
1026
  // Recursive initialization of the one and only field within an aggregate
1027
  // class is considered idiomatic. This case arises in particular for
1028
  // initialization of std::array, where the C++ standard suggests the idiom of
1029
  //
1030
  //   std::array<T, N> arr = {1, 2, 3};
1031
  //
1032
  // (where std::array is an aggregate struct containing a single array field.
1033
1034
0
  if (!Entity.getParent())
1035
0
    return false;
1036
1037
  // Allows elide brace initialization for aggregates with empty base.
1038
0
  if (Entity.getKind() == InitializedEntity::EK_Base) {
1039
0
    auto *ParentRD =
1040
0
        Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1041
0
    CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1042
0
    return CXXRD->getNumBases() == 1 && CXXRD->field_empty();
1043
0
  }
1044
1045
  // Allow brace elision if the only subobject is a field.
1046
0
  if (Entity.getKind() == InitializedEntity::EK_Member) {
1047
0
    auto *ParentRD =
1048
0
        Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1049
0
    if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1050
0
      if (CXXRD->getNumBases()) {
1051
0
        return false;
1052
0
      }
1053
0
    }
1054
0
    auto FieldIt = ParentRD->field_begin();
1055
0
    assert(FieldIt != ParentRD->field_end() &&
1056
0
           "no fields but have initializer for member?");
1057
0
    return ++FieldIt == ParentRD->field_end();
1058
0
  }
1059
1060
0
  return false;
1061
0
}
1062
1063
/// Check whether the range of the initializer \p ParentIList from element
1064
/// \p Index onwards can be used to initialize an object of type \p T. Update
1065
/// \p Index to indicate how many elements of the list were consumed.
1066
///
1067
/// This also fills in \p StructuredList, from element \p StructuredIndex
1068
/// onwards, with the fully-braced, desugared form of the initialization.
1069
void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1070
                                            InitListExpr *ParentIList,
1071
                                            QualType T, unsigned &Index,
1072
                                            InitListExpr *StructuredList,
1073
0
                                            unsigned &StructuredIndex) {
1074
0
  int maxElements = 0;
1075
1076
0
  if (T->isArrayType())
1077
0
    maxElements = numArrayElements(T);
1078
0
  else if (T->isRecordType())
1079
0
    maxElements = numStructUnionElements(T);
1080
0
  else if (T->isVectorType())
1081
0
    maxElements = T->castAs<VectorType>()->getNumElements();
1082
0
  else
1083
0
    llvm_unreachable("CheckImplicitInitList(): Illegal type");
1084
1085
0
  if (maxElements == 0) {
1086
0
    if (!VerifyOnly)
1087
0
      SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1088
0
                   diag::err_implicit_empty_initializer);
1089
0
    ++Index;
1090
0
    hadError = true;
1091
0
    return;
1092
0
  }
1093
1094
  // Build a structured initializer list corresponding to this subobject.
1095
0
  InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1096
0
      ParentIList, Index, T, StructuredList, StructuredIndex,
1097
0
      SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1098
0
                  ParentIList->getSourceRange().getEnd()));
1099
0
  unsigned StructuredSubobjectInitIndex = 0;
1100
1101
  // Check the element types and build the structural subobject.
1102
0
  unsigned StartIndex = Index;
1103
0
  CheckListElementTypes(Entity, ParentIList, T,
1104
0
                        /*SubobjectIsDesignatorContext=*/false, Index,
1105
0
                        StructuredSubobjectInitList,
1106
0
                        StructuredSubobjectInitIndex);
1107
1108
0
  if (StructuredSubobjectInitList) {
1109
0
    StructuredSubobjectInitList->setType(T);
1110
1111
0
    unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
1112
    // Update the structured sub-object initializer so that it's ending
1113
    // range corresponds with the end of the last initializer it used.
1114
0
    if (EndIndex < ParentIList->getNumInits() &&
1115
0
        ParentIList->getInit(EndIndex)) {
1116
0
      SourceLocation EndLoc
1117
0
        = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1118
0
      StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1119
0
    }
1120
1121
    // Complain about missing braces.
1122
0
    if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) &&
1123
0
        !ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) &&
1124
0
        !isIdiomaticBraceElisionEntity(Entity)) {
1125
0
      SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1126
0
                   diag::warn_missing_braces)
1127
0
          << StructuredSubobjectInitList->getSourceRange()
1128
0
          << FixItHint::CreateInsertion(
1129
0
                 StructuredSubobjectInitList->getBeginLoc(), "{")
1130
0
          << FixItHint::CreateInsertion(
1131
0
                 SemaRef.getLocForEndOfToken(
1132
0
                     StructuredSubobjectInitList->getEndLoc()),
1133
0
                 "}");
1134
0
    }
1135
1136
    // Warn if this type won't be an aggregate in future versions of C++.
1137
0
    auto *CXXRD = T->getAsCXXRecordDecl();
1138
0
    if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1139
0
      SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1140
0
                   diag::warn_cxx20_compat_aggregate_init_with_ctors)
1141
0
          << StructuredSubobjectInitList->getSourceRange() << T;
1142
0
    }
1143
0
  }
1144
0
}
1145
1146
/// Warn that \p Entity was of scalar type and was initialized by a
1147
/// single-element braced initializer list.
1148
static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1149
0
                                 SourceRange Braces) {
1150
  // Don't warn during template instantiation. If the initialization was
1151
  // non-dependent, we warned during the initial parse; otherwise, the
1152
  // type might not be scalar in some uses of the template.
1153
0
  if (S.inTemplateInstantiation())
1154
0
    return;
1155
1156
0
  unsigned DiagID = 0;
1157
1158
0
  switch (Entity.getKind()) {
1159
0
  case InitializedEntity::EK_VectorElement:
1160
0
  case InitializedEntity::EK_ComplexElement:
1161
0
  case InitializedEntity::EK_ArrayElement:
1162
0
  case InitializedEntity::EK_Parameter:
1163
0
  case InitializedEntity::EK_Parameter_CF_Audited:
1164
0
  case InitializedEntity::EK_TemplateParameter:
1165
0
  case InitializedEntity::EK_Result:
1166
0
  case InitializedEntity::EK_ParenAggInitMember:
1167
    // Extra braces here are suspicious.
1168
0
    DiagID = diag::warn_braces_around_init;
1169
0
    break;
1170
1171
0
  case InitializedEntity::EK_Member:
1172
    // Warn on aggregate initialization but not on ctor init list or
1173
    // default member initializer.
1174
0
    if (Entity.getParent())
1175
0
      DiagID = diag::warn_braces_around_init;
1176
0
    break;
1177
1178
0
  case InitializedEntity::EK_Variable:
1179
0
  case InitializedEntity::EK_LambdaCapture:
1180
    // No warning, might be direct-list-initialization.
1181
    // FIXME: Should we warn for copy-list-initialization in these cases?
1182
0
    break;
1183
1184
0
  case InitializedEntity::EK_New:
1185
0
  case InitializedEntity::EK_Temporary:
1186
0
  case InitializedEntity::EK_CompoundLiteralInit:
1187
    // No warning, braces are part of the syntax of the underlying construct.
1188
0
    break;
1189
1190
0
  case InitializedEntity::EK_RelatedResult:
1191
    // No warning, we already warned when initializing the result.
1192
0
    break;
1193
1194
0
  case InitializedEntity::EK_Exception:
1195
0
  case InitializedEntity::EK_Base:
1196
0
  case InitializedEntity::EK_Delegating:
1197
0
  case InitializedEntity::EK_BlockElement:
1198
0
  case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1199
0
  case InitializedEntity::EK_Binding:
1200
0
  case InitializedEntity::EK_StmtExprResult:
1201
0
    llvm_unreachable("unexpected braced scalar init");
1202
0
  }
1203
1204
0
  if (DiagID) {
1205
0
    S.Diag(Braces.getBegin(), DiagID)
1206
0
        << Entity.getType()->isSizelessBuiltinType() << Braces
1207
0
        << FixItHint::CreateRemoval(Braces.getBegin())
1208
0
        << FixItHint::CreateRemoval(Braces.getEnd());
1209
0
  }
1210
0
}
1211
1212
/// Check whether the initializer \p IList (that was written with explicit
1213
/// braces) can be used to initialize an object of type \p T.
1214
///
1215
/// This also fills in \p StructuredList with the fully-braced, desugared
1216
/// form of the initialization.
1217
void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1218
                                            InitListExpr *IList, QualType &T,
1219
                                            InitListExpr *StructuredList,
1220
0
                                            bool TopLevelObject) {
1221
0
  unsigned Index = 0, StructuredIndex = 0;
1222
0
  CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1223
0
                        Index, StructuredList, StructuredIndex, TopLevelObject);
1224
0
  if (StructuredList) {
1225
0
    QualType ExprTy = T;
1226
0
    if (!ExprTy->isArrayType())
1227
0
      ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1228
0
    if (!VerifyOnly)
1229
0
      IList->setType(ExprTy);
1230
0
    StructuredList->setType(ExprTy);
1231
0
  }
1232
0
  if (hadError)
1233
0
    return;
1234
1235
  // Don't complain for incomplete types, since we'll get an error elsewhere.
1236
0
  if (Index < IList->getNumInits() && !T->isIncompleteType()) {
1237
    // We have leftover initializers
1238
0
    bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1239
0
          (SemaRef.getLangOpts().OpenCL && T->isVectorType());
1240
0
    hadError = ExtraInitsIsError;
1241
0
    if (VerifyOnly) {
1242
0
      return;
1243
0
    } else if (StructuredIndex == 1 &&
1244
0
               IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1245
0
                   SIF_None) {
1246
0
      unsigned DK =
1247
0
          ExtraInitsIsError
1248
0
              ? diag::err_excess_initializers_in_char_array_initializer
1249
0
              : diag::ext_excess_initializers_in_char_array_initializer;
1250
0
      SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1251
0
          << IList->getInit(Index)->getSourceRange();
1252
0
    } else if (T->isSizelessBuiltinType()) {
1253
0
      unsigned DK = ExtraInitsIsError
1254
0
                        ? diag::err_excess_initializers_for_sizeless_type
1255
0
                        : diag::ext_excess_initializers_for_sizeless_type;
1256
0
      SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1257
0
          << T << IList->getInit(Index)->getSourceRange();
1258
0
    } else {
1259
0
      int initKind = T->isArrayType() ? 0 :
1260
0
                     T->isVectorType() ? 1 :
1261
0
                     T->isScalarType() ? 2 :
1262
0
                     T->isUnionType() ? 3 :
1263
0
                     4;
1264
1265
0
      unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers
1266
0
                                      : diag::ext_excess_initializers;
1267
0
      SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1268
0
          << initKind << IList->getInit(Index)->getSourceRange();
1269
0
    }
1270
0
  }
1271
1272
0
  if (!VerifyOnly) {
1273
0
    if (T->isScalarType() && IList->getNumInits() == 1 &&
1274
0
        !isa<InitListExpr>(IList->getInit(0)))
1275
0
      warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1276
1277
    // Warn if this is a class type that won't be an aggregate in future
1278
    // versions of C++.
1279
0
    auto *CXXRD = T->getAsCXXRecordDecl();
1280
0
    if (CXXRD && CXXRD->hasUserDeclaredConstructor()) {
1281
      // Don't warn if there's an equivalent default constructor that would be
1282
      // used instead.
1283
0
      bool HasEquivCtor = false;
1284
0
      if (IList->getNumInits() == 0) {
1285
0
        auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1286
0
        HasEquivCtor = CD && !CD->isDeleted();
1287
0
      }
1288
1289
0
      if (!HasEquivCtor) {
1290
0
        SemaRef.Diag(IList->getBeginLoc(),
1291
0
                     diag::warn_cxx20_compat_aggregate_init_with_ctors)
1292
0
            << IList->getSourceRange() << T;
1293
0
      }
1294
0
    }
1295
0
  }
1296
0
}
1297
1298
void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1299
                                            InitListExpr *IList,
1300
                                            QualType &DeclType,
1301
                                            bool SubobjectIsDesignatorContext,
1302
                                            unsigned &Index,
1303
                                            InitListExpr *StructuredList,
1304
                                            unsigned &StructuredIndex,
1305
0
                                            bool TopLevelObject) {
1306
0
  if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
1307
    // Explicitly braced initializer for complex type can be real+imaginary
1308
    // parts.
1309
0
    CheckComplexType(Entity, IList, DeclType, Index,
1310
0
                     StructuredList, StructuredIndex);
1311
0
  } else if (DeclType->isScalarType()) {
1312
0
    CheckScalarType(Entity, IList, DeclType, Index,
1313
0
                    StructuredList, StructuredIndex);
1314
0
  } else if (DeclType->isVectorType()) {
1315
0
    CheckVectorType(Entity, IList, DeclType, Index,
1316
0
                    StructuredList, StructuredIndex);
1317
0
  } else if (const RecordDecl *RD = getRecordDecl(DeclType)) {
1318
0
    auto Bases =
1319
0
        CXXRecordDecl::base_class_const_range(CXXRecordDecl::base_class_const_iterator(),
1320
0
                                        CXXRecordDecl::base_class_const_iterator());
1321
0
    if (DeclType->isRecordType()) {
1322
0
      assert(DeclType->isAggregateType() &&
1323
0
             "non-aggregate records should be handed in CheckSubElementType");
1324
0
      if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1325
0
        Bases = CXXRD->bases();
1326
0
    } else {
1327
0
      Bases = cast<CXXRecordDecl>(RD)->bases();
1328
0
    }
1329
0
    CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1330
0
                          SubobjectIsDesignatorContext, Index, StructuredList,
1331
0
                          StructuredIndex, TopLevelObject);
1332
0
  } else if (DeclType->isArrayType()) {
1333
0
    llvm::APSInt Zero(
1334
0
                    SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1335
0
                    false);
1336
0
    CheckArrayType(Entity, IList, DeclType, Zero,
1337
0
                   SubobjectIsDesignatorContext, Index,
1338
0
                   StructuredList, StructuredIndex);
1339
0
  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
1340
    // This type is invalid, issue a diagnostic.
1341
0
    ++Index;
1342
0
    if (!VerifyOnly)
1343
0
      SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1344
0
          << DeclType;
1345
0
    hadError = true;
1346
0
  } else if (DeclType->isReferenceType()) {
1347
0
    CheckReferenceType(Entity, IList, DeclType, Index,
1348
0
                       StructuredList, StructuredIndex);
1349
0
  } else if (DeclType->isObjCObjectType()) {
1350
0
    if (!VerifyOnly)
1351
0
      SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1352
0
    hadError = true;
1353
0
  } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1354
0
             DeclType->isSizelessBuiltinType()) {
1355
    // Checks for scalar type are sufficient for these types too.
1356
0
    CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1357
0
                    StructuredIndex);
1358
0
  } else if (DeclType->isDependentType()) {
1359
    // C++ [over.match.class.deduct]p1.5:
1360
    //   brace elision is not considered for any aggregate element that has a
1361
    //   dependent non-array type or an array type with a value-dependent bound
1362
0
    ++Index;
1363
0
    assert(AggrDeductionCandidateParamTypes);
1364
0
    AggrDeductionCandidateParamTypes->push_back(DeclType);
1365
0
  } else {
1366
0
    if (!VerifyOnly)
1367
0
      SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1368
0
          << DeclType;
1369
0
    hadError = true;
1370
0
  }
1371
0
}
1372
1373
void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1374
                                          InitListExpr *IList,
1375
                                          QualType ElemType,
1376
                                          unsigned &Index,
1377
                                          InitListExpr *StructuredList,
1378
                                          unsigned &StructuredIndex,
1379
0
                                          bool DirectlyDesignated) {
1380
0
  Expr *expr = IList->getInit(Index);
1381
1382
0
  if (ElemType->isReferenceType())
1383
0
    return CheckReferenceType(Entity, IList, ElemType, Index,
1384
0
                              StructuredList, StructuredIndex);
1385
1386
0
  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1387
0
    if (SubInitList->getNumInits() == 1 &&
1388
0
        IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1389
0
        SIF_None) {
1390
      // FIXME: It would be more faithful and no less correct to include an
1391
      // InitListExpr in the semantic form of the initializer list in this case.
1392
0
      expr = SubInitList->getInit(0);
1393
0
    }
1394
    // Nested aggregate initialization and C++ initialization are handled later.
1395
0
  } else if (isa<ImplicitValueInitExpr>(expr)) {
1396
    // This happens during template instantiation when we see an InitListExpr
1397
    // that we've already checked once.
1398
0
    assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1399
0
           "found implicit initialization for the wrong type");
1400
0
    UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1401
0
    ++Index;
1402
0
    return;
1403
0
  }
1404
1405
0
  if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(expr)) {
1406
    // C++ [dcl.init.aggr]p2:
1407
    //   Each member is copy-initialized from the corresponding
1408
    //   initializer-clause.
1409
1410
    // FIXME: Better EqualLoc?
1411
0
    InitializationKind Kind =
1412
0
        InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1413
1414
    // Vector elements can be initialized from other vectors in which case
1415
    // we need initialization entity with a type of a vector (and not a vector
1416
    // element!) initializing multiple vector elements.
1417
0
    auto TmpEntity =
1418
0
        (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType())
1419
0
            ? InitializedEntity::InitializeTemporary(ElemType)
1420
0
            : Entity;
1421
1422
0
    if (TmpEntity.getType()->isDependentType()) {
1423
      // C++ [over.match.class.deduct]p1.5:
1424
      //   brace elision is not considered for any aggregate element that has a
1425
      //   dependent non-array type or an array type with a value-dependent
1426
      //   bound
1427
0
      assert(AggrDeductionCandidateParamTypes);
1428
0
      if (!isa_and_nonnull<ConstantArrayType>(
1429
0
              SemaRef.Context.getAsArrayType(ElemType))) {
1430
0
        ++Index;
1431
0
        AggrDeductionCandidateParamTypes->push_back(ElemType);
1432
0
        return;
1433
0
      }
1434
0
    } else {
1435
0
      InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1436
0
                                 /*TopLevelOfInitList*/ true);
1437
      // C++14 [dcl.init.aggr]p13:
1438
      //   If the assignment-expression can initialize a member, the member is
1439
      //   initialized. Otherwise [...] brace elision is assumed
1440
      //
1441
      // Brace elision is never performed if the element is not an
1442
      // assignment-expression.
1443
0
      if (Seq || isa<InitListExpr>(expr)) {
1444
0
        if (!VerifyOnly) {
1445
0
          ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1446
0
          if (Result.isInvalid())
1447
0
            hadError = true;
1448
1449
0
          UpdateStructuredListElement(StructuredList, StructuredIndex,
1450
0
                                      Result.getAs<Expr>());
1451
0
        } else if (!Seq) {
1452
0
          hadError = true;
1453
0
        } else if (StructuredList) {
1454
0
          UpdateStructuredListElement(StructuredList, StructuredIndex,
1455
0
                                      getDummyInit());
1456
0
        }
1457
0
        ++Index;
1458
0
        if (AggrDeductionCandidateParamTypes)
1459
0
          AggrDeductionCandidateParamTypes->push_back(ElemType);
1460
0
        return;
1461
0
      }
1462
0
    }
1463
1464
    // Fall through for subaggregate initialization
1465
0
  } else if (ElemType->isScalarType() || ElemType->isAtomicType()) {
1466
    // FIXME: Need to handle atomic aggregate types with implicit init lists.
1467
0
    return CheckScalarType(Entity, IList, ElemType, Index,
1468
0
                           StructuredList, StructuredIndex);
1469
0
  } else if (const ArrayType *arrayType =
1470
0
                 SemaRef.Context.getAsArrayType(ElemType)) {
1471
    // arrayType can be incomplete if we're initializing a flexible
1472
    // array member.  There's nothing we can do with the completed
1473
    // type here, though.
1474
1475
0
    if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1476
      // FIXME: Should we do this checking in verify-only mode?
1477
0
      if (!VerifyOnly)
1478
0
        CheckStringInit(expr, ElemType, arrayType, SemaRef);
1479
0
      if (StructuredList)
1480
0
        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1481
0
      ++Index;
1482
0
      return;
1483
0
    }
1484
1485
    // Fall through for subaggregate initialization.
1486
1487
0
  } else {
1488
0
    assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1489
0
            ElemType->isOpenCLSpecificType()) && "Unexpected type");
1490
1491
    // C99 6.7.8p13:
1492
    //
1493
    //   The initializer for a structure or union object that has
1494
    //   automatic storage duration shall be either an initializer
1495
    //   list as described below, or a single expression that has
1496
    //   compatible structure or union type. In the latter case, the
1497
    //   initial value of the object, including unnamed members, is
1498
    //   that of the expression.
1499
0
    ExprResult ExprRes = expr;
1500
0
    if (SemaRef.CheckSingleAssignmentConstraints(
1501
0
            ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1502
0
      if (ExprRes.isInvalid())
1503
0
        hadError = true;
1504
0
      else {
1505
0
        ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1506
0
        if (ExprRes.isInvalid())
1507
0
          hadError = true;
1508
0
      }
1509
0
      UpdateStructuredListElement(StructuredList, StructuredIndex,
1510
0
                                  ExprRes.getAs<Expr>());
1511
0
      ++Index;
1512
0
      return;
1513
0
    }
1514
0
    ExprRes.get();
1515
    // Fall through for subaggregate initialization
1516
0
  }
1517
1518
  // C++ [dcl.init.aggr]p12:
1519
  //
1520
  //   [...] Otherwise, if the member is itself a non-empty
1521
  //   subaggregate, brace elision is assumed and the initializer is
1522
  //   considered for the initialization of the first member of
1523
  //   the subaggregate.
1524
  // OpenCL vector initializer is handled elsewhere.
1525
0
  if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) ||
1526
0
      ElemType->isAggregateType()) {
1527
0
    CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1528
0
                          StructuredIndex);
1529
0
    ++StructuredIndex;
1530
1531
    // In C++20, brace elision is not permitted for a designated initializer.
1532
0
    if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) {
1533
0
      if (InOverloadResolution)
1534
0
        hadError = true;
1535
0
      if (!VerifyOnly) {
1536
0
        SemaRef.Diag(expr->getBeginLoc(),
1537
0
                     diag::ext_designated_init_brace_elision)
1538
0
            << expr->getSourceRange()
1539
0
            << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1540
0
            << FixItHint::CreateInsertion(
1541
0
                   SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1542
0
      }
1543
0
    }
1544
0
  } else {
1545
0
    if (!VerifyOnly) {
1546
      // We cannot initialize this element, so let PerformCopyInitialization
1547
      // produce the appropriate diagnostic. We already checked that this
1548
      // initialization will fail.
1549
0
      ExprResult Copy =
1550
0
          SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1551
0
                                            /*TopLevelOfInitList=*/true);
1552
0
      (void)Copy;
1553
0
      assert(Copy.isInvalid() &&
1554
0
             "expected non-aggregate initialization to fail");
1555
0
    }
1556
0
    hadError = true;
1557
0
    ++Index;
1558
0
    ++StructuredIndex;
1559
0
  }
1560
0
}
1561
1562
void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1563
                                       InitListExpr *IList, QualType DeclType,
1564
                                       unsigned &Index,
1565
                                       InitListExpr *StructuredList,
1566
0
                                       unsigned &StructuredIndex) {
1567
0
  assert(Index == 0 && "Index in explicit init list must be zero");
1568
1569
  // As an extension, clang supports complex initializers, which initialize
1570
  // a complex number component-wise.  When an explicit initializer list for
1571
  // a complex number contains two initializers, this extension kicks in:
1572
  // it expects the initializer list to contain two elements convertible to
1573
  // the element type of the complex type. The first element initializes
1574
  // the real part, and the second element intitializes the imaginary part.
1575
1576
0
  if (IList->getNumInits() < 2)
1577
0
    return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1578
0
                           StructuredIndex);
1579
1580
  // This is an extension in C.  (The builtin _Complex type does not exist
1581
  // in the C++ standard.)
1582
0
  if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
1583
0
    SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1584
0
        << IList->getSourceRange();
1585
1586
  // Initialize the complex number.
1587
0
  QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1588
0
  InitializedEntity ElementEntity =
1589
0
    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1590
1591
0
  for (unsigned i = 0; i < 2; ++i) {
1592
0
    ElementEntity.setElementIndex(Index);
1593
0
    CheckSubElementType(ElementEntity, IList, elementType, Index,
1594
0
                        StructuredList, StructuredIndex);
1595
0
  }
1596
0
}
1597
1598
void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1599
                                      InitListExpr *IList, QualType DeclType,
1600
                                      unsigned &Index,
1601
                                      InitListExpr *StructuredList,
1602
0
                                      unsigned &StructuredIndex) {
1603
0
  if (Index >= IList->getNumInits()) {
1604
0
    if (!VerifyOnly) {
1605
0
      if (SemaRef.getLangOpts().CPlusPlus) {
1606
0
        if (DeclType->isSizelessBuiltinType())
1607
0
          SemaRef.Diag(IList->getBeginLoc(),
1608
0
                       SemaRef.getLangOpts().CPlusPlus11
1609
0
                           ? diag::warn_cxx98_compat_empty_sizeless_initializer
1610
0
                           : diag::err_empty_sizeless_initializer)
1611
0
              << DeclType << IList->getSourceRange();
1612
0
        else
1613
0
          SemaRef.Diag(IList->getBeginLoc(),
1614
0
                       SemaRef.getLangOpts().CPlusPlus11
1615
0
                           ? diag::warn_cxx98_compat_empty_scalar_initializer
1616
0
                           : diag::err_empty_scalar_initializer)
1617
0
              << IList->getSourceRange();
1618
0
      }
1619
0
    }
1620
0
    hadError =
1621
0
        SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11;
1622
0
    ++Index;
1623
0
    ++StructuredIndex;
1624
0
    return;
1625
0
  }
1626
1627
0
  Expr *expr = IList->getInit(Index);
1628
0
  if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1629
    // FIXME: This is invalid, and accepting it causes overload resolution
1630
    // to pick the wrong overload in some corner cases.
1631
0
    if (!VerifyOnly)
1632
0
      SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1633
0
          << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1634
1635
0
    CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1636
0
                    StructuredIndex);
1637
0
    return;
1638
0
  } else if (isa<DesignatedInitExpr>(expr)) {
1639
0
    if (!VerifyOnly)
1640
0
      SemaRef.Diag(expr->getBeginLoc(),
1641
0
                   diag::err_designator_for_scalar_or_sizeless_init)
1642
0
          << DeclType->isSizelessBuiltinType() << DeclType
1643
0
          << expr->getSourceRange();
1644
0
    hadError = true;
1645
0
    ++Index;
1646
0
    ++StructuredIndex;
1647
0
    return;
1648
0
  }
1649
1650
0
  ExprResult Result;
1651
0
  if (VerifyOnly) {
1652
0
    if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1653
0
      Result = getDummyInit();
1654
0
    else
1655
0
      Result = ExprError();
1656
0
  } else {
1657
0
    Result =
1658
0
        SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1659
0
                                          /*TopLevelOfInitList=*/true);
1660
0
  }
1661
1662
0
  Expr *ResultExpr = nullptr;
1663
1664
0
  if (Result.isInvalid())
1665
0
    hadError = true; // types weren't compatible.
1666
0
  else {
1667
0
    ResultExpr = Result.getAs<Expr>();
1668
1669
0
    if (ResultExpr != expr && !VerifyOnly) {
1670
      // The type was promoted, update initializer list.
1671
      // FIXME: Why are we updating the syntactic init list?
1672
0
      IList->setInit(Index, ResultExpr);
1673
0
    }
1674
0
  }
1675
0
  UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1676
0
  ++Index;
1677
0
  if (AggrDeductionCandidateParamTypes)
1678
0
    AggrDeductionCandidateParamTypes->push_back(DeclType);
1679
0
}
1680
1681
void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1682
                                         InitListExpr *IList, QualType DeclType,
1683
                                         unsigned &Index,
1684
                                         InitListExpr *StructuredList,
1685
0
                                         unsigned &StructuredIndex) {
1686
0
  if (Index >= IList->getNumInits()) {
1687
    // FIXME: It would be wonderful if we could point at the actual member. In
1688
    // general, it would be useful to pass location information down the stack,
1689
    // so that we know the location (or decl) of the "current object" being
1690
    // initialized.
1691
0
    if (!VerifyOnly)
1692
0
      SemaRef.Diag(IList->getBeginLoc(),
1693
0
                   diag::err_init_reference_member_uninitialized)
1694
0
          << DeclType << IList->getSourceRange();
1695
0
    hadError = true;
1696
0
    ++Index;
1697
0
    ++StructuredIndex;
1698
0
    return;
1699
0
  }
1700
1701
0
  Expr *expr = IList->getInit(Index);
1702
0
  if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1703
0
    if (!VerifyOnly)
1704
0
      SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1705
0
          << DeclType << IList->getSourceRange();
1706
0
    hadError = true;
1707
0
    ++Index;
1708
0
    ++StructuredIndex;
1709
0
    return;
1710
0
  }
1711
1712
0
  ExprResult Result;
1713
0
  if (VerifyOnly) {
1714
0
    if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1715
0
      Result = getDummyInit();
1716
0
    else
1717
0
      Result = ExprError();
1718
0
  } else {
1719
0
    Result =
1720
0
        SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1721
0
                                          /*TopLevelOfInitList=*/true);
1722
0
  }
1723
1724
0
  if (Result.isInvalid())
1725
0
    hadError = true;
1726
1727
0
  expr = Result.getAs<Expr>();
1728
  // FIXME: Why are we updating the syntactic init list?
1729
0
  if (!VerifyOnly && expr)
1730
0
    IList->setInit(Index, expr);
1731
1732
0
  UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1733
0
  ++Index;
1734
0
  if (AggrDeductionCandidateParamTypes)
1735
0
    AggrDeductionCandidateParamTypes->push_back(DeclType);
1736
0
}
1737
1738
void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1739
                                      InitListExpr *IList, QualType DeclType,
1740
                                      unsigned &Index,
1741
                                      InitListExpr *StructuredList,
1742
0
                                      unsigned &StructuredIndex) {
1743
0
  const VectorType *VT = DeclType->castAs<VectorType>();
1744
0
  unsigned maxElements = VT->getNumElements();
1745
0
  unsigned numEltsInit = 0;
1746
0
  QualType elementType = VT->getElementType();
1747
1748
0
  if (Index >= IList->getNumInits()) {
1749
    // Make sure the element type can be value-initialized.
1750
0
    CheckEmptyInitializable(
1751
0
        InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1752
0
        IList->getEndLoc());
1753
0
    return;
1754
0
  }
1755
1756
0
  if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) {
1757
    // If the initializing element is a vector, try to copy-initialize
1758
    // instead of breaking it apart (which is doomed to failure anyway).
1759
0
    Expr *Init = IList->getInit(Index);
1760
0
    if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1761
0
      ExprResult Result;
1762
0
      if (VerifyOnly) {
1763
0
        if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1764
0
          Result = getDummyInit();
1765
0
        else
1766
0
          Result = ExprError();
1767
0
      } else {
1768
0
        Result =
1769
0
            SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1770
0
                                              /*TopLevelOfInitList=*/true);
1771
0
      }
1772
1773
0
      Expr *ResultExpr = nullptr;
1774
0
      if (Result.isInvalid())
1775
0
        hadError = true; // types weren't compatible.
1776
0
      else {
1777
0
        ResultExpr = Result.getAs<Expr>();
1778
1779
0
        if (ResultExpr != Init && !VerifyOnly) {
1780
          // The type was promoted, update initializer list.
1781
          // FIXME: Why are we updating the syntactic init list?
1782
0
          IList->setInit(Index, ResultExpr);
1783
0
        }
1784
0
      }
1785
0
      UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1786
0
      ++Index;
1787
0
      if (AggrDeductionCandidateParamTypes)
1788
0
        AggrDeductionCandidateParamTypes->push_back(elementType);
1789
0
      return;
1790
0
    }
1791
1792
0
    InitializedEntity ElementEntity =
1793
0
      InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1794
1795
0
    for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1796
      // Don't attempt to go past the end of the init list
1797
0
      if (Index >= IList->getNumInits()) {
1798
0
        CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1799
0
        break;
1800
0
      }
1801
1802
0
      ElementEntity.setElementIndex(Index);
1803
0
      CheckSubElementType(ElementEntity, IList, elementType, Index,
1804
0
                          StructuredList, StructuredIndex);
1805
0
    }
1806
1807
0
    if (VerifyOnly)
1808
0
      return;
1809
1810
0
    bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1811
0
    const VectorType *T = Entity.getType()->castAs<VectorType>();
1812
0
    if (isBigEndian && (T->getVectorKind() == VectorKind::Neon ||
1813
0
                        T->getVectorKind() == VectorKind::NeonPoly)) {
1814
      // The ability to use vector initializer lists is a GNU vector extension
1815
      // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1816
      // endian machines it works fine, however on big endian machines it
1817
      // exhibits surprising behaviour:
1818
      //
1819
      //   uint32x2_t x = {42, 64};
1820
      //   return vget_lane_u32(x, 0); // Will return 64.
1821
      //
1822
      // Because of this, explicitly call out that it is non-portable.
1823
      //
1824
0
      SemaRef.Diag(IList->getBeginLoc(),
1825
0
                   diag::warn_neon_vector_initializer_non_portable);
1826
1827
0
      const char *typeCode;
1828
0
      unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1829
1830
0
      if (elementType->isFloatingType())
1831
0
        typeCode = "f";
1832
0
      else if (elementType->isSignedIntegerType())
1833
0
        typeCode = "s";
1834
0
      else if (elementType->isUnsignedIntegerType())
1835
0
        typeCode = "u";
1836
0
      else
1837
0
        llvm_unreachable("Invalid element type!");
1838
1839
0
      SemaRef.Diag(IList->getBeginLoc(),
1840
0
                   SemaRef.Context.getTypeSize(VT) > 64
1841
0
                       ? diag::note_neon_vector_initializer_non_portable_q
1842
0
                       : diag::note_neon_vector_initializer_non_portable)
1843
0
          << typeCode << typeSize;
1844
0
    }
1845
1846
0
    return;
1847
0
  }
1848
1849
0
  InitializedEntity ElementEntity =
1850
0
    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1851
1852
  // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1853
0
  for (unsigned i = 0; i < maxElements; ++i) {
1854
    // Don't attempt to go past the end of the init list
1855
0
    if (Index >= IList->getNumInits())
1856
0
      break;
1857
1858
0
    ElementEntity.setElementIndex(Index);
1859
1860
0
    QualType IType = IList->getInit(Index)->getType();
1861
0
    if (!IType->isVectorType()) {
1862
0
      CheckSubElementType(ElementEntity, IList, elementType, Index,
1863
0
                          StructuredList, StructuredIndex);
1864
0
      ++numEltsInit;
1865
0
    } else {
1866
0
      QualType VecType;
1867
0
      const VectorType *IVT = IType->castAs<VectorType>();
1868
0
      unsigned numIElts = IVT->getNumElements();
1869
1870
0
      if (IType->isExtVectorType())
1871
0
        VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1872
0
      else
1873
0
        VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1874
0
                                                IVT->getVectorKind());
1875
0
      CheckSubElementType(ElementEntity, IList, VecType, Index,
1876
0
                          StructuredList, StructuredIndex);
1877
0
      numEltsInit += numIElts;
1878
0
    }
1879
0
  }
1880
1881
  // OpenCL and HLSL require all elements to be initialized.
1882
0
  if (numEltsInit != maxElements) {
1883
0
    if (!VerifyOnly)
1884
0
      SemaRef.Diag(IList->getBeginLoc(),
1885
0
                   diag::err_vector_incorrect_num_initializers)
1886
0
          << (numEltsInit < maxElements) << maxElements << numEltsInit;
1887
0
    hadError = true;
1888
0
  }
1889
0
}
1890
1891
/// Check if the type of a class element has an accessible destructor, and marks
1892
/// it referenced. Returns true if we shouldn't form a reference to the
1893
/// destructor.
1894
///
1895
/// Aggregate initialization requires a class element's destructor be
1896
/// accessible per 11.6.1 [dcl.init.aggr]:
1897
///
1898
/// The destructor for each element of class type is potentially invoked
1899
/// (15.4 [class.dtor]) from the context where the aggregate initialization
1900
/// occurs.
1901
static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1902
0
                                     Sema &SemaRef) {
1903
0
  auto *CXXRD = ElementType->getAsCXXRecordDecl();
1904
0
  if (!CXXRD)
1905
0
    return false;
1906
1907
0
  CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1908
0
  SemaRef.CheckDestructorAccess(Loc, Destructor,
1909
0
                                SemaRef.PDiag(diag::err_access_dtor_temp)
1910
0
                                << ElementType);
1911
0
  SemaRef.MarkFunctionReferenced(Loc, Destructor);
1912
0
  return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1913
0
}
1914
1915
void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1916
                                     InitListExpr *IList, QualType &DeclType,
1917
                                     llvm::APSInt elementIndex,
1918
                                     bool SubobjectIsDesignatorContext,
1919
                                     unsigned &Index,
1920
                                     InitListExpr *StructuredList,
1921
0
                                     unsigned &StructuredIndex) {
1922
0
  const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1923
1924
0
  if (!VerifyOnly) {
1925
0
    if (checkDestructorReference(arrayType->getElementType(),
1926
0
                                 IList->getEndLoc(), SemaRef)) {
1927
0
      hadError = true;
1928
0
      return;
1929
0
    }
1930
0
  }
1931
1932
  // Check for the special-case of initializing an array with a string.
1933
0
  if (Index < IList->getNumInits()) {
1934
0
    if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1935
0
        SIF_None) {
1936
      // We place the string literal directly into the resulting
1937
      // initializer list. This is the only place where the structure
1938
      // of the structured initializer list doesn't match exactly,
1939
      // because doing so would involve allocating one character
1940
      // constant for each string.
1941
      // FIXME: Should we do these checks in verify-only mode too?
1942
0
      if (!VerifyOnly)
1943
0
        CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1944
0
      if (StructuredList) {
1945
0
        UpdateStructuredListElement(StructuredList, StructuredIndex,
1946
0
                                    IList->getInit(Index));
1947
0
        StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1948
0
      }
1949
0
      ++Index;
1950
0
      if (AggrDeductionCandidateParamTypes)
1951
0
        AggrDeductionCandidateParamTypes->push_back(DeclType);
1952
0
      return;
1953
0
    }
1954
0
  }
1955
0
  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1956
    // Check for VLAs; in standard C it would be possible to check this
1957
    // earlier, but I don't know where clang accepts VLAs (gcc accepts
1958
    // them in all sorts of strange places).
1959
0
    bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus;
1960
0
    if (!VerifyOnly) {
1961
      // C23 6.7.10p4: An entity of variable length array type shall not be
1962
      // initialized except by an empty initializer.
1963
      //
1964
      // The C extension warnings are issued from ParseBraceInitializer() and
1965
      // do not need to be issued here. However, we continue to issue an error
1966
      // in the case there are initializers or we are compiling C++. We allow
1967
      // use of VLAs in C++, but it's not clear we want to allow {} to zero
1968
      // init a VLA in C++ in all cases (such as with non-trivial constructors).
1969
      // FIXME: should we allow this construct in C++ when it makes sense to do
1970
      // so?
1971
0
      if (HasErr)
1972
0
        SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1973
0
                     diag::err_variable_object_no_init)
1974
0
            << VAT->getSizeExpr()->getSourceRange();
1975
0
    }
1976
0
    hadError = HasErr;
1977
0
    ++Index;
1978
0
    ++StructuredIndex;
1979
0
    return;
1980
0
  }
1981
1982
  // We might know the maximum number of elements in advance.
1983
0
  llvm::APSInt maxElements(elementIndex.getBitWidth(),
1984
0
                           elementIndex.isUnsigned());
1985
0
  bool maxElementsKnown = false;
1986
0
  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1987
0
    maxElements = CAT->getSize();
1988
0
    elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1989
0
    elementIndex.setIsUnsigned(maxElements.isUnsigned());
1990
0
    maxElementsKnown = true;
1991
0
  }
1992
1993
0
  QualType elementType = arrayType->getElementType();
1994
0
  while (Index < IList->getNumInits()) {
1995
0
    Expr *Init = IList->getInit(Index);
1996
0
    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1997
      // If we're not the subobject that matches up with the '{' for
1998
      // the designator, we shouldn't be handling the
1999
      // designator. Return immediately.
2000
0
      if (!SubobjectIsDesignatorContext)
2001
0
        return;
2002
2003
      // Handle this designated initializer. elementIndex will be
2004
      // updated to be the next array element we'll initialize.
2005
0
      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2006
0
                                     DeclType, nullptr, &elementIndex, Index,
2007
0
                                     StructuredList, StructuredIndex, true,
2008
0
                                     false)) {
2009
0
        hadError = true;
2010
0
        continue;
2011
0
      }
2012
2013
0
      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
2014
0
        maxElements = maxElements.extend(elementIndex.getBitWidth());
2015
0
      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
2016
0
        elementIndex = elementIndex.extend(maxElements.getBitWidth());
2017
0
      elementIndex.setIsUnsigned(maxElements.isUnsigned());
2018
2019
      // If the array is of incomplete type, keep track of the number of
2020
      // elements in the initializer.
2021
0
      if (!maxElementsKnown && elementIndex > maxElements)
2022
0
        maxElements = elementIndex;
2023
2024
0
      continue;
2025
0
    }
2026
2027
    // If we know the maximum number of elements, and we've already
2028
    // hit it, stop consuming elements in the initializer list.
2029
0
    if (maxElementsKnown && elementIndex == maxElements)
2030
0
      break;
2031
2032
0
    InitializedEntity ElementEntity =
2033
0
      InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
2034
0
                                           Entity);
2035
    // Check this element.
2036
0
    CheckSubElementType(ElementEntity, IList, elementType, Index,
2037
0
                        StructuredList, StructuredIndex);
2038
0
    ++elementIndex;
2039
2040
    // If the array is of incomplete type, keep track of the number of
2041
    // elements in the initializer.
2042
0
    if (!maxElementsKnown && elementIndex > maxElements)
2043
0
      maxElements = elementIndex;
2044
0
  }
2045
0
  if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
2046
    // If this is an incomplete array type, the actual type needs to
2047
    // be calculated here.
2048
0
    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
2049
0
    if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) {
2050
      // Sizing an array implicitly to zero is not allowed by ISO C,
2051
      // but is supported by GNU.
2052
0
      SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
2053
0
    }
2054
2055
0
    DeclType = SemaRef.Context.getConstantArrayType(
2056
0
        elementType, maxElements, nullptr, ArraySizeModifier::Normal, 0);
2057
0
  }
2058
0
  if (!hadError) {
2059
    // If there are any members of the array that get value-initialized, check
2060
    // that is possible. That happens if we know the bound and don't have
2061
    // enough elements, or if we're performing an array new with an unknown
2062
    // bound.
2063
0
    if ((maxElementsKnown && elementIndex < maxElements) ||
2064
0
        Entity.isVariableLengthArrayNew())
2065
0
      CheckEmptyInitializable(
2066
0
          InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
2067
0
          IList->getEndLoc());
2068
0
  }
2069
0
}
2070
2071
bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
2072
                                             Expr *InitExpr,
2073
                                             FieldDecl *Field,
2074
0
                                             bool TopLevelObject) {
2075
  // Handle GNU flexible array initializers.
2076
0
  unsigned FlexArrayDiag;
2077
0
  if (isa<InitListExpr>(InitExpr) &&
2078
0
      cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
2079
    // Empty flexible array init always allowed as an extension
2080
0
    FlexArrayDiag = diag::ext_flexible_array_init;
2081
0
  } else if (!TopLevelObject) {
2082
    // Disallow flexible array init on non-top-level object
2083
0
    FlexArrayDiag = diag::err_flexible_array_init;
2084
0
  } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2085
    // Disallow flexible array init on anything which is not a variable.
2086
0
    FlexArrayDiag = diag::err_flexible_array_init;
2087
0
  } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2088
    // Disallow flexible array init on local variables.
2089
0
    FlexArrayDiag = diag::err_flexible_array_init;
2090
0
  } else {
2091
    // Allow other cases.
2092
0
    FlexArrayDiag = diag::ext_flexible_array_init;
2093
0
  }
2094
2095
0
  if (!VerifyOnly) {
2096
0
    SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2097
0
        << InitExpr->getBeginLoc();
2098
0
    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2099
0
      << Field;
2100
0
  }
2101
2102
0
  return FlexArrayDiag != diag::ext_flexible_array_init;
2103
0
}
2104
2105
void InitListChecker::CheckStructUnionTypes(
2106
    const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2107
    CXXRecordDecl::base_class_const_range Bases, RecordDecl::field_iterator Field,
2108
    bool SubobjectIsDesignatorContext, unsigned &Index,
2109
    InitListExpr *StructuredList, unsigned &StructuredIndex,
2110
0
    bool TopLevelObject) {
2111
0
  const RecordDecl *RD = getRecordDecl(DeclType);
2112
2113
  // If the record is invalid, some of it's members are invalid. To avoid
2114
  // confusion, we forgo checking the initializer for the entire record.
2115
0
  if (RD->isInvalidDecl()) {
2116
    // Assume it was supposed to consume a single initializer.
2117
0
    ++Index;
2118
0
    hadError = true;
2119
0
    return;
2120
0
  }
2121
2122
0
  if (RD->isUnion() && IList->getNumInits() == 0) {
2123
0
    if (!VerifyOnly)
2124
0
      for (FieldDecl *FD : RD->fields()) {
2125
0
        QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2126
0
        if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2127
0
          hadError = true;
2128
0
          return;
2129
0
        }
2130
0
      }
2131
2132
    // If there's a default initializer, use it.
2133
0
    if (isa<CXXRecordDecl>(RD) &&
2134
0
        cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
2135
0
      if (!StructuredList)
2136
0
        return;
2137
0
      for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2138
0
           Field != FieldEnd; ++Field) {
2139
0
        if (Field->hasInClassInitializer()) {
2140
0
          StructuredList->setInitializedFieldInUnion(*Field);
2141
          // FIXME: Actually build a CXXDefaultInitExpr?
2142
0
          return;
2143
0
        }
2144
0
      }
2145
0
    }
2146
2147
    // Value-initialize the first member of the union that isn't an unnamed
2148
    // bitfield.
2149
0
    for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2150
0
         Field != FieldEnd; ++Field) {
2151
0
      if (!Field->isUnnamedBitfield()) {
2152
0
        CheckEmptyInitializable(
2153
0
            InitializedEntity::InitializeMember(*Field, &Entity),
2154
0
            IList->getEndLoc());
2155
0
        if (StructuredList)
2156
0
          StructuredList->setInitializedFieldInUnion(*Field);
2157
0
        break;
2158
0
      }
2159
0
    }
2160
0
    return;
2161
0
  }
2162
2163
0
  bool InitializedSomething = false;
2164
2165
  // If we have any base classes, they are initialized prior to the fields.
2166
0
  for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) {
2167
0
    auto &Base = *I;
2168
0
    Expr *Init = Index < IList->getNumInits() ? IList->getInit(Index) : nullptr;
2169
2170
    // Designated inits always initialize fields, so if we see one, all
2171
    // remaining base classes have no explicit initializer.
2172
0
    if (Init && isa<DesignatedInitExpr>(Init))
2173
0
      Init = nullptr;
2174
2175
    // C++ [over.match.class.deduct]p1.6:
2176
    //   each non-trailing aggregate element that is a pack expansion is assumed
2177
    //   to correspond to no elements of the initializer list, and (1.7) a
2178
    //   trailing aggregate element that is a pack expansion is assumed to
2179
    //   correspond to all remaining elements of the initializer list (if any).
2180
2181
    // C++ [over.match.class.deduct]p1.9:
2182
    //   ... except that additional parameter packs of the form P_j... are
2183
    //   inserted into the parameter list in their original aggregate element
2184
    //   position corresponding to each non-trailing aggregate element of
2185
    //   type P_j that was skipped because it was a parameter pack, and the
2186
    //   trailing sequence of parameters corresponding to a trailing
2187
    //   aggregate element that is a pack expansion (if any) is replaced
2188
    //   by a single parameter of the form T_n....
2189
0
    if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) {
2190
0
      AggrDeductionCandidateParamTypes->push_back(
2191
0
          SemaRef.Context.getPackExpansionType(Base.getType(), std::nullopt));
2192
2193
      // Trailing pack expansion
2194
0
      if (I + 1 == E && RD->field_empty()) {
2195
0
        if (Index < IList->getNumInits())
2196
0
          Index = IList->getNumInits();
2197
0
        return;
2198
0
      }
2199
2200
0
      continue;
2201
0
    }
2202
2203
0
    SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc();
2204
0
    InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2205
0
        SemaRef.Context, &Base, false, &Entity);
2206
0
    if (Init) {
2207
0
      CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2208
0
                          StructuredList, StructuredIndex);
2209
0
      InitializedSomething = true;
2210
0
    } else {
2211
0
      CheckEmptyInitializable(BaseEntity, InitLoc);
2212
0
    }
2213
2214
0
    if (!VerifyOnly)
2215
0
      if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2216
0
        hadError = true;
2217
0
        return;
2218
0
      }
2219
0
  }
2220
2221
  // If structDecl is a forward declaration, this loop won't do
2222
  // anything except look at designated initializers; That's okay,
2223
  // because an error should get printed out elsewhere. It might be
2224
  // worthwhile to skip over the rest of the initializer, though.
2225
0
  RecordDecl::field_iterator FieldEnd = RD->field_end();
2226
0
  size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2227
0
    return isa<FieldDecl>(D) || isa<RecordDecl>(D);
2228
0
  });
2229
0
  bool CheckForMissingFields =
2230
0
    !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
2231
0
  bool HasDesignatedInit = false;
2232
2233
0
  llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
2234
2235
0
  while (Index < IList->getNumInits()) {
2236
0
    Expr *Init = IList->getInit(Index);
2237
0
    SourceLocation InitLoc = Init->getBeginLoc();
2238
2239
0
    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2240
      // If we're not the subobject that matches up with the '{' for
2241
      // the designator, we shouldn't be handling the
2242
      // designator. Return immediately.
2243
0
      if (!SubobjectIsDesignatorContext)
2244
0
        return;
2245
2246
0
      HasDesignatedInit = true;
2247
2248
      // Handle this designated initializer. Field will be updated to
2249
      // the next field that we'll be initializing.
2250
0
      bool DesignatedInitFailed = CheckDesignatedInitializer(
2251
0
          Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
2252
0
          StructuredList, StructuredIndex, true, TopLevelObject);
2253
0
      if (DesignatedInitFailed)
2254
0
        hadError = true;
2255
2256
      // Find the field named by the designated initializer.
2257
0
      DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
2258
0
      if (!VerifyOnly && D->isFieldDesignator()) {
2259
0
        FieldDecl *F = D->getFieldDecl();
2260
0
        InitializedFields.insert(F);
2261
0
        if (!DesignatedInitFailed) {
2262
0
          QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2263
0
          if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2264
0
            hadError = true;
2265
0
            return;
2266
0
          }
2267
0
        }
2268
0
      }
2269
2270
0
      InitializedSomething = true;
2271
2272
      // Disable check for missing fields when designators are used.
2273
      // This matches gcc behaviour.
2274
0
      if (!SemaRef.getLangOpts().CPlusPlus)
2275
0
        CheckForMissingFields = false;
2276
0
      continue;
2277
0
    }
2278
2279
    // Check if this is an initializer of forms:
2280
    //
2281
    //   struct foo f = {};
2282
    //   struct foo g = {0};
2283
    //
2284
    // These are okay for randomized structures. [C99 6.7.8p19]
2285
    //
2286
    // Also, if there is only one element in the structure, we allow something
2287
    // like this, because it's really not randomized in the tranditional sense.
2288
    //
2289
    //   struct foo h = {bar};
2290
0
    auto IsZeroInitializer = [&](const Expr *I) {
2291
0
      if (IList->getNumInits() == 1) {
2292
0
        if (NumRecordDecls == 1)
2293
0
          return true;
2294
0
        if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2295
0
          return IL->getValue().isZero();
2296
0
      }
2297
0
      return false;
2298
0
    };
2299
2300
    // Don't allow non-designated initializers on randomized structures.
2301
0
    if (RD->isRandomized() && !IsZeroInitializer(Init)) {
2302
0
      if (!VerifyOnly)
2303
0
        SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2304
0
      hadError = true;
2305
0
      break;
2306
0
    }
2307
2308
0
    if (Field == FieldEnd) {
2309
      // We've run out of fields. We're done.
2310
0
      break;
2311
0
    }
2312
2313
    // We've already initialized a member of a union. We're done.
2314
0
    if (InitializedSomething && RD->isUnion())
2315
0
      break;
2316
2317
    // If we've hit the flexible array member at the end, we're done.
2318
0
    if (Field->getType()->isIncompleteArrayType())
2319
0
      break;
2320
2321
0
    if (Field->isUnnamedBitfield()) {
2322
      // Don't initialize unnamed bitfields, e.g. "int : 20;"
2323
0
      ++Field;
2324
0
      continue;
2325
0
    }
2326
2327
    // Make sure we can use this declaration.
2328
0
    bool InvalidUse;
2329
0
    if (VerifyOnly)
2330
0
      InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2331
0
    else
2332
0
      InvalidUse = SemaRef.DiagnoseUseOfDecl(
2333
0
          *Field, IList->getInit(Index)->getBeginLoc());
2334
0
    if (InvalidUse) {
2335
0
      ++Index;
2336
0
      ++Field;
2337
0
      hadError = true;
2338
0
      continue;
2339
0
    }
2340
2341
0
    if (!VerifyOnly) {
2342
0
      QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2343
0
      if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2344
0
        hadError = true;
2345
0
        return;
2346
0
      }
2347
0
    }
2348
2349
0
    InitializedEntity MemberEntity =
2350
0
      InitializedEntity::InitializeMember(*Field, &Entity);
2351
0
    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2352
0
                        StructuredList, StructuredIndex);
2353
0
    InitializedSomething = true;
2354
0
    InitializedFields.insert(*Field);
2355
2356
0
    if (RD->isUnion() && StructuredList) {
2357
      // Initialize the first field within the union.
2358
0
      StructuredList->setInitializedFieldInUnion(*Field);
2359
0
    }
2360
2361
0
    ++Field;
2362
0
  }
2363
2364
  // Emit warnings for missing struct field initializers.
2365
0
  if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
2366
0
      !RD->isUnion()) {
2367
    // It is possible we have one or more unnamed bitfields remaining.
2368
    // Find first (if any) named field and emit warning.
2369
0
    for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
2370
0
                                                           : Field,
2371
0
                                    end = RD->field_end();
2372
0
         it != end; ++it) {
2373
0
      if (HasDesignatedInit && InitializedFields.count(*it))
2374
0
        continue;
2375
2376
0
      if (!it->isUnnamedBitfield() && !it->hasInClassInitializer() &&
2377
0
          !it->getType()->isIncompleteArrayType()) {
2378
0
        SemaRef.Diag(IList->getSourceRange().getEnd(),
2379
0
                     diag::warn_missing_field_initializers)
2380
0
            << *it;
2381
0
        break;
2382
0
      }
2383
0
    }
2384
0
  }
2385
2386
  // Check that any remaining fields can be value-initialized if we're not
2387
  // building a structured list. (If we are, we'll check this later.)
2388
0
  if (!StructuredList && Field != FieldEnd && !RD->isUnion() &&
2389
0
      !Field->getType()->isIncompleteArrayType()) {
2390
0
    for (; Field != FieldEnd && !hadError; ++Field) {
2391
0
      if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
2392
0
        CheckEmptyInitializable(
2393
0
            InitializedEntity::InitializeMember(*Field, &Entity),
2394
0
            IList->getEndLoc());
2395
0
    }
2396
0
  }
2397
2398
  // Check that the types of the remaining fields have accessible destructors.
2399
0
  if (!VerifyOnly) {
2400
    // If the initializer expression has a designated initializer, check the
2401
    // elements for which a designated initializer is not provided too.
2402
0
    RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin()
2403
0
                                                     : Field;
2404
0
    for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) {
2405
0
      QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2406
0
      if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2407
0
        hadError = true;
2408
0
        return;
2409
0
      }
2410
0
    }
2411
0
  }
2412
2413
0
  if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
2414
0
      Index >= IList->getNumInits())
2415
0
    return;
2416
2417
0
  if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2418
0
                             TopLevelObject)) {
2419
0
    hadError = true;
2420
0
    ++Index;
2421
0
    return;
2422
0
  }
2423
2424
0
  InitializedEntity MemberEntity =
2425
0
    InitializedEntity::InitializeMember(*Field, &Entity);
2426
2427
0
  if (isa<InitListExpr>(IList->getInit(Index)) ||
2428
0
      AggrDeductionCandidateParamTypes)
2429
0
    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2430
0
                        StructuredList, StructuredIndex);
2431
0
  else
2432
0
    CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2433
0
                          StructuredList, StructuredIndex);
2434
0
}
2435
2436
/// Expand a field designator that refers to a member of an
2437
/// anonymous struct or union into a series of field designators that
2438
/// refers to the field within the appropriate subobject.
2439
///
2440
static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2441
                                           DesignatedInitExpr *DIE,
2442
                                           unsigned DesigIdx,
2443
0
                                           IndirectFieldDecl *IndirectField) {
2444
0
  typedef DesignatedInitExpr::Designator Designator;
2445
2446
  // Build the replacement designators.
2447
0
  SmallVector<Designator, 4> Replacements;
2448
0
  for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2449
0
       PE = IndirectField->chain_end(); PI != PE; ++PI) {
2450
0
    if (PI + 1 == PE)
2451
0
      Replacements.push_back(Designator::CreateFieldDesignator(
2452
0
          (IdentifierInfo *)nullptr, DIE->getDesignator(DesigIdx)->getDotLoc(),
2453
0
          DIE->getDesignator(DesigIdx)->getFieldLoc()));
2454
0
    else
2455
0
      Replacements.push_back(Designator::CreateFieldDesignator(
2456
0
          (IdentifierInfo *)nullptr, SourceLocation(), SourceLocation()));
2457
0
    assert(isa<FieldDecl>(*PI));
2458
0
    Replacements.back().setFieldDecl(cast<FieldDecl>(*PI));
2459
0
  }
2460
2461
  // Expand the current designator into the set of replacement
2462
  // designators, so we have a full subobject path down to where the
2463
  // member of the anonymous struct/union is actually stored.
2464
0
  DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2465
0
                        &Replacements[0] + Replacements.size());
2466
0
}
2467
2468
static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2469
0
                                                   DesignatedInitExpr *DIE) {
2470
0
  unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2471
0
  SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2472
0
  for (unsigned I = 0; I < NumIndexExprs; ++I)
2473
0
    IndexExprs[I] = DIE->getSubExpr(I + 1);
2474
0
  return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2475
0
                                    IndexExprs,
2476
0
                                    DIE->getEqualOrColonLoc(),
2477
0
                                    DIE->usesGNUSyntax(), DIE->getInit());
2478
0
}
2479
2480
namespace {
2481
2482
// Callback to only accept typo corrections that are for field members of
2483
// the given struct or union.
2484
class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2485
 public:
2486
  explicit FieldInitializerValidatorCCC(const RecordDecl *RD)
2487
0
      : Record(RD) {}
2488
2489
0
  bool ValidateCandidate(const TypoCorrection &candidate) override {
2490
0
    FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2491
0
    return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
2492
0
  }
2493
2494
0
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
2495
0
    return std::make_unique<FieldInitializerValidatorCCC>(*this);
2496
0
  }
2497
2498
 private:
2499
  const RecordDecl *Record;
2500
};
2501
2502
} // end anonymous namespace
2503
2504
/// Check the well-formedness of a C99 designated initializer.
2505
///
2506
/// Determines whether the designated initializer @p DIE, which
2507
/// resides at the given @p Index within the initializer list @p
2508
/// IList, is well-formed for a current object of type @p DeclType
2509
/// (C99 6.7.8). The actual subobject that this designator refers to
2510
/// within the current subobject is returned in either
2511
/// @p NextField or @p NextElementIndex (whichever is appropriate).
2512
///
2513
/// @param IList  The initializer list in which this designated
2514
/// initializer occurs.
2515
///
2516
/// @param DIE The designated initializer expression.
2517
///
2518
/// @param DesigIdx  The index of the current designator.
2519
///
2520
/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2521
/// into which the designation in @p DIE should refer.
2522
///
2523
/// @param NextField  If non-NULL and the first designator in @p DIE is
2524
/// a field, this will be set to the field declaration corresponding
2525
/// to the field named by the designator. On input, this is expected to be
2526
/// the next field that would be initialized in the absence of designation,
2527
/// if the complete object being initialized is a struct.
2528
///
2529
/// @param NextElementIndex  If non-NULL and the first designator in @p
2530
/// DIE is an array designator or GNU array-range designator, this
2531
/// will be set to the last index initialized by this designator.
2532
///
2533
/// @param Index  Index into @p IList where the designated initializer
2534
/// @p DIE occurs.
2535
///
2536
/// @param StructuredList  The initializer list expression that
2537
/// describes all of the subobject initializers in the order they'll
2538
/// actually be initialized.
2539
///
2540
/// @returns true if there was an error, false otherwise.
2541
bool
2542
InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2543
                                            InitListExpr *IList,
2544
                                            DesignatedInitExpr *DIE,
2545
                                            unsigned DesigIdx,
2546
                                            QualType &CurrentObjectType,
2547
                                          RecordDecl::field_iterator *NextField,
2548
                                            llvm::APSInt *NextElementIndex,
2549
                                            unsigned &Index,
2550
                                            InitListExpr *StructuredList,
2551
                                            unsigned &StructuredIndex,
2552
                                            bool FinishSubobjectInit,
2553
0
                                            bool TopLevelObject) {
2554
0
  if (DesigIdx == DIE->size()) {
2555
    // C++20 designated initialization can result in direct-list-initialization
2556
    // of the designated subobject. This is the only way that we can end up
2557
    // performing direct initialization as part of aggregate initialization, so
2558
    // it needs special handling.
2559
0
    if (DIE->isDirectInit()) {
2560
0
      Expr *Init = DIE->getInit();
2561
0
      assert(isa<InitListExpr>(Init) &&
2562
0
             "designator result in direct non-list initialization?");
2563
0
      InitializationKind Kind = InitializationKind::CreateDirectList(
2564
0
          DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2565
0
      InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2566
0
                                 /*TopLevelOfInitList*/ true);
2567
0
      if (StructuredList) {
2568
0
        ExprResult Result = VerifyOnly
2569
0
                                ? getDummyInit()
2570
0
                                : Seq.Perform(SemaRef, Entity, Kind, Init);
2571
0
        UpdateStructuredListElement(StructuredList, StructuredIndex,
2572
0
                                    Result.get());
2573
0
      }
2574
0
      ++Index;
2575
0
      if (AggrDeductionCandidateParamTypes)
2576
0
        AggrDeductionCandidateParamTypes->push_back(CurrentObjectType);
2577
0
      return !Seq;
2578
0
    }
2579
2580
    // Check the actual initialization for the designated object type.
2581
0
    bool prevHadError = hadError;
2582
2583
    // Temporarily remove the designator expression from the
2584
    // initializer list that the child calls see, so that we don't try
2585
    // to re-process the designator.
2586
0
    unsigned OldIndex = Index;
2587
0
    IList->setInit(OldIndex, DIE->getInit());
2588
2589
0
    CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2590
0
                        StructuredIndex, /*DirectlyDesignated=*/true);
2591
2592
    // Restore the designated initializer expression in the syntactic
2593
    // form of the initializer list.
2594
0
    if (IList->getInit(OldIndex) != DIE->getInit())
2595
0
      DIE->setInit(IList->getInit(OldIndex));
2596
0
    IList->setInit(OldIndex, DIE);
2597
2598
0
    return hadError && !prevHadError;
2599
0
  }
2600
2601
0
  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2602
0
  bool IsFirstDesignator = (DesigIdx == 0);
2603
0
  if (IsFirstDesignator ? FullyStructuredList : StructuredList) {
2604
    // Determine the structural initializer list that corresponds to the
2605
    // current subobject.
2606
0
    if (IsFirstDesignator)
2607
0
      StructuredList = FullyStructuredList;
2608
0
    else {
2609
0
      Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2610
0
          StructuredList->getInit(StructuredIndex) : nullptr;
2611
0
      if (!ExistingInit && StructuredList->hasArrayFiller())
2612
0
        ExistingInit = StructuredList->getArrayFiller();
2613
2614
0
      if (!ExistingInit)
2615
0
        StructuredList = getStructuredSubobjectInit(
2616
0
            IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2617
0
            SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2618
0
      else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2619
0
        StructuredList = Result;
2620
0
      else {
2621
        // We are creating an initializer list that initializes the
2622
        // subobjects of the current object, but there was already an
2623
        // initialization that completely initialized the current
2624
        // subobject, e.g., by a compound literal:
2625
        //
2626
        // struct X { int a, b; };
2627
        // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2628
        //
2629
        // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2630
        // designated initializer re-initializes only its current object
2631
        // subobject [0].b.
2632
0
        diagnoseInitOverride(ExistingInit,
2633
0
                             SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2634
0
                             /*UnionOverride=*/false,
2635
0
                             /*FullyOverwritten=*/false);
2636
2637
0
        if (!VerifyOnly) {
2638
0
          if (DesignatedInitUpdateExpr *E =
2639
0
                  dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2640
0
            StructuredList = E->getUpdater();
2641
0
          else {
2642
0
            DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2643
0
                DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2644
0
                                         ExistingInit, DIE->getEndLoc());
2645
0
            StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2646
0
            StructuredList = DIUE->getUpdater();
2647
0
          }
2648
0
        } else {
2649
          // We don't need to track the structured representation of a
2650
          // designated init update of an already-fully-initialized object in
2651
          // verify-only mode. The only reason we would need the structure is
2652
          // to determine where the uninitialized "holes" are, and in this
2653
          // case, we know there aren't any and we can't introduce any.
2654
0
          StructuredList = nullptr;
2655
0
        }
2656
0
      }
2657
0
    }
2658
0
  }
2659
2660
0
  if (D->isFieldDesignator()) {
2661
    // C99 6.7.8p7:
2662
    //
2663
    //   If a designator has the form
2664
    //
2665
    //      . identifier
2666
    //
2667
    //   then the current object (defined below) shall have
2668
    //   structure or union type and the identifier shall be the
2669
    //   name of a member of that type.
2670
0
    RecordDecl *RD = getRecordDecl(CurrentObjectType);
2671
0
    if (!RD) {
2672
0
      SourceLocation Loc = D->getDotLoc();
2673
0
      if (Loc.isInvalid())
2674
0
        Loc = D->getFieldLoc();
2675
0
      if (!VerifyOnly)
2676
0
        SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2677
0
          << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2678
0
      ++Index;
2679
0
      return true;
2680
0
    }
2681
2682
0
    FieldDecl *KnownField = D->getFieldDecl();
2683
0
    if (!KnownField) {
2684
0
      const IdentifierInfo *FieldName = D->getFieldName();
2685
0
      ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(RD, FieldName);
2686
0
      if (auto *FD = dyn_cast_if_present<FieldDecl>(VD)) {
2687
0
        KnownField = FD;
2688
0
      } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(VD)) {
2689
        // In verify mode, don't modify the original.
2690
0
        if (VerifyOnly)
2691
0
          DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2692
0
        ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2693
0
        D = DIE->getDesignator(DesigIdx);
2694
0
        KnownField = cast<FieldDecl>(*IFD->chain_begin());
2695
0
      }
2696
0
      if (!KnownField) {
2697
0
        if (VerifyOnly) {
2698
0
          ++Index;
2699
0
          return true;  // No typo correction when just trying this out.
2700
0
        }
2701
2702
        // We found a placeholder variable
2703
0
        if (SemaRef.DiagRedefinedPlaceholderFieldDecl(DIE->getBeginLoc(), RD,
2704
0
                                                      FieldName)) {
2705
0
          ++Index;
2706
0
          return true;
2707
0
        }
2708
        // Name lookup found something, but it wasn't a field.
2709
0
        if (DeclContextLookupResult Lookup = RD->lookup(FieldName);
2710
0
            !Lookup.empty()) {
2711
0
          SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2712
0
              << FieldName;
2713
0
          SemaRef.Diag(Lookup.front()->getLocation(),
2714
0
                       diag::note_field_designator_found);
2715
0
          ++Index;
2716
0
          return true;
2717
0
        }
2718
2719
        // Name lookup didn't find anything.
2720
        // Determine whether this was a typo for another field name.
2721
0
        FieldInitializerValidatorCCC CCC(RD);
2722
0
        if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2723
0
                DeclarationNameInfo(FieldName, D->getFieldLoc()),
2724
0
                Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2725
0
                Sema::CTK_ErrorRecovery, RD)) {
2726
0
          SemaRef.diagnoseTypo(
2727
0
              Corrected,
2728
0
              SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2729
0
                << FieldName << CurrentObjectType);
2730
0
          KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2731
0
          hadError = true;
2732
0
        } else {
2733
          // Typo correction didn't find anything.
2734
0
          SourceLocation Loc = D->getFieldLoc();
2735
2736
          // The loc can be invalid with a "null" designator (i.e. an anonymous
2737
          // union/struct). Do our best to approximate the location.
2738
0
          if (Loc.isInvalid())
2739
0
            Loc = IList->getBeginLoc();
2740
2741
0
          SemaRef.Diag(Loc, diag::err_field_designator_unknown)
2742
0
            << FieldName << CurrentObjectType << DIE->getSourceRange();
2743
0
          ++Index;
2744
0
          return true;
2745
0
        }
2746
0
      }
2747
0
    }
2748
2749
0
    unsigned NumBases = 0;
2750
0
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2751
0
      NumBases = CXXRD->getNumBases();
2752
2753
0
    unsigned FieldIndex = NumBases;
2754
2755
0
    for (auto *FI : RD->fields()) {
2756
0
      if (FI->isUnnamedBitfield())
2757
0
        continue;
2758
0
      if (declaresSameEntity(KnownField, FI)) {
2759
0
        KnownField = FI;
2760
0
        break;
2761
0
      }
2762
0
      ++FieldIndex;
2763
0
    }
2764
2765
0
    RecordDecl::field_iterator Field =
2766
0
        RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2767
2768
    // All of the fields of a union are located at the same place in
2769
    // the initializer list.
2770
0
    if (RD->isUnion()) {
2771
0
      FieldIndex = 0;
2772
0
      if (StructuredList) {
2773
0
        FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2774
0
        if (CurrentField && !declaresSameEntity(CurrentField, *Field)) {
2775
0
          assert(StructuredList->getNumInits() == 1
2776
0
                 && "A union should never have more than one initializer!");
2777
2778
0
          Expr *ExistingInit = StructuredList->getInit(0);
2779
0
          if (ExistingInit) {
2780
            // We're about to throw away an initializer, emit warning.
2781
0
            diagnoseInitOverride(
2782
0
                ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2783
0
                /*UnionOverride=*/true,
2784
0
                /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false
2785
0
                                                                     : true);
2786
0
          }
2787
2788
          // remove existing initializer
2789
0
          StructuredList->resizeInits(SemaRef.Context, 0);
2790
0
          StructuredList->setInitializedFieldInUnion(nullptr);
2791
0
        }
2792
2793
0
        StructuredList->setInitializedFieldInUnion(*Field);
2794
0
      }
2795
0
    }
2796
2797
    // Make sure we can use this declaration.
2798
0
    bool InvalidUse;
2799
0
    if (VerifyOnly)
2800
0
      InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2801
0
    else
2802
0
      InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2803
0
    if (InvalidUse) {
2804
0
      ++Index;
2805
0
      return true;
2806
0
    }
2807
2808
    // C++20 [dcl.init.list]p3:
2809
    //   The ordered identifiers in the designators of the designated-
2810
    //   initializer-list shall form a subsequence of the ordered identifiers
2811
    //   in the direct non-static data members of T.
2812
    //
2813
    // Note that this is not a condition on forming the aggregate
2814
    // initialization, only on actually performing initialization,
2815
    // so it is not checked in VerifyOnly mode.
2816
    //
2817
    // FIXME: This is the only reordering diagnostic we produce, and it only
2818
    // catches cases where we have a top-level field designator that jumps
2819
    // backwards. This is the only such case that is reachable in an
2820
    // otherwise-valid C++20 program, so is the only case that's required for
2821
    // conformance, but for consistency, we should diagnose all the other
2822
    // cases where a designator takes us backwards too.
2823
0
    if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus &&
2824
0
        NextField &&
2825
0
        (*NextField == RD->field_end() ||
2826
0
         (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) {
2827
      // Find the field that we just initialized.
2828
0
      FieldDecl *PrevField = nullptr;
2829
0
      for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) {
2830
0
        if (FI->isUnnamedBitfield())
2831
0
          continue;
2832
0
        if (*NextField != RD->field_end() &&
2833
0
            declaresSameEntity(*FI, **NextField))
2834
0
          break;
2835
0
        PrevField = *FI;
2836
0
      }
2837
2838
0
      if (PrevField &&
2839
0
          PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2840
0
        SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2841
0
                     diag::ext_designated_init_reordered)
2842
0
            << KnownField << PrevField << DIE->getSourceRange();
2843
2844
0
        unsigned OldIndex = StructuredIndex - 1;
2845
0
        if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2846
0
          if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2847
0
            SemaRef.Diag(PrevInit->getBeginLoc(),
2848
0
                         diag::note_previous_field_init)
2849
0
                << PrevField << PrevInit->getSourceRange();
2850
0
          }
2851
0
        }
2852
0
      }
2853
0
    }
2854
2855
2856
    // Update the designator with the field declaration.
2857
0
    if (!VerifyOnly)
2858
0
      D->setFieldDecl(*Field);
2859
2860
    // Make sure that our non-designated initializer list has space
2861
    // for a subobject corresponding to this field.
2862
0
    if (StructuredList && FieldIndex >= StructuredList->getNumInits())
2863
0
      StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2864
2865
    // This designator names a flexible array member.
2866
0
    if (Field->getType()->isIncompleteArrayType()) {
2867
0
      bool Invalid = false;
2868
0
      if ((DesigIdx + 1) != DIE->size()) {
2869
        // We can't designate an object within the flexible array
2870
        // member (because GCC doesn't allow it).
2871
0
        if (!VerifyOnly) {
2872
0
          DesignatedInitExpr::Designator *NextD
2873
0
            = DIE->getDesignator(DesigIdx + 1);
2874
0
          SemaRef.Diag(NextD->getBeginLoc(),
2875
0
                       diag::err_designator_into_flexible_array_member)
2876
0
              << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2877
0
          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2878
0
            << *Field;
2879
0
        }
2880
0
        Invalid = true;
2881
0
      }
2882
2883
0
      if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2884
0
          !isa<StringLiteral>(DIE->getInit())) {
2885
        // The initializer is not an initializer list.
2886
0
        if (!VerifyOnly) {
2887
0
          SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2888
0
                       diag::err_flexible_array_init_needs_braces)
2889
0
              << DIE->getInit()->getSourceRange();
2890
0
          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2891
0
            << *Field;
2892
0
        }
2893
0
        Invalid = true;
2894
0
      }
2895
2896
      // Check GNU flexible array initializer.
2897
0
      if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2898
0
                                             TopLevelObject))
2899
0
        Invalid = true;
2900
2901
0
      if (Invalid) {
2902
0
        ++Index;
2903
0
        return true;
2904
0
      }
2905
2906
      // Initialize the array.
2907
0
      bool prevHadError = hadError;
2908
0
      unsigned newStructuredIndex = FieldIndex;
2909
0
      unsigned OldIndex = Index;
2910
0
      IList->setInit(Index, DIE->getInit());
2911
2912
0
      InitializedEntity MemberEntity =
2913
0
        InitializedEntity::InitializeMember(*Field, &Entity);
2914
0
      CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2915
0
                          StructuredList, newStructuredIndex);
2916
2917
0
      IList->setInit(OldIndex, DIE);
2918
0
      if (hadError && !prevHadError) {
2919
0
        ++Field;
2920
0
        ++FieldIndex;
2921
0
        if (NextField)
2922
0
          *NextField = Field;
2923
0
        StructuredIndex = FieldIndex;
2924
0
        return true;
2925
0
      }
2926
0
    } else {
2927
      // Recurse to check later designated subobjects.
2928
0
      QualType FieldType = Field->getType();
2929
0
      unsigned newStructuredIndex = FieldIndex;
2930
2931
0
      InitializedEntity MemberEntity =
2932
0
        InitializedEntity::InitializeMember(*Field, &Entity);
2933
0
      if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2934
0
                                     FieldType, nullptr, nullptr, Index,
2935
0
                                     StructuredList, newStructuredIndex,
2936
0
                                     FinishSubobjectInit, false))
2937
0
        return true;
2938
0
    }
2939
2940
    // Find the position of the next field to be initialized in this
2941
    // subobject.
2942
0
    ++Field;
2943
0
    ++FieldIndex;
2944
2945
    // If this the first designator, our caller will continue checking
2946
    // the rest of this struct/class/union subobject.
2947
0
    if (IsFirstDesignator) {
2948
0
      if (Field != RD->field_end() && Field->isUnnamedBitfield())
2949
0
        ++Field;
2950
2951
0
      if (NextField)
2952
0
        *NextField = Field;
2953
2954
0
      StructuredIndex = FieldIndex;
2955
0
      return false;
2956
0
    }
2957
2958
0
    if (!FinishSubobjectInit)
2959
0
      return false;
2960
2961
    // We've already initialized something in the union; we're done.
2962
0
    if (RD->isUnion())
2963
0
      return hadError;
2964
2965
    // Check the remaining fields within this class/struct/union subobject.
2966
0
    bool prevHadError = hadError;
2967
2968
0
    auto NoBases =
2969
0
        CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2970
0
                                        CXXRecordDecl::base_class_iterator());
2971
0
    CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2972
0
                          false, Index, StructuredList, FieldIndex);
2973
0
    return hadError && !prevHadError;
2974
0
  }
2975
2976
  // C99 6.7.8p6:
2977
  //
2978
  //   If a designator has the form
2979
  //
2980
  //      [ constant-expression ]
2981
  //
2982
  //   then the current object (defined below) shall have array
2983
  //   type and the expression shall be an integer constant
2984
  //   expression. If the array is of unknown size, any
2985
  //   nonnegative value is valid.
2986
  //
2987
  // Additionally, cope with the GNU extension that permits
2988
  // designators of the form
2989
  //
2990
  //      [ constant-expression ... constant-expression ]
2991
0
  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2992
0
  if (!AT) {
2993
0
    if (!VerifyOnly)
2994
0
      SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2995
0
        << CurrentObjectType;
2996
0
    ++Index;
2997
0
    return true;
2998
0
  }
2999
3000
0
  Expr *IndexExpr = nullptr;
3001
0
  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
3002
0
  if (D->isArrayDesignator()) {
3003
0
    IndexExpr = DIE->getArrayIndex(*D);
3004
0
    DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
3005
0
    DesignatedEndIndex = DesignatedStartIndex;
3006
0
  } else {
3007
0
    assert(D->isArrayRangeDesignator() && "Need array-range designator");
3008
3009
0
    DesignatedStartIndex =
3010
0
      DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
3011
0
    DesignatedEndIndex =
3012
0
      DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
3013
0
    IndexExpr = DIE->getArrayRangeEnd(*D);
3014
3015
    // Codegen can't handle evaluating array range designators that have side
3016
    // effects, because we replicate the AST value for each initialized element.
3017
    // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
3018
    // elements with something that has a side effect, so codegen can emit an
3019
    // "error unsupported" error instead of miscompiling the app.
3020
0
    if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
3021
0
        DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
3022
0
      FullyStructuredList->sawArrayRangeDesignator();
3023
0
  }
3024
3025
0
  if (isa<ConstantArrayType>(AT)) {
3026
0
    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
3027
0
    DesignatedStartIndex
3028
0
      = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
3029
0
    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
3030
0
    DesignatedEndIndex
3031
0
      = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
3032
0
    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
3033
0
    if (DesignatedEndIndex >= MaxElements) {
3034
0
      if (!VerifyOnly)
3035
0
        SemaRef.Diag(IndexExpr->getBeginLoc(),
3036
0
                     diag::err_array_designator_too_large)
3037
0
            << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
3038
0
            << IndexExpr->getSourceRange();
3039
0
      ++Index;
3040
0
      return true;
3041
0
    }
3042
0
  } else {
3043
0
    unsigned DesignatedIndexBitWidth =
3044
0
      ConstantArrayType::getMaxSizeBits(SemaRef.Context);
3045
0
    DesignatedStartIndex =
3046
0
      DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
3047
0
    DesignatedEndIndex =
3048
0
      DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
3049
0
    DesignatedStartIndex.setIsUnsigned(true);
3050
0
    DesignatedEndIndex.setIsUnsigned(true);
3051
0
  }
3052
3053
0
  bool IsStringLiteralInitUpdate =
3054
0
      StructuredList && StructuredList->isStringLiteralInit();
3055
0
  if (IsStringLiteralInitUpdate && VerifyOnly) {
3056
    // We're just verifying an update to a string literal init. We don't need
3057
    // to split the string up into individual characters to do that.
3058
0
    StructuredList = nullptr;
3059
0
  } else if (IsStringLiteralInitUpdate) {
3060
    // We're modifying a string literal init; we have to decompose the string
3061
    // so we can modify the individual characters.
3062
0
    ASTContext &Context = SemaRef.Context;
3063
0
    Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
3064
3065
    // Compute the character type
3066
0
    QualType CharTy = AT->getElementType();
3067
3068
    // Compute the type of the integer literals.
3069
0
    QualType PromotedCharTy = CharTy;
3070
0
    if (Context.isPromotableIntegerType(CharTy))
3071
0
      PromotedCharTy = Context.getPromotedIntegerType(CharTy);
3072
0
    unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
3073
3074
0
    if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
3075
      // Get the length of the string.
3076
0
      uint64_t StrLen = SL->getLength();
3077
0
      if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3078
0
        StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
3079
0
      StructuredList->resizeInits(Context, StrLen);
3080
3081
      // Build a literal for each character in the string, and put them into
3082
      // the init list.
3083
0
      for (unsigned i = 0, e = StrLen; i != e; ++i) {
3084
0
        llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
3085
0
        Expr *Init = new (Context) IntegerLiteral(
3086
0
            Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3087
0
        if (CharTy != PromotedCharTy)
3088
0
          Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3089
0
                                          Init, nullptr, VK_PRValue,
3090
0
                                          FPOptionsOverride());
3091
0
        StructuredList->updateInit(Context, i, Init);
3092
0
      }
3093
0
    } else {
3094
0
      ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
3095
0
      std::string Str;
3096
0
      Context.getObjCEncodingForType(E->getEncodedType(), Str);
3097
3098
      // Get the length of the string.
3099
0
      uint64_t StrLen = Str.size();
3100
0
      if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
3101
0
        StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
3102
0
      StructuredList->resizeInits(Context, StrLen);
3103
3104
      // Build a literal for each character in the string, and put them into
3105
      // the init list.
3106
0
      for (unsigned i = 0, e = StrLen; i != e; ++i) {
3107
0
        llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
3108
0
        Expr *Init = new (Context) IntegerLiteral(
3109
0
            Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
3110
0
        if (CharTy != PromotedCharTy)
3111
0
          Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
3112
0
                                          Init, nullptr, VK_PRValue,
3113
0
                                          FPOptionsOverride());
3114
0
        StructuredList->updateInit(Context, i, Init);
3115
0
      }
3116
0
    }
3117
0
  }
3118
3119
  // Make sure that our non-designated initializer list has space
3120
  // for a subobject corresponding to this array element.
3121
0
  if (StructuredList &&
3122
0
      DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
3123
0
    StructuredList->resizeInits(SemaRef.Context,
3124
0
                                DesignatedEndIndex.getZExtValue() + 1);
3125
3126
  // Repeatedly perform subobject initializations in the range
3127
  // [DesignatedStartIndex, DesignatedEndIndex].
3128
3129
  // Move to the next designator
3130
0
  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
3131
0
  unsigned OldIndex = Index;
3132
3133
0
  InitializedEntity ElementEntity =
3134
0
    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
3135
3136
0
  while (DesignatedStartIndex <= DesignatedEndIndex) {
3137
    // Recurse to check later designated subobjects.
3138
0
    QualType ElementType = AT->getElementType();
3139
0
    Index = OldIndex;
3140
3141
0
    ElementEntity.setElementIndex(ElementIndex);
3142
0
    if (CheckDesignatedInitializer(
3143
0
            ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3144
0
            nullptr, Index, StructuredList, ElementIndex,
3145
0
            FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex),
3146
0
            false))
3147
0
      return true;
3148
3149
    // Move to the next index in the array that we'll be initializing.
3150
0
    ++DesignatedStartIndex;
3151
0
    ElementIndex = DesignatedStartIndex.getZExtValue();
3152
0
  }
3153
3154
  // If this the first designator, our caller will continue checking
3155
  // the rest of this array subobject.
3156
0
  if (IsFirstDesignator) {
3157
0
    if (NextElementIndex)
3158
0
      *NextElementIndex = DesignatedStartIndex;
3159
0
    StructuredIndex = ElementIndex;
3160
0
    return false;
3161
0
  }
3162
3163
0
  if (!FinishSubobjectInit)
3164
0
    return false;
3165
3166
  // Check the remaining elements within this array subobject.
3167
0
  bool prevHadError = hadError;
3168
0
  CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3169
0
                 /*SubobjectIsDesignatorContext=*/false, Index,
3170
0
                 StructuredList, ElementIndex);
3171
0
  return hadError && !prevHadError;
3172
0
}
3173
3174
// Get the structured initializer list for a subobject of type
3175
// @p CurrentObjectType.
3176
InitListExpr *
3177
InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3178
                                            QualType CurrentObjectType,
3179
                                            InitListExpr *StructuredList,
3180
                                            unsigned StructuredIndex,
3181
                                            SourceRange InitRange,
3182
0
                                            bool IsFullyOverwritten) {
3183
0
  if (!StructuredList)
3184
0
    return nullptr;
3185
3186
0
  Expr *ExistingInit = nullptr;
3187
0
  if (StructuredIndex < StructuredList->getNumInits())
3188
0
    ExistingInit = StructuredList->getInit(StructuredIndex);
3189
3190
0
  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3191
    // There might have already been initializers for subobjects of the current
3192
    // object, but a subsequent initializer list will overwrite the entirety
3193
    // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3194
    //
3195
    // struct P { char x[6]; };
3196
    // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3197
    //
3198
    // The first designated initializer is ignored, and l.x is just "f".
3199
0
    if (!IsFullyOverwritten)
3200
0
      return Result;
3201
3202
0
  if (ExistingInit) {
3203
    // We are creating an initializer list that initializes the
3204
    // subobjects of the current object, but there was already an
3205
    // initialization that completely initialized the current
3206
    // subobject:
3207
    //
3208
    // struct X { int a, b; };
3209
    // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3210
    //
3211
    // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3212
    // designated initializer overwrites the [0].b initializer
3213
    // from the prior initialization.
3214
    //
3215
    // When the existing initializer is an expression rather than an
3216
    // initializer list, we cannot decompose and update it in this way.
3217
    // For example:
3218
    //
3219
    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3220
    //
3221
    // This case is handled by CheckDesignatedInitializer.
3222
0
    diagnoseInitOverride(ExistingInit, InitRange);
3223
0
  }
3224
3225
0
  unsigned ExpectedNumInits = 0;
3226
0
  if (Index < IList->getNumInits()) {
3227
0
    if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3228
0
      ExpectedNumInits = Init->getNumInits();
3229
0
    else
3230
0
      ExpectedNumInits = IList->getNumInits() - Index;
3231
0
  }
3232
3233
0
  InitListExpr *Result =
3234
0
      createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3235
3236
  // Link this new initializer list into the structured initializer
3237
  // lists.
3238
0
  StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3239
0
  return Result;
3240
0
}
3241
3242
InitListExpr *
3243
InitListChecker::createInitListExpr(QualType CurrentObjectType,
3244
                                    SourceRange InitRange,
3245
0
                                    unsigned ExpectedNumInits) {
3246
0
  InitListExpr *Result = new (SemaRef.Context) InitListExpr(
3247
0
      SemaRef.Context, InitRange.getBegin(), std::nullopt, InitRange.getEnd());
3248
3249
0
  QualType ResultType = CurrentObjectType;
3250
0
  if (!ResultType->isArrayType())
3251
0
    ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3252
0
  Result->setType(ResultType);
3253
3254
  // Pre-allocate storage for the structured initializer list.
3255
0
  unsigned NumElements = 0;
3256
3257
0
  if (const ArrayType *AType
3258
0
      = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3259
0
    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3260
0
      NumElements = CAType->getSize().getZExtValue();
3261
      // Simple heuristic so that we don't allocate a very large
3262
      // initializer with many empty entries at the end.
3263
0
      if (NumElements > ExpectedNumInits)
3264
0
        NumElements = 0;
3265
0
    }
3266
0
  } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3267
0
    NumElements = VType->getNumElements();
3268
0
  } else if (CurrentObjectType->isRecordType()) {
3269
0
    NumElements = numStructUnionElements(CurrentObjectType);
3270
0
  } else if (CurrentObjectType->isDependentType()) {
3271
0
    NumElements = 1;
3272
0
  }
3273
3274
0
  Result->reserveInits(SemaRef.Context, NumElements);
3275
3276
0
  return Result;
3277
0
}
3278
3279
/// Update the initializer at index @p StructuredIndex within the
3280
/// structured initializer list to the value @p expr.
3281
void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3282
                                                  unsigned &StructuredIndex,
3283
0
                                                  Expr *expr) {
3284
  // No structured initializer list to update
3285
0
  if (!StructuredList)
3286
0
    return;
3287
3288
0
  if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3289
0
                                                  StructuredIndex, expr)) {
3290
    // This initializer overwrites a previous initializer.
3291
    // No need to diagnose when `expr` is nullptr because a more relevant
3292
    // diagnostic has already been issued and this diagnostic is potentially
3293
    // noise.
3294
0
    if (expr)
3295
0
      diagnoseInitOverride(PrevInit, expr->getSourceRange());
3296
0
  }
3297
3298
0
  ++StructuredIndex;
3299
0
}
3300
3301
/// Determine whether we can perform aggregate initialization for the purposes
3302
/// of overload resolution.
3303
bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3304
0
    const InitializedEntity &Entity, InitListExpr *From) {
3305
0
  QualType Type = Entity.getType();
3306
0
  InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3307
0
                        /*TreatUnavailableAsInvalid=*/false,
3308
0
                        /*InOverloadResolution=*/true);
3309
0
  return !Check.HadError();
3310
0
}
3311
3312
/// Check that the given Index expression is a valid array designator
3313
/// value. This is essentially just a wrapper around
3314
/// VerifyIntegerConstantExpression that also checks for negative values
3315
/// and produces a reasonable diagnostic if there is a
3316
/// failure. Returns the index expression, possibly with an implicit cast
3317
/// added, on success.  If everything went okay, Value will receive the
3318
/// value of the constant expression.
3319
static ExprResult
3320
0
CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3321
0
  SourceLocation Loc = Index->getBeginLoc();
3322
3323
  // Make sure this is an integer constant expression.
3324
0
  ExprResult Result =
3325
0
      S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold);
3326
0
  if (Result.isInvalid())
3327
0
    return Result;
3328
3329
0
  if (Value.isSigned() && Value.isNegative())
3330
0
    return S.Diag(Loc, diag::err_array_designator_negative)
3331
0
           << toString(Value, 10) << Index->getSourceRange();
3332
3333
0
  Value.setIsUnsigned(true);
3334
0
  return Result;
3335
0
}
3336
3337
ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
3338
                                            SourceLocation EqualOrColonLoc,
3339
                                            bool GNUSyntax,
3340
1
                                            ExprResult Init) {
3341
1
  typedef DesignatedInitExpr::Designator ASTDesignator;
3342
3343
1
  bool Invalid = false;
3344
1
  SmallVector<ASTDesignator, 32> Designators;
3345
1
  SmallVector<Expr *, 32> InitExpressions;
3346
3347
  // Build designators and check array designator expressions.
3348
2
  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
3349
1
    const Designator &D = Desig.getDesignator(Idx);
3350
3351
1
    if (D.isFieldDesignator()) {
3352
1
      Designators.push_back(ASTDesignator::CreateFieldDesignator(
3353
1
          D.getFieldDecl(), D.getDotLoc(), D.getFieldLoc()));
3354
1
    } else if (D.isArrayDesignator()) {
3355
0
      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3356
0
      llvm::APSInt IndexValue;
3357
0
      if (!Index->isTypeDependent() && !Index->isValueDependent())
3358
0
        Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3359
0
      if (!Index)
3360
0
        Invalid = true;
3361
0
      else {
3362
0
        Designators.push_back(ASTDesignator::CreateArrayDesignator(
3363
0
            InitExpressions.size(), D.getLBracketLoc(), D.getRBracketLoc()));
3364
0
        InitExpressions.push_back(Index);
3365
0
      }
3366
0
    } else if (D.isArrayRangeDesignator()) {
3367
0
      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3368
0
      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3369
0
      llvm::APSInt StartValue;
3370
0
      llvm::APSInt EndValue;
3371
0
      bool StartDependent = StartIndex->isTypeDependent() ||
3372
0
                            StartIndex->isValueDependent();
3373
0
      bool EndDependent = EndIndex->isTypeDependent() ||
3374
0
                          EndIndex->isValueDependent();
3375
0
      if (!StartDependent)
3376
0
        StartIndex =
3377
0
            CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3378
0
      if (!EndDependent)
3379
0
        EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3380
3381
0
      if (!StartIndex || !EndIndex)
3382
0
        Invalid = true;
3383
0
      else {
3384
        // Make sure we're comparing values with the same bit width.
3385
0
        if (StartDependent || EndDependent) {
3386
          // Nothing to compute.
3387
0
        } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3388
0
          EndValue = EndValue.extend(StartValue.getBitWidth());
3389
0
        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3390
0
          StartValue = StartValue.extend(EndValue.getBitWidth());
3391
3392
0
        if (!StartDependent && !EndDependent && EndValue < StartValue) {
3393
0
          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3394
0
            << toString(StartValue, 10) << toString(EndValue, 10)
3395
0
            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3396
0
          Invalid = true;
3397
0
        } else {
3398
0
          Designators.push_back(ASTDesignator::CreateArrayRangeDesignator(
3399
0
              InitExpressions.size(), D.getLBracketLoc(), D.getEllipsisLoc(),
3400
0
              D.getRBracketLoc()));
3401
0
          InitExpressions.push_back(StartIndex);
3402
0
          InitExpressions.push_back(EndIndex);
3403
0
        }
3404
0
      }
3405
0
    }
3406
1
  }
3407
3408
1
  if (Invalid || Init.isInvalid())
3409
1
    return ExprError();
3410
3411
0
  return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3412
0
                                    EqualOrColonLoc, GNUSyntax,
3413
0
                                    Init.getAs<Expr>());
3414
1
}
3415
3416
//===----------------------------------------------------------------------===//
3417
// Initialization entity
3418
//===----------------------------------------------------------------------===//
3419
3420
InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3421
                                     const InitializedEntity &Parent)
3422
  : Parent(&Parent), Index(Index)
3423
0
{
3424
0
  if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3425
0
    Kind = EK_ArrayElement;
3426
0
    Type = AT->getElementType();
3427
0
  } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3428
0
    Kind = EK_VectorElement;
3429
0
    Type = VT->getElementType();
3430
0
  } else {
3431
0
    const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3432
0
    assert(CT && "Unexpected type");
3433
0
    Kind = EK_ComplexElement;
3434
0
    Type = CT->getElementType();
3435
0
  }
3436
0
}
3437
3438
InitializedEntity
3439
InitializedEntity::InitializeBase(ASTContext &Context,
3440
                                  const CXXBaseSpecifier *Base,
3441
                                  bool IsInheritedVirtualBase,
3442
0
                                  const InitializedEntity *Parent) {
3443
0
  InitializedEntity Result;
3444
0
  Result.Kind = EK_Base;
3445
0
  Result.Parent = Parent;
3446
0
  Result.Base = {Base, IsInheritedVirtualBase};
3447
0
  Result.Type = Base->getType();
3448
0
  return Result;
3449
0
}
3450
3451
0
DeclarationName InitializedEntity::getName() const {
3452
0
  switch (getKind()) {
3453
0
  case EK_Parameter:
3454
0
  case EK_Parameter_CF_Audited: {
3455
0
    ParmVarDecl *D = Parameter.getPointer();
3456
0
    return (D ? D->getDeclName() : DeclarationName());
3457
0
  }
3458
3459
0
  case EK_Variable:
3460
0
  case EK_Member:
3461
0
  case EK_ParenAggInitMember:
3462
0
  case EK_Binding:
3463
0
  case EK_TemplateParameter:
3464
0
    return Variable.VariableOrMember->getDeclName();
3465
3466
0
  case EK_LambdaCapture:
3467
0
    return DeclarationName(Capture.VarID);
3468
3469
0
  case EK_Result:
3470
0
  case EK_StmtExprResult:
3471
0
  case EK_Exception:
3472
0
  case EK_New:
3473
0
  case EK_Temporary:
3474
0
  case EK_Base:
3475
0
  case EK_Delegating:
3476
0
  case EK_ArrayElement:
3477
0
  case EK_VectorElement:
3478
0
  case EK_ComplexElement:
3479
0
  case EK_BlockElement:
3480
0
  case EK_LambdaToBlockConversionBlockElement:
3481
0
  case EK_CompoundLiteralInit:
3482
0
  case EK_RelatedResult:
3483
0
    return DeclarationName();
3484
0
  }
3485
3486
0
  llvm_unreachable("Invalid EntityKind!");
3487
0
}
3488
3489
14
ValueDecl *InitializedEntity::getDecl() const {
3490
14
  switch (getKind()) {
3491
14
  case EK_Variable:
3492
14
  case EK_Member:
3493
14
  case EK_ParenAggInitMember:
3494
14
  case EK_Binding:
3495
14
  case EK_TemplateParameter:
3496
14
    return Variable.VariableOrMember;
3497
3498
0
  case EK_Parameter:
3499
0
  case EK_Parameter_CF_Audited:
3500
0
    return Parameter.getPointer();
3501
3502
0
  case EK_Result:
3503
0
  case EK_StmtExprResult:
3504
0
  case EK_Exception:
3505
0
  case EK_New:
3506
0
  case EK_Temporary:
3507
0
  case EK_Base:
3508
0
  case EK_Delegating:
3509
0
  case EK_ArrayElement:
3510
0
  case EK_VectorElement:
3511
0
  case EK_ComplexElement:
3512
0
  case EK_BlockElement:
3513
0
  case EK_LambdaToBlockConversionBlockElement:
3514
0
  case EK_LambdaCapture:
3515
0
  case EK_CompoundLiteralInit:
3516
0
  case EK_RelatedResult:
3517
0
    return nullptr;
3518
14
  }
3519
3520
0
  llvm_unreachable("Invalid EntityKind!");
3521
0
}
3522
3523
0
bool InitializedEntity::allowsNRVO() const {
3524
0
  switch (getKind()) {
3525
0
  case EK_Result:
3526
0
  case EK_Exception:
3527
0
    return LocAndNRVO.NRVO;
3528
3529
0
  case EK_StmtExprResult:
3530
0
  case EK_Variable:
3531
0
  case EK_Parameter:
3532
0
  case EK_Parameter_CF_Audited:
3533
0
  case EK_TemplateParameter:
3534
0
  case EK_Member:
3535
0
  case EK_ParenAggInitMember:
3536
0
  case EK_Binding:
3537
0
  case EK_New:
3538
0
  case EK_Temporary:
3539
0
  case EK_CompoundLiteralInit:
3540
0
  case EK_Base:
3541
0
  case EK_Delegating:
3542
0
  case EK_ArrayElement:
3543
0
  case EK_VectorElement:
3544
0
  case EK_ComplexElement:
3545
0
  case EK_BlockElement:
3546
0
  case EK_LambdaToBlockConversionBlockElement:
3547
0
  case EK_LambdaCapture:
3548
0
  case EK_RelatedResult:
3549
0
    break;
3550
0
  }
3551
3552
0
  return false;
3553
0
}
3554
3555
0
unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3556
0
  assert(getParent() != this);
3557
0
  unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3558
0
  for (unsigned I = 0; I != Depth; ++I)
3559
0
    OS << "`-";
3560
3561
0
  switch (getKind()) {
3562
0
  case EK_Variable: OS << "Variable"; break;
3563
0
  case EK_Parameter: OS << "Parameter"; break;
3564
0
  case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3565
0
    break;
3566
0
  case EK_TemplateParameter: OS << "TemplateParameter"; break;
3567
0
  case EK_Result: OS << "Result"; break;
3568
0
  case EK_StmtExprResult: OS << "StmtExprResult"; break;
3569
0
  case EK_Exception: OS << "Exception"; break;
3570
0
  case EK_Member:
3571
0
  case EK_ParenAggInitMember:
3572
0
    OS << "Member";
3573
0
    break;
3574
0
  case EK_Binding: OS << "Binding"; break;
3575
0
  case EK_New: OS << "New"; break;
3576
0
  case EK_Temporary: OS << "Temporary"; break;
3577
0
  case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3578
0
  case EK_RelatedResult: OS << "RelatedResult"; break;
3579
0
  case EK_Base: OS << "Base"; break;
3580
0
  case EK_Delegating: OS << "Delegating"; break;
3581
0
  case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3582
0
  case EK_VectorElement: OS << "VectorElement " << Index; break;
3583
0
  case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3584
0
  case EK_BlockElement: OS << "Block"; break;
3585
0
  case EK_LambdaToBlockConversionBlockElement:
3586
0
    OS << "Block (lambda)";
3587
0
    break;
3588
0
  case EK_LambdaCapture:
3589
0
    OS << "LambdaCapture ";
3590
0
    OS << DeclarationName(Capture.VarID);
3591
0
    break;
3592
0
  }
3593
3594
0
  if (auto *D = getDecl()) {
3595
0
    OS << " ";
3596
0
    D->printQualifiedName(OS);
3597
0
  }
3598
3599
0
  OS << " '" << getType() << "'\n";
3600
3601
0
  return Depth + 1;
3602
0
}
3603
3604
0
LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3605
0
  dumpImpl(llvm::errs());
3606
0
}
3607
3608
//===----------------------------------------------------------------------===//
3609
// Initialization sequence
3610
//===----------------------------------------------------------------------===//
3611
3612
7
void InitializationSequence::Step::Destroy() {
3613
7
  switch (Kind) {
3614
0
  case SK_ResolveAddressOfOverloadedFunction:
3615
0
  case SK_CastDerivedToBasePRValue:
3616
0
  case SK_CastDerivedToBaseXValue:
3617
0
  case SK_CastDerivedToBaseLValue:
3618
0
  case SK_BindReference:
3619
0
  case SK_BindReferenceToTemporary:
3620
0
  case SK_FinalCopy:
3621
0
  case SK_ExtraneousCopyToTemporary:
3622
0
  case SK_UserConversion:
3623
0
  case SK_QualificationConversionPRValue:
3624
0
  case SK_QualificationConversionXValue:
3625
0
  case SK_QualificationConversionLValue:
3626
0
  case SK_FunctionReferenceConversion:
3627
0
  case SK_AtomicConversion:
3628
0
  case SK_ListInitialization:
3629
0
  case SK_UnwrapInitList:
3630
0
  case SK_RewrapInitList:
3631
0
  case SK_ConstructorInitialization:
3632
0
  case SK_ConstructorInitializationFromList:
3633
0
  case SK_ZeroInitialization:
3634
7
  case SK_CAssignment:
3635
7
  case SK_StringInit:
3636
7
  case SK_ObjCObjectConversion:
3637
7
  case SK_ArrayLoopIndex:
3638
7
  case SK_ArrayLoopInit:
3639
7
  case SK_ArrayInit:
3640
7
  case SK_GNUArrayInit:
3641
7
  case SK_ParenthesizedArrayInit:
3642
7
  case SK_PassByIndirectCopyRestore:
3643
7
  case SK_PassByIndirectRestore:
3644
7
  case SK_ProduceObjCObject:
3645
7
  case SK_StdInitializerList:
3646
7
  case SK_StdInitializerListConstructorCall:
3647
7
  case SK_OCLSamplerInit:
3648
7
  case SK_OCLZeroOpaqueType:
3649
7
  case SK_ParenthesizedListInit:
3650
7
    break;
3651
3652
0
  case SK_ConversionSequence:
3653
0
  case SK_ConversionSequenceNoNarrowing:
3654
0
    delete ICS;
3655
7
  }
3656
7
}
3657
3658
0
bool InitializationSequence::isDirectReferenceBinding() const {
3659
  // There can be some lvalue adjustments after the SK_BindReference step.
3660
0
  for (const Step &S : llvm::reverse(Steps)) {
3661
0
    if (S.Kind == SK_BindReference)
3662
0
      return true;
3663
0
    if (S.Kind == SK_BindReferenceToTemporary)
3664
0
      return false;
3665
0
  }
3666
0
  return false;
3667
0
}
3668
3669
0
bool InitializationSequence::isAmbiguous() const {
3670
0
  if (!Failed())
3671
0
    return false;
3672
3673
0
  switch (getFailureKind()) {
3674
0
  case FK_TooManyInitsForReference:
3675
0
  case FK_ParenthesizedListInitForReference:
3676
0
  case FK_ArrayNeedsInitList:
3677
0
  case FK_ArrayNeedsInitListOrStringLiteral:
3678
0
  case FK_ArrayNeedsInitListOrWideStringLiteral:
3679
0
  case FK_NarrowStringIntoWideCharArray:
3680
0
  case FK_WideStringIntoCharArray:
3681
0
  case FK_IncompatWideStringIntoWideChar:
3682
0
  case FK_PlainStringIntoUTF8Char:
3683
0
  case FK_UTF8StringIntoPlainChar:
3684
0
  case FK_AddressOfOverloadFailed: // FIXME: Could do better
3685
0
  case FK_NonConstLValueReferenceBindingToTemporary:
3686
0
  case FK_NonConstLValueReferenceBindingToBitfield:
3687
0
  case FK_NonConstLValueReferenceBindingToVectorElement:
3688
0
  case FK_NonConstLValueReferenceBindingToMatrixElement:
3689
0
  case FK_NonConstLValueReferenceBindingToUnrelated:
3690
0
  case FK_RValueReferenceBindingToLValue:
3691
0
  case FK_ReferenceAddrspaceMismatchTemporary:
3692
0
  case FK_ReferenceInitDropsQualifiers:
3693
0
  case FK_ReferenceInitFailed:
3694
0
  case FK_ConversionFailed:
3695
0
  case FK_ConversionFromPropertyFailed:
3696
0
  case FK_TooManyInitsForScalar:
3697
0
  case FK_ParenthesizedListInitForScalar:
3698
0
  case FK_ReferenceBindingToInitList:
3699
0
  case FK_InitListBadDestinationType:
3700
0
  case FK_DefaultInitOfConst:
3701
0
  case FK_Incomplete:
3702
0
  case FK_ArrayTypeMismatch:
3703
0
  case FK_NonConstantArrayInit:
3704
0
  case FK_ListInitializationFailed:
3705
0
  case FK_VariableLengthArrayHasInitializer:
3706
0
  case FK_PlaceholderType:
3707
0
  case FK_ExplicitConstructor:
3708
0
  case FK_AddressOfUnaddressableFunction:
3709
0
  case FK_ParenthesizedListInitFailed:
3710
0
  case FK_DesignatedInitForNonAggregate:
3711
0
    return false;
3712
3713
0
  case FK_ReferenceInitOverloadFailed:
3714
0
  case FK_UserConversionOverloadFailed:
3715
0
  case FK_ConstructorOverloadFailed:
3716
0
  case FK_ListConstructorOverloadFailed:
3717
0
    return FailedOverloadResult == OR_Ambiguous;
3718
0
  }
3719
3720
0
  llvm_unreachable("Invalid EntityKind!");
3721
0
}
3722
3723
0
bool InitializationSequence::isConstructorInitialization() const {
3724
0
  return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
3725
0
}
3726
3727
void
3728
InitializationSequence
3729
::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3730
                                   DeclAccessPair Found,
3731
0
                                   bool HadMultipleCandidates) {
3732
0
  Step S;
3733
0
  S.Kind = SK_ResolveAddressOfOverloadedFunction;
3734
0
  S.Type = Function->getType();
3735
0
  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3736
0
  S.Function.Function = Function;
3737
0
  S.Function.FoundDecl = Found;
3738
0
  Steps.push_back(S);
3739
0
}
3740
3741
void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3742
0
                                                      ExprValueKind VK) {
3743
0
  Step S;
3744
0
  switch (VK) {
3745
0
  case VK_PRValue:
3746
0
    S.Kind = SK_CastDerivedToBasePRValue;
3747
0
    break;
3748
0
  case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3749
0
  case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3750
0
  }
3751
0
  S.Type = BaseType;
3752
0
  Steps.push_back(S);
3753
0
}
3754
3755
void InitializationSequence::AddReferenceBindingStep(QualType T,
3756
0
                                                     bool BindingTemporary) {
3757
0
  Step S;
3758
0
  S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
3759
0
  S.Type = T;
3760
0
  Steps.push_back(S);
3761
0
}
3762
3763
0
void InitializationSequence::AddFinalCopy(QualType T) {
3764
0
  Step S;
3765
0
  S.Kind = SK_FinalCopy;
3766
0
  S.Type = T;
3767
0
  Steps.push_back(S);
3768
0
}
3769
3770
0
void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3771
0
  Step S;
3772
0
  S.Kind = SK_ExtraneousCopyToTemporary;
3773
0
  S.Type = T;
3774
0
  Steps.push_back(S);
3775
0
}
3776
3777
void
3778
InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3779
                                              DeclAccessPair FoundDecl,
3780
                                              QualType T,
3781
0
                                              bool HadMultipleCandidates) {
3782
0
  Step S;
3783
0
  S.Kind = SK_UserConversion;
3784
0
  S.Type = T;
3785
0
  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3786
0
  S.Function.Function = Function;
3787
0
  S.Function.FoundDecl = FoundDecl;
3788
0
  Steps.push_back(S);
3789
0
}
3790
3791
void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3792
0
                                                            ExprValueKind VK) {
3793
0
  Step S;
3794
0
  S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3795
0
  switch (VK) {
3796
0
  case VK_PRValue:
3797
0
    S.Kind = SK_QualificationConversionPRValue;
3798
0
    break;
3799
0
  case VK_XValue:
3800
0
    S.Kind = SK_QualificationConversionXValue;
3801
0
    break;
3802
0
  case VK_LValue:
3803
0
    S.Kind = SK_QualificationConversionLValue;
3804
0
    break;
3805
0
  }
3806
0
  S.Type = Ty;
3807
0
  Steps.push_back(S);
3808
0
}
3809
3810
0
void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
3811
0
  Step S;
3812
0
  S.Kind = SK_FunctionReferenceConversion;
3813
0
  S.Type = Ty;
3814
0
  Steps.push_back(S);
3815
0
}
3816
3817
0
void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3818
0
  Step S;
3819
0
  S.Kind = SK_AtomicConversion;
3820
0
  S.Type = Ty;
3821
0
  Steps.push_back(S);
3822
0
}
3823
3824
void InitializationSequence::AddConversionSequenceStep(
3825
    const ImplicitConversionSequence &ICS, QualType T,
3826
0
    bool TopLevelOfInitList) {
3827
0
  Step S;
3828
0
  S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
3829
0
                              : SK_ConversionSequence;
3830
0
  S.Type = T;
3831
0
  S.ICS = new ImplicitConversionSequence(ICS);
3832
0
  Steps.push_back(S);
3833
0
}
3834
3835
0
void InitializationSequence::AddListInitializationStep(QualType T) {
3836
0
  Step S;
3837
0
  S.Kind = SK_ListInitialization;
3838
0
  S.Type = T;
3839
0
  Steps.push_back(S);
3840
0
}
3841
3842
void InitializationSequence::AddConstructorInitializationStep(
3843
    DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3844
0
    bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3845
0
  Step S;
3846
0
  S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall
3847
0
                                     : SK_ConstructorInitializationFromList
3848
0
                        : SK_ConstructorInitialization;
3849
0
  S.Type = T;
3850
0
  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3851
0
  S.Function.Function = Constructor;
3852
0
  S.Function.FoundDecl = FoundDecl;
3853
0
  Steps.push_back(S);
3854
0
}
3855
3856
0
void InitializationSequence::AddZeroInitializationStep(QualType T) {
3857
0
  Step S;
3858
0
  S.Kind = SK_ZeroInitialization;
3859
0
  S.Type = T;
3860
0
  Steps.push_back(S);
3861
0
}
3862
3863
7
void InitializationSequence::AddCAssignmentStep(QualType T) {
3864
7
  Step S;
3865
7
  S.Kind = SK_CAssignment;
3866
7
  S.Type = T;
3867
7
  Steps.push_back(S);
3868
7
}
3869
3870
0
void InitializationSequence::AddStringInitStep(QualType T) {
3871
0
  Step S;
3872
0
  S.Kind = SK_StringInit;
3873
0
  S.Type = T;
3874
0
  Steps.push_back(S);
3875
0
}
3876
3877
0
void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3878
0
  Step S;
3879
0
  S.Kind = SK_ObjCObjectConversion;
3880
0
  S.Type = T;
3881
0
  Steps.push_back(S);
3882
0
}
3883
3884
0
void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3885
0
  Step S;
3886
0
  S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit;
3887
0
  S.Type = T;
3888
0
  Steps.push_back(S);
3889
0
}
3890
3891
0
void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3892
0
  Step S;
3893
0
  S.Kind = SK_ArrayLoopIndex;
3894
0
  S.Type = EltT;
3895
0
  Steps.insert(Steps.begin(), S);
3896
3897
0
  S.Kind = SK_ArrayLoopInit;
3898
0
  S.Type = T;
3899
0
  Steps.push_back(S);
3900
0
}
3901
3902
0
void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3903
0
  Step S;
3904
0
  S.Kind = SK_ParenthesizedArrayInit;
3905
0
  S.Type = T;
3906
0
  Steps.push_back(S);
3907
0
}
3908
3909
void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3910
0
                                                              bool shouldCopy) {
3911
0
  Step s;
3912
0
  s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
3913
0
                       : SK_PassByIndirectRestore);
3914
0
  s.Type = type;
3915
0
  Steps.push_back(s);
3916
0
}
3917
3918
0
void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3919
0
  Step S;
3920
0
  S.Kind = SK_ProduceObjCObject;
3921
0
  S.Type = T;
3922
0
  Steps.push_back(S);
3923
0
}
3924
3925
0
void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3926
0
  Step S;
3927
0
  S.Kind = SK_StdInitializerList;
3928
0
  S.Type = T;
3929
0
  Steps.push_back(S);
3930
0
}
3931
3932
0
void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3933
0
  Step S;
3934
0
  S.Kind = SK_OCLSamplerInit;
3935
0
  S.Type = T;
3936
0
  Steps.push_back(S);
3937
0
}
3938
3939
0
void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
3940
0
  Step S;
3941
0
  S.Kind = SK_OCLZeroOpaqueType;
3942
0
  S.Type = T;
3943
0
  Steps.push_back(S);
3944
0
}
3945
3946
0
void InitializationSequence::AddParenthesizedListInitStep(QualType T) {
3947
0
  Step S;
3948
0
  S.Kind = SK_ParenthesizedListInit;
3949
0
  S.Type = T;
3950
0
  Steps.push_back(S);
3951
0
}
3952
3953
void InitializationSequence::RewrapReferenceInitList(QualType T,
3954
0
                                                     InitListExpr *Syntactic) {
3955
0
  assert(Syntactic->getNumInits() == 1 &&
3956
0
         "Can only rewrap trivial init lists.");
3957
0
  Step S;
3958
0
  S.Kind = SK_UnwrapInitList;
3959
0
  S.Type = Syntactic->getInit(0)->getType();
3960
0
  Steps.insert(Steps.begin(), S);
3961
3962
0
  S.Kind = SK_RewrapInitList;
3963
0
  S.Type = T;
3964
0
  S.WrappingSyntacticList = Syntactic;
3965
0
  Steps.push_back(S);
3966
0
}
3967
3968
void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3969
0
                                                OverloadingResult Result) {
3970
0
  setSequenceKind(FailedSequence);
3971
0
  this->Failure = Failure;
3972
0
  this->FailedOverloadResult = Result;
3973
0
}
3974
3975
//===----------------------------------------------------------------------===//
3976
// Attempt initialization
3977
//===----------------------------------------------------------------------===//
3978
3979
/// Tries to add a zero initializer. Returns true if that worked.
3980
static bool
3981
maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3982
0
                                   const InitializedEntity &Entity) {
3983
0
  if (Entity.getKind() != InitializedEntity::EK_Variable)
3984
0
    return false;
3985
3986
0
  VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3987
0
  if (VD->getInit() || VD->getEndLoc().isMacroID())
3988
0
    return false;
3989
3990
0
  QualType VariableTy = VD->getType().getCanonicalType();
3991
0
  SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
3992
0
  std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3993
0
  if (!Init.empty()) {
3994
0
    Sequence.AddZeroInitializationStep(Entity.getType());
3995
0
    Sequence.SetZeroInitializationFixit(Init, Loc);
3996
0
    return true;
3997
0
  }
3998
0
  return false;
3999
0
}
4000
4001
static void MaybeProduceObjCObject(Sema &S,
4002
                                   InitializationSequence &Sequence,
4003
7
                                   const InitializedEntity &Entity) {
4004
7
  if (!S.getLangOpts().ObjCAutoRefCount) return;
4005
4006
  /// When initializing a parameter, produce the value if it's marked
4007
  /// __attribute__((ns_consumed)).
4008
0
  if (Entity.isParameterKind()) {
4009
0
    if (!Entity.isParameterConsumed())
4010
0
      return;
4011
4012
0
    assert(Entity.getType()->isObjCRetainableType() &&
4013
0
           "consuming an object of unretainable type?");
4014
0
    Sequence.AddProduceObjCObjectStep(Entity.getType());
4015
4016
  /// When initializing a return value, if the return type is a
4017
  /// retainable type, then returns need to immediately retain the
4018
  /// object.  If an autorelease is required, it will be done at the
4019
  /// last instant.
4020
0
  } else if (Entity.getKind() == InitializedEntity::EK_Result ||
4021
0
             Entity.getKind() == InitializedEntity::EK_StmtExprResult) {
4022
0
    if (!Entity.getType()->isObjCRetainableType())
4023
0
      return;
4024
4025
0
    Sequence.AddProduceObjCObjectStep(Entity.getType());
4026
0
  }
4027
0
}
4028
4029
static void TryListInitialization(Sema &S,
4030
                                  const InitializedEntity &Entity,
4031
                                  const InitializationKind &Kind,
4032
                                  InitListExpr *InitList,
4033
                                  InitializationSequence &Sequence,
4034
                                  bool TreatUnavailableAsInvalid);
4035
4036
/// When initializing from init list via constructor, handle
4037
/// initialization of an object of type std::initializer_list<T>.
4038
///
4039
/// \return true if we have handled initialization of an object of type
4040
/// std::initializer_list<T>, false otherwise.
4041
static bool TryInitializerListConstruction(Sema &S,
4042
                                           InitListExpr *List,
4043
                                           QualType DestType,
4044
                                           InitializationSequence &Sequence,
4045
0
                                           bool TreatUnavailableAsInvalid) {
4046
0
  QualType E;
4047
0
  if (!S.isStdInitializerList(DestType, &E))
4048
0
    return false;
4049
4050
0
  if (!S.isCompleteType(List->getExprLoc(), E)) {
4051
0
    Sequence.setIncompleteTypeFailure(E);
4052
0
    return true;
4053
0
  }
4054
4055
  // Try initializing a temporary array from the init list.
4056
0
  QualType ArrayType = S.Context.getConstantArrayType(
4057
0
      E.withConst(),
4058
0
      llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
4059
0
                  List->getNumInits()),
4060
0
      nullptr, clang::ArraySizeModifier::Normal, 0);
4061
0
  InitializedEntity HiddenArray =
4062
0
      InitializedEntity::InitializeTemporary(ArrayType);
4063
0
  InitializationKind Kind = InitializationKind::CreateDirectList(
4064
0
      List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
4065
0
  TryListInitialization(S, HiddenArray, Kind, List, Sequence,
4066
0
                        TreatUnavailableAsInvalid);
4067
0
  if (Sequence)
4068
0
    Sequence.AddStdInitializerListConstructionStep(DestType);
4069
0
  return true;
4070
0
}
4071
4072
/// Determine if the constructor has the signature of a copy or move
4073
/// constructor for the type T of the class in which it was found. That is,
4074
/// determine if its first parameter is of type T or reference to (possibly
4075
/// cv-qualified) T.
4076
static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
4077
0
                                   const ConstructorInfo &Info) {
4078
0
  if (Info.Constructor->getNumParams() == 0)
4079
0
    return false;
4080
4081
0
  QualType ParmT =
4082
0
      Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
4083
0
  QualType ClassT =
4084
0
      Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
4085
4086
0
  return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
4087
0
}
4088
4089
static OverloadingResult ResolveConstructorOverload(
4090
    Sema &S, SourceLocation DeclLoc, MultiExprArg Args,
4091
    OverloadCandidateSet &CandidateSet, QualType DestType,
4092
    DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best,
4093
    bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors,
4094
    bool IsListInit, bool RequireActualConstructor,
4095
0
    bool SecondStepOfCopyInit = false) {
4096
0
  CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
4097
0
  CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
4098
4099
0
  for (NamedDecl *D : Ctors) {
4100
0
    auto Info = getConstructorInfo(D);
4101
0
    if (!Info.Constructor || Info.Constructor->isInvalidDecl())
4102
0
      continue;
4103
4104
0
    if (OnlyListConstructors && !S.isInitListConstructor(Info.Constructor))
4105
0
      continue;
4106
4107
    // C++11 [over.best.ics]p4:
4108
    //   ... and the constructor or user-defined conversion function is a
4109
    //   candidate by
4110
    //   - 13.3.1.3, when the argument is the temporary in the second step
4111
    //     of a class copy-initialization, or
4112
    //   - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
4113
    //   - the second phase of 13.3.1.7 when the initializer list has exactly
4114
    //     one element that is itself an initializer list, and the target is
4115
    //     the first parameter of a constructor of class X, and the conversion
4116
    //     is to X or reference to (possibly cv-qualified X),
4117
    //   user-defined conversion sequences are not considered.
4118
0
    bool SuppressUserConversions =
4119
0
        SecondStepOfCopyInit ||
4120
0
        (IsListInit && Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
4121
0
         hasCopyOrMoveCtorParam(S.Context, Info));
4122
4123
0
    if (Info.ConstructorTmpl)
4124
0
      S.AddTemplateOverloadCandidate(
4125
0
          Info.ConstructorTmpl, Info.FoundDecl,
4126
0
          /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
4127
0
          /*PartialOverloading=*/false, AllowExplicit);
4128
0
    else {
4129
      // C++ [over.match.copy]p1:
4130
      //   - When initializing a temporary to be bound to the first parameter
4131
      //     of a constructor [for type T] that takes a reference to possibly
4132
      //     cv-qualified T as its first argument, called with a single
4133
      //     argument in the context of direct-initialization, explicit
4134
      //     conversion functions are also considered.
4135
      // FIXME: What if a constructor template instantiates to such a signature?
4136
0
      bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
4137
0
                               Args.size() == 1 &&
4138
0
                               hasCopyOrMoveCtorParam(S.Context, Info);
4139
0
      S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4140
0
                             CandidateSet, SuppressUserConversions,
4141
0
                             /*PartialOverloading=*/false, AllowExplicit,
4142
0
                             AllowExplicitConv);
4143
0
    }
4144
0
  }
4145
4146
  // FIXME: Work around a bug in C++17 guaranteed copy elision.
4147
  //
4148
  // When initializing an object of class type T by constructor
4149
  // ([over.match.ctor]) or by list-initialization ([over.match.list])
4150
  // from a single expression of class type U, conversion functions of
4151
  // U that convert to the non-reference type cv T are candidates.
4152
  // Explicit conversion functions are only candidates during
4153
  // direct-initialization.
4154
  //
4155
  // Note: SecondStepOfCopyInit is only ever true in this case when
4156
  // evaluating whether to produce a C++98 compatibility warning.
4157
0
  if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 &&
4158
0
      !RequireActualConstructor && !SecondStepOfCopyInit) {
4159
0
    Expr *Initializer = Args[0];
4160
0
    auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4161
0
    if (SourceRD && S.isCompleteType(DeclLoc, Initializer->getType())) {
4162
0
      const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4163
0
      for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4164
0
        NamedDecl *D = *I;
4165
0
        CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4166
0
        D = D->getUnderlyingDecl();
4167
4168
0
        FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4169
0
        CXXConversionDecl *Conv;
4170
0
        if (ConvTemplate)
4171
0
          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4172
0
        else
4173
0
          Conv = cast<CXXConversionDecl>(D);
4174
4175
0
        if (ConvTemplate)
4176
0
          S.AddTemplateConversionCandidate(
4177
0
              ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4178
0
              CandidateSet, AllowExplicit, AllowExplicit,
4179
0
              /*AllowResultConversion*/ false);
4180
0
        else
4181
0
          S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4182
0
                                   DestType, CandidateSet, AllowExplicit,
4183
0
                                   AllowExplicit,
4184
0
                                   /*AllowResultConversion*/ false);
4185
0
      }
4186
0
    }
4187
0
  }
4188
4189
  // Perform overload resolution and return the result.
4190
0
  return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4191
0
}
4192
4193
/// Attempt initialization by constructor (C++ [dcl.init]), which
4194
/// enumerates the constructors of the initialized entity and performs overload
4195
/// resolution to select the best.
4196
/// \param DestType       The destination class type.
4197
/// \param DestArrayType  The destination type, which is either DestType or
4198
///                       a (possibly multidimensional) array of DestType.
4199
/// \param IsListInit     Is this list-initialization?
4200
/// \param IsInitListCopy Is this non-list-initialization resulting from a
4201
///                       list-initialization from {x} where x is the same
4202
///                       type as the entity?
4203
static void TryConstructorInitialization(Sema &S,
4204
                                         const InitializedEntity &Entity,
4205
                                         const InitializationKind &Kind,
4206
                                         MultiExprArg Args, QualType DestType,
4207
                                         QualType DestArrayType,
4208
                                         InitializationSequence &Sequence,
4209
                                         bool IsListInit = false,
4210
0
                                         bool IsInitListCopy = false) {
4211
0
  assert(((!IsListInit && !IsInitListCopy) ||
4212
0
          (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4213
0
         "IsListInit/IsInitListCopy must come with a single initializer list "
4214
0
         "argument.");
4215
0
  InitListExpr *ILE =
4216
0
      (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Args[0]) : nullptr;
4217
0
  MultiExprArg UnwrappedArgs =
4218
0
      ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args;
4219
4220
  // The type we're constructing needs to be complete.
4221
0
  if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4222
0
    Sequence.setIncompleteTypeFailure(DestType);
4223
0
    return;
4224
0
  }
4225
4226
0
  bool RequireActualConstructor =
4227
0
      !(Entity.getKind() != InitializedEntity::EK_Base &&
4228
0
        Entity.getKind() != InitializedEntity::EK_Delegating &&
4229
0
        Entity.getKind() !=
4230
0
            InitializedEntity::EK_LambdaToBlockConversionBlockElement);
4231
4232
  // C++17 [dcl.init]p17:
4233
  //     - If the initializer expression is a prvalue and the cv-unqualified
4234
  //       version of the source type is the same class as the class of the
4235
  //       destination, the initializer expression is used to initialize the
4236
  //       destination object.
4237
  // Per DR (no number yet), this does not apply when initializing a base
4238
  // class or delegating to another constructor from a mem-initializer.
4239
  // ObjC++: Lambda captured by the block in the lambda to block conversion
4240
  // should avoid copy elision.
4241
0
  if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
4242
0
      UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
4243
0
      S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4244
    // Convert qualifications if necessary.
4245
0
    Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4246
0
    if (ILE)
4247
0
      Sequence.RewrapReferenceInitList(DestType, ILE);
4248
0
    return;
4249
0
  }
4250
4251
0
  const RecordType *DestRecordType = DestType->getAs<RecordType>();
4252
0
  assert(DestRecordType && "Constructor initialization requires record type");
4253
0
  CXXRecordDecl *DestRecordDecl
4254
0
    = cast<CXXRecordDecl>(DestRecordType->getDecl());
4255
4256
  // Build the candidate set directly in the initialization sequence
4257
  // structure, so that it will persist if we fail.
4258
0
  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4259
4260
  // Determine whether we are allowed to call explicit constructors or
4261
  // explicit conversion operators.
4262
0
  bool AllowExplicit = Kind.AllowExplicit() || IsListInit;
4263
0
  bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4264
4265
  //   - Otherwise, if T is a class type, constructors are considered. The
4266
  //     applicable constructors are enumerated, and the best one is chosen
4267
  //     through overload resolution.
4268
0
  DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4269
4270
0
  OverloadingResult Result = OR_No_Viable_Function;
4271
0
  OverloadCandidateSet::iterator Best;
4272
0
  bool AsInitializerList = false;
4273
4274
  // C++11 [over.match.list]p1, per DR1467:
4275
  //   When objects of non-aggregate type T are list-initialized, such that
4276
  //   8.5.4 [dcl.init.list] specifies that overload resolution is performed
4277
  //   according to the rules in this section, overload resolution selects
4278
  //   the constructor in two phases:
4279
  //
4280
  //   - Initially, the candidate functions are the initializer-list
4281
  //     constructors of the class T and the argument list consists of the
4282
  //     initializer list as a single argument.
4283
0
  if (IsListInit) {
4284
0
    AsInitializerList = true;
4285
4286
    // If the initializer list has no elements and T has a default constructor,
4287
    // the first phase is omitted.
4288
0
    if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(DestRecordDecl)))
4289
0
      Result = ResolveConstructorOverload(
4290
0
          S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
4291
0
          CopyInitialization, AllowExplicit,
4292
0
          /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4293
0
  }
4294
4295
  // C++11 [over.match.list]p1:
4296
  //   - If no viable initializer-list constructor is found, overload resolution
4297
  //     is performed again, where the candidate functions are all the
4298
  //     constructors of the class T and the argument list consists of the
4299
  //     elements of the initializer list.
4300
0
  if (Result == OR_No_Viable_Function) {
4301
0
    AsInitializerList = false;
4302
0
    Result = ResolveConstructorOverload(
4303
0
        S, Kind.getLocation(), UnwrappedArgs, CandidateSet, DestType, Ctors,
4304
0
        Best, CopyInitialization, AllowExplicit,
4305
0
        /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor);
4306
0
  }
4307
0
  if (Result) {
4308
0
    Sequence.SetOverloadFailure(
4309
0
        IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed
4310
0
                   : InitializationSequence::FK_ConstructorOverloadFailed,
4311
0
        Result);
4312
4313
0
    if (Result != OR_Deleted)
4314
0
      return;
4315
0
  }
4316
4317
0
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4318
4319
  // In C++17, ResolveConstructorOverload can select a conversion function
4320
  // instead of a constructor.
4321
0
  if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4322
    // Add the user-defined conversion step that calls the conversion function.
4323
0
    QualType ConvType = CD->getConversionType();
4324
0
    assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4325
0
           "should not have selected this conversion function");
4326
0
    Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4327
0
                                   HadMultipleCandidates);
4328
0
    if (!S.Context.hasSameType(ConvType, DestType))
4329
0
      Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4330
0
    if (IsListInit)
4331
0
      Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4332
0
    return;
4333
0
  }
4334
4335
0
  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4336
0
  if (Result != OR_Deleted) {
4337
    // C++11 [dcl.init]p6:
4338
    //   If a program calls for the default initialization of an object
4339
    //   of a const-qualified type T, T shall be a class type with a
4340
    //   user-provided default constructor.
4341
    // C++ core issue 253 proposal:
4342
    //   If the implicit default constructor initializes all subobjects, no
4343
    //   initializer should be required.
4344
    // The 253 proposal is for example needed to process libstdc++ headers
4345
    // in 5.x.
4346
0
    if (Kind.getKind() == InitializationKind::IK_Default &&
4347
0
        Entity.getType().isConstQualified()) {
4348
0
      if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4349
0
        if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4350
0
          Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4351
0
        return;
4352
0
      }
4353
0
    }
4354
4355
    // C++11 [over.match.list]p1:
4356
    //   In copy-list-initialization, if an explicit constructor is chosen, the
4357
    //   initializer is ill-formed.
4358
0
    if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
4359
0
      Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4360
0
      return;
4361
0
    }
4362
0
  }
4363
4364
  // [class.copy.elision]p3:
4365
  // In some copy-initialization contexts, a two-stage overload resolution
4366
  // is performed.
4367
  // If the first overload resolution selects a deleted function, we also
4368
  // need the initialization sequence to decide whether to perform the second
4369
  // overload resolution.
4370
  // For deleted functions in other contexts, there is no need to get the
4371
  // initialization sequence.
4372
0
  if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy)
4373
0
    return;
4374
4375
  // Add the constructor initialization step. Any cv-qualification conversion is
4376
  // subsumed by the initialization.
4377
0
  Sequence.AddConstructorInitializationStep(
4378
0
      Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4379
0
      IsListInit | IsInitListCopy, AsInitializerList);
4380
0
}
4381
4382
static bool
4383
ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4384
                                             Expr *Initializer,
4385
                                             QualType &SourceType,
4386
                                             QualType &UnqualifiedSourceType,
4387
                                             QualType UnqualifiedTargetType,
4388
0
                                             InitializationSequence &Sequence) {
4389
0
  if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4390
0
        S.Context.OverloadTy) {
4391
0
    DeclAccessPair Found;
4392
0
    bool HadMultipleCandidates = false;
4393
0
    if (FunctionDecl *Fn
4394
0
        = S.ResolveAddressOfOverloadedFunction(Initializer,
4395
0
                                               UnqualifiedTargetType,
4396
0
                                               false, Found,
4397
0
                                               &HadMultipleCandidates)) {
4398
0
      Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4399
0
                                                HadMultipleCandidates);
4400
0
      SourceType = Fn->getType();
4401
0
      UnqualifiedSourceType = SourceType.getUnqualifiedType();
4402
0
    } else if (!UnqualifiedTargetType->isRecordType()) {
4403
0
      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4404
0
      return true;
4405
0
    }
4406
0
  }
4407
0
  return false;
4408
0
}
4409
4410
static void TryReferenceInitializationCore(Sema &S,
4411
                                           const InitializedEntity &Entity,
4412
                                           const InitializationKind &Kind,
4413
                                           Expr *Initializer,
4414
                                           QualType cv1T1, QualType T1,
4415
                                           Qualifiers T1Quals,
4416
                                           QualType cv2T2, QualType T2,
4417
                                           Qualifiers T2Quals,
4418
                                           InitializationSequence &Sequence,
4419
                                           bool TopLevelOfInitList);
4420
4421
static void TryValueInitialization(Sema &S,
4422
                                   const InitializedEntity &Entity,
4423
                                   const InitializationKind &Kind,
4424
                                   InitializationSequence &Sequence,
4425
                                   InitListExpr *InitList = nullptr);
4426
4427
/// Attempt list initialization of a reference.
4428
static void TryReferenceListInitialization(Sema &S,
4429
                                           const InitializedEntity &Entity,
4430
                                           const InitializationKind &Kind,
4431
                                           InitListExpr *InitList,
4432
                                           InitializationSequence &Sequence,
4433
0
                                           bool TreatUnavailableAsInvalid) {
4434
  // First, catch C++03 where this isn't possible.
4435
0
  if (!S.getLangOpts().CPlusPlus11) {
4436
0
    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4437
0
    return;
4438
0
  }
4439
  // Can't reference initialize a compound literal.
4440
0
  if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4441
0
    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4442
0
    return;
4443
0
  }
4444
4445
0
  QualType DestType = Entity.getType();
4446
0
  QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4447
0
  Qualifiers T1Quals;
4448
0
  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4449
4450
  // Reference initialization via an initializer list works thus:
4451
  // If the initializer list consists of a single element that is
4452
  // reference-related to the referenced type, bind directly to that element
4453
  // (possibly creating temporaries).
4454
  // Otherwise, initialize a temporary with the initializer list and
4455
  // bind to that.
4456
0
  if (InitList->getNumInits() == 1) {
4457
0
    Expr *Initializer = InitList->getInit(0);
4458
0
    QualType cv2T2 = S.getCompletedType(Initializer);
4459
0
    Qualifiers T2Quals;
4460
0
    QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4461
4462
    // If this fails, creating a temporary wouldn't work either.
4463
0
    if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4464
0
                                                     T1, Sequence))
4465
0
      return;
4466
4467
0
    SourceLocation DeclLoc = Initializer->getBeginLoc();
4468
0
    Sema::ReferenceCompareResult RefRelationship
4469
0
      = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4470
0
    if (RefRelationship >= Sema::Ref_Related) {
4471
      // Try to bind the reference here.
4472
0
      TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4473
0
                                     T1Quals, cv2T2, T2, T2Quals, Sequence,
4474
0
                                     /*TopLevelOfInitList=*/true);
4475
0
      if (Sequence)
4476
0
        Sequence.RewrapReferenceInitList(cv1T1, InitList);
4477
0
      return;
4478
0
    }
4479
4480
    // Update the initializer if we've resolved an overloaded function.
4481
0
    if (Sequence.step_begin() != Sequence.step_end())
4482
0
      Sequence.RewrapReferenceInitList(cv1T1, InitList);
4483
0
  }
4484
  // Perform address space compatibility check.
4485
0
  QualType cv1T1IgnoreAS = cv1T1;
4486
0
  if (T1Quals.hasAddressSpace()) {
4487
0
    Qualifiers T2Quals;
4488
0
    (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4489
0
    if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4490
0
      Sequence.SetFailed(
4491
0
          InitializationSequence::FK_ReferenceInitDropsQualifiers);
4492
0
      return;
4493
0
    }
4494
    // Ignore address space of reference type at this point and perform address
4495
    // space conversion after the reference binding step.
4496
0
    cv1T1IgnoreAS =
4497
0
        S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());
4498
0
  }
4499
  // Not reference-related. Create a temporary and bind to that.
4500
0
  InitializedEntity TempEntity =
4501
0
      InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
4502
4503
0
  TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4504
0
                        TreatUnavailableAsInvalid);
4505
0
  if (Sequence) {
4506
0
    if (DestType->isRValueReferenceType() ||
4507
0
        (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
4508
0
      if (S.getLangOpts().CPlusPlus20 &&
4509
0
          isa<IncompleteArrayType>(T1->getUnqualifiedDesugaredType()) &&
4510
0
          DestType->isRValueReferenceType()) {
4511
        // C++20 [dcl.init.list]p3.10:
4512
        // List-initialization of an object or reference of type T is defined as
4513
        // follows:
4514
        // ..., unless T is “reference to array of unknown bound of U”, in which
4515
        // case the type of the prvalue is the type of x in the declaration U
4516
        // x[] H, where H is the initializer list.
4517
0
        Sequence.AddQualificationConversionStep(cv1T1, clang::VK_PRValue);
4518
0
      }
4519
0
      Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4520
0
                                       /*BindingTemporary=*/true);
4521
0
      if (T1Quals.hasAddressSpace())
4522
0
        Sequence.AddQualificationConversionStep(
4523
0
            cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
4524
0
    } else
4525
0
      Sequence.SetFailed(
4526
0
          InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4527
0
  }
4528
0
}
4529
4530
/// Attempt list initialization (C++0x [dcl.init.list])
4531
static void TryListInitialization(Sema &S,
4532
                                  const InitializedEntity &Entity,
4533
                                  const InitializationKind &Kind,
4534
                                  InitListExpr *InitList,
4535
                                  InitializationSequence &Sequence,
4536
0
                                  bool TreatUnavailableAsInvalid) {
4537
0
  QualType DestType = Entity.getType();
4538
4539
  // C++ doesn't allow scalar initialization with more than one argument.
4540
  // But C99 complex numbers are scalars and it makes sense there.
4541
0
  if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
4542
0
      !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
4543
0
    Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4544
0
    return;
4545
0
  }
4546
0
  if (DestType->isReferenceType()) {
4547
0
    TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4548
0
                                   TreatUnavailableAsInvalid);
4549
0
    return;
4550
0
  }
4551
4552
0
  if (DestType->isRecordType() &&
4553
0
      !S.isCompleteType(InitList->getBeginLoc(), DestType)) {
4554
0
    Sequence.setIncompleteTypeFailure(DestType);
4555
0
    return;
4556
0
  }
4557
4558
  // C++20 [dcl.init.list]p3:
4559
  // - If the braced-init-list contains a designated-initializer-list, T shall
4560
  //   be an aggregate class. [...] Aggregate initialization is performed.
4561
  //
4562
  // We allow arrays here too in order to support array designators.
4563
  //
4564
  // FIXME: This check should precede the handling of reference initialization.
4565
  // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};'
4566
  // as a tentative DR resolution.
4567
0
  bool IsDesignatedInit = InitList->hasDesignatedInit();
4568
0
  if (!DestType->isAggregateType() && IsDesignatedInit) {
4569
0
    Sequence.SetFailed(
4570
0
        InitializationSequence::FK_DesignatedInitForNonAggregate);
4571
0
    return;
4572
0
  }
4573
4574
  // C++11 [dcl.init.list]p3, per DR1467:
4575
  // - If T is a class type and the initializer list has a single element of
4576
  //   type cv U, where U is T or a class derived from T, the object is
4577
  //   initialized from that element (by copy-initialization for
4578
  //   copy-list-initialization, or by direct-initialization for
4579
  //   direct-list-initialization).
4580
  // - Otherwise, if T is a character array and the initializer list has a
4581
  //   single element that is an appropriately-typed string literal
4582
  //   (8.5.2 [dcl.init.string]), initialization is performed as described
4583
  //   in that section.
4584
  // - Otherwise, if T is an aggregate, [...] (continue below).
4585
0
  if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
4586
0
      !IsDesignatedInit) {
4587
0
    if (DestType->isRecordType()) {
4588
0
      QualType InitType = InitList->getInit(0)->getType();
4589
0
      if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4590
0
          S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {
4591
0
        Expr *InitListAsExpr = InitList;
4592
0
        TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4593
0
                                     DestType, Sequence,
4594
0
                                     /*InitListSyntax*/false,
4595
0
                                     /*IsInitListCopy*/true);
4596
0
        return;
4597
0
      }
4598
0
    }
4599
0
    if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4600
0
      Expr *SubInit[1] = {InitList->getInit(0)};
4601
0
      if (!isa<VariableArrayType>(DestAT) &&
4602
0
          IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4603
0
        InitializationKind SubKind =
4604
0
            Kind.getKind() == InitializationKind::IK_DirectList
4605
0
                ? InitializationKind::CreateDirect(Kind.getLocation(),
4606
0
                                                   InitList->getLBraceLoc(),
4607
0
                                                   InitList->getRBraceLoc())
4608
0
                : Kind;
4609
0
        Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4610
0
                                /*TopLevelOfInitList*/ true,
4611
0
                                TreatUnavailableAsInvalid);
4612
4613
        // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4614
        // the element is not an appropriately-typed string literal, in which
4615
        // case we should proceed as in C++11 (below).
4616
0
        if (Sequence) {
4617
0
          Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4618
0
          return;
4619
0
        }
4620
0
      }
4621
0
    }
4622
0
  }
4623
4624
  // C++11 [dcl.init.list]p3:
4625
  //   - If T is an aggregate, aggregate initialization is performed.
4626
0
  if ((DestType->isRecordType() && !DestType->isAggregateType()) ||
4627
0
      (S.getLangOpts().CPlusPlus11 &&
4628
0
       S.isStdInitializerList(DestType, nullptr) && !IsDesignatedInit)) {
4629
0
    if (S.getLangOpts().CPlusPlus11) {
4630
      //   - Otherwise, if the initializer list has no elements and T is a
4631
      //     class type with a default constructor, the object is
4632
      //     value-initialized.
4633
0
      if (InitList->getNumInits() == 0) {
4634
0
        CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4635
0
        if (S.LookupDefaultConstructor(RD)) {
4636
0
          TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4637
0
          return;
4638
0
        }
4639
0
      }
4640
4641
      //   - Otherwise, if T is a specialization of std::initializer_list<E>,
4642
      //     an initializer_list object constructed [...]
4643
0
      if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4644
0
                                         TreatUnavailableAsInvalid))
4645
0
        return;
4646
4647
      //   - Otherwise, if T is a class type, constructors are considered.
4648
0
      Expr *InitListAsExpr = InitList;
4649
0
      TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4650
0
                                   DestType, Sequence, /*InitListSyntax*/true);
4651
0
    } else
4652
0
      Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4653
0
    return;
4654
0
  }
4655
4656
0
  if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
4657
0
      InitList->getNumInits() == 1) {
4658
0
    Expr *E = InitList->getInit(0);
4659
4660
    //   - Otherwise, if T is an enumeration with a fixed underlying type,
4661
    //     the initializer-list has a single element v, and the initialization
4662
    //     is direct-list-initialization, the object is initialized with the
4663
    //     value T(v); if a narrowing conversion is required to convert v to
4664
    //     the underlying type of T, the program is ill-formed.
4665
0
    auto *ET = DestType->getAs<EnumType>();
4666
0
    if (S.getLangOpts().CPlusPlus17 &&
4667
0
        Kind.getKind() == InitializationKind::IK_DirectList &&
4668
0
        ET && ET->getDecl()->isFixed() &&
4669
0
        !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
4670
0
        (E->getType()->isIntegralOrUnscopedEnumerationType() ||
4671
0
         E->getType()->isFloatingType())) {
4672
      // There are two ways that T(v) can work when T is an enumeration type.
4673
      // If there is either an implicit conversion sequence from v to T or
4674
      // a conversion function that can convert from v to T, then we use that.
4675
      // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4676
      // type, it is converted to the enumeration type via its underlying type.
4677
      // There is no overlap possible between these two cases (except when the
4678
      // source value is already of the destination type), and the first
4679
      // case is handled by the general case for single-element lists below.
4680
0
      ImplicitConversionSequence ICS;
4681
0
      ICS.setStandard();
4682
0
      ICS.Standard.setAsIdentityConversion();
4683
0
      if (!E->isPRValue())
4684
0
        ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4685
      // If E is of a floating-point type, then the conversion is ill-formed
4686
      // due to narrowing, but go through the motions in order to produce the
4687
      // right diagnostic.
4688
0
      ICS.Standard.Second = E->getType()->isFloatingType()
4689
0
                                ? ICK_Floating_Integral
4690
0
                                : ICK_Integral_Conversion;
4691
0
      ICS.Standard.setFromType(E->getType());
4692
0
      ICS.Standard.setToType(0, E->getType());
4693
0
      ICS.Standard.setToType(1, DestType);
4694
0
      ICS.Standard.setToType(2, DestType);
4695
0
      Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4696
0
                                         /*TopLevelOfInitList*/true);
4697
0
      Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4698
0
      return;
4699
0
    }
4700
4701
    //   - Otherwise, if the initializer list has a single element of type E
4702
    //     [...references are handled above...], the object or reference is
4703
    //     initialized from that element (by copy-initialization for
4704
    //     copy-list-initialization, or by direct-initialization for
4705
    //     direct-list-initialization); if a narrowing conversion is required
4706
    //     to convert the element to T, the program is ill-formed.
4707
    //
4708
    // Per core-24034, this is direct-initialization if we were performing
4709
    // direct-list-initialization and copy-initialization otherwise.
4710
    // We can't use InitListChecker for this, because it always performs
4711
    // copy-initialization. This only matters if we might use an 'explicit'
4712
    // conversion operator, or for the special case conversion of nullptr_t to
4713
    // bool, so we only need to handle those cases.
4714
    //
4715
    // FIXME: Why not do this in all cases?
4716
0
    Expr *Init = InitList->getInit(0);
4717
0
    if (Init->getType()->isRecordType() ||
4718
0
        (Init->getType()->isNullPtrType() && DestType->isBooleanType())) {
4719
0
      InitializationKind SubKind =
4720
0
          Kind.getKind() == InitializationKind::IK_DirectList
4721
0
              ? InitializationKind::CreateDirect(Kind.getLocation(),
4722
0
                                                 InitList->getLBraceLoc(),
4723
0
                                                 InitList->getRBraceLoc())
4724
0
              : Kind;
4725
0
      Expr *SubInit[1] = { Init };
4726
0
      Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4727
0
                              /*TopLevelOfInitList*/true,
4728
0
                              TreatUnavailableAsInvalid);
4729
0
      if (Sequence)
4730
0
        Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4731
0
      return;
4732
0
    }
4733
0
  }
4734
4735
0
  InitListChecker CheckInitList(S, Entity, InitList,
4736
0
          DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4737
0
  if (CheckInitList.HadError()) {
4738
0
    Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4739
0
    return;
4740
0
  }
4741
4742
  // Add the list initialization step with the built init list.
4743
0
  Sequence.AddListInitializationStep(DestType);
4744
0
}
4745
4746
/// Try a reference initialization that involves calling a conversion
4747
/// function.
4748
static OverloadingResult TryRefInitWithConversionFunction(
4749
    Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4750
    Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4751
0
    InitializationSequence &Sequence) {
4752
0
  QualType DestType = Entity.getType();
4753
0
  QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4754
0
  QualType T1 = cv1T1.getUnqualifiedType();
4755
0
  QualType cv2T2 = Initializer->getType();
4756
0
  QualType T2 = cv2T2.getUnqualifiedType();
4757
4758
0
  assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
4759
0
         "Must have incompatible references when binding via conversion");
4760
4761
  // Build the candidate set directly in the initialization sequence
4762
  // structure, so that it will persist if we fail.
4763
0
  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4764
0
  CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4765
4766
  // Determine whether we are allowed to call explicit conversion operators.
4767
  // Note that none of [over.match.copy], [over.match.conv], nor
4768
  // [over.match.ref] permit an explicit constructor to be chosen when
4769
  // initializing a reference, not even for direct-initialization.
4770
0
  bool AllowExplicitCtors = false;
4771
0
  bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4772
4773
0
  const RecordType *T1RecordType = nullptr;
4774
0
  if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
4775
0
      S.isCompleteType(Kind.getLocation(), T1)) {
4776
    // The type we're converting to is a class type. Enumerate its constructors
4777
    // to see if there is a suitable conversion.
4778
0
    CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4779
4780
0
    for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4781
0
      auto Info = getConstructorInfo(D);
4782
0
      if (!Info.Constructor)
4783
0
        continue;
4784
4785
0
      if (!Info.Constructor->isInvalidDecl() &&
4786
0
          Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4787
0
        if (Info.ConstructorTmpl)
4788
0
          S.AddTemplateOverloadCandidate(
4789
0
              Info.ConstructorTmpl, Info.FoundDecl,
4790
0
              /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4791
0
              /*SuppressUserConversions=*/true,
4792
0
              /*PartialOverloading*/ false, AllowExplicitCtors);
4793
0
        else
4794
0
          S.AddOverloadCandidate(
4795
0
              Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4796
0
              /*SuppressUserConversions=*/true,
4797
0
              /*PartialOverloading*/ false, AllowExplicitCtors);
4798
0
      }
4799
0
    }
4800
0
  }
4801
0
  if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
4802
0
    return OR_No_Viable_Function;
4803
4804
0
  const RecordType *T2RecordType = nullptr;
4805
0
  if ((T2RecordType = T2->getAs<RecordType>()) &&
4806
0
      S.isCompleteType(Kind.getLocation(), T2)) {
4807
    // The type we're converting from is a class type, enumerate its conversion
4808
    // functions.
4809
0
    CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4810
4811
0
    const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4812
0
    for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4813
0
      NamedDecl *D = *I;
4814
0
      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4815
0
      if (isa<UsingShadowDecl>(D))
4816
0
        D = cast<UsingShadowDecl>(D)->getTargetDecl();
4817
4818
0
      FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4819
0
      CXXConversionDecl *Conv;
4820
0
      if (ConvTemplate)
4821
0
        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4822
0
      else
4823
0
        Conv = cast<CXXConversionDecl>(D);
4824
4825
      // If the conversion function doesn't return a reference type,
4826
      // it can't be considered for this conversion unless we're allowed to
4827
      // consider rvalues.
4828
      // FIXME: Do we need to make sure that we only consider conversion
4829
      // candidates with reference-compatible results? That might be needed to
4830
      // break recursion.
4831
0
      if ((AllowRValues ||
4832
0
           Conv->getConversionType()->isLValueReferenceType())) {
4833
0
        if (ConvTemplate)
4834
0
          S.AddTemplateConversionCandidate(
4835
0
              ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4836
0
              CandidateSet,
4837
0
              /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4838
0
        else
4839
0
          S.AddConversionCandidate(
4840
0
              Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4841
0
              /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4842
0
      }
4843
0
    }
4844
0
  }
4845
0
  if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4846
0
    return OR_No_Viable_Function;
4847
4848
0
  SourceLocation DeclLoc = Initializer->getBeginLoc();
4849
4850
  // Perform overload resolution. If it fails, return the failed result.
4851
0
  OverloadCandidateSet::iterator Best;
4852
0
  if (OverloadingResult Result
4853
0
        = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4854
0
    return Result;
4855
4856
0
  FunctionDecl *Function = Best->Function;
4857
  // This is the overload that will be used for this initialization step if we
4858
  // use this initialization. Mark it as referenced.
4859
0
  Function->setReferenced();
4860
4861
  // Compute the returned type and value kind of the conversion.
4862
0
  QualType cv3T3;
4863
0
  if (isa<CXXConversionDecl>(Function))
4864
0
    cv3T3 = Function->getReturnType();
4865
0
  else
4866
0
    cv3T3 = T1;
4867
4868
0
  ExprValueKind VK = VK_PRValue;
4869
0
  if (cv3T3->isLValueReferenceType())
4870
0
    VK = VK_LValue;
4871
0
  else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4872
0
    VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
4873
0
  cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4874
4875
  // Add the user-defined conversion step.
4876
0
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4877
0
  Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4878
0
                                 HadMultipleCandidates);
4879
4880
  // Determine whether we'll need to perform derived-to-base adjustments or
4881
  // other conversions.
4882
0
  Sema::ReferenceConversions RefConv;
4883
0
  Sema::ReferenceCompareResult NewRefRelationship =
4884
0
      S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
4885
4886
  // Add the final conversion sequence, if necessary.
4887
0
  if (NewRefRelationship == Sema::Ref_Incompatible) {
4888
0
    assert(!isa<CXXConstructorDecl>(Function) &&
4889
0
           "should not have conversion after constructor");
4890
4891
0
    ImplicitConversionSequence ICS;
4892
0
    ICS.setStandard();
4893
0
    ICS.Standard = Best->FinalConversion;
4894
0
    Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4895
4896
    // Every implicit conversion results in a prvalue, except for a glvalue
4897
    // derived-to-base conversion, which we handle below.
4898
0
    cv3T3 = ICS.Standard.getToType(2);
4899
0
    VK = VK_PRValue;
4900
0
  }
4901
4902
  //   If the converted initializer is a prvalue, its type T4 is adjusted to
4903
  //   type "cv1 T4" and the temporary materialization conversion is applied.
4904
  //
4905
  // We adjust the cv-qualifications to match the reference regardless of
4906
  // whether we have a prvalue so that the AST records the change. In this
4907
  // case, T4 is "cv3 T3".
4908
0
  QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4909
0
  if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4910
0
    Sequence.AddQualificationConversionStep(cv1T4, VK);
4911
0
  Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
4912
0
  VK = IsLValueRef ? VK_LValue : VK_XValue;
4913
4914
0
  if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4915
0
    Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4916
0
  else if (RefConv & Sema::ReferenceConversions::ObjC)
4917
0
    Sequence.AddObjCObjectConversionStep(cv1T1);
4918
0
  else if (RefConv & Sema::ReferenceConversions::Function)
4919
0
    Sequence.AddFunctionReferenceConversionStep(cv1T1);
4920
0
  else if (RefConv & Sema::ReferenceConversions::Qualification) {
4921
0
    if (!S.Context.hasSameType(cv1T4, cv1T1))
4922
0
      Sequence.AddQualificationConversionStep(cv1T1, VK);
4923
0
  }
4924
4925
0
  return OR_Success;
4926
0
}
4927
4928
static void CheckCXX98CompatAccessibleCopy(Sema &S,
4929
                                           const InitializedEntity &Entity,
4930
                                           Expr *CurInitExpr);
4931
4932
/// Attempt reference initialization (C++0x [dcl.init.ref])
4933
static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity,
4934
                                       const InitializationKind &Kind,
4935
                                       Expr *Initializer,
4936
                                       InitializationSequence &Sequence,
4937
0
                                       bool TopLevelOfInitList) {
4938
0
  QualType DestType = Entity.getType();
4939
0
  QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4940
0
  Qualifiers T1Quals;
4941
0
  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4942
0
  QualType cv2T2 = S.getCompletedType(Initializer);
4943
0
  Qualifiers T2Quals;
4944
0
  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4945
4946
  // If the initializer is the address of an overloaded function, try
4947
  // to resolve the overloaded function. If all goes well, T2 is the
4948
  // type of the resulting function.
4949
0
  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4950
0
                                                   T1, Sequence))
4951
0
    return;
4952
4953
  // Delegate everything else to a subfunction.
4954
0
  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4955
0
                                 T1Quals, cv2T2, T2, T2Quals, Sequence,
4956
0
                                 TopLevelOfInitList);
4957
0
}
4958
4959
/// Determine whether an expression is a non-referenceable glvalue (one to
4960
/// which a reference can never bind). Attempting to bind a reference to
4961
/// such a glvalue will always create a temporary.
4962
0
static bool isNonReferenceableGLValue(Expr *E) {
4963
0
  return E->refersToBitField() || E->refersToVectorElement() ||
4964
0
         E->refersToMatrixElement();
4965
0
}
4966
4967
/// Reference initialization without resolving overloaded functions.
4968
///
4969
/// We also can get here in C if we call a builtin which is declared as
4970
/// a function with a parameter of reference type (such as __builtin_va_end()).
4971
static void TryReferenceInitializationCore(Sema &S,
4972
                                           const InitializedEntity &Entity,
4973
                                           const InitializationKind &Kind,
4974
                                           Expr *Initializer,
4975
                                           QualType cv1T1, QualType T1,
4976
                                           Qualifiers T1Quals,
4977
                                           QualType cv2T2, QualType T2,
4978
                                           Qualifiers T2Quals,
4979
                                           InitializationSequence &Sequence,
4980
0
                                           bool TopLevelOfInitList) {
4981
0
  QualType DestType = Entity.getType();
4982
0
  SourceLocation DeclLoc = Initializer->getBeginLoc();
4983
4984
  // Compute some basic properties of the types and the initializer.
4985
0
  bool isLValueRef = DestType->isLValueReferenceType();
4986
0
  bool isRValueRef = !isLValueRef;
4987
0
  Expr::Classification InitCategory = Initializer->Classify(S.Context);
4988
4989
0
  Sema::ReferenceConversions RefConv;
4990
0
  Sema::ReferenceCompareResult RefRelationship =
4991
0
      S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
4992
4993
  // C++0x [dcl.init.ref]p5:
4994
  //   A reference to type "cv1 T1" is initialized by an expression of type
4995
  //   "cv2 T2" as follows:
4996
  //
4997
  //     - If the reference is an lvalue reference and the initializer
4998
  //       expression
4999
  // Note the analogous bullet points for rvalue refs to functions. Because
5000
  // there are no function rvalues in C++, rvalue refs to functions are treated
5001
  // like lvalue refs.
5002
0
  OverloadingResult ConvOvlResult = OR_Success;
5003
0
  bool T1Function = T1->isFunctionType();
5004
0
  if (isLValueRef || T1Function) {
5005
0
    if (InitCategory.isLValue() && !isNonReferenceableGLValue(Initializer) &&
5006
0
        (RefRelationship == Sema::Ref_Compatible ||
5007
0
         (Kind.isCStyleOrFunctionalCast() &&
5008
0
          RefRelationship == Sema::Ref_Related))) {
5009
      //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
5010
      //     reference-compatible with "cv2 T2," or
5011
0
      if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
5012
0
                     Sema::ReferenceConversions::ObjC)) {
5013
        // If we're converting the pointee, add any qualifiers first;
5014
        // these qualifiers must all be top-level, so just convert to "cv1 T2".
5015
0
        if (RefConv & (Sema::ReferenceConversions::Qualification))
5016
0
          Sequence.AddQualificationConversionStep(
5017
0
              S.Context.getQualifiedType(T2, T1Quals),
5018
0
              Initializer->getValueKind());
5019
0
        if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5020
0
          Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
5021
0
        else
5022
0
          Sequence.AddObjCObjectConversionStep(cv1T1);
5023
0
      } else if (RefConv & Sema::ReferenceConversions::Qualification) {
5024
        // Perform a (possibly multi-level) qualification conversion.
5025
0
        Sequence.AddQualificationConversionStep(cv1T1,
5026
0
                                                Initializer->getValueKind());
5027
0
      } else if (RefConv & Sema::ReferenceConversions::Function) {
5028
0
        Sequence.AddFunctionReferenceConversionStep(cv1T1);
5029
0
      }
5030
5031
      // We only create a temporary here when binding a reference to a
5032
      // bit-field or vector element. Those cases are't supposed to be
5033
      // handled by this bullet, but the outcome is the same either way.
5034
0
      Sequence.AddReferenceBindingStep(cv1T1, false);
5035
0
      return;
5036
0
    }
5037
5038
    //     - has a class type (i.e., T2 is a class type), where T1 is not
5039
    //       reference-related to T2, and can be implicitly converted to an
5040
    //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
5041
    //       with "cv3 T3" (this conversion is selected by enumerating the
5042
    //       applicable conversion functions (13.3.1.6) and choosing the best
5043
    //       one through overload resolution (13.3)),
5044
    // If we have an rvalue ref to function type here, the rhs must be
5045
    // an rvalue. DR1287 removed the "implicitly" here.
5046
0
    if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
5047
0
        (isLValueRef || InitCategory.isRValue())) {
5048
0
      if (S.getLangOpts().CPlusPlus) {
5049
        // Try conversion functions only for C++.
5050
0
        ConvOvlResult = TryRefInitWithConversionFunction(
5051
0
            S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
5052
0
            /*IsLValueRef*/ isLValueRef, Sequence);
5053
0
        if (ConvOvlResult == OR_Success)
5054
0
          return;
5055
0
        if (ConvOvlResult != OR_No_Viable_Function)
5056
0
          Sequence.SetOverloadFailure(
5057
0
              InitializationSequence::FK_ReferenceInitOverloadFailed,
5058
0
              ConvOvlResult);
5059
0
      } else {
5060
0
        ConvOvlResult = OR_No_Viable_Function;
5061
0
      }
5062
0
    }
5063
0
  }
5064
5065
  //     - Otherwise, the reference shall be an lvalue reference to a
5066
  //       non-volatile const type (i.e., cv1 shall be const), or the reference
5067
  //       shall be an rvalue reference.
5068
  //       For address spaces, we interpret this to mean that an addr space
5069
  //       of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
5070
0
  if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile() &&
5071
0
                       T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5072
0
    if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5073
0
      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5074
0
    else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5075
0
      Sequence.SetOverloadFailure(
5076
0
                        InitializationSequence::FK_ReferenceInitOverloadFailed,
5077
0
                                  ConvOvlResult);
5078
0
    else if (!InitCategory.isLValue())
5079
0
      Sequence.SetFailed(
5080
0
          T1Quals.isAddressSpaceSupersetOf(T2Quals)
5081
0
              ? InitializationSequence::
5082
0
                    FK_NonConstLValueReferenceBindingToTemporary
5083
0
              : InitializationSequence::FK_ReferenceInitDropsQualifiers);
5084
0
    else {
5085
0
      InitializationSequence::FailureKind FK;
5086
0
      switch (RefRelationship) {
5087
0
      case Sema::Ref_Compatible:
5088
0
        if (Initializer->refersToBitField())
5089
0
          FK = InitializationSequence::
5090
0
              FK_NonConstLValueReferenceBindingToBitfield;
5091
0
        else if (Initializer->refersToVectorElement())
5092
0
          FK = InitializationSequence::
5093
0
              FK_NonConstLValueReferenceBindingToVectorElement;
5094
0
        else if (Initializer->refersToMatrixElement())
5095
0
          FK = InitializationSequence::
5096
0
              FK_NonConstLValueReferenceBindingToMatrixElement;
5097
0
        else
5098
0
          llvm_unreachable("unexpected kind of compatible initializer");
5099
0
        break;
5100
0
      case Sema::Ref_Related:
5101
0
        FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
5102
0
        break;
5103
0
      case Sema::Ref_Incompatible:
5104
0
        FK = InitializationSequence::
5105
0
            FK_NonConstLValueReferenceBindingToUnrelated;
5106
0
        break;
5107
0
      }
5108
0
      Sequence.SetFailed(FK);
5109
0
    }
5110
0
    return;
5111
0
  }
5112
5113
  //    - If the initializer expression
5114
  //      - is an
5115
  // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
5116
  // [1z]   rvalue (but not a bit-field) or
5117
  //        function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
5118
  //
5119
  // Note: functions are handled above and below rather than here...
5120
0
  if (!T1Function &&
5121
0
      (RefRelationship == Sema::Ref_Compatible ||
5122
0
       (Kind.isCStyleOrFunctionalCast() &&
5123
0
        RefRelationship == Sema::Ref_Related)) &&
5124
0
      ((InitCategory.isXValue() && !isNonReferenceableGLValue(Initializer)) ||
5125
0
       (InitCategory.isPRValue() &&
5126
0
        (S.getLangOpts().CPlusPlus17 || T2->isRecordType() ||
5127
0
         T2->isArrayType())))) {
5128
0
    ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue;
5129
0
    if (InitCategory.isPRValue() && T2->isRecordType()) {
5130
      // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
5131
      // compiler the freedom to perform a copy here or bind to the
5132
      // object, while C++0x requires that we bind directly to the
5133
      // object. Hence, we always bind to the object without making an
5134
      // extra copy. However, in C++03 requires that we check for the
5135
      // presence of a suitable copy constructor:
5136
      //
5137
      //   The constructor that would be used to make the copy shall
5138
      //   be callable whether or not the copy is actually done.
5139
0
      if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
5140
0
        Sequence.AddExtraneousCopyToTemporary(cv2T2);
5141
0
      else if (S.getLangOpts().CPlusPlus11)
5142
0
        CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
5143
0
    }
5144
5145
    // C++1z [dcl.init.ref]/5.2.1.2:
5146
    //   If the converted initializer is a prvalue, its type T4 is adjusted
5147
    //   to type "cv1 T4" and the temporary materialization conversion is
5148
    //   applied.
5149
    // Postpone address space conversions to after the temporary materialization
5150
    // conversion to allow creating temporaries in the alloca address space.
5151
0
    auto T1QualsIgnoreAS = T1Quals;
5152
0
    auto T2QualsIgnoreAS = T2Quals;
5153
0
    if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5154
0
      T1QualsIgnoreAS.removeAddressSpace();
5155
0
      T2QualsIgnoreAS.removeAddressSpace();
5156
0
    }
5157
0
    QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
5158
0
    if (T1QualsIgnoreAS != T2QualsIgnoreAS)
5159
0
      Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
5160
0
    Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
5161
0
    ValueKind = isLValueRef ? VK_LValue : VK_XValue;
5162
    // Add addr space conversion if required.
5163
0
    if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
5164
0
      auto T4Quals = cv1T4.getQualifiers();
5165
0
      T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5166
0
      QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5167
0
      Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5168
0
      cv1T4 = cv1T4WithAS;
5169
0
    }
5170
5171
    //   In any case, the reference is bound to the resulting glvalue (or to
5172
    //   an appropriate base class subobject).
5173
0
    if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5174
0
      Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5175
0
    else if (RefConv & Sema::ReferenceConversions::ObjC)
5176
0
      Sequence.AddObjCObjectConversionStep(cv1T1);
5177
0
    else if (RefConv & Sema::ReferenceConversions::Qualification) {
5178
0
      if (!S.Context.hasSameType(cv1T4, cv1T1))
5179
0
        Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5180
0
    }
5181
0
    return;
5182
0
  }
5183
5184
  //       - has a class type (i.e., T2 is a class type), where T1 is not
5185
  //         reference-related to T2, and can be implicitly converted to an
5186
  //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
5187
  //         where "cv1 T1" is reference-compatible with "cv3 T3",
5188
  //
5189
  // DR1287 removes the "implicitly" here.
5190
0
  if (T2->isRecordType()) {
5191
0
    if (RefRelationship == Sema::Ref_Incompatible) {
5192
0
      ConvOvlResult = TryRefInitWithConversionFunction(
5193
0
          S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5194
0
          /*IsLValueRef*/ isLValueRef, Sequence);
5195
0
      if (ConvOvlResult)
5196
0
        Sequence.SetOverloadFailure(
5197
0
            InitializationSequence::FK_ReferenceInitOverloadFailed,
5198
0
            ConvOvlResult);
5199
5200
0
      return;
5201
0
    }
5202
5203
0
    if (RefRelationship == Sema::Ref_Compatible &&
5204
0
        isRValueRef && InitCategory.isLValue()) {
5205
0
      Sequence.SetFailed(
5206
0
        InitializationSequence::FK_RValueReferenceBindingToLValue);
5207
0
      return;
5208
0
    }
5209
5210
0
    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5211
0
    return;
5212
0
  }
5213
5214
  //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
5215
  //        from the initializer expression using the rules for a non-reference
5216
  //        copy-initialization (8.5). The reference is then bound to the
5217
  //        temporary. [...]
5218
5219
  // Ignore address space of reference type at this point and perform address
5220
  // space conversion after the reference binding step.
5221
0
  QualType cv1T1IgnoreAS =
5222
0
      T1Quals.hasAddressSpace()
5223
0
          ? S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace())
5224
0
          : cv1T1;
5225
5226
0
  InitializedEntity TempEntity =
5227
0
      InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
5228
5229
  // FIXME: Why do we use an implicit conversion here rather than trying
5230
  // copy-initialization?
5231
0
  ImplicitConversionSequence ICS
5232
0
    = S.TryImplicitConversion(Initializer, TempEntity.getType(),
5233
0
                              /*SuppressUserConversions=*/false,
5234
0
                              Sema::AllowedExplicit::None,
5235
0
                              /*FIXME:InOverloadResolution=*/false,
5236
0
                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
5237
0
                              /*AllowObjCWritebackConversion=*/false);
5238
5239
0
  if (ICS.isBad()) {
5240
    // FIXME: Use the conversion function set stored in ICS to turn
5241
    // this into an overloading ambiguity diagnostic. However, we need
5242
    // to keep that set as an OverloadCandidateSet rather than as some
5243
    // other kind of set.
5244
0
    if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
5245
0
      Sequence.SetOverloadFailure(
5246
0
                        InitializationSequence::FK_ReferenceInitOverloadFailed,
5247
0
                                  ConvOvlResult);
5248
0
    else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
5249
0
      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
5250
0
    else
5251
0
      Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
5252
0
    return;
5253
0
  } else {
5254
0
    Sequence.AddConversionSequenceStep(ICS, TempEntity.getType(),
5255
0
                                       TopLevelOfInitList);
5256
0
  }
5257
5258
  //        [...] If T1 is reference-related to T2, cv1 must be the
5259
  //        same cv-qualification as, or greater cv-qualification
5260
  //        than, cv2; otherwise, the program is ill-formed.
5261
0
  unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
5262
0
  unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
5263
0
  if (RefRelationship == Sema::Ref_Related &&
5264
0
      ((T1CVRQuals | T2CVRQuals) != T1CVRQuals ||
5265
0
       !T1Quals.isAddressSpaceSupersetOf(T2Quals))) {
5266
0
    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5267
0
    return;
5268
0
  }
5269
5270
  //   [...] If T1 is reference-related to T2 and the reference is an rvalue
5271
  //   reference, the initializer expression shall not be an lvalue.
5272
0
  if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
5273
0
      InitCategory.isLValue()) {
5274
0
    Sequence.SetFailed(
5275
0
                    InitializationSequence::FK_RValueReferenceBindingToLValue);
5276
0
    return;
5277
0
  }
5278
5279
0
  Sequence.AddReferenceBindingStep(cv1T1IgnoreAS, /*BindingTemporary=*/true);
5280
5281
0
  if (T1Quals.hasAddressSpace()) {
5282
0
    if (!Qualifiers::isAddressSpaceSupersetOf(T1Quals.getAddressSpace(),
5283
0
                                              LangAS::Default)) {
5284
0
      Sequence.SetFailed(
5285
0
          InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary);
5286
0
      return;
5287
0
    }
5288
0
    Sequence.AddQualificationConversionStep(cv1T1, isLValueRef ? VK_LValue
5289
0
                                                               : VK_XValue);
5290
0
  }
5291
0
}
5292
5293
/// Attempt character array initialization from a string literal
5294
/// (C++ [dcl.init.string], C99 6.7.8).
5295
static void TryStringLiteralInitialization(Sema &S,
5296
                                           const InitializedEntity &Entity,
5297
                                           const InitializationKind &Kind,
5298
                                           Expr *Initializer,
5299
0
                                       InitializationSequence &Sequence) {
5300
0
  Sequence.AddStringInitStep(Entity.getType());
5301
0
}
5302
5303
/// Attempt value initialization (C++ [dcl.init]p7).
5304
static void TryValueInitialization(Sema &S,
5305
                                   const InitializedEntity &Entity,
5306
                                   const InitializationKind &Kind,
5307
                                   InitializationSequence &Sequence,
5308
0
                                   InitListExpr *InitList) {
5309
0
  assert((!InitList || InitList->getNumInits() == 0) &&
5310
0
         "Shouldn't use value-init for non-empty init lists");
5311
5312
  // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
5313
  //
5314
  //   To value-initialize an object of type T means:
5315
0
  QualType T = Entity.getType();
5316
5317
  //     -- if T is an array type, then each element is value-initialized;
5318
0
  T = S.Context.getBaseElementType(T);
5319
5320
0
  if (const RecordType *RT = T->getAs<RecordType>()) {
5321
0
    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
5322
0
      bool NeedZeroInitialization = true;
5323
      // C++98:
5324
      // -- if T is a class type (clause 9) with a user-declared constructor
5325
      //    (12.1), then the default constructor for T is called (and the
5326
      //    initialization is ill-formed if T has no accessible default
5327
      //    constructor);
5328
      // C++11:
5329
      // -- if T is a class type (clause 9) with either no default constructor
5330
      //    (12.1 [class.ctor]) or a default constructor that is user-provided
5331
      //    or deleted, then the object is default-initialized;
5332
      //
5333
      // Note that the C++11 rule is the same as the C++98 rule if there are no
5334
      // defaulted or deleted constructors, so we just use it unconditionally.
5335
0
      CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
5336
0
      if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
5337
0
        NeedZeroInitialization = false;
5338
5339
      // -- if T is a (possibly cv-qualified) non-union class type without a
5340
      //    user-provided or deleted default constructor, then the object is
5341
      //    zero-initialized and, if T has a non-trivial default constructor,
5342
      //    default-initialized;
5343
      // The 'non-union' here was removed by DR1502. The 'non-trivial default
5344
      // constructor' part was removed by DR1507.
5345
0
      if (NeedZeroInitialization)
5346
0
        Sequence.AddZeroInitializationStep(Entity.getType());
5347
5348
      // C++03:
5349
      // -- if T is a non-union class type without a user-declared constructor,
5350
      //    then every non-static data member and base class component of T is
5351
      //    value-initialized;
5352
      // [...] A program that calls for [...] value-initialization of an
5353
      // entity of reference type is ill-formed.
5354
      //
5355
      // C++11 doesn't need this handling, because value-initialization does not
5356
      // occur recursively there, and the implicit default constructor is
5357
      // defined as deleted in the problematic cases.
5358
0
      if (!S.getLangOpts().CPlusPlus11 &&
5359
0
          ClassDecl->hasUninitializedReferenceMember()) {
5360
0
        Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
5361
0
        return;
5362
0
      }
5363
5364
      // If this is list-value-initialization, pass the empty init list on when
5365
      // building the constructor call. This affects the semantics of a few
5366
      // things (such as whether an explicit default constructor can be called).
5367
0
      Expr *InitListAsExpr = InitList;
5368
0
      MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
5369
0
      bool InitListSyntax = InitList;
5370
5371
      // FIXME: Instead of creating a CXXConstructExpr of array type here,
5372
      // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr.
5373
0
      return TryConstructorInitialization(
5374
0
          S, Entity, Kind, Args, T, Entity.getType(), Sequence, InitListSyntax);
5375
0
    }
5376
0
  }
5377
5378
0
  Sequence.AddZeroInitializationStep(Entity.getType());
5379
0
}
5380
5381
/// Attempt default initialization (C++ [dcl.init]p6).
5382
static void TryDefaultInitialization(Sema &S,
5383
                                     const InitializedEntity &Entity,
5384
                                     const InitializationKind &Kind,
5385
0
                                     InitializationSequence &Sequence) {
5386
0
  assert(Kind.getKind() == InitializationKind::IK_Default);
5387
5388
  // C++ [dcl.init]p6:
5389
  //   To default-initialize an object of type T means:
5390
  //     - if T is an array type, each element is default-initialized;
5391
0
  QualType DestType = S.Context.getBaseElementType(Entity.getType());
5392
5393
  //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
5394
  //       constructor for T is called (and the initialization is ill-formed if
5395
  //       T has no accessible default constructor);
5396
0
  if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
5397
0
    TryConstructorInitialization(S, Entity, Kind, std::nullopt, DestType,
5398
0
                                 Entity.getType(), Sequence);
5399
0
    return;
5400
0
  }
5401
5402
  //     - otherwise, no initialization is performed.
5403
5404
  //   If a program calls for the default initialization of an object of
5405
  //   a const-qualified type T, T shall be a class type with a user-provided
5406
  //   default constructor.
5407
0
  if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
5408
0
    if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
5409
0
      Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
5410
0
    return;
5411
0
  }
5412
5413
  // If the destination type has a lifetime property, zero-initialize it.
5414
0
  if (DestType.getQualifiers().hasObjCLifetime()) {
5415
0
    Sequence.AddZeroInitializationStep(Entity.getType());
5416
0
    return;
5417
0
  }
5418
0
}
5419
5420
static void TryOrBuildParenListInitialization(
5421
    Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
5422
    ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly,
5423
0
    ExprResult *Result = nullptr) {
5424
0
  unsigned EntityIndexToProcess = 0;
5425
0
  SmallVector<Expr *, 4> InitExprs;
5426
0
  QualType ResultType;
5427
0
  Expr *ArrayFiller = nullptr;
5428
0
  FieldDecl *InitializedFieldInUnion = nullptr;
5429
5430
0
  auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity,
5431
0
                                     const InitializationKind &SubKind,
5432
0
                                     Expr *Arg, Expr **InitExpr = nullptr) {
5433
0
    InitializationSequence IS = InitializationSequence(
5434
0
        S, SubEntity, SubKind, Arg ? MultiExprArg(Arg) : std::nullopt);
5435
5436
0
    if (IS.Failed()) {
5437
0
      if (!VerifyOnly) {
5438
0
        IS.Diagnose(S, SubEntity, SubKind, Arg ? ArrayRef(Arg) : std::nullopt);
5439
0
      } else {
5440
0
        Sequence.SetFailed(
5441
0
            InitializationSequence::FK_ParenthesizedListInitFailed);
5442
0
      }
5443
5444
0
      return false;
5445
0
    }
5446
0
    if (!VerifyOnly) {
5447
0
      ExprResult ER;
5448
0
      ER = IS.Perform(S, SubEntity, SubKind,
5449
0
                      Arg ? MultiExprArg(Arg) : std::nullopt);
5450
0
      if (InitExpr)
5451
0
        *InitExpr = ER.get();
5452
0
      else
5453
0
        InitExprs.push_back(ER.get());
5454
0
    }
5455
0
    return true;
5456
0
  };
5457
5458
0
  if (const ArrayType *AT =
5459
0
          S.getASTContext().getAsArrayType(Entity.getType())) {
5460
0
    SmallVector<InitializedEntity, 4> ElementEntities;
5461
0
    uint64_t ArrayLength;
5462
    // C++ [dcl.init]p16.5
5463
    //   if the destination type is an array, the object is initialized as
5464
    //   follows. Let x1, . . . , xk be the elements of the expression-list. If
5465
    //   the destination type is an array of unknown bound, it is defined as
5466
    //   having k elements.
5467
0
    if (const ConstantArrayType *CAT =
5468
0
            S.getASTContext().getAsConstantArrayType(Entity.getType())) {
5469
0
      ArrayLength = CAT->getSize().getZExtValue();
5470
0
      ResultType = Entity.getType();
5471
0
    } else if (const VariableArrayType *VAT =
5472
0
                   S.getASTContext().getAsVariableArrayType(Entity.getType())) {
5473
      // Braced-initialization of variable array types is not allowed, even if
5474
      // the size is greater than or equal to the number of args, so we don't
5475
      // allow them to be initialized via parenthesized aggregate initialization
5476
      // either.
5477
0
      const Expr *SE = VAT->getSizeExpr();
5478
0
      S.Diag(SE->getBeginLoc(), diag::err_variable_object_no_init)
5479
0
          << SE->getSourceRange();
5480
0
      return;
5481
0
    } else {
5482
0
      assert(isa<IncompleteArrayType>(Entity.getType()));
5483
0
      ArrayLength = Args.size();
5484
0
    }
5485
0
    EntityIndexToProcess = ArrayLength;
5486
5487
    //   ...the ith array element is copy-initialized with xi for each
5488
    //   1 <= i <= k
5489
0
    for (Expr *E : Args) {
5490
0
      InitializedEntity SubEntity = InitializedEntity::InitializeElement(
5491
0
          S.getASTContext(), EntityIndexToProcess, Entity);
5492
0
      InitializationKind SubKind = InitializationKind::CreateForInit(
5493
0
          E->getExprLoc(), /*isDirectInit=*/false, E);
5494
0
      if (!HandleInitializedEntity(SubEntity, SubKind, E))
5495
0
        return;
5496
0
    }
5497
    //   ...and value-initialized for each k < i <= n;
5498
0
    if (ArrayLength > Args.size()) {
5499
0
      InitializedEntity SubEntity = InitializedEntity::InitializeElement(
5500
0
          S.getASTContext(), Args.size(), Entity);
5501
0
      InitializationKind SubKind = InitializationKind::CreateValue(
5502
0
          Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5503
0
      if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller))
5504
0
        return;
5505
0
    }
5506
5507
0
    if (ResultType.isNull()) {
5508
0
      ResultType = S.Context.getConstantArrayType(
5509
0
          AT->getElementType(), llvm::APInt(/*numBits=*/32, ArrayLength),
5510
0
          /*SizeExpr=*/nullptr, ArraySizeModifier::Normal, 0);
5511
0
    }
5512
0
  } else if (auto *RT = Entity.getType()->getAs<RecordType>()) {
5513
0
    bool IsUnion = RT->isUnionType();
5514
0
    const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5515
0
    if (RD->isInvalidDecl()) {
5516
      // Exit early to avoid confusion when processing members.
5517
      // We do the same for braced list initialization in
5518
      // `CheckStructUnionTypes`.
5519
0
      Sequence.SetFailed(
5520
0
          clang::InitializationSequence::FK_ParenthesizedListInitFailed);
5521
0
      return;
5522
0
    }
5523
5524
0
    if (!IsUnion) {
5525
0
      for (const CXXBaseSpecifier &Base : RD->bases()) {
5526
0
        InitializedEntity SubEntity = InitializedEntity::InitializeBase(
5527
0
            S.getASTContext(), &Base, false, &Entity);
5528
0
        if (EntityIndexToProcess < Args.size()) {
5529
          // C++ [dcl.init]p16.6.2.2.
5530
          //   ...the object is initialized is follows. Let e1, ..., en be the
5531
          //   elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be
5532
          //   the elements of the expression-list...The element ei is
5533
          //   copy-initialized with xi for 1 <= i <= k.
5534
0
          Expr *E = Args[EntityIndexToProcess];
5535
0
          InitializationKind SubKind = InitializationKind::CreateForInit(
5536
0
              E->getExprLoc(), /*isDirectInit=*/false, E);
5537
0
          if (!HandleInitializedEntity(SubEntity, SubKind, E))
5538
0
            return;
5539
0
        } else {
5540
          // We've processed all of the args, but there are still base classes
5541
          // that have to be initialized.
5542
          // C++ [dcl.init]p17.6.2.2
5543
          //   The remaining elements...otherwise are value initialzed
5544
0
          InitializationKind SubKind = InitializationKind::CreateValue(
5545
0
              Kind.getLocation(), Kind.getLocation(), Kind.getLocation(),
5546
0
              /*IsImplicit=*/true);
5547
0
          if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5548
0
            return;
5549
0
        }
5550
0
        EntityIndexToProcess++;
5551
0
      }
5552
0
    }
5553
5554
0
    for (FieldDecl *FD : RD->fields()) {
5555
      // Unnamed bitfields should not be initialized at all, either with an arg
5556
      // or by default.
5557
0
      if (FD->isUnnamedBitfield())
5558
0
        continue;
5559
5560
0
      InitializedEntity SubEntity =
5561
0
          InitializedEntity::InitializeMemberFromParenAggInit(FD);
5562
5563
0
      if (EntityIndexToProcess < Args.size()) {
5564
        //   ...The element ei is copy-initialized with xi for 1 <= i <= k.
5565
0
        Expr *E = Args[EntityIndexToProcess];
5566
5567
        // Incomplete array types indicate flexible array members. Do not allow
5568
        // paren list initializations of structs with these members, as GCC
5569
        // doesn't either.
5570
0
        if (FD->getType()->isIncompleteArrayType()) {
5571
0
          if (!VerifyOnly) {
5572
0
            S.Diag(E->getBeginLoc(), diag::err_flexible_array_init)
5573
0
                << SourceRange(E->getBeginLoc(), E->getEndLoc());
5574
0
            S.Diag(FD->getLocation(), diag::note_flexible_array_member) << FD;
5575
0
          }
5576
0
          Sequence.SetFailed(
5577
0
              InitializationSequence::FK_ParenthesizedListInitFailed);
5578
0
          return;
5579
0
        }
5580
5581
0
        InitializationKind SubKind = InitializationKind::CreateForInit(
5582
0
            E->getExprLoc(), /*isDirectInit=*/false, E);
5583
0
        if (!HandleInitializedEntity(SubEntity, SubKind, E))
5584
0
          return;
5585
5586
        // Unions should have only one initializer expression, so we bail out
5587
        // after processing the first field. If there are more initializers then
5588
        // it will be caught when we later check whether EntityIndexToProcess is
5589
        // less than Args.size();
5590
0
        if (IsUnion) {
5591
0
          InitializedFieldInUnion = FD;
5592
0
          EntityIndexToProcess = 1;
5593
0
          break;
5594
0
        }
5595
0
      } else {
5596
        // We've processed all of the args, but there are still members that
5597
        // have to be initialized.
5598
0
        if (FD->hasInClassInitializer()) {
5599
0
          if (!VerifyOnly) {
5600
            // C++ [dcl.init]p16.6.2.2
5601
            //   The remaining elements are initialized with their default
5602
            //   member initializers, if any
5603
0
            ExprResult DIE = S.BuildCXXDefaultInitExpr(
5604
0
                Kind.getParenOrBraceRange().getEnd(), FD);
5605
0
            if (DIE.isInvalid())
5606
0
              return;
5607
0
            S.checkInitializerLifetime(SubEntity, DIE.get());
5608
0
            InitExprs.push_back(DIE.get());
5609
0
          }
5610
0
        } else {
5611
          // C++ [dcl.init]p17.6.2.2
5612
          //   The remaining elements...otherwise are value initialzed
5613
0
          if (FD->getType()->isReferenceType()) {
5614
0
            Sequence.SetFailed(
5615
0
                InitializationSequence::FK_ParenthesizedListInitFailed);
5616
0
            if (!VerifyOnly) {
5617
0
              SourceRange SR = Kind.getParenOrBraceRange();
5618
0
              S.Diag(SR.getEnd(), diag::err_init_reference_member_uninitialized)
5619
0
                  << FD->getType() << SR;
5620
0
              S.Diag(FD->getLocation(), diag::note_uninit_reference_member);
5621
0
            }
5622
0
            return;
5623
0
          }
5624
0
          InitializationKind SubKind = InitializationKind::CreateValue(
5625
0
              Kind.getLocation(), Kind.getLocation(), Kind.getLocation(), true);
5626
0
          if (!HandleInitializedEntity(SubEntity, SubKind, nullptr))
5627
0
            return;
5628
0
        }
5629
0
      }
5630
0
      EntityIndexToProcess++;
5631
0
    }
5632
0
    ResultType = Entity.getType();
5633
0
  }
5634
5635
  // Not all of the args have been processed, so there must've been more args
5636
  // than were required to initialize the element.
5637
0
  if (EntityIndexToProcess < Args.size()) {
5638
0
    Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed);
5639
0
    if (!VerifyOnly) {
5640
0
      QualType T = Entity.getType();
5641
0
      int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 3 : 4;
5642
0
      SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(),
5643
0
                               Args.back()->getEndLoc());
5644
0
      S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5645
0
          << InitKind << ExcessInitSR;
5646
0
    }
5647
0
    return;
5648
0
  }
5649
5650
0
  if (VerifyOnly) {
5651
0
    Sequence.setSequenceKind(InitializationSequence::NormalSequence);
5652
0
    Sequence.AddParenthesizedListInitStep(Entity.getType());
5653
0
  } else if (Result) {
5654
0
    SourceRange SR = Kind.getParenOrBraceRange();
5655
0
    auto *CPLIE = CXXParenListInitExpr::Create(
5656
0
        S.getASTContext(), InitExprs, ResultType, Args.size(),
5657
0
        Kind.getLocation(), SR.getBegin(), SR.getEnd());
5658
0
    if (ArrayFiller)
5659
0
      CPLIE->setArrayFiller(ArrayFiller);
5660
0
    if (InitializedFieldInUnion)
5661
0
      CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion);
5662
0
    *Result = CPLIE;
5663
0
    S.Diag(Kind.getLocation(),
5664
0
           diag::warn_cxx17_compat_aggregate_init_paren_list)
5665
0
        << Kind.getLocation() << SR << ResultType;
5666
0
  }
5667
0
}
5668
5669
/// Attempt a user-defined conversion between two types (C++ [dcl.init]),
5670
/// which enumerates all conversion functions and performs overload resolution
5671
/// to select the best.
5672
static void TryUserDefinedConversion(Sema &S,
5673
                                     QualType DestType,
5674
                                     const InitializationKind &Kind,
5675
                                     Expr *Initializer,
5676
                                     InitializationSequence &Sequence,
5677
0
                                     bool TopLevelOfInitList) {
5678
0
  assert(!DestType->isReferenceType() && "References are handled elsewhere");
5679
0
  QualType SourceType = Initializer->getType();
5680
0
  assert((DestType->isRecordType() || SourceType->isRecordType()) &&
5681
0
         "Must have a class type to perform a user-defined conversion");
5682
5683
  // Build the candidate set directly in the initialization sequence
5684
  // structure, so that it will persist if we fail.
5685
0
  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
5686
0
  CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5687
0
  CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
5688
5689
  // Determine whether we are allowed to call explicit constructors or
5690
  // explicit conversion operators.
5691
0
  bool AllowExplicit = Kind.AllowExplicit();
5692
5693
0
  if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
5694
    // The type we're converting to is a class type. Enumerate its constructors
5695
    // to see if there is a suitable conversion.
5696
0
    CXXRecordDecl *DestRecordDecl
5697
0
      = cast<CXXRecordDecl>(DestRecordType->getDecl());
5698
5699
    // Try to complete the type we're converting to.
5700
0
    if (S.isCompleteType(Kind.getLocation(), DestType)) {
5701
0
      for (NamedDecl *D : S.LookupConstructors(DestRecordDecl)) {
5702
0
        auto Info = getConstructorInfo(D);
5703
0
        if (!Info.Constructor)
5704
0
          continue;
5705
5706
0
        if (!Info.Constructor->isInvalidDecl() &&
5707
0
            Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
5708
0
          if (Info.ConstructorTmpl)
5709
0
            S.AddTemplateOverloadCandidate(
5710
0
                Info.ConstructorTmpl, Info.FoundDecl,
5711
0
                /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
5712
0
                /*SuppressUserConversions=*/true,
5713
0
                /*PartialOverloading*/ false, AllowExplicit);
5714
0
          else
5715
0
            S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
5716
0
                                   Initializer, CandidateSet,
5717
0
                                   /*SuppressUserConversions=*/true,
5718
0
                                   /*PartialOverloading*/ false, AllowExplicit);
5719
0
        }
5720
0
      }
5721
0
    }
5722
0
  }
5723
5724
0
  SourceLocation DeclLoc = Initializer->getBeginLoc();
5725
5726
0
  if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
5727
    // The type we're converting from is a class type, enumerate its conversion
5728
    // functions.
5729
5730
    // We can only enumerate the conversion functions for a complete type; if
5731
    // the type isn't complete, simply skip this step.
5732
0
    if (S.isCompleteType(DeclLoc, SourceType)) {
5733
0
      CXXRecordDecl *SourceRecordDecl
5734
0
        = cast<CXXRecordDecl>(SourceRecordType->getDecl());
5735
5736
0
      const auto &Conversions =
5737
0
          SourceRecordDecl->getVisibleConversionFunctions();
5738
0
      for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5739
0
        NamedDecl *D = *I;
5740
0
        CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5741
0
        if (isa<UsingShadowDecl>(D))
5742
0
          D = cast<UsingShadowDecl>(D)->getTargetDecl();
5743
5744
0
        FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5745
0
        CXXConversionDecl *Conv;
5746
0
        if (ConvTemplate)
5747
0
          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5748
0
        else
5749
0
          Conv = cast<CXXConversionDecl>(D);
5750
5751
0
        if (ConvTemplate)
5752
0
          S.AddTemplateConversionCandidate(
5753
0
              ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
5754
0
              CandidateSet, AllowExplicit, AllowExplicit);
5755
0
        else
5756
0
          S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
5757
0
                                   DestType, CandidateSet, AllowExplicit,
5758
0
                                   AllowExplicit);
5759
0
      }
5760
0
    }
5761
0
  }
5762
5763
  // Perform overload resolution. If it fails, return the failed result.
5764
0
  OverloadCandidateSet::iterator Best;
5765
0
  if (OverloadingResult Result
5766
0
        = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5767
0
    Sequence.SetOverloadFailure(
5768
0
        InitializationSequence::FK_UserConversionOverloadFailed, Result);
5769
5770
    // [class.copy.elision]p3:
5771
    // In some copy-initialization contexts, a two-stage overload resolution
5772
    // is performed.
5773
    // If the first overload resolution selects a deleted function, we also
5774
    // need the initialization sequence to decide whether to perform the second
5775
    // overload resolution.
5776
0
    if (!(Result == OR_Deleted &&
5777
0
          Kind.getKind() == InitializationKind::IK_Copy))
5778
0
      return;
5779
0
  }
5780
5781
0
  FunctionDecl *Function = Best->Function;
5782
0
  Function->setReferenced();
5783
0
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
5784
5785
0
  if (isa<CXXConstructorDecl>(Function)) {
5786
    // Add the user-defined conversion step. Any cv-qualification conversion is
5787
    // subsumed by the initialization. Per DR5, the created temporary is of the
5788
    // cv-unqualified type of the destination.
5789
0
    Sequence.AddUserConversionStep(Function, Best->FoundDecl,
5790
0
                                   DestType.getUnqualifiedType(),
5791
0
                                   HadMultipleCandidates);
5792
5793
    // C++14 and before:
5794
    //   - if the function is a constructor, the call initializes a temporary
5795
    //     of the cv-unqualified version of the destination type. The [...]
5796
    //     temporary [...] is then used to direct-initialize, according to the
5797
    //     rules above, the object that is the destination of the
5798
    //     copy-initialization.
5799
    // Note that this just performs a simple object copy from the temporary.
5800
    //
5801
    // C++17:
5802
    //   - if the function is a constructor, the call is a prvalue of the
5803
    //     cv-unqualified version of the destination type whose return object
5804
    //     is initialized by the constructor. The call is used to
5805
    //     direct-initialize, according to the rules above, the object that
5806
    //     is the destination of the copy-initialization.
5807
    // Therefore we need to do nothing further.
5808
    //
5809
    // FIXME: Mark this copy as extraneous.
5810
0
    if (!S.getLangOpts().CPlusPlus17)
5811
0
      Sequence.AddFinalCopy(DestType);
5812
0
    else if (DestType.hasQualifiers())
5813
0
      Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5814
0
    return;
5815
0
  }
5816
5817
  // Add the user-defined conversion step that calls the conversion function.
5818
0
  QualType ConvType = Function->getCallResultType();
5819
0
  Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
5820
0
                                 HadMultipleCandidates);
5821
5822
0
  if (ConvType->getAs<RecordType>()) {
5823
    //   The call is used to direct-initialize [...] the object that is the
5824
    //   destination of the copy-initialization.
5825
    //
5826
    // In C++17, this does not call a constructor if we enter /17.6.1:
5827
    //   - If the initializer expression is a prvalue and the cv-unqualified
5828
    //     version of the source type is the same as the class of the
5829
    //     destination [... do not make an extra copy]
5830
    //
5831
    // FIXME: Mark this copy as extraneous.
5832
0
    if (!S.getLangOpts().CPlusPlus17 ||
5833
0
        Function->getReturnType()->isReferenceType() ||
5834
0
        !S.Context.hasSameUnqualifiedType(ConvType, DestType))
5835
0
      Sequence.AddFinalCopy(DestType);
5836
0
    else if (!S.Context.hasSameType(ConvType, DestType))
5837
0
      Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
5838
0
    return;
5839
0
  }
5840
5841
  // If the conversion following the call to the conversion function
5842
  // is interesting, add it as a separate step.
5843
0
  if (Best->FinalConversion.First || Best->FinalConversion.Second ||
5844
0
      Best->FinalConversion.Third) {
5845
0
    ImplicitConversionSequence ICS;
5846
0
    ICS.setStandard();
5847
0
    ICS.Standard = Best->FinalConversion;
5848
0
    Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
5849
0
  }
5850
0
}
5851
5852
/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
5853
/// a function with a pointer return type contains a 'return false;' statement.
5854
/// In C++11, 'false' is not a null pointer, so this breaks the build of any
5855
/// code using that header.
5856
///
5857
/// Work around this by treating 'return false;' as zero-initializing the result
5858
/// if it's used in a pointer-returning function in a system header.
5859
static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
5860
                                              const InitializedEntity &Entity,
5861
0
                                              const Expr *Init) {
5862
0
  return S.getLangOpts().CPlusPlus11 &&
5863
0
         Entity.getKind() == InitializedEntity::EK_Result &&
5864
0
         Entity.getType()->isPointerType() &&
5865
0
         isa<CXXBoolLiteralExpr>(Init) &&
5866
0
         !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
5867
0
         S.getSourceManager().isInSystemHeader(Init->getExprLoc());
5868
0
}
5869
5870
/// The non-zero enum values here are indexes into diagnostic alternatives.
5871
enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
5872
5873
/// Determines whether this expression is an acceptable ICR source.
5874
static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
5875
0
                                         bool isAddressOf, bool &isWeakAccess) {
5876
  // Skip parens.
5877
0
  e = e->IgnoreParens();
5878
5879
  // Skip address-of nodes.
5880
0
  if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
5881
0
    if (op->getOpcode() == UO_AddrOf)
5882
0
      return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
5883
0
                                isWeakAccess);
5884
5885
  // Skip certain casts.
5886
0
  } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
5887
0
    switch (ce->getCastKind()) {
5888
0
    case CK_Dependent:
5889
0
    case CK_BitCast:
5890
0
    case CK_LValueBitCast:
5891
0
    case CK_NoOp:
5892
0
      return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
5893
5894
0
    case CK_ArrayToPointerDecay:
5895
0
      return IIK_nonscalar;
5896
5897
0
    case CK_NullToPointer:
5898
0
      return IIK_okay;
5899
5900
0
    default:
5901
0
      break;
5902
0
    }
5903
5904
  // If we have a declaration reference, it had better be a local variable.
5905
0
  } else if (isa<DeclRefExpr>(e)) {
5906
    // set isWeakAccess to true, to mean that there will be an implicit
5907
    // load which requires a cleanup.
5908
0
    if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
5909
0
      isWeakAccess = true;
5910
5911
0
    if (!isAddressOf) return IIK_nonlocal;
5912
5913
0
    VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
5914
0
    if (!var) return IIK_nonlocal;
5915
5916
0
    return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
5917
5918
  // If we have a conditional operator, check both sides.
5919
0
  } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
5920
0
    if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
5921
0
                                                isWeakAccess))
5922
0
      return iik;
5923
5924
0
    return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
5925
5926
  // These are never scalar.
5927
0
  } else if (isa<ArraySubscriptExpr>(e)) {
5928
0
    return IIK_nonscalar;
5929
5930
  // Otherwise, it needs to be a null pointer constant.
5931
0
  } else {
5932
0
    return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
5933
0
            ? IIK_okay : IIK_nonlocal);
5934
0
  }
5935
5936
0
  return IIK_nonlocal;
5937
0
}
5938
5939
/// Check whether the given expression is a valid operand for an
5940
/// indirect copy/restore.
5941
0
static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
5942
0
  assert(src->isPRValue());
5943
0
  bool isWeakAccess = false;
5944
0
  InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
5945
  // If isWeakAccess to true, there will be an implicit
5946
  // load which requires a cleanup.
5947
0
  if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
5948
0
    S.Cleanup.setExprNeedsCleanups(true);
5949
5950
0
  if (iik == IIK_okay) return;
5951
5952
0
  S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
5953
0
    << ((unsigned) iik - 1)  // shift index into diagnostic explanations
5954
0
    << src->getSourceRange();
5955
0
}
5956
5957
/// Determine whether we have compatible array types for the
5958
/// purposes of GNU by-copy array initialization.
5959
static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest,
5960
0
                                    const ArrayType *Source) {
5961
  // If the source and destination array types are equivalent, we're
5962
  // done.
5963
0
  if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
5964
0
    return true;
5965
5966
  // Make sure that the element types are the same.
5967
0
  if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
5968
0
    return false;
5969
5970
  // The only mismatch we allow is when the destination is an
5971
  // incomplete array type and the source is a constant array type.
5972
0
  return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
5973
0
}
5974
5975
static bool tryObjCWritebackConversion(Sema &S,
5976
                                       InitializationSequence &Sequence,
5977
                                       const InitializedEntity &Entity,
5978
0
                                       Expr *Initializer) {
5979
0
  bool ArrayDecay = false;
5980
0
  QualType ArgType = Initializer->getType();
5981
0
  QualType ArgPointee;
5982
0
  if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
5983
0
    ArrayDecay = true;
5984
0
    ArgPointee = ArgArrayType->getElementType();
5985
0
    ArgType = S.Context.getPointerType(ArgPointee);
5986
0
  }
5987
5988
  // Handle write-back conversion.
5989
0
  QualType ConvertedArgType;
5990
0
  if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
5991
0
                                   ConvertedArgType))
5992
0
    return false;
5993
5994
  // We should copy unless we're passing to an argument explicitly
5995
  // marked 'out'.
5996
0
  bool ShouldCopy = true;
5997
0
  if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
5998
0
    ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
5999
6000
  // Do we need an lvalue conversion?
6001
0
  if (ArrayDecay || Initializer->isGLValue()) {
6002
0
    ImplicitConversionSequence ICS;
6003
0
    ICS.setStandard();
6004
0
    ICS.Standard.setAsIdentityConversion();
6005
6006
0
    QualType ResultType;
6007
0
    if (ArrayDecay) {
6008
0
      ICS.Standard.First = ICK_Array_To_Pointer;
6009
0
      ResultType = S.Context.getPointerType(ArgPointee);
6010
0
    } else {
6011
0
      ICS.Standard.First = ICK_Lvalue_To_Rvalue;
6012
0
      ResultType = Initializer->getType().getNonLValueExprType(S.Context);
6013
0
    }
6014
6015
0
    Sequence.AddConversionSequenceStep(ICS, ResultType);
6016
0
  }
6017
6018
0
  Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
6019
0
  return true;
6020
0
}
6021
6022
static bool TryOCLSamplerInitialization(Sema &S,
6023
                                        InitializationSequence &Sequence,
6024
                                        QualType DestType,
6025
7
                                        Expr *Initializer) {
6026
7
  if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
6027
7
      (!Initializer->isIntegerConstantExpr(S.Context) &&
6028
0
      !Initializer->getType()->isSamplerT()))
6029
7
    return false;
6030
6031
0
  Sequence.AddOCLSamplerInitStep(DestType);
6032
0
  return true;
6033
7
}
6034
6035
0
static bool IsZeroInitializer(Expr *Initializer, Sema &S) {
6036
0
  return Initializer->isIntegerConstantExpr(S.getASTContext()) &&
6037
0
    (Initializer->EvaluateKnownConstInt(S.getASTContext()) == 0);
6038
0
}
6039
6040
static bool TryOCLZeroOpaqueTypeInitialization(Sema &S,
6041
                                               InitializationSequence &Sequence,
6042
                                               QualType DestType,
6043
7
                                               Expr *Initializer) {
6044
7
  if (!S.getLangOpts().OpenCL)
6045
7
    return false;
6046
6047
  //
6048
  // OpenCL 1.2 spec, s6.12.10
6049
  //
6050
  // The event argument can also be used to associate the
6051
  // async_work_group_copy with a previous async copy allowing
6052
  // an event to be shared by multiple async copies; otherwise
6053
  // event should be zero.
6054
  //
6055
0
  if (DestType->isEventT() || DestType->isQueueT()) {
6056
0
    if (!IsZeroInitializer(Initializer, S))
6057
0
      return false;
6058
6059
0
    Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6060
0
    return true;
6061
0
  }
6062
6063
  // We should allow zero initialization for all types defined in the
6064
  // cl_intel_device_side_avc_motion_estimation extension, except
6065
  // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t.
6066
0
  if (S.getOpenCLOptions().isAvailableOption(
6067
0
          "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()) &&
6068
0
      DestType->isOCLIntelSubgroupAVCType()) {
6069
0
    if (DestType->isOCLIntelSubgroupAVCMcePayloadType() ||
6070
0
        DestType->isOCLIntelSubgroupAVCMceResultType())
6071
0
      return false;
6072
0
    if (!IsZeroInitializer(Initializer, S))
6073
0
      return false;
6074
6075
0
    Sequence.AddOCLZeroOpaqueTypeStep(DestType);
6076
0
    return true;
6077
0
  }
6078
6079
0
  return false;
6080
0
}
6081
6082
InitializationSequence::InitializationSequence(
6083
    Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
6084
    MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid)
6085
    : FailedOverloadResult(OR_Success),
6086
20
      FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) {
6087
20
  InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList,
6088
20
                 TreatUnavailableAsInvalid);
6089
20
}
6090
6091
/// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the
6092
/// address of that function, this returns true. Otherwise, it returns false.
6093
0
static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) {
6094
0
  auto *DRE = dyn_cast<DeclRefExpr>(E);
6095
0
  if (!DRE || !isa<FunctionDecl>(DRE->getDecl()))
6096
0
    return false;
6097
6098
0
  return !S.checkAddressOfFunctionIsAvailable(
6099
0
      cast<FunctionDecl>(DRE->getDecl()));
6100
0
}
6101
6102
/// Determine whether we can perform an elementwise array copy for this kind
6103
/// of entity.
6104
0
static bool canPerformArrayCopy(const InitializedEntity &Entity) {
6105
0
  switch (Entity.getKind()) {
6106
0
  case InitializedEntity::EK_LambdaCapture:
6107
    // C++ [expr.prim.lambda]p24:
6108
    //   For array members, the array elements are direct-initialized in
6109
    //   increasing subscript order.
6110
0
    return true;
6111
6112
0
  case InitializedEntity::EK_Variable:
6113
    // C++ [dcl.decomp]p1:
6114
    //   [...] each element is copy-initialized or direct-initialized from the
6115
    //   corresponding element of the assignment-expression [...]
6116
0
    return isa<DecompositionDecl>(Entity.getDecl());
6117
6118
0
  case InitializedEntity::EK_Member:
6119
    // C++ [class.copy.ctor]p14:
6120
    //   - if the member is an array, each element is direct-initialized with
6121
    //     the corresponding subobject of x
6122
0
    return Entity.isImplicitMemberInitializer();
6123
6124
0
  case InitializedEntity::EK_ArrayElement:
6125
    // All the above cases are intended to apply recursively, even though none
6126
    // of them actually say that.
6127
0
    if (auto *E = Entity.getParent())
6128
0
      return canPerformArrayCopy(*E);
6129
0
    break;
6130
6131
0
  default:
6132
0
    break;
6133
0
  }
6134
6135
0
  return false;
6136
0
}
6137
6138
void InitializationSequence::InitializeFrom(Sema &S,
6139
                                            const InitializedEntity &Entity,
6140
                                            const InitializationKind &Kind,
6141
                                            MultiExprArg Args,
6142
                                            bool TopLevelOfInitList,
6143
20
                                            bool TreatUnavailableAsInvalid) {
6144
20
  ASTContext &Context = S.Context;
6145
6146
  // Eliminate non-overload placeholder types in the arguments.  We
6147
  // need to do this before checking whether types are dependent
6148
  // because lowering a pseudo-object expression might well give us
6149
  // something of dependent type.
6150
40
  for (unsigned I = 0, E = Args.size(); I != E; ++I)
6151
20
    if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
6152
      // FIXME: should we be doing this here?
6153
0
      ExprResult result = S.CheckPlaceholderExpr(Args[I]);
6154
0
      if (result.isInvalid()) {
6155
0
        SetFailed(FK_PlaceholderType);
6156
0
        return;
6157
0
      }
6158
0
      Args[I] = result.get();
6159
0
    }
6160
6161
  // C++0x [dcl.init]p16:
6162
  //   The semantics of initializers are as follows. The destination type is
6163
  //   the type of the object or reference being initialized and the source
6164
  //   type is the type of the initializer expression. The source type is not
6165
  //   defined when the initializer is a braced-init-list or when it is a
6166
  //   parenthesized list of expressions.
6167
20
  QualType DestType = Entity.getType();
6168
6169
20
  if (DestType->isDependentType() ||
6170
20
      Expr::hasAnyTypeDependentArguments(Args)) {
6171
13
    SequenceKind = DependentSequence;
6172
13
    return;
6173
13
  }
6174
6175
  // Almost everything is a normal sequence.
6176
7
  setSequenceKind(NormalSequence);
6177
6178
7
  QualType SourceType;
6179
7
  Expr *Initializer = nullptr;
6180
7
  if (Args.size() == 1) {
6181
7
    Initializer = Args[0];
6182
7
    if (S.getLangOpts().ObjC) {
6183
7
      if (S.CheckObjCBridgeRelatedConversions(Initializer->getBeginLoc(),
6184
7
                                              DestType, Initializer->getType(),
6185
7
                                              Initializer) ||
6186
7
          S.CheckConversionToObjCLiteral(DestType, Initializer))
6187
0
        Args[0] = Initializer;
6188
7
    }
6189
7
    if (!isa<InitListExpr>(Initializer))
6190
7
      SourceType = Initializer->getType();
6191
7
  }
6192
6193
  //     - If the initializer is a (non-parenthesized) braced-init-list, the
6194
  //       object is list-initialized (8.5.4).
6195
7
  if (Kind.getKind() != InitializationKind::IK_Direct) {
6196
7
    if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
6197
0
      TryListInitialization(S, Entity, Kind, InitList, *this,
6198
0
                            TreatUnavailableAsInvalid);
6199
0
      return;
6200
0
    }
6201
7
  }
6202
6203
  //     - If the destination type is a reference type, see 8.5.3.
6204
7
  if (DestType->isReferenceType()) {
6205
    // C++0x [dcl.init.ref]p1:
6206
    //   A variable declared to be a T& or T&&, that is, "reference to type T"
6207
    //   (8.3.2), shall be initialized by an object, or function, of type T or
6208
    //   by an object that can be converted into a T.
6209
    // (Therefore, multiple arguments are not permitted.)
6210
0
    if (Args.size() != 1)
6211
0
      SetFailed(FK_TooManyInitsForReference);
6212
    // C++17 [dcl.init.ref]p5:
6213
    //   A reference [...] is initialized by an expression [...] as follows:
6214
    // If the initializer is not an expression, presumably we should reject,
6215
    // but the standard fails to actually say so.
6216
0
    else if (isa<InitListExpr>(Args[0]))
6217
0
      SetFailed(FK_ParenthesizedListInitForReference);
6218
0
    else
6219
0
      TryReferenceInitialization(S, Entity, Kind, Args[0], *this,
6220
0
                                 TopLevelOfInitList);
6221
0
    return;
6222
0
  }
6223
6224
  //     - If the initializer is (), the object is value-initialized.
6225
7
  if (Kind.getKind() == InitializationKind::IK_Value ||
6226
7
      (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
6227
0
    TryValueInitialization(S, Entity, Kind, *this);
6228
0
    return;
6229
0
  }
6230
6231
  // Handle default initialization.
6232
7
  if (Kind.getKind() == InitializationKind::IK_Default) {
6233
0
    TryDefaultInitialization(S, Entity, Kind, *this);
6234
0
    return;
6235
0
  }
6236
6237
  //     - If the destination type is an array of characters, an array of
6238
  //       char16_t, an array of char32_t, or an array of wchar_t, and the
6239
  //       initializer is a string literal, see 8.5.2.
6240
  //     - Otherwise, if the destination type is an array, the program is
6241
  //       ill-formed.
6242
7
  if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
6243
0
    if (Initializer && isa<VariableArrayType>(DestAT)) {
6244
0
      SetFailed(FK_VariableLengthArrayHasInitializer);
6245
0
      return;
6246
0
    }
6247
6248
0
    if (Initializer) {
6249
0
      switch (IsStringInit(Initializer, DestAT, Context)) {
6250
0
      case SIF_None:
6251
0
        TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
6252
0
        return;
6253
0
      case SIF_NarrowStringIntoWideChar:
6254
0
        SetFailed(FK_NarrowStringIntoWideCharArray);
6255
0
        return;
6256
0
      case SIF_WideStringIntoChar:
6257
0
        SetFailed(FK_WideStringIntoCharArray);
6258
0
        return;
6259
0
      case SIF_IncompatWideStringIntoWideChar:
6260
0
        SetFailed(FK_IncompatWideStringIntoWideChar);
6261
0
        return;
6262
0
      case SIF_PlainStringIntoUTF8Char:
6263
0
        SetFailed(FK_PlainStringIntoUTF8Char);
6264
0
        return;
6265
0
      case SIF_UTF8StringIntoPlainChar:
6266
0
        SetFailed(FK_UTF8StringIntoPlainChar);
6267
0
        return;
6268
0
      case SIF_Other:
6269
0
        break;
6270
0
      }
6271
0
    }
6272
6273
    // Some kinds of initialization permit an array to be initialized from
6274
    // another array of the same type, and perform elementwise initialization.
6275
0
    if (Initializer && isa<ConstantArrayType>(DestAT) &&
6276
0
        S.Context.hasSameUnqualifiedType(Initializer->getType(),
6277
0
                                         Entity.getType()) &&
6278
0
        canPerformArrayCopy(Entity)) {
6279
      // If source is a prvalue, use it directly.
6280
0
      if (Initializer->isPRValue()) {
6281
0
        AddArrayInitStep(DestType, /*IsGNUExtension*/false);
6282
0
        return;
6283
0
      }
6284
6285
      // Emit element-at-a-time copy loop.
6286
0
      InitializedEntity Element =
6287
0
          InitializedEntity::InitializeElement(S.Context, 0, Entity);
6288
0
      QualType InitEltT =
6289
0
          Context.getAsArrayType(Initializer->getType())->getElementType();
6290
0
      OpaqueValueExpr OVE(Initializer->getExprLoc(), InitEltT,
6291
0
                          Initializer->getValueKind(),
6292
0
                          Initializer->getObjectKind());
6293
0
      Expr *OVEAsExpr = &OVE;
6294
0
      InitializeFrom(S, Element, Kind, OVEAsExpr, TopLevelOfInitList,
6295
0
                     TreatUnavailableAsInvalid);
6296
0
      if (!Failed())
6297
0
        AddArrayInitLoopStep(Entity.getType(), InitEltT);
6298
0
      return;
6299
0
    }
6300
6301
    // Note: as an GNU C extension, we allow initialization of an
6302
    // array from a compound literal that creates an array of the same
6303
    // type, so long as the initializer has no side effects.
6304
0
    if (!S.getLangOpts().CPlusPlus && Initializer &&
6305
0
        isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
6306
0
        Initializer->getType()->isArrayType()) {
6307
0
      const ArrayType *SourceAT
6308
0
        = Context.getAsArrayType(Initializer->getType());
6309
0
      if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
6310
0
        SetFailed(FK_ArrayTypeMismatch);
6311
0
      else if (Initializer->HasSideEffects(S.Context))
6312
0
        SetFailed(FK_NonConstantArrayInit);
6313
0
      else {
6314
0
        AddArrayInitStep(DestType, /*IsGNUExtension*/true);
6315
0
      }
6316
0
    }
6317
    // Note: as a GNU C++ extension, we allow list-initialization of a
6318
    // class member of array type from a parenthesized initializer list.
6319
0
    else if (S.getLangOpts().CPlusPlus &&
6320
0
             Entity.getKind() == InitializedEntity::EK_Member &&
6321
0
             Initializer && isa<InitListExpr>(Initializer)) {
6322
0
      TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
6323
0
                            *this, TreatUnavailableAsInvalid);
6324
0
      AddParenthesizedArrayInitStep(DestType);
6325
0
    } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList &&
6326
0
               Kind.getKind() == InitializationKind::IK_Direct)
6327
0
      TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6328
0
                                        /*VerifyOnly=*/true);
6329
0
    else if (DestAT->getElementType()->isCharType())
6330
0
      SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
6331
0
    else if (IsWideCharCompatible(DestAT->getElementType(), Context))
6332
0
      SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
6333
0
    else
6334
0
      SetFailed(FK_ArrayNeedsInitList);
6335
6336
0
    return;
6337
0
  }
6338
6339
  // Determine whether we should consider writeback conversions for
6340
  // Objective-C ARC.
6341
7
  bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
6342
7
         Entity.isParameterKind();
6343
6344
7
  if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
6345
0
    return;
6346
6347
  // We're at the end of the line for C: it's either a write-back conversion
6348
  // or it's a C assignment. There's no need to check anything else.
6349
7
  if (!S.getLangOpts().CPlusPlus) {
6350
7
    assert(Initializer && "Initializer must be non-null");
6351
    // If allowed, check whether this is an Objective-C writeback conversion.
6352
7
    if (allowObjCWritebackConversion &&
6353
7
        tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
6354
0
      return;
6355
0
    }
6356
6357
7
    if (TryOCLZeroOpaqueTypeInitialization(S, *this, DestType, Initializer))
6358
0
      return;
6359
6360
    // Handle initialization in C
6361
7
    AddCAssignmentStep(DestType);
6362
7
    MaybeProduceObjCObject(S, *this, Entity);
6363
7
    return;
6364
7
  }
6365
6366
0
  assert(S.getLangOpts().CPlusPlus);
6367
6368
  //     - If the destination type is a (possibly cv-qualified) class type:
6369
0
  if (DestType->isRecordType()) {
6370
    //     - If the initialization is direct-initialization, or if it is
6371
    //       copy-initialization where the cv-unqualified version of the
6372
    //       source type is the same class as, or a derived class of, the
6373
    //       class of the destination, constructors are considered. [...]
6374
0
    if (Kind.getKind() == InitializationKind::IK_Direct ||
6375
0
        (Kind.getKind() == InitializationKind::IK_Copy &&
6376
0
         (Context.hasSameUnqualifiedType(SourceType, DestType) ||
6377
0
          (Initializer && S.IsDerivedFrom(Initializer->getBeginLoc(),
6378
0
                                          SourceType, DestType))))) {
6379
0
      TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestType,
6380
0
                                   *this);
6381
6382
      // We fall back to the "no matching constructor" path if the
6383
      // failed candidate set has functions other than the three default
6384
      // constructors. For example, conversion function.
6385
0
      if (const auto *RD =
6386
0
              dyn_cast<CXXRecordDecl>(DestType->getAs<RecordType>()->getDecl());
6387
          // In general, we should call isCompleteType for RD to check its
6388
          // completeness, we don't call it here as it was already called in the
6389
          // above TryConstructorInitialization.
6390
0
          S.getLangOpts().CPlusPlus20 && RD && RD->hasDefinition() &&
6391
0
          RD->isAggregate() && Failed() &&
6392
0
          getFailureKind() == FK_ConstructorOverloadFailed) {
6393
        // Do not attempt paren list initialization if overload resolution
6394
        // resolves to a deleted function .
6395
        //
6396
        // We may reach this condition if we have a union wrapping a class with
6397
        // a non-trivial copy or move constructor and we call one of those two
6398
        // constructors. The union is an aggregate, but the matched constructor
6399
        // is implicitly deleted, so we need to prevent aggregate initialization
6400
        // (otherwise, it'll attempt aggregate initialization by initializing
6401
        // the first element with a reference to the union).
6402
0
        OverloadCandidateSet::iterator Best;
6403
0
        OverloadingResult OR = getFailedCandidateSet().BestViableFunction(
6404
0
            S, Kind.getLocation(), Best);
6405
0
        if (OR != OverloadingResult::OR_Deleted) {
6406
          // C++20 [dcl.init] 17.6.2.2:
6407
          //   - Otherwise, if no constructor is viable, the destination type is
6408
          //   an
6409
          //      aggregate class, and the initializer is a parenthesized
6410
          //      expression-list.
6411
0
          TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
6412
0
                                            /*VerifyOnly=*/true);
6413
0
        }
6414
0
      }
6415
0
    } else {
6416
      //     - Otherwise (i.e., for the remaining copy-initialization cases),
6417
      //       user-defined conversion sequences that can convert from the
6418
      //       source type to the destination type or (when a conversion
6419
      //       function is used) to a derived class thereof are enumerated as
6420
      //       described in 13.3.1.4, and the best one is chosen through
6421
      //       overload resolution (13.3).
6422
0
      assert(Initializer && "Initializer must be non-null");
6423
0
      TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6424
0
                               TopLevelOfInitList);
6425
0
    }
6426
0
    return;
6427
0
  }
6428
6429
0
  assert(Args.size() >= 1 && "Zero-argument case handled above");
6430
6431
  // For HLSL ext vector types we allow list initialization behavior for C++
6432
  // constructor syntax. This is accomplished by converting initialization
6433
  // arguments an InitListExpr late.
6434
0
  if (S.getLangOpts().HLSL && DestType->isExtVectorType() &&
6435
0
      (SourceType.isNull() ||
6436
0
       !Context.hasSameUnqualifiedType(SourceType, DestType))) {
6437
6438
0
    llvm::SmallVector<Expr *> InitArgs;
6439
0
    for (auto *Arg : Args) {
6440
0
      if (Arg->getType()->isExtVectorType()) {
6441
0
        const auto *VTy = Arg->getType()->castAs<ExtVectorType>();
6442
0
        unsigned Elm = VTy->getNumElements();
6443
0
        for (unsigned Idx = 0; Idx < Elm; ++Idx) {
6444
0
          InitArgs.emplace_back(new (Context) ArraySubscriptExpr(
6445
0
              Arg,
6446
0
              IntegerLiteral::Create(
6447
0
                  Context, llvm::APInt(Context.getIntWidth(Context.IntTy), Idx),
6448
0
                  Context.IntTy, SourceLocation()),
6449
0
              VTy->getElementType(), Arg->getValueKind(), Arg->getObjectKind(),
6450
0
              SourceLocation()));
6451
0
        }
6452
0
      } else
6453
0
        InitArgs.emplace_back(Arg);
6454
0
    }
6455
0
    InitListExpr *ILE = new (Context) InitListExpr(
6456
0
        S.getASTContext(), SourceLocation(), InitArgs, SourceLocation());
6457
0
    Args[0] = ILE;
6458
0
    AddListInitializationStep(DestType);
6459
0
    return;
6460
0
  }
6461
6462
  // The remaining cases all need a source type.
6463
0
  if (Args.size() > 1) {
6464
0
    SetFailed(FK_TooManyInitsForScalar);
6465
0
    return;
6466
0
  } else if (isa<InitListExpr>(Args[0])) {
6467
0
    SetFailed(FK_ParenthesizedListInitForScalar);
6468
0
    return;
6469
0
  }
6470
6471
  //    - Otherwise, if the source type is a (possibly cv-qualified) class
6472
  //      type, conversion functions are considered.
6473
0
  if (!SourceType.isNull() && SourceType->isRecordType()) {
6474
0
    assert(Initializer && "Initializer must be non-null");
6475
    // For a conversion to _Atomic(T) from either T or a class type derived
6476
    // from T, initialize the T object then convert to _Atomic type.
6477
0
    bool NeedAtomicConversion = false;
6478
0
    if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) {
6479
0
      if (Context.hasSameUnqualifiedType(SourceType, Atomic->getValueType()) ||
6480
0
          S.IsDerivedFrom(Initializer->getBeginLoc(), SourceType,
6481
0
                          Atomic->getValueType())) {
6482
0
        DestType = Atomic->getValueType();
6483
0
        NeedAtomicConversion = true;
6484
0
      }
6485
0
    }
6486
6487
0
    TryUserDefinedConversion(S, DestType, Kind, Initializer, *this,
6488
0
                             TopLevelOfInitList);
6489
0
    MaybeProduceObjCObject(S, *this, Entity);
6490
0
    if (!Failed() && NeedAtomicConversion)
6491
0
      AddAtomicConversionStep(Entity.getType());
6492
0
    return;
6493
0
  }
6494
6495
  //    - Otherwise, if the initialization is direct-initialization, the source
6496
  //    type is std::nullptr_t, and the destination type is bool, the initial
6497
  //    value of the object being initialized is false.
6498
0
  if (!SourceType.isNull() && SourceType->isNullPtrType() &&
6499
0
      DestType->isBooleanType() &&
6500
0
      Kind.getKind() == InitializationKind::IK_Direct) {
6501
0
    AddConversionSequenceStep(
6502
0
        ImplicitConversionSequence::getNullptrToBool(SourceType, DestType,
6503
0
                                                     Initializer->isGLValue()),
6504
0
        DestType);
6505
0
    return;
6506
0
  }
6507
6508
  //    - Otherwise, the initial value of the object being initialized is the
6509
  //      (possibly converted) value of the initializer expression. Standard
6510
  //      conversions (Clause 4) will be used, if necessary, to convert the
6511
  //      initializer expression to the cv-unqualified version of the
6512
  //      destination type; no user-defined conversions are considered.
6513
6514
0
  ImplicitConversionSequence ICS
6515
0
    = S.TryImplicitConversion(Initializer, DestType,
6516
0
                              /*SuppressUserConversions*/true,
6517
0
                              Sema::AllowedExplicit::None,
6518
0
                              /*InOverloadResolution*/ false,
6519
0
                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
6520
0
                              allowObjCWritebackConversion);
6521
6522
0
  if (ICS.isStandard() &&
6523
0
      ICS.Standard.Second == ICK_Writeback_Conversion) {
6524
    // Objective-C ARC writeback conversion.
6525
6526
    // We should copy unless we're passing to an argument explicitly
6527
    // marked 'out'.
6528
0
    bool ShouldCopy = true;
6529
0
    if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
6530
0
      ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
6531
6532
    // If there was an lvalue adjustment, add it as a separate conversion.
6533
0
    if (ICS.Standard.First == ICK_Array_To_Pointer ||
6534
0
        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6535
0
      ImplicitConversionSequence LvalueICS;
6536
0
      LvalueICS.setStandard();
6537
0
      LvalueICS.Standard.setAsIdentityConversion();
6538
0
      LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
6539
0
      LvalueICS.Standard.First = ICS.Standard.First;
6540
0
      AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
6541
0
    }
6542
6543
0
    AddPassByIndirectCopyRestoreStep(DestType, ShouldCopy);
6544
0
  } else if (ICS.isBad()) {
6545
0
    DeclAccessPair dap;
6546
0
    if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
6547
0
      AddZeroInitializationStep(Entity.getType());
6548
0
    } else if (Initializer->getType() == Context.OverloadTy &&
6549
0
               !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
6550
0
                                                     false, dap))
6551
0
      SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
6552
0
    else if (Initializer->getType()->isFunctionType() &&
6553
0
             isExprAnUnaddressableFunction(S, Initializer))
6554
0
      SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction);
6555
0
    else
6556
0
      SetFailed(InitializationSequence::FK_ConversionFailed);
6557
0
  } else {
6558
0
    AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
6559
6560
0
    MaybeProduceObjCObject(S, *this, Entity);
6561
0
  }
6562
0
}
6563
6564
20
InitializationSequence::~InitializationSequence() {
6565
20
  for (auto &S : Steps)
6566
7
    S.Destroy();
6567
20
}
6568
6569
//===----------------------------------------------------------------------===//
6570
// Perform initialization
6571
//===----------------------------------------------------------------------===//
6572
static Sema::AssignmentAction
6573
7
getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
6574
7
  switch(Entity.getKind()) {
6575
7
  case InitializedEntity::EK_Variable:
6576
7
  case InitializedEntity::EK_New:
6577
7
  case InitializedEntity::EK_Exception:
6578
7
  case InitializedEntity::EK_Base:
6579
7
  case InitializedEntity::EK_Delegating:
6580
7
    return Sema::AA_Initializing;
6581
6582
0
  case InitializedEntity::EK_Parameter:
6583
0
    if (Entity.getDecl() &&
6584
0
        isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6585
0
      return Sema::AA_Sending;
6586
6587
0
    return Sema::AA_Passing;
6588
6589
0
  case InitializedEntity::EK_Parameter_CF_Audited:
6590
0
    if (Entity.getDecl() &&
6591
0
      isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
6592
0
      return Sema::AA_Sending;
6593
6594
0
    return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
6595
6596
0
  case InitializedEntity::EK_Result:
6597
0
  case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right.
6598
0
    return Sema::AA_Returning;
6599
6600
0
  case InitializedEntity::EK_Temporary:
6601
0
  case InitializedEntity::EK_RelatedResult:
6602
    // FIXME: Can we tell apart casting vs. converting?
6603
0
    return Sema::AA_Casting;
6604
6605
0
  case InitializedEntity::EK_TemplateParameter:
6606
    // This is really initialization, but refer to it as conversion for
6607
    // consistency with CheckConvertedConstantExpression.
6608
0
    return Sema::AA_Converting;
6609
6610
0
  case InitializedEntity::EK_Member:
6611
0
  case InitializedEntity::EK_ParenAggInitMember:
6612
0
  case InitializedEntity::EK_Binding:
6613
0
  case InitializedEntity::EK_ArrayElement:
6614
0
  case InitializedEntity::EK_VectorElement:
6615
0
  case InitializedEntity::EK_ComplexElement:
6616
0
  case InitializedEntity::EK_BlockElement:
6617
0
  case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6618
0
  case InitializedEntity::EK_LambdaCapture:
6619
0
  case InitializedEntity::EK_CompoundLiteralInit:
6620
0
    return Sema::AA_Initializing;
6621
7
  }
6622
6623
0
  llvm_unreachable("Invalid EntityKind!");
6624
0
}
6625
6626
/// Whether we should bind a created object as a temporary when
6627
/// initializing the given entity.
6628
0
static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
6629
0
  switch (Entity.getKind()) {
6630
0
  case InitializedEntity::EK_ArrayElement:
6631
0
  case InitializedEntity::EK_Member:
6632
0
  case InitializedEntity::EK_ParenAggInitMember:
6633
0
  case InitializedEntity::EK_Result:
6634
0
  case InitializedEntity::EK_StmtExprResult:
6635
0
  case InitializedEntity::EK_New:
6636
0
  case InitializedEntity::EK_Variable:
6637
0
  case InitializedEntity::EK_Base:
6638
0
  case InitializedEntity::EK_Delegating:
6639
0
  case InitializedEntity::EK_VectorElement:
6640
0
  case InitializedEntity::EK_ComplexElement:
6641
0
  case InitializedEntity::EK_Exception:
6642
0
  case InitializedEntity::EK_BlockElement:
6643
0
  case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6644
0
  case InitializedEntity::EK_LambdaCapture:
6645
0
  case InitializedEntity::EK_CompoundLiteralInit:
6646
0
  case InitializedEntity::EK_TemplateParameter:
6647
0
    return false;
6648
6649
0
  case InitializedEntity::EK_Parameter:
6650
0
  case InitializedEntity::EK_Parameter_CF_Audited:
6651
0
  case InitializedEntity::EK_Temporary:
6652
0
  case InitializedEntity::EK_RelatedResult:
6653
0
  case InitializedEntity::EK_Binding:
6654
0
    return true;
6655
0
  }
6656
6657
0
  llvm_unreachable("missed an InitializedEntity kind?");
6658
0
}
6659
6660
/// Whether the given entity, when initialized with an object
6661
/// created for that initialization, requires destruction.
6662
0
static bool shouldDestroyEntity(const InitializedEntity &Entity) {
6663
0
  switch (Entity.getKind()) {
6664
0
    case InitializedEntity::EK_Result:
6665
0
    case InitializedEntity::EK_StmtExprResult:
6666
0
    case InitializedEntity::EK_New:
6667
0
    case InitializedEntity::EK_Base:
6668
0
    case InitializedEntity::EK_Delegating:
6669
0
    case InitializedEntity::EK_VectorElement:
6670
0
    case InitializedEntity::EK_ComplexElement:
6671
0
    case InitializedEntity::EK_BlockElement:
6672
0
    case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6673
0
    case InitializedEntity::EK_LambdaCapture:
6674
0
      return false;
6675
6676
0
    case InitializedEntity::EK_Member:
6677
0
    case InitializedEntity::EK_ParenAggInitMember:
6678
0
    case InitializedEntity::EK_Binding:
6679
0
    case InitializedEntity::EK_Variable:
6680
0
    case InitializedEntity::EK_Parameter:
6681
0
    case InitializedEntity::EK_Parameter_CF_Audited:
6682
0
    case InitializedEntity::EK_TemplateParameter:
6683
0
    case InitializedEntity::EK_Temporary:
6684
0
    case InitializedEntity::EK_ArrayElement:
6685
0
    case InitializedEntity::EK_Exception:
6686
0
    case InitializedEntity::EK_CompoundLiteralInit:
6687
0
    case InitializedEntity::EK_RelatedResult:
6688
0
      return true;
6689
0
  }
6690
6691
0
  llvm_unreachable("missed an InitializedEntity kind?");
6692
0
}
6693
6694
/// Get the location at which initialization diagnostics should appear.
6695
static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
6696
0
                                           Expr *Initializer) {
6697
0
  switch (Entity.getKind()) {
6698
0
  case InitializedEntity::EK_Result:
6699
0
  case InitializedEntity::EK_StmtExprResult:
6700
0
    return Entity.getReturnLoc();
6701
6702
0
  case InitializedEntity::EK_Exception:
6703
0
    return Entity.getThrowLoc();
6704
6705
0
  case InitializedEntity::EK_Variable:
6706
0
  case InitializedEntity::EK_Binding:
6707
0
    return Entity.getDecl()->getLocation();
6708
6709
0
  case InitializedEntity::EK_LambdaCapture:
6710
0
    return Entity.getCaptureLoc();
6711
6712
0
  case InitializedEntity::EK_ArrayElement:
6713
0
  case InitializedEntity::EK_Member:
6714
0
  case InitializedEntity::EK_ParenAggInitMember:
6715
0
  case InitializedEntity::EK_Parameter:
6716
0
  case InitializedEntity::EK_Parameter_CF_Audited:
6717
0
  case InitializedEntity::EK_TemplateParameter:
6718
0
  case InitializedEntity::EK_Temporary:
6719
0
  case InitializedEntity::EK_New:
6720
0
  case InitializedEntity::EK_Base:
6721
0
  case InitializedEntity::EK_Delegating:
6722
0
  case InitializedEntity::EK_VectorElement:
6723
0
  case InitializedEntity::EK_ComplexElement:
6724
0
  case InitializedEntity::EK_BlockElement:
6725
0
  case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
6726
0
  case InitializedEntity::EK_CompoundLiteralInit:
6727
0
  case InitializedEntity::EK_RelatedResult:
6728
0
    return Initializer->getBeginLoc();
6729
0
  }
6730
0
  llvm_unreachable("missed an InitializedEntity kind?");
6731
0
}
6732
6733
/// Make a (potentially elidable) temporary copy of the object
6734
/// provided by the given initializer by calling the appropriate copy
6735
/// constructor.
6736
///
6737
/// \param S The Sema object used for type-checking.
6738
///
6739
/// \param T The type of the temporary object, which must either be
6740
/// the type of the initializer expression or a superclass thereof.
6741
///
6742
/// \param Entity The entity being initialized.
6743
///
6744
/// \param CurInit The initializer expression.
6745
///
6746
/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
6747
/// is permitted in C++03 (but not C++0x) when binding a reference to
6748
/// an rvalue.
6749
///
6750
/// \returns An expression that copies the initializer expression into
6751
/// a temporary object, or an error expression if a copy could not be
6752
/// created.
6753
static ExprResult CopyObject(Sema &S,
6754
                             QualType T,
6755
                             const InitializedEntity &Entity,
6756
                             ExprResult CurInit,
6757
0
                             bool IsExtraneousCopy) {
6758
0
  if (CurInit.isInvalid())
6759
0
    return CurInit;
6760
  // Determine which class type we're copying to.
6761
0
  Expr *CurInitExpr = (Expr *)CurInit.get();
6762
0
  CXXRecordDecl *Class = nullptr;
6763
0
  if (const RecordType *Record = T->getAs<RecordType>())
6764
0
    Class = cast<CXXRecordDecl>(Record->getDecl());
6765
0
  if (!Class)
6766
0
    return CurInit;
6767
6768
0
  SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
6769
6770
  // Make sure that the type we are copying is complete.
6771
0
  if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
6772
0
    return CurInit;
6773
6774
  // Perform overload resolution using the class's constructors. Per
6775
  // C++11 [dcl.init]p16, second bullet for class types, this initialization
6776
  // is direct-initialization.
6777
0
  OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6778
0
  DeclContext::lookup_result Ctors = S.LookupConstructors(Class);
6779
6780
0
  OverloadCandidateSet::iterator Best;
6781
0
  switch (ResolveConstructorOverload(
6782
0
      S, Loc, CurInitExpr, CandidateSet, T, Ctors, Best,
6783
0
      /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6784
0
      /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6785
0
      /*RequireActualConstructor=*/false,
6786
0
      /*SecondStepOfCopyInit=*/true)) {
6787
0
  case OR_Success:
6788
0
    break;
6789
6790
0
  case OR_No_Viable_Function:
6791
0
    CandidateSet.NoteCandidates(
6792
0
        PartialDiagnosticAt(
6793
0
            Loc, S.PDiag(IsExtraneousCopy && !S.isSFINAEContext()
6794
0
                             ? diag::ext_rvalue_to_reference_temp_copy_no_viable
6795
0
                             : diag::err_temp_copy_no_viable)
6796
0
                     << (int)Entity.getKind() << CurInitExpr->getType()
6797
0
                     << CurInitExpr->getSourceRange()),
6798
0
        S, OCD_AllCandidates, CurInitExpr);
6799
0
    if (!IsExtraneousCopy || S.isSFINAEContext())
6800
0
      return ExprError();
6801
0
    return CurInit;
6802
6803
0
  case OR_Ambiguous:
6804
0
    CandidateSet.NoteCandidates(
6805
0
        PartialDiagnosticAt(Loc, S.PDiag(diag::err_temp_copy_ambiguous)
6806
0
                                     << (int)Entity.getKind()
6807
0
                                     << CurInitExpr->getType()
6808
0
                                     << CurInitExpr->getSourceRange()),
6809
0
        S, OCD_AmbiguousCandidates, CurInitExpr);
6810
0
    return ExprError();
6811
6812
0
  case OR_Deleted:
6813
0
    S.Diag(Loc, diag::err_temp_copy_deleted)
6814
0
      << (int)Entity.getKind() << CurInitExpr->getType()
6815
0
      << CurInitExpr->getSourceRange();
6816
0
    S.NoteDeletedFunction(Best->Function);
6817
0
    return ExprError();
6818
0
  }
6819
6820
0
  bool HadMultipleCandidates = CandidateSet.size() > 1;
6821
6822
0
  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
6823
0
  SmallVector<Expr*, 8> ConstructorArgs;
6824
0
  CurInit.get(); // Ownership transferred into MultiExprArg, below.
6825
6826
0
  S.CheckConstructorAccess(Loc, Constructor, Best->FoundDecl, Entity,
6827
0
                           IsExtraneousCopy);
6828
6829
0
  if (IsExtraneousCopy) {
6830
    // If this is a totally extraneous copy for C++03 reference
6831
    // binding purposes, just return the original initialization
6832
    // expression. We don't generate an (elided) copy operation here
6833
    // because doing so would require us to pass down a flag to avoid
6834
    // infinite recursion, where each step adds another extraneous,
6835
    // elidable copy.
6836
6837
    // Instantiate the default arguments of any extra parameters in
6838
    // the selected copy constructor, as if we were going to create a
6839
    // proper call to the copy constructor.
6840
0
    for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
6841
0
      ParmVarDecl *Parm = Constructor->getParamDecl(I);
6842
0
      if (S.RequireCompleteType(Loc, Parm->getType(),
6843
0
                                diag::err_call_incomplete_argument))
6844
0
        break;
6845
6846
      // Build the default argument expression; we don't actually care
6847
      // if this succeeds or not, because this routine will complain
6848
      // if there was a problem.
6849
0
      S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
6850
0
    }
6851
6852
0
    return CurInitExpr;
6853
0
  }
6854
6855
  // Determine the arguments required to actually perform the
6856
  // constructor call (we might have derived-to-base conversions, or
6857
  // the copy constructor may have default arguments).
6858
0
  if (S.CompleteConstructorCall(Constructor, T, CurInitExpr, Loc,
6859
0
                                ConstructorArgs))
6860
0
    return ExprError();
6861
6862
  // C++0x [class.copy]p32:
6863
  //   When certain criteria are met, an implementation is allowed to
6864
  //   omit the copy/move construction of a class object, even if the
6865
  //   copy/move constructor and/or destructor for the object have
6866
  //   side effects. [...]
6867
  //     - when a temporary class object that has not been bound to a
6868
  //       reference (12.2) would be copied/moved to a class object
6869
  //       with the same cv-unqualified type, the copy/move operation
6870
  //       can be omitted by constructing the temporary object
6871
  //       directly into the target of the omitted copy/move
6872
  //
6873
  // Note that the other three bullets are handled elsewhere. Copy
6874
  // elision for return statements and throw expressions are handled as part
6875
  // of constructor initialization, while copy elision for exception handlers
6876
  // is handled by the run-time.
6877
  //
6878
  // FIXME: If the function parameter is not the same type as the temporary, we
6879
  // should still be able to elide the copy, but we don't have a way to
6880
  // represent in the AST how much should be elided in this case.
6881
0
  bool Elidable =
6882
0
      CurInitExpr->isTemporaryObject(S.Context, Class) &&
6883
0
      S.Context.hasSameUnqualifiedType(
6884
0
          Best->Function->getParamDecl(0)->getType().getNonReferenceType(),
6885
0
          CurInitExpr->getType());
6886
6887
  // Actually perform the constructor call.
6888
0
  CurInit = S.BuildCXXConstructExpr(
6889
0
      Loc, T, Best->FoundDecl, Constructor, Elidable, ConstructorArgs,
6890
0
      HadMultipleCandidates,
6891
0
      /*ListInit*/ false,
6892
0
      /*StdInitListInit*/ false,
6893
0
      /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
6894
6895
  // If we're supposed to bind temporaries, do so.
6896
0
  if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
6897
0
    CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
6898
0
  return CurInit;
6899
0
}
6900
6901
/// Check whether elidable copy construction for binding a reference to
6902
/// a temporary would have succeeded if we were building in C++98 mode, for
6903
/// -Wc++98-compat.
6904
static void CheckCXX98CompatAccessibleCopy(Sema &S,
6905
                                           const InitializedEntity &Entity,
6906
0
                                           Expr *CurInitExpr) {
6907
0
  assert(S.getLangOpts().CPlusPlus11);
6908
6909
0
  const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
6910
0
  if (!Record)
6911
0
    return;
6912
6913
0
  SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
6914
0
  if (S.Diags.isIgnored(diag::warn_cxx98_compat_temp_copy, Loc))
6915
0
    return;
6916
6917
  // Find constructors which would have been considered.
6918
0
  OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6919
0
  DeclContext::lookup_result Ctors =
6920
0
      S.LookupConstructors(cast<CXXRecordDecl>(Record->getDecl()));
6921
6922
  // Perform overload resolution.
6923
0
  OverloadCandidateSet::iterator Best;
6924
0
  OverloadingResult OR = ResolveConstructorOverload(
6925
0
      S, Loc, CurInitExpr, CandidateSet, CurInitExpr->getType(), Ctors, Best,
6926
0
      /*CopyInitializing=*/false, /*AllowExplicit=*/true,
6927
0
      /*OnlyListConstructors=*/false, /*IsListInit=*/false,
6928
0
      /*RequireActualConstructor=*/false,
6929
0
      /*SecondStepOfCopyInit=*/true);
6930
6931
0
  PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
6932
0
    << OR << (int)Entity.getKind() << CurInitExpr->getType()
6933
0
    << CurInitExpr->getSourceRange();
6934
6935
0
  switch (OR) {
6936
0
  case OR_Success:
6937
0
    S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
6938
0
                             Best->FoundDecl, Entity, Diag);
6939
    // FIXME: Check default arguments as far as that's possible.
6940
0
    break;
6941
6942
0
  case OR_No_Viable_Function:
6943
0
    CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6944
0
                                OCD_AllCandidates, CurInitExpr);
6945
0
    break;
6946
6947
0
  case OR_Ambiguous:
6948
0
    CandidateSet.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S,
6949
0
                                OCD_AmbiguousCandidates, CurInitExpr);
6950
0
    break;
6951
6952
0
  case OR_Deleted:
6953
0
    S.Diag(Loc, Diag);
6954
0
    S.NoteDeletedFunction(Best->Function);
6955
0
    break;
6956
0
  }
6957
0
}
6958
6959
void InitializationSequence::PrintInitLocationNote(Sema &S,
6960
1
                                              const InitializedEntity &Entity) {
6961
1
  if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) {
6962
0
    if (Entity.getDecl()->getLocation().isInvalid())
6963
0
      return;
6964
6965
0
    if (Entity.getDecl()->getDeclName())
6966
0
      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
6967
0
        << Entity.getDecl()->getDeclName();
6968
0
    else
6969
0
      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
6970
0
  }
6971
1
  else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
6972
1
           Entity.getMethodDecl())
6973
0
    S.Diag(Entity.getMethodDecl()->getLocation(),
6974
0
           diag::note_method_return_type_change)
6975
0
      << Entity.getMethodDecl()->getDeclName();
6976
1
}
6977
6978
/// Returns true if the parameters describe a constructor initialization of
6979
/// an explicit temporary object, e.g. "Point(x, y)".
6980
static bool isExplicitTemporary(const InitializedEntity &Entity,
6981
                                const InitializationKind &Kind,
6982
0
                                unsigned NumArgs) {
6983
0
  switch (Entity.getKind()) {
6984
0
  case InitializedEntity::EK_Temporary:
6985
0
  case InitializedEntity::EK_CompoundLiteralInit:
6986
0
  case InitializedEntity::EK_RelatedResult:
6987
0
    break;
6988
0
  default:
6989
0
    return false;
6990
0
  }
6991
6992
0
  switch (Kind.getKind()) {
6993
0
  case InitializationKind::IK_DirectList:
6994
0
    return true;
6995
  // FIXME: Hack to work around cast weirdness.
6996
0
  case InitializationKind::IK_Direct:
6997
0
  case InitializationKind::IK_Value:
6998
0
    return NumArgs != 1;
6999
0
  default:
7000
0
    return false;
7001
0
  }
7002
0
}
7003
7004
static ExprResult
7005
PerformConstructorInitialization(Sema &S,
7006
                                 const InitializedEntity &Entity,
7007
                                 const InitializationKind &Kind,
7008
                                 MultiExprArg Args,
7009
                                 const InitializationSequence::Step& Step,
7010
                                 bool &ConstructorInitRequiresZeroInit,
7011
                                 bool IsListInitialization,
7012
                                 bool IsStdInitListInitialization,
7013
                                 SourceLocation LBraceLoc,
7014
0
                                 SourceLocation RBraceLoc) {
7015
0
  unsigned NumArgs = Args.size();
7016
0
  CXXConstructorDecl *Constructor
7017
0
    = cast<CXXConstructorDecl>(Step.Function.Function);
7018
0
  bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
7019
7020
  // Build a call to the selected constructor.
7021
0
  SmallVector<Expr*, 8> ConstructorArgs;
7022
0
  SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
7023
0
                         ? Kind.getEqualLoc()
7024
0
                         : Kind.getLocation();
7025
7026
0
  if (Kind.getKind() == InitializationKind::IK_Default) {
7027
    // Force even a trivial, implicit default constructor to be
7028
    // semantically checked. We do this explicitly because we don't build
7029
    // the definition for completely trivial constructors.
7030
0
    assert(Constructor->getParent() && "No parent class for constructor.");
7031
0
    if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7032
0
        Constructor->isTrivial() && !Constructor->isUsed(false)) {
7033
0
      S.runWithSufficientStackSpace(Loc, [&] {
7034
0
        S.DefineImplicitDefaultConstructor(Loc, Constructor);
7035
0
      });
7036
0
    }
7037
0
  }
7038
7039
0
  ExprResult CurInit((Expr *)nullptr);
7040
7041
  // C++ [over.match.copy]p1:
7042
  //   - When initializing a temporary to be bound to the first parameter
7043
  //     of a constructor that takes a reference to possibly cv-qualified
7044
  //     T as its first argument, called with a single argument in the
7045
  //     context of direct-initialization, explicit conversion functions
7046
  //     are also considered.
7047
0
  bool AllowExplicitConv =
7048
0
      Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 &&
7049
0
      hasCopyOrMoveCtorParam(S.Context,
7050
0
                             getConstructorInfo(Step.Function.FoundDecl));
7051
7052
  // Determine the arguments required to actually perform the constructor
7053
  // call.
7054
0
  if (S.CompleteConstructorCall(Constructor, Step.Type, Args, Loc,
7055
0
                                ConstructorArgs, AllowExplicitConv,
7056
0
                                IsListInitialization))
7057
0
    return ExprError();
7058
7059
0
  if (isExplicitTemporary(Entity, Kind, NumArgs)) {
7060
    // An explicitly-constructed temporary, e.g., X(1, 2).
7061
0
    if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7062
0
      return ExprError();
7063
7064
0
    TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
7065
0
    if (!TSInfo)
7066
0
      TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
7067
0
    SourceRange ParenOrBraceRange =
7068
0
        (Kind.getKind() == InitializationKind::IK_DirectList)
7069
0
        ? SourceRange(LBraceLoc, RBraceLoc)
7070
0
        : Kind.getParenOrBraceRange();
7071
7072
0
    CXXConstructorDecl *CalleeDecl = Constructor;
7073
0
    if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(
7074
0
            Step.Function.FoundDecl.getDecl())) {
7075
0
      CalleeDecl = S.findInheritingConstructor(Loc, Constructor, Shadow);
7076
0
    }
7077
0
    S.MarkFunctionReferenced(Loc, CalleeDecl);
7078
7079
0
    CurInit = S.CheckForImmediateInvocation(
7080
0
        CXXTemporaryObjectExpr::Create(
7081
0
            S.Context, CalleeDecl,
7082
0
            Entity.getType().getNonLValueExprType(S.Context), TSInfo,
7083
0
            ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates,
7084
0
            IsListInitialization, IsStdInitListInitialization,
7085
0
            ConstructorInitRequiresZeroInit),
7086
0
        CalleeDecl);
7087
0
  } else {
7088
0
    CXXConstructionKind ConstructKind = CXXConstructionKind::Complete;
7089
7090
0
    if (Entity.getKind() == InitializedEntity::EK_Base) {
7091
0
      ConstructKind = Entity.getBaseSpecifier()->isVirtual()
7092
0
                          ? CXXConstructionKind::VirtualBase
7093
0
                          : CXXConstructionKind::NonVirtualBase;
7094
0
    } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
7095
0
      ConstructKind = CXXConstructionKind::Delegating;
7096
0
    }
7097
7098
    // Only get the parenthesis or brace range if it is a list initialization or
7099
    // direct construction.
7100
0
    SourceRange ParenOrBraceRange;
7101
0
    if (IsListInitialization)
7102
0
      ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
7103
0
    else if (Kind.getKind() == InitializationKind::IK_Direct)
7104
0
      ParenOrBraceRange = Kind.getParenOrBraceRange();
7105
7106
    // If the entity allows NRVO, mark the construction as elidable
7107
    // unconditionally.
7108
0
    if (Entity.allowsNRVO())
7109
0
      CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7110
0
                                        Step.Function.FoundDecl,
7111
0
                                        Constructor, /*Elidable=*/true,
7112
0
                                        ConstructorArgs,
7113
0
                                        HadMultipleCandidates,
7114
0
                                        IsListInitialization,
7115
0
                                        IsStdInitListInitialization,
7116
0
                                        ConstructorInitRequiresZeroInit,
7117
0
                                        ConstructKind,
7118
0
                                        ParenOrBraceRange);
7119
0
    else
7120
0
      CurInit = S.BuildCXXConstructExpr(Loc, Step.Type,
7121
0
                                        Step.Function.FoundDecl,
7122
0
                                        Constructor,
7123
0
                                        ConstructorArgs,
7124
0
                                        HadMultipleCandidates,
7125
0
                                        IsListInitialization,
7126
0
                                        IsStdInitListInitialization,
7127
0
                                        ConstructorInitRequiresZeroInit,
7128
0
                                        ConstructKind,
7129
0
                                        ParenOrBraceRange);
7130
0
  }
7131
0
  if (CurInit.isInvalid())
7132
0
    return ExprError();
7133
7134
  // Only check access if all of that succeeded.
7135
0
  S.CheckConstructorAccess(Loc, Constructor, Step.Function.FoundDecl, Entity);
7136
0
  if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
7137
0
    return ExprError();
7138
7139
0
  if (const ArrayType *AT = S.Context.getAsArrayType(Entity.getType()))
7140
0
    if (checkDestructorReference(S.Context.getBaseElementType(AT), Loc, S))
7141
0
      return ExprError();
7142
7143
0
  if (shouldBindAsTemporary(Entity))
7144
0
    CurInit = S.MaybeBindToTemporary(CurInit.get());
7145
7146
0
  return CurInit;
7147
0
}
7148
7149
namespace {
7150
enum LifetimeKind {
7151
  /// The lifetime of a temporary bound to this entity ends at the end of the
7152
  /// full-expression, and that's (probably) fine.
7153
  LK_FullExpression,
7154
7155
  /// The lifetime of a temporary bound to this entity is extended to the
7156
  /// lifeitme of the entity itself.
7157
  LK_Extended,
7158
7159
  /// The lifetime of a temporary bound to this entity probably ends too soon,
7160
  /// because the entity is allocated in a new-expression.
7161
  LK_New,
7162
7163
  /// The lifetime of a temporary bound to this entity ends too soon, because
7164
  /// the entity is a return object.
7165
  LK_Return,
7166
7167
  /// The lifetime of a temporary bound to this entity ends too soon, because
7168
  /// the entity is the result of a statement expression.
7169
  LK_StmtExprResult,
7170
7171
  /// This is a mem-initializer: if it would extend a temporary (other than via
7172
  /// a default member initializer), the program is ill-formed.
7173
  LK_MemInitializer,
7174
};
7175
using LifetimeResult =
7176
    llvm::PointerIntPair<const InitializedEntity *, 3, LifetimeKind>;
7177
}
7178
7179
/// Determine the declaration which an initialized entity ultimately refers to,
7180
/// for the purpose of lifetime-extending a temporary bound to a reference in
7181
/// the initialization of \p Entity.
7182
static LifetimeResult getEntityLifetime(
7183
    const InitializedEntity *Entity,
7184
7
    const InitializedEntity *InitField = nullptr) {
7185
  // C++11 [class.temporary]p5:
7186
7
  switch (Entity->getKind()) {
7187
7
  case InitializedEntity::EK_Variable:
7188
    //   The temporary [...] persists for the lifetime of the reference
7189
7
    return {Entity, LK_Extended};
7190
7191
0
  case InitializedEntity::EK_Member:
7192
    // For subobjects, we look at the complete object.
7193
0
    if (Entity->getParent())
7194
0
      return getEntityLifetime(Entity->getParent(), Entity);
7195
7196
    //   except:
7197
    // C++17 [class.base.init]p8:
7198
    //   A temporary expression bound to a reference member in a
7199
    //   mem-initializer is ill-formed.
7200
    // C++17 [class.base.init]p11:
7201
    //   A temporary expression bound to a reference member from a
7202
    //   default member initializer is ill-formed.
7203
    //
7204
    // The context of p11 and its example suggest that it's only the use of a
7205
    // default member initializer from a constructor that makes the program
7206
    // ill-formed, not its mere existence, and that it can even be used by
7207
    // aggregate initialization.
7208
0
    return {Entity, Entity->isDefaultMemberInitializer() ? LK_Extended
7209
0
                                                         : LK_MemInitializer};
7210
7211
0
  case InitializedEntity::EK_Binding:
7212
    // Per [dcl.decomp]p3, the binding is treated as a variable of reference
7213
    // type.
7214
0
    return {Entity, LK_Extended};
7215
7216
0
  case InitializedEntity::EK_Parameter:
7217
0
  case InitializedEntity::EK_Parameter_CF_Audited:
7218
    //   -- A temporary bound to a reference parameter in a function call
7219
    //      persists until the completion of the full-expression containing
7220
    //      the call.
7221
0
    return {nullptr, LK_FullExpression};
7222
7223
0
  case InitializedEntity::EK_TemplateParameter:
7224
    // FIXME: This will always be ill-formed; should we eagerly diagnose it here?
7225
0
    return {nullptr, LK_FullExpression};
7226
7227
0
  case InitializedEntity::EK_Result:
7228
    //   -- The lifetime of a temporary bound to the returned value in a
7229
    //      function return statement is not extended; the temporary is
7230
    //      destroyed at the end of the full-expression in the return statement.
7231
0
    return {nullptr, LK_Return};
7232
7233
0
  case InitializedEntity::EK_StmtExprResult:
7234
    // FIXME: Should we lifetime-extend through the result of a statement
7235
    // expression?
7236
0
    return {nullptr, LK_StmtExprResult};
7237
7238
0
  case InitializedEntity::EK_New:
7239
    //   -- A temporary bound to a reference in a new-initializer persists
7240
    //      until the completion of the full-expression containing the
7241
    //      new-initializer.
7242
0
    return {nullptr, LK_New};
7243
7244
0
  case InitializedEntity::EK_Temporary:
7245
0
  case InitializedEntity::EK_CompoundLiteralInit:
7246
0
  case InitializedEntity::EK_RelatedResult:
7247
    // We don't yet know the storage duration of the surrounding temporary.
7248
    // Assume it's got full-expression duration for now, it will patch up our
7249
    // storage duration if that's not correct.
7250
0
    return {nullptr, LK_FullExpression};
7251
7252
0
  case InitializedEntity::EK_ArrayElement:
7253
    // For subobjects, we look at the complete object.
7254
0
    return getEntityLifetime(Entity->getParent(), InitField);
7255
7256
0
  case InitializedEntity::EK_Base:
7257
    // For subobjects, we look at the complete object.
7258
0
    if (Entity->getParent())
7259
0
      return getEntityLifetime(Entity->getParent(), InitField);
7260
0
    return {InitField, LK_MemInitializer};
7261
7262
0
  case InitializedEntity::EK_Delegating:
7263
    // We can reach this case for aggregate initialization in a constructor:
7264
    //   struct A { int &&r; };
7265
    //   struct B : A { B() : A{0} {} };
7266
    // In this case, use the outermost field decl as the context.
7267
0
    return {InitField, LK_MemInitializer};
7268
7269
0
  case InitializedEntity::EK_BlockElement:
7270
0
  case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
7271
0
  case InitializedEntity::EK_LambdaCapture:
7272
0
  case InitializedEntity::EK_VectorElement:
7273
0
  case InitializedEntity::EK_ComplexElement:
7274
0
    return {nullptr, LK_FullExpression};
7275
7276
0
  case InitializedEntity::EK_Exception:
7277
    // FIXME: Can we diagnose lifetime problems with exceptions?
7278
0
    return {nullptr, LK_FullExpression};
7279
7280
0
  case InitializedEntity::EK_ParenAggInitMember:
7281
    //   -- A temporary object bound to a reference element of an aggregate of
7282
    //      class type initialized from a parenthesized expression-list
7283
    //      [dcl.init, 9.3] persists until the completion of the full-expression
7284
    //      containing the expression-list.
7285
0
    return {nullptr, LK_FullExpression};
7286
7
  }
7287
7288
0
  llvm_unreachable("unknown entity kind");
7289
0
}
7290
7291
namespace {
7292
enum ReferenceKind {
7293
  /// Lifetime would be extended by a reference binding to a temporary.
7294
  RK_ReferenceBinding,
7295
  /// Lifetime would be extended by a std::initializer_list object binding to
7296
  /// its backing array.
7297
  RK_StdInitializerList,
7298
};
7299
7300
/// A temporary or local variable. This will be one of:
7301
///  * A MaterializeTemporaryExpr.
7302
///  * A DeclRefExpr whose declaration is a local.
7303
///  * An AddrLabelExpr.
7304
///  * A BlockExpr for a block with captures.
7305
using Local = Expr*;
7306
7307
/// Expressions we stepped over when looking for the local state. Any steps
7308
/// that would inhibit lifetime extension or take us out of subexpressions of
7309
/// the initializer are included.
7310
struct IndirectLocalPathEntry {
7311
  enum EntryKind {
7312
    DefaultInit,
7313
    AddressOf,
7314
    VarInit,
7315
    LValToRVal,
7316
    LifetimeBoundCall,
7317
    TemporaryCopy,
7318
    LambdaCaptureInit,
7319
    GslReferenceInit,
7320
    GslPointerInit
7321
  } Kind;
7322
  Expr *E;
7323
  union {
7324
    const Decl *D = nullptr;
7325
    const LambdaCapture *Capture;
7326
  };
7327
0
  IndirectLocalPathEntry() {}
7328
4
  IndirectLocalPathEntry(EntryKind K, Expr *E) : Kind(K), E(E) {}
7329
  IndirectLocalPathEntry(EntryKind K, Expr *E, const Decl *D)
7330
0
      : Kind(K), E(E), D(D) {}
7331
  IndirectLocalPathEntry(EntryKind K, Expr *E, const LambdaCapture *Capture)
7332
0
      : Kind(K), E(E), Capture(Capture) {}
7333
};
7334
7335
using IndirectLocalPath = llvm::SmallVectorImpl<IndirectLocalPathEntry>;
7336
7337
struct RevertToOldSizeRAII {
7338
  IndirectLocalPath &Path;
7339
  unsigned OldSize = Path.size();
7340
11
  RevertToOldSizeRAII(IndirectLocalPath &Path) : Path(Path) {}
7341
11
  ~RevertToOldSizeRAII() { Path.resize(OldSize); }
7342
};
7343
7344
using LocalVisitor = llvm::function_ref<bool(IndirectLocalPath &Path, Local L,
7345
                                             ReferenceKind RK)>;
7346
}
7347
7348
0
static bool isVarOnPath(IndirectLocalPath &Path, VarDecl *VD) {
7349
0
  for (auto E : Path)
7350
0
    if (E.Kind == IndirectLocalPathEntry::VarInit && E.D == VD)
7351
0
      return true;
7352
0
  return false;
7353
0
}
7354
7355
0
static bool pathContainsInit(IndirectLocalPath &Path) {
7356
0
  return llvm::any_of(Path, [=](IndirectLocalPathEntry E) {
7357
0
    return E.Kind == IndirectLocalPathEntry::DefaultInit ||
7358
0
           E.Kind == IndirectLocalPathEntry::VarInit;
7359
0
  });
7360
0
}
7361
7362
static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7363
                                             Expr *Init, LocalVisitor Visit,
7364
                                             bool RevisitSubinits,
7365
                                             bool EnableLifetimeWarnings);
7366
7367
static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7368
                                                  Expr *Init, ReferenceKind RK,
7369
                                                  LocalVisitor Visit,
7370
                                                  bool EnableLifetimeWarnings);
7371
7372
0
template <typename T> static bool isRecordWithAttr(QualType Type) {
7373
0
  if (auto *RD = Type->getAsCXXRecordDecl())
7374
0
    return RD->hasAttr<T>();
7375
0
  return false;
7376
0
}
Unexecuted instantiation: SemaInit.cpp:bool isRecordWithAttr<clang::PointerAttr>(clang::QualType)
Unexecuted instantiation: SemaInit.cpp:bool isRecordWithAttr<clang::OwnerAttr>(clang::QualType)
7377
7378
// Decl::isInStdNamespace will return false for iterators in some STL
7379
// implementations due to them being defined in a namespace outside of the std
7380
// namespace.
7381
0
static bool isInStlNamespace(const Decl *D) {
7382
0
  const DeclContext *DC = D->getDeclContext();
7383
0
  if (!DC)
7384
0
    return false;
7385
0
  if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
7386
0
    if (const IdentifierInfo *II = ND->getIdentifier()) {
7387
0
      StringRef Name = II->getName();
7388
0
      if (Name.size() >= 2 && Name.front() == '_' &&
7389
0
          (Name[1] == '_' || isUppercase(Name[1])))
7390
0
        return true;
7391
0
    }
7392
7393
0
  return DC->isStdNamespace();
7394
0
}
7395
7396
0
static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
7397
0
  if (auto *Conv = dyn_cast_or_null<CXXConversionDecl>(Callee))
7398
0
    if (isRecordWithAttr<PointerAttr>(Conv->getConversionType()))
7399
0
      return true;
7400
0
  if (!isInStlNamespace(Callee->getParent()))
7401
0
    return false;
7402
0
  if (!isRecordWithAttr<PointerAttr>(
7403
0
          Callee->getFunctionObjectParameterType()) &&
7404
0
      !isRecordWithAttr<OwnerAttr>(Callee->getFunctionObjectParameterType()))
7405
0
    return false;
7406
0
  if (Callee->getReturnType()->isPointerType() ||
7407
0
      isRecordWithAttr<PointerAttr>(Callee->getReturnType())) {
7408
0
    if (!Callee->getIdentifier())
7409
0
      return false;
7410
0
    return llvm::StringSwitch<bool>(Callee->getName())
7411
0
        .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7412
0
        .Cases("end", "rend", "cend", "crend", true)
7413
0
        .Cases("c_str", "data", "get", true)
7414
        // Map and set types.
7415
0
        .Cases("find", "equal_range", "lower_bound", "upper_bound", true)
7416
0
        .Default(false);
7417
0
  } else if (Callee->getReturnType()->isReferenceType()) {
7418
0
    if (!Callee->getIdentifier()) {
7419
0
      auto OO = Callee->getOverloadedOperator();
7420
0
      return OO == OverloadedOperatorKind::OO_Subscript ||
7421
0
             OO == OverloadedOperatorKind::OO_Star;
7422
0
    }
7423
0
    return llvm::StringSwitch<bool>(Callee->getName())
7424
0
        .Cases("front", "back", "at", "top", "value", true)
7425
0
        .Default(false);
7426
0
  }
7427
0
  return false;
7428
0
}
7429
7430
0
static bool shouldTrackFirstArgument(const FunctionDecl *FD) {
7431
0
  if (!FD->getIdentifier() || FD->getNumParams() != 1)
7432
0
    return false;
7433
0
  const auto *RD = FD->getParamDecl(0)->getType()->getPointeeCXXRecordDecl();
7434
0
  if (!FD->isInStdNamespace() || !RD || !RD->isInStdNamespace())
7435
0
    return false;
7436
0
  if (!isRecordWithAttr<PointerAttr>(QualType(RD->getTypeForDecl(), 0)) &&
7437
0
      !isRecordWithAttr<OwnerAttr>(QualType(RD->getTypeForDecl(), 0)))
7438
0
    return false;
7439
0
  if (FD->getReturnType()->isPointerType() ||
7440
0
      isRecordWithAttr<PointerAttr>(FD->getReturnType())) {
7441
0
    return llvm::StringSwitch<bool>(FD->getName())
7442
0
        .Cases("begin", "rbegin", "cbegin", "crbegin", true)
7443
0
        .Cases("end", "rend", "cend", "crend", true)
7444
0
        .Case("data", true)
7445
0
        .Default(false);
7446
0
  } else if (FD->getReturnType()->isReferenceType()) {
7447
0
    return llvm::StringSwitch<bool>(FD->getName())
7448
0
        .Cases("get", "any_cast", true)
7449
0
        .Default(false);
7450
0
  }
7451
0
  return false;
7452
0
}
7453
7454
static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
7455
0
                                    LocalVisitor Visit) {
7456
0
  auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
7457
    // We are not interested in the temporary base objects of gsl Pointers:
7458
    //   Temp().ptr; // Here ptr might not dangle.
7459
0
    if (isa<MemberExpr>(Arg->IgnoreImpCasts()))
7460
0
      return;
7461
    // Once we initialized a value with a reference, it can no longer dangle.
7462
0
    if (!Value) {
7463
0
      for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
7464
0
        if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit)
7465
0
          continue;
7466
0
        if (PE.Kind == IndirectLocalPathEntry::GslPointerInit)
7467
0
          return;
7468
0
        break;
7469
0
      }
7470
0
    }
7471
0
    Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
7472
0
                          : IndirectLocalPathEntry::GslReferenceInit,
7473
0
                    Arg, D});
7474
0
    if (Arg->isGLValue())
7475
0
      visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7476
0
                                            Visit,
7477
0
                                            /*EnableLifetimeWarnings=*/true);
7478
0
    else
7479
0
      visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7480
0
                                       /*EnableLifetimeWarnings=*/true);
7481
0
    Path.pop_back();
7482
0
  };
7483
7484
0
  if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7485
0
    const auto *MD = cast_or_null<CXXMethodDecl>(MCE->getDirectCallee());
7486
0
    if (MD && shouldTrackImplicitObjectArg(MD))
7487
0
      VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
7488
0
                      !MD->getReturnType()->isReferenceType());
7489
0
    return;
7490
0
  } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(Call)) {
7491
0
    FunctionDecl *Callee = OCE->getDirectCallee();
7492
0
    if (Callee && Callee->isCXXInstanceMember() &&
7493
0
        shouldTrackImplicitObjectArg(cast<CXXMethodDecl>(Callee)))
7494
0
      VisitPointerArg(Callee, OCE->getArg(0),
7495
0
                      !Callee->getReturnType()->isReferenceType());
7496
0
    return;
7497
0
  } else if (auto *CE = dyn_cast<CallExpr>(Call)) {
7498
0
    FunctionDecl *Callee = CE->getDirectCallee();
7499
0
    if (Callee && shouldTrackFirstArgument(Callee))
7500
0
      VisitPointerArg(Callee, CE->getArg(0),
7501
0
                      !Callee->getReturnType()->isReferenceType());
7502
0
    return;
7503
0
  }
7504
7505
0
  if (auto *CCE = dyn_cast<CXXConstructExpr>(Call)) {
7506
0
    const auto *Ctor = CCE->getConstructor();
7507
0
    const CXXRecordDecl *RD = Ctor->getParent();
7508
0
    if (CCE->getNumArgs() > 0 && RD->hasAttr<PointerAttr>())
7509
0
      VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
7510
0
  }
7511
0
}
7512
7513
0
static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
7514
0
  const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7515
0
  if (!TSI)
7516
0
    return false;
7517
  // Don't declare this variable in the second operand of the for-statement;
7518
  // GCC miscompiles that by ending its lifetime before evaluating the
7519
  // third operand. See gcc.gnu.org/PR86769.
7520
0
  AttributedTypeLoc ATL;
7521
0
  for (TypeLoc TL = TSI->getTypeLoc();
7522
0
       (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7523
0
       TL = ATL.getModifiedLoc()) {
7524
0
    if (ATL.getAttrAs<LifetimeBoundAttr>())
7525
0
      return true;
7526
0
  }
7527
7528
  // Assume that all assignment operators with a "normal" return type return
7529
  // *this, that is, an lvalue reference that is the same type as the implicit
7530
  // object parameter (or the LHS for a non-member operator$=).
7531
0
  OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator();
7532
0
  if (OO == OO_Equal || isCompoundAssignmentOperator(OO)) {
7533
0
    QualType RetT = FD->getReturnType();
7534
0
    if (RetT->isLValueReferenceType()) {
7535
0
      ASTContext &Ctx = FD->getASTContext();
7536
0
      QualType LHST;
7537
0
      auto *MD = dyn_cast<CXXMethodDecl>(FD);
7538
0
      if (MD && MD->isCXXInstanceMember())
7539
0
        LHST = Ctx.getLValueReferenceType(MD->getFunctionObjectParameterType());
7540
0
      else
7541
0
        LHST = MD->getParamDecl(0)->getType();
7542
0
      if (Ctx.hasSameType(RetT, LHST))
7543
0
        return true;
7544
0
    }
7545
0
  }
7546
7547
0
  return false;
7548
0
}
7549
7550
static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
7551
0
                                        LocalVisitor Visit) {
7552
0
  const FunctionDecl *Callee;
7553
0
  ArrayRef<Expr*> Args;
7554
7555
0
  if (auto *CE = dyn_cast<CallExpr>(Call)) {
7556
0
    Callee = CE->getDirectCallee();
7557
0
    Args = llvm::ArrayRef(CE->getArgs(), CE->getNumArgs());
7558
0
  } else {
7559
0
    auto *CCE = cast<CXXConstructExpr>(Call);
7560
0
    Callee = CCE->getConstructor();
7561
0
    Args = llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs());
7562
0
  }
7563
0
  if (!Callee)
7564
0
    return;
7565
7566
0
  Expr *ObjectArg = nullptr;
7567
0
  if (isa<CXXOperatorCallExpr>(Call) && Callee->isCXXInstanceMember()) {
7568
0
    ObjectArg = Args[0];
7569
0
    Args = Args.slice(1);
7570
0
  } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(Call)) {
7571
0
    ObjectArg = MCE->getImplicitObjectArgument();
7572
0
  }
7573
7574
0
  auto VisitLifetimeBoundArg = [&](const Decl *D, Expr *Arg) {
7575
0
    Path.push_back({IndirectLocalPathEntry::LifetimeBoundCall, Arg, D});
7576
0
    if (Arg->isGLValue())
7577
0
      visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
7578
0
                                            Visit,
7579
0
                                            /*EnableLifetimeWarnings=*/false);
7580
0
    else
7581
0
      visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7582
0
                                       /*EnableLifetimeWarnings=*/false);
7583
0
    Path.pop_back();
7584
0
  };
7585
7586
0
  if (ObjectArg && implicitObjectParamIsLifetimeBound(Callee))
7587
0
    VisitLifetimeBoundArg(Callee, ObjectArg);
7588
7589
0
  bool CheckCoroCall = false;
7590
0
  if (const auto *RD = Callee->getReturnType()->getAsRecordDecl()) {
7591
0
    CheckCoroCall = RD->hasAttr<CoroLifetimeBoundAttr>() &&
7592
0
                    RD->hasAttr<CoroReturnTypeAttr>() &&
7593
0
                    !Callee->hasAttr<CoroDisableLifetimeBoundAttr>();
7594
0
  }
7595
0
  for (unsigned I = 0,
7596
0
                N = std::min<unsigned>(Callee->getNumParams(), Args.size());
7597
0
       I != N; ++I) {
7598
0
    if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
7599
0
      VisitLifetimeBoundArg(Callee->getParamDecl(I), Args[I]);
7600
0
  }
7601
0
}
7602
7603
/// Visit the locals that would be reachable through a reference bound to the
7604
/// glvalue expression \c Init.
7605
static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
7606
                                                  Expr *Init, ReferenceKind RK,
7607
                                                  LocalVisitor Visit,
7608
4
                                                  bool EnableLifetimeWarnings) {
7609
4
  RevertToOldSizeRAII RAII(Path);
7610
7611
  // Walk past any constructs which we can lifetime-extend across.
7612
4
  Expr *Old;
7613
8
  do {
7614
8
    Old = Init;
7615
7616
8
    if (auto *FE = dyn_cast<FullExpr>(Init))
7617
0
      Init = FE->getSubExpr();
7618
7619
8
    if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7620
      // If this is just redundant braces around an initializer, step over it.
7621
0
      if (ILE->isTransparent())
7622
0
        Init = ILE->getInit(0);
7623
0
    }
7624
7625
    // Step over any subobject adjustments; we may have a materialized
7626
    // temporary inside them.
7627
8
    Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7628
7629
    // Per current approach for DR1376, look through casts to reference type
7630
    // when performing lifetime extension.
7631
8
    if (CastExpr *CE = dyn_cast<CastExpr>(Init))
7632
4
      if (CE->getSubExpr()->isGLValue())
7633
4
        Init = CE->getSubExpr();
7634
7635
    // Per the current approach for DR1299, look through array element access
7636
    // on array glvalues when performing lifetime extension.
7637
8
    if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Init)) {
7638
0
      Init = ASE->getBase();
7639
0
      auto *ICE = dyn_cast<ImplicitCastExpr>(Init);
7640
0
      if (ICE && ICE->getCastKind() == CK_ArrayToPointerDecay)
7641
0
        Init = ICE->getSubExpr();
7642
0
      else
7643
        // We can't lifetime extend through this but we might still find some
7644
        // retained temporaries.
7645
0
        return visitLocalsRetainedByInitializer(Path, Init, Visit, true,
7646
0
                                                EnableLifetimeWarnings);
7647
0
    }
7648
7649
    // Step into CXXDefaultInitExprs so we can diagnose cases where a
7650
    // constructor inherits one as an implicit mem-initializer.
7651
8
    if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7652
0
      Path.push_back(
7653
0
          {IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7654
0
      Init = DIE->getExpr();
7655
0
    }
7656
8
  } while (Init != Old);
7657
7658
4
  if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
7659
0
    if (Visit(Path, Local(MTE), RK))
7660
0
      visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit, true,
7661
0
                                       EnableLifetimeWarnings);
7662
0
  }
7663
7664
4
  if (isa<CallExpr>(Init)) {
7665
0
    if (EnableLifetimeWarnings)
7666
0
      handleGslAnnotatedTypes(Path, Init, Visit);
7667
0
    return visitLifetimeBoundArguments(Path, Init, Visit);
7668
0
  }
7669
7670
4
  switch (Init->getStmtClass()) {
7671
4
  case Stmt::DeclRefExprClass: {
7672
    // If we find the name of a local non-reference parameter, we could have a
7673
    // lifetime problem.
7674
4
    auto *DRE = cast<DeclRefExpr>(Init);
7675
4
    auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7676
4
    if (VD && VD->hasLocalStorage() &&
7677
4
        !DRE->refersToEnclosingVariableOrCapture()) {
7678
0
      if (!VD->getType()->isReferenceType()) {
7679
0
        Visit(Path, Local(DRE), RK);
7680
0
      } else if (isa<ParmVarDecl>(DRE->getDecl())) {
7681
        // The lifetime of a reference parameter is unknown; assume it's OK
7682
        // for now.
7683
0
        break;
7684
0
      } else if (VD->getInit() && !isVarOnPath(Path, VD)) {
7685
0
        Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7686
0
        visitLocalsRetainedByReferenceBinding(Path, VD->getInit(),
7687
0
                                              RK_ReferenceBinding, Visit,
7688
0
                                              EnableLifetimeWarnings);
7689
0
      }
7690
0
    }
7691
4
    break;
7692
4
  }
7693
7694
4
  case Stmt::UnaryOperatorClass: {
7695
    // The only unary operator that make sense to handle here
7696
    // is Deref.  All others don't resolve to a "name."  This includes
7697
    // handling all sorts of rvalues passed to a unary operator.
7698
0
    const UnaryOperator *U = cast<UnaryOperator>(Init);
7699
0
    if (U->getOpcode() == UO_Deref)
7700
0
      visitLocalsRetainedByInitializer(Path, U->getSubExpr(), Visit, true,
7701
0
                                       EnableLifetimeWarnings);
7702
0
    break;
7703
4
  }
7704
7705
0
  case Stmt::OMPArraySectionExprClass: {
7706
0
    visitLocalsRetainedByInitializer(Path,
7707
0
                                     cast<OMPArraySectionExpr>(Init)->getBase(),
7708
0
                                     Visit, true, EnableLifetimeWarnings);
7709
0
    break;
7710
4
  }
7711
7712
0
  case Stmt::ConditionalOperatorClass:
7713
0
  case Stmt::BinaryConditionalOperatorClass: {
7714
0
    auto *C = cast<AbstractConditionalOperator>(Init);
7715
0
    if (!C->getTrueExpr()->getType()->isVoidType())
7716
0
      visitLocalsRetainedByReferenceBinding(Path, C->getTrueExpr(), RK, Visit,
7717
0
                                            EnableLifetimeWarnings);
7718
0
    if (!C->getFalseExpr()->getType()->isVoidType())
7719
0
      visitLocalsRetainedByReferenceBinding(Path, C->getFalseExpr(), RK, Visit,
7720
0
                                            EnableLifetimeWarnings);
7721
0
    break;
7722
0
  }
7723
7724
  // FIXME: Visit the left-hand side of an -> or ->*.
7725
7726
0
  default:
7727
0
    break;
7728
4
  }
7729
4
}
7730
7731
/// Visit the locals that would be reachable through an object initialized by
7732
/// the prvalue expression \c Init.
7733
static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
7734
                                             Expr *Init, LocalVisitor Visit,
7735
                                             bool RevisitSubinits,
7736
7
                                             bool EnableLifetimeWarnings) {
7737
7
  RevertToOldSizeRAII RAII(Path);
7738
7739
7
  Expr *Old;
7740
8
  do {
7741
8
    Old = Init;
7742
7743
    // Step into CXXDefaultInitExprs so we can diagnose cases where a
7744
    // constructor inherits one as an implicit mem-initializer.
7745
8
    if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Init)) {
7746
0
      Path.push_back({IndirectLocalPathEntry::DefaultInit, DIE, DIE->getField()});
7747
0
      Init = DIE->getExpr();
7748
0
    }
7749
7750
8
    if (auto *FE = dyn_cast<FullExpr>(Init))
7751
0
      Init = FE->getSubExpr();
7752
7753
    // Dig out the expression which constructs the extended temporary.
7754
8
    Init = const_cast<Expr *>(Init->skipRValueSubobjectAdjustments());
7755
7756
8
    if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
7757
0
      Init = BTE->getSubExpr();
7758
7759
8
    Init = Init->IgnoreParens();
7760
7761
    // Step over value-preserving rvalue casts.
7762
8
    if (auto *CE = dyn_cast<CastExpr>(Init)) {
7763
5
      switch (CE->getCastKind()) {
7764
4
      case CK_LValueToRValue:
7765
        // If we can match the lvalue to a const object, we can look at its
7766
        // initializer.
7767
4
        Path.push_back({IndirectLocalPathEntry::LValToRVal, CE});
7768
4
        return visitLocalsRetainedByReferenceBinding(
7769
4
            Path, Init, RK_ReferenceBinding,
7770
4
            [&](IndirectLocalPath &Path, Local L, ReferenceKind RK) -> bool {
7771
0
          if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
7772
0
            auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
7773
0
            if (VD && VD->getType().isConstQualified() && VD->getInit() &&
7774
0
                !isVarOnPath(Path, VD)) {
7775
0
              Path.push_back({IndirectLocalPathEntry::VarInit, DRE, VD});
7776
0
              visitLocalsRetainedByInitializer(Path, VD->getInit(), Visit, true,
7777
0
                                               EnableLifetimeWarnings);
7778
0
            }
7779
0
          } else if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L)) {
7780
0
            if (MTE->getType().isConstQualified())
7781
0
              visitLocalsRetainedByInitializer(Path, MTE->getSubExpr(), Visit,
7782
0
                                               true, EnableLifetimeWarnings);
7783
0
          }
7784
0
          return false;
7785
0
        }, EnableLifetimeWarnings);
7786
7787
        // We assume that objects can be retained by pointers cast to integers,
7788
        // but not if the integer is cast to floating-point type or to _Complex.
7789
        // We assume that casts to 'bool' do not preserve enough information to
7790
        // retain a local object.
7791
0
      case CK_NoOp:
7792
0
      case CK_BitCast:
7793
0
      case CK_BaseToDerived:
7794
0
      case CK_DerivedToBase:
7795
0
      case CK_UncheckedDerivedToBase:
7796
0
      case CK_Dynamic:
7797
0
      case CK_ToUnion:
7798
0
      case CK_UserDefinedConversion:
7799
0
      case CK_ConstructorConversion:
7800
1
      case CK_IntegralToPointer:
7801
1
      case CK_PointerToIntegral:
7802
1
      case CK_VectorSplat:
7803
1
      case CK_IntegralCast:
7804
1
      case CK_CPointerToObjCPointerCast:
7805
1
      case CK_BlockPointerToObjCPointerCast:
7806
1
      case CK_AnyPointerToBlockPointerCast:
7807
1
      case CK_AddressSpaceConversion:
7808
1
        break;
7809
7810
0
      case CK_ArrayToPointerDecay:
7811
        // Model array-to-pointer decay as taking the address of the array
7812
        // lvalue.
7813
0
        Path.push_back({IndirectLocalPathEntry::AddressOf, CE});
7814
0
        return visitLocalsRetainedByReferenceBinding(Path, CE->getSubExpr(),
7815
0
                                                     RK_ReferenceBinding, Visit,
7816
0
                                                     EnableLifetimeWarnings);
7817
7818
0
      default:
7819
0
        return;
7820
5
      }
7821
7822
1
      Init = CE->getSubExpr();
7823
1
    }
7824
8
  } while (Old != Init);
7825
7826
  // C++17 [dcl.init.list]p6:
7827
  //   initializing an initializer_list object from the array extends the
7828
  //   lifetime of the array exactly like binding a reference to a temporary.
7829
3
  if (auto *ILE = dyn_cast<CXXStdInitializerListExpr>(Init))
7830
0
    return visitLocalsRetainedByReferenceBinding(Path, ILE->getSubExpr(),
7831
0
                                                 RK_StdInitializerList, Visit,
7832
0
                                                 EnableLifetimeWarnings);
7833
7834
3
  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
7835
    // We already visited the elements of this initializer list while
7836
    // performing the initialization. Don't visit them again unless we've
7837
    // changed the lifetime of the initialized entity.
7838
0
    if (!RevisitSubinits)
7839
0
      return;
7840
7841
0
    if (ILE->isTransparent())
7842
0
      return visitLocalsRetainedByInitializer(Path, ILE->getInit(0), Visit,
7843
0
                                              RevisitSubinits,
7844
0
                                              EnableLifetimeWarnings);
7845
7846
0
    if (ILE->getType()->isArrayType()) {
7847
0
      for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
7848
0
        visitLocalsRetainedByInitializer(Path, ILE->getInit(I), Visit,
7849
0
                                         RevisitSubinits,
7850
0
                                         EnableLifetimeWarnings);
7851
0
      return;
7852
0
    }
7853
7854
0
    if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
7855
0
      assert(RD->isAggregate() && "aggregate init on non-aggregate");
7856
7857
      // If we lifetime-extend a braced initializer which is initializing an
7858
      // aggregate, and that aggregate contains reference members which are
7859
      // bound to temporaries, those temporaries are also lifetime-extended.
7860
0
      if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
7861
0
          ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
7862
0
        visitLocalsRetainedByReferenceBinding(Path, ILE->getInit(0),
7863
0
                                              RK_ReferenceBinding, Visit,
7864
0
                                              EnableLifetimeWarnings);
7865
0
      else {
7866
0
        unsigned Index = 0;
7867
0
        for (; Index < RD->getNumBases() && Index < ILE->getNumInits(); ++Index)
7868
0
          visitLocalsRetainedByInitializer(Path, ILE->getInit(Index), Visit,
7869
0
                                           RevisitSubinits,
7870
0
                                           EnableLifetimeWarnings);
7871
0
        for (const auto *I : RD->fields()) {
7872
0
          if (Index >= ILE->getNumInits())
7873
0
            break;
7874
0
          if (I->isUnnamedBitfield())
7875
0
            continue;
7876
0
          Expr *SubInit = ILE->getInit(Index);
7877
0
          if (I->getType()->isReferenceType())
7878
0
            visitLocalsRetainedByReferenceBinding(Path, SubInit,
7879
0
                                                  RK_ReferenceBinding, Visit,
7880
0
                                                  EnableLifetimeWarnings);
7881
0
          else
7882
            // This might be either aggregate-initialization of a member or
7883
            // initialization of a std::initializer_list object. Regardless,
7884
            // we should recursively lifetime-extend that initializer.
7885
0
            visitLocalsRetainedByInitializer(Path, SubInit, Visit,
7886
0
                                             RevisitSubinits,
7887
0
                                             EnableLifetimeWarnings);
7888
0
          ++Index;
7889
0
        }
7890
0
      }
7891
0
    }
7892
0
    return;
7893
0
  }
7894
7895
  // The lifetime of an init-capture is that of the closure object constructed
7896
  // by a lambda-expression.
7897
3
  if (auto *LE = dyn_cast<LambdaExpr>(Init)) {
7898
0
    LambdaExpr::capture_iterator CapI = LE->capture_begin();
7899
0
    for (Expr *E : LE->capture_inits()) {
7900
0
      assert(CapI != LE->capture_end());
7901
0
      const LambdaCapture &Cap = *CapI++;
7902
0
      if (!E)
7903
0
        continue;
7904
0
      if (Cap.capturesVariable())
7905
0
        Path.push_back({IndirectLocalPathEntry::LambdaCaptureInit, E, &Cap});
7906
0
      if (E->isGLValue())
7907
0
        visitLocalsRetainedByReferenceBinding(Path, E, RK_ReferenceBinding,
7908
0
                                              Visit, EnableLifetimeWarnings);
7909
0
      else
7910
0
        visitLocalsRetainedByInitializer(Path, E, Visit, true,
7911
0
                                         EnableLifetimeWarnings);
7912
0
      if (Cap.capturesVariable())
7913
0
        Path.pop_back();
7914
0
    }
7915
0
  }
7916
7917
  // Assume that a copy or move from a temporary references the same objects
7918
  // that the temporary does.
7919
3
  if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
7920
0
    if (CCE->getConstructor()->isCopyOrMoveConstructor()) {
7921
0
      if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(CCE->getArg(0))) {
7922
0
        Expr *Arg = MTE->getSubExpr();
7923
0
        Path.push_back({IndirectLocalPathEntry::TemporaryCopy, Arg,
7924
0
                        CCE->getConstructor()});
7925
0
        visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
7926
0
                                         /*EnableLifetimeWarnings*/false);
7927
0
        Path.pop_back();
7928
0
      }
7929
0
    }
7930
0
  }
7931
7932
3
  if (isa<CallExpr>(Init) || isa<CXXConstructExpr>(Init)) {
7933
0
    if (EnableLifetimeWarnings)
7934
0
      handleGslAnnotatedTypes(Path, Init, Visit);
7935
0
    return visitLifetimeBoundArguments(Path, Init, Visit);
7936
0
  }
7937
7938
3
  switch (Init->getStmtClass()) {
7939
0
  case Stmt::UnaryOperatorClass: {
7940
0
    auto *UO = cast<UnaryOperator>(Init);
7941
    // If the initializer is the address of a local, we could have a lifetime
7942
    // problem.
7943
0
    if (UO->getOpcode() == UO_AddrOf) {
7944
      // If this is &rvalue, then it's ill-formed and we have already diagnosed
7945
      // it. Don't produce a redundant warning about the lifetime of the
7946
      // temporary.
7947
0
      if (isa<MaterializeTemporaryExpr>(UO->getSubExpr()))
7948
0
        return;
7949
7950
0
      Path.push_back({IndirectLocalPathEntry::AddressOf, UO});
7951
0
      visitLocalsRetainedByReferenceBinding(Path, UO->getSubExpr(),
7952
0
                                            RK_ReferenceBinding, Visit,
7953
0
                                            EnableLifetimeWarnings);
7954
0
    }
7955
0
    break;
7956
0
  }
7957
7958
0
  case Stmt::BinaryOperatorClass: {
7959
    // Handle pointer arithmetic.
7960
0
    auto *BO = cast<BinaryOperator>(Init);
7961
0
    BinaryOperatorKind BOK = BO->getOpcode();
7962
0
    if (!BO->getType()->isPointerType() || (BOK != BO_Add && BOK != BO_Sub))
7963
0
      break;
7964
7965
0
    if (BO->getLHS()->getType()->isPointerType())
7966
0
      visitLocalsRetainedByInitializer(Path, BO->getLHS(), Visit, true,
7967
0
                                       EnableLifetimeWarnings);
7968
0
    else if (BO->getRHS()->getType()->isPointerType())
7969
0
      visitLocalsRetainedByInitializer(Path, BO->getRHS(), Visit, true,
7970
0
                                       EnableLifetimeWarnings);
7971
0
    break;
7972
0
  }
7973
7974
0
  case Stmt::ConditionalOperatorClass:
7975
0
  case Stmt::BinaryConditionalOperatorClass: {
7976
0
    auto *C = cast<AbstractConditionalOperator>(Init);
7977
    // In C++, we can have a throw-expression operand, which has 'void' type
7978
    // and isn't interesting from a lifetime perspective.
7979
0
    if (!C->getTrueExpr()->getType()->isVoidType())
7980
0
      visitLocalsRetainedByInitializer(Path, C->getTrueExpr(), Visit, true,
7981
0
                                       EnableLifetimeWarnings);
7982
0
    if (!C->getFalseExpr()->getType()->isVoidType())
7983
0
      visitLocalsRetainedByInitializer(Path, C->getFalseExpr(), Visit, true,
7984
0
                                       EnableLifetimeWarnings);
7985
0
    break;
7986
0
  }
7987
7988
0
  case Stmt::BlockExprClass:
7989
0
    if (cast<BlockExpr>(Init)->getBlockDecl()->hasCaptures()) {
7990
      // This is a local block, whose lifetime is that of the function.
7991
0
      Visit(Path, Local(cast<BlockExpr>(Init)), RK_ReferenceBinding);
7992
0
    }
7993
0
    break;
7994
7995
0
  case Stmt::AddrLabelExprClass:
7996
    // We want to warn if the address of a label would escape the function.
7997
0
    Visit(Path, Local(cast<AddrLabelExpr>(Init)), RK_ReferenceBinding);
7998
0
    break;
7999
8000
3
  default:
8001
3
    break;
8002
3
  }
8003
3
}
8004
8005
/// Whether a path to an object supports lifetime extension.
8006
enum PathLifetimeKind {
8007
  /// Lifetime-extend along this path.
8008
  Extend,
8009
  /// We should lifetime-extend, but we don't because (due to technical
8010
  /// limitations) we can't. This happens for default member initializers,
8011
  /// which we don't clone for every use, so we don't have a unique
8012
  /// MaterializeTemporaryExpr to update.
8013
  ShouldExtend,
8014
  /// Do not lifetime extend along this path.
8015
  NoExtend
8016
};
8017
8018
/// Determine whether this is an indirect path to a temporary that we are
8019
/// supposed to lifetime-extend along.
8020
static PathLifetimeKind
8021
0
shouldLifetimeExtendThroughPath(const IndirectLocalPath &Path) {
8022
0
  PathLifetimeKind Kind = PathLifetimeKind::Extend;
8023
0
  for (auto Elem : Path) {
8024
0
    if (Elem.Kind == IndirectLocalPathEntry::DefaultInit)
8025
0
      Kind = PathLifetimeKind::ShouldExtend;
8026
0
    else if (Elem.Kind != IndirectLocalPathEntry::LambdaCaptureInit)
8027
0
      return PathLifetimeKind::NoExtend;
8028
0
  }
8029
0
  return Kind;
8030
0
}
8031
8032
/// Find the range for the first interesting entry in the path at or after I.
8033
static SourceRange nextPathEntryRange(const IndirectLocalPath &Path, unsigned I,
8034
0
                                      Expr *E) {
8035
0
  for (unsigned N = Path.size(); I != N; ++I) {
8036
0
    switch (Path[I].Kind) {
8037
0
    case IndirectLocalPathEntry::AddressOf:
8038
0
    case IndirectLocalPathEntry::LValToRVal:
8039
0
    case IndirectLocalPathEntry::LifetimeBoundCall:
8040
0
    case IndirectLocalPathEntry::TemporaryCopy:
8041
0
    case IndirectLocalPathEntry::GslReferenceInit:
8042
0
    case IndirectLocalPathEntry::GslPointerInit:
8043
      // These exist primarily to mark the path as not permitting or
8044
      // supporting lifetime extension.
8045
0
      break;
8046
8047
0
    case IndirectLocalPathEntry::VarInit:
8048
0
      if (cast<VarDecl>(Path[I].D)->isImplicit())
8049
0
        return SourceRange();
8050
0
      [[fallthrough]];
8051
0
    case IndirectLocalPathEntry::DefaultInit:
8052
0
      return Path[I].E->getSourceRange();
8053
8054
0
    case IndirectLocalPathEntry::LambdaCaptureInit:
8055
0
      if (!Path[I].Capture->capturesVariable())
8056
0
        continue;
8057
0
      return Path[I].E->getSourceRange();
8058
0
    }
8059
0
  }
8060
0
  return E->getSourceRange();
8061
0
}
8062
8063
0
static bool pathOnlyInitializesGslPointer(IndirectLocalPath &Path) {
8064
0
  for (const auto &It : llvm::reverse(Path)) {
8065
0
    if (It.Kind == IndirectLocalPathEntry::VarInit)
8066
0
      continue;
8067
0
    if (It.Kind == IndirectLocalPathEntry::AddressOf)
8068
0
      continue;
8069
0
    if (It.Kind == IndirectLocalPathEntry::LifetimeBoundCall)
8070
0
      continue;
8071
0
    return It.Kind == IndirectLocalPathEntry::GslPointerInit ||
8072
0
           It.Kind == IndirectLocalPathEntry::GslReferenceInit;
8073
0
  }
8074
0
  return false;
8075
0
}
8076
8077
void Sema::checkInitializerLifetime(const InitializedEntity &Entity,
8078
7
                                    Expr *Init) {
8079
7
  LifetimeResult LR = getEntityLifetime(&Entity);
8080
7
  LifetimeKind LK = LR.getInt();
8081
7
  const InitializedEntity *ExtendingEntity = LR.getPointer();
8082
8083
  // If this entity doesn't have an interesting lifetime, don't bother looking
8084
  // for temporaries within its initializer.
8085
7
  if (LK == LK_FullExpression)
8086
0
    return;
8087
8088
7
  auto TemporaryVisitor = [&](IndirectLocalPath &Path, Local L,
8089
7
                              ReferenceKind RK) -> bool {
8090
0
    SourceRange DiagRange = nextPathEntryRange(Path, 0, L);
8091
0
    SourceLocation DiagLoc = DiagRange.getBegin();
8092
8093
0
    auto *MTE = dyn_cast<MaterializeTemporaryExpr>(L);
8094
8095
0
    bool IsGslPtrInitWithGslTempOwner = false;
8096
0
    bool IsLocalGslOwner = false;
8097
0
    if (pathOnlyInitializesGslPointer(Path)) {
8098
0
      if (isa<DeclRefExpr>(L)) {
8099
        // We do not want to follow the references when returning a pointer originating
8100
        // from a local owner to avoid the following false positive:
8101
        //   int &p = *localUniquePtr;
8102
        //   someContainer.add(std::move(localUniquePtr));
8103
        //   return p;
8104
0
        IsLocalGslOwner = isRecordWithAttr<OwnerAttr>(L->getType());
8105
0
        if (pathContainsInit(Path) || !IsLocalGslOwner)
8106
0
          return false;
8107
0
      } else {
8108
0
        IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
8109
0
                            isRecordWithAttr<OwnerAttr>(MTE->getType());
8110
        // Skipping a chain of initializing gsl::Pointer annotated objects.
8111
        // We are looking only for the final source to find out if it was
8112
        // a local or temporary owner or the address of a local variable/param.
8113
0
        if (!IsGslPtrInitWithGslTempOwner)
8114
0
          return true;
8115
0
      }
8116
0
    }
8117
8118
0
    switch (LK) {
8119
0
    case LK_FullExpression:
8120
0
      llvm_unreachable("already handled this");
8121
8122
0
    case LK_Extended: {
8123
0
      if (!MTE) {
8124
        // The initialized entity has lifetime beyond the full-expression,
8125
        // and the local entity does too, so don't warn.
8126
        //
8127
        // FIXME: We should consider warning if a static / thread storage
8128
        // duration variable retains an automatic storage duration local.
8129
0
        return false;
8130
0
      }
8131
8132
0
      if (IsGslPtrInitWithGslTempOwner && DiagLoc.isValid()) {
8133
0
        Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8134
0
        return false;
8135
0
      }
8136
8137
0
      switch (shouldLifetimeExtendThroughPath(Path)) {
8138
0
      case PathLifetimeKind::Extend:
8139
        // Update the storage duration of the materialized temporary.
8140
        // FIXME: Rebuild the expression instead of mutating it.
8141
0
        MTE->setExtendingDecl(ExtendingEntity->getDecl(),
8142
0
                              ExtendingEntity->allocateManglingNumber());
8143
        // Also visit the temporaries lifetime-extended by this initializer.
8144
0
        return true;
8145
8146
0
      case PathLifetimeKind::ShouldExtend:
8147
        // We're supposed to lifetime-extend the temporary along this path (per
8148
        // the resolution of DR1815), but we don't support that yet.
8149
        //
8150
        // FIXME: Properly handle this situation. Perhaps the easiest approach
8151
        // would be to clone the initializer expression on each use that would
8152
        // lifetime extend its temporaries.
8153
0
        Diag(DiagLoc, diag::warn_unsupported_lifetime_extension)
8154
0
            << RK << DiagRange;
8155
0
        break;
8156
8157
0
      case PathLifetimeKind::NoExtend:
8158
        // If the path goes through the initialization of a variable or field,
8159
        // it can't possibly reach a temporary created in this full-expression.
8160
        // We will have already diagnosed any problems with the initializer.
8161
0
        if (pathContainsInit(Path))
8162
0
          return false;
8163
8164
0
        Diag(DiagLoc, diag::warn_dangling_variable)
8165
0
            << RK << !Entity.getParent()
8166
0
            << ExtendingEntity->getDecl()->isImplicit()
8167
0
            << ExtendingEntity->getDecl() << Init->isGLValue() << DiagRange;
8168
0
        break;
8169
0
      }
8170
0
      break;
8171
0
    }
8172
8173
0
    case LK_MemInitializer: {
8174
0
      if (isa<MaterializeTemporaryExpr>(L)) {
8175
        // Under C++ DR1696, if a mem-initializer (or a default member
8176
        // initializer used by the absence of one) would lifetime-extend a
8177
        // temporary, the program is ill-formed.
8178
0
        if (auto *ExtendingDecl =
8179
0
                ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8180
0
          if (IsGslPtrInitWithGslTempOwner) {
8181
0
            Diag(DiagLoc, diag::warn_dangling_lifetime_pointer_member)
8182
0
                << ExtendingDecl << DiagRange;
8183
0
            Diag(ExtendingDecl->getLocation(),
8184
0
                 diag::note_ref_or_ptr_member_declared_here)
8185
0
                << true;
8186
0
            return false;
8187
0
          }
8188
0
          bool IsSubobjectMember = ExtendingEntity != &Entity;
8189
0
          Diag(DiagLoc, shouldLifetimeExtendThroughPath(Path) !=
8190
0
                                PathLifetimeKind::NoExtend
8191
0
                            ? diag::err_dangling_member
8192
0
                            : diag::warn_dangling_member)
8193
0
              << ExtendingDecl << IsSubobjectMember << RK << DiagRange;
8194
          // Don't bother adding a note pointing to the field if we're inside
8195
          // its default member initializer; our primary diagnostic points to
8196
          // the same place in that case.
8197
0
          if (Path.empty() ||
8198
0
              Path.back().Kind != IndirectLocalPathEntry::DefaultInit) {
8199
0
            Diag(ExtendingDecl->getLocation(),
8200
0
                 diag::note_lifetime_extending_member_declared_here)
8201
0
                << RK << IsSubobjectMember;
8202
0
          }
8203
0
        } else {
8204
          // We have a mem-initializer but no particular field within it; this
8205
          // is either a base class or a delegating initializer directly
8206
          // initializing the base-class from something that doesn't live long
8207
          // enough.
8208
          //
8209
          // FIXME: Warn on this.
8210
0
          return false;
8211
0
        }
8212
0
      } else {
8213
        // Paths via a default initializer can only occur during error recovery
8214
        // (there's no other way that a default initializer can refer to a
8215
        // local). Don't produce a bogus warning on those cases.
8216
0
        if (pathContainsInit(Path))
8217
0
          return false;
8218
8219
        // Suppress false positives for code like the one below:
8220
        //   Ctor(unique_ptr<T> up) : member(*up), member2(move(up)) {}
8221
0
        if (IsLocalGslOwner && pathOnlyInitializesGslPointer(Path))
8222
0
          return false;
8223
8224
0
        auto *DRE = dyn_cast<DeclRefExpr>(L);
8225
0
        auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
8226
0
        if (!VD) {
8227
          // A member was initialized to a local block.
8228
          // FIXME: Warn on this.
8229
0
          return false;
8230
0
        }
8231
8232
0
        if (auto *Member =
8233
0
                ExtendingEntity ? ExtendingEntity->getDecl() : nullptr) {
8234
0
          bool IsPointer = !Member->getType()->isReferenceType();
8235
0
          Diag(DiagLoc, IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
8236
0
                                  : diag::warn_bind_ref_member_to_parameter)
8237
0
              << Member << VD << isa<ParmVarDecl>(VD) << DiagRange;
8238
0
          Diag(Member->getLocation(),
8239
0
               diag::note_ref_or_ptr_member_declared_here)
8240
0
              << (unsigned)IsPointer;
8241
0
        }
8242
0
      }
8243
0
      break;
8244
0
    }
8245
8246
0
    case LK_New:
8247
0
      if (isa<MaterializeTemporaryExpr>(L)) {
8248
0
        if (IsGslPtrInitWithGslTempOwner)
8249
0
          Diag(DiagLoc, diag::warn_dangling_lifetime_pointer) << DiagRange;
8250
0
        else
8251
0
          Diag(DiagLoc, RK == RK_ReferenceBinding
8252
0
                            ? diag::warn_new_dangling_reference
8253
0
                            : diag::warn_new_dangling_initializer_list)
8254
0
              << !Entity.getParent() << DiagRange;
8255
0
      } else {
8256
        // We can't determine if the allocation outlives the local declaration.
8257
0
        return false;
8258
0
      }
8259
0
      break;
8260
8261
0
    case LK_Return:
8262
0
    case LK_StmtExprResult:
8263
0
      if (auto *DRE = dyn_cast<DeclRefExpr>(L)) {
8264
        // We can't determine if the local variable outlives the statement
8265
        // expression.
8266
0
        if (LK == LK_StmtExprResult)
8267
0
          return false;
8268
0
        Diag(DiagLoc, diag::warn_ret_stack_addr_ref)
8269
0
            << Entity.getType()->isReferenceType() << DRE->getDecl()
8270
0
            << isa<ParmVarDecl>(DRE->getDecl()) << DiagRange;
8271
0
      } else if (isa<BlockExpr>(L)) {
8272
0
        Diag(DiagLoc, diag::err_ret_local_block) << DiagRange;
8273
0
      } else if (isa<AddrLabelExpr>(L)) {
8274
        // Don't warn when returning a label from a statement expression.
8275
        // Leaving the scope doesn't end its lifetime.
8276
0
        if (LK == LK_StmtExprResult)
8277
0
          return false;
8278
0
        Diag(DiagLoc, diag::warn_ret_addr_label) << DiagRange;
8279
0
      } else {
8280
0
        Diag(DiagLoc, diag::warn_ret_local_temp_addr_ref)
8281
0
         << Entity.getType()->isReferenceType() << DiagRange;
8282
0
      }
8283
0
      break;
8284
0
    }
8285
8286
0
    for (unsigned I = 0; I != Path.size(); ++I) {
8287
0
      auto Elem = Path[I];
8288
8289
0
      switch (Elem.Kind) {
8290
0
      case IndirectLocalPathEntry::AddressOf:
8291
0
      case IndirectLocalPathEntry::LValToRVal:
8292
        // These exist primarily to mark the path as not permitting or
8293
        // supporting lifetime extension.
8294
0
        break;
8295
8296
0
      case IndirectLocalPathEntry::LifetimeBoundCall:
8297
0
      case IndirectLocalPathEntry::TemporaryCopy:
8298
0
      case IndirectLocalPathEntry::GslPointerInit:
8299
0
      case IndirectLocalPathEntry::GslReferenceInit:
8300
        // FIXME: Consider adding a note for these.
8301
0
        break;
8302
8303
0
      case IndirectLocalPathEntry::DefaultInit: {
8304
0
        auto *FD = cast<FieldDecl>(Elem.D);
8305
0
        Diag(FD->getLocation(), diag::note_init_with_default_member_initializer)
8306
0
            << FD << nextPathEntryRange(Path, I + 1, L);
8307
0
        break;
8308
0
      }
8309
8310
0
      case IndirectLocalPathEntry::VarInit: {
8311
0
        const VarDecl *VD = cast<VarDecl>(Elem.D);
8312
0
        Diag(VD->getLocation(), diag::note_local_var_initializer)
8313
0
            << VD->getType()->isReferenceType()
8314
0
            << VD->isImplicit() << VD->getDeclName()
8315
0
            << nextPathEntryRange(Path, I + 1, L);
8316
0
        break;
8317
0
      }
8318
8319
0
      case IndirectLocalPathEntry::LambdaCaptureInit:
8320
0
        if (!Elem.Capture->capturesVariable())
8321
0
          break;
8322
        // FIXME: We can't easily tell apart an init-capture from a nested
8323
        // capture of an init-capture.
8324
0
        const ValueDecl *VD = Elem.Capture->getCapturedVar();
8325
0
        Diag(Elem.Capture->getLocation(), diag::note_lambda_capture_initializer)
8326
0
            << VD << VD->isInitCapture() << Elem.Capture->isExplicit()
8327
0
            << (Elem.Capture->getCaptureKind() == LCK_ByRef) << VD
8328
0
            << nextPathEntryRange(Path, I + 1, L);
8329
0
        break;
8330
0
      }
8331
0
    }
8332
8333
    // We didn't lifetime-extend, so don't go any further; we don't need more
8334
    // warnings or errors on inner temporaries within this one's initializer.
8335
0
    return false;
8336
0
  };
8337
8338
7
  bool EnableLifetimeWarnings = !getDiagnostics().isIgnored(
8339
7
      diag::warn_dangling_lifetime_pointer, SourceLocation());
8340
7
  llvm::SmallVector<IndirectLocalPathEntry, 8> Path;
8341
7
  if (Init->isGLValue())
8342
0
    visitLocalsRetainedByReferenceBinding(Path, Init, RK_ReferenceBinding,
8343
0
                                          TemporaryVisitor,
8344
0
                                          EnableLifetimeWarnings);
8345
7
  else
8346
7
    visitLocalsRetainedByInitializer(Path, Init, TemporaryVisitor, false,
8347
7
                                     EnableLifetimeWarnings);
8348
7
}
8349
8350
static void DiagnoseNarrowingInInitList(Sema &S,
8351
                                        const ImplicitConversionSequence &ICS,
8352
                                        QualType PreNarrowingType,
8353
                                        QualType EntityType,
8354
                                        const Expr *PostInit);
8355
8356
/// Provide warnings when std::move is used on construction.
8357
static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr,
8358
7
                                    bool IsReturnStmt) {
8359
7
  if (!InitExpr)
8360
0
    return;
8361
8362
7
  if (S.inTemplateInstantiation())
8363
0
    return;
8364
8365
7
  QualType DestType = InitExpr->getType();
8366
7
  if (!DestType->isRecordType())
8367
7
    return;
8368
8369
0
  unsigned DiagID = 0;
8370
0
  if (IsReturnStmt) {
8371
0
    const CXXConstructExpr *CCE =
8372
0
        dyn_cast<CXXConstructExpr>(InitExpr->IgnoreParens());
8373
0
    if (!CCE || CCE->getNumArgs() != 1)
8374
0
      return;
8375
8376
0
    if (!CCE->getConstructor()->isCopyOrMoveConstructor())
8377
0
      return;
8378
8379
0
    InitExpr = CCE->getArg(0)->IgnoreImpCasts();
8380
0
  }
8381
8382
  // Find the std::move call and get the argument.
8383
0
  const CallExpr *CE = dyn_cast<CallExpr>(InitExpr->IgnoreParens());
8384
0
  if (!CE || !CE->isCallToStdMove())
8385
0
    return;
8386
8387
0
  const Expr *Arg = CE->getArg(0)->IgnoreImplicit();
8388
8389
0
  if (IsReturnStmt) {
8390
0
    const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts());
8391
0
    if (!DRE || DRE->refersToEnclosingVariableOrCapture())
8392
0
      return;
8393
8394
0
    const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
8395
0
    if (!VD || !VD->hasLocalStorage())
8396
0
      return;
8397
8398
    // __block variables are not moved implicitly.
8399
0
    if (VD->hasAttr<BlocksAttr>())
8400
0
      return;
8401
8402
0
    QualType SourceType = VD->getType();
8403
0
    if (!SourceType->isRecordType())
8404
0
      return;
8405
8406
0
    if (!S.Context.hasSameUnqualifiedType(DestType, SourceType)) {
8407
0
      return;
8408
0
    }
8409
8410
    // If we're returning a function parameter, copy elision
8411
    // is not possible.
8412
0
    if (isa<ParmVarDecl>(VD))
8413
0
      DiagID = diag::warn_redundant_move_on_return;
8414
0
    else
8415
0
      DiagID = diag::warn_pessimizing_move_on_return;
8416
0
  } else {
8417
0
    DiagID = diag::warn_pessimizing_move_on_initialization;
8418
0
    const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens();
8419
0
    if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType())
8420
0
      return;
8421
0
  }
8422
8423
0
  S.Diag(CE->getBeginLoc(), DiagID);
8424
8425
  // Get all the locations for a fix-it.  Don't emit the fix-it if any location
8426
  // is within a macro.
8427
0
  SourceLocation CallBegin = CE->getCallee()->getBeginLoc();
8428
0
  if (CallBegin.isMacroID())
8429
0
    return;
8430
0
  SourceLocation RParen = CE->getRParenLoc();
8431
0
  if (RParen.isMacroID())
8432
0
    return;
8433
0
  SourceLocation LParen;
8434
0
  SourceLocation ArgLoc = Arg->getBeginLoc();
8435
8436
  // Special testing for the argument location.  Since the fix-it needs the
8437
  // location right before the argument, the argument location can be in a
8438
  // macro only if it is at the beginning of the macro.
8439
0
  while (ArgLoc.isMacroID() &&
8440
0
         S.getSourceManager().isAtStartOfImmediateMacroExpansion(ArgLoc)) {
8441
0
    ArgLoc = S.getSourceManager().getImmediateExpansionRange(ArgLoc).getBegin();
8442
0
  }
8443
8444
0
  if (LParen.isMacroID())
8445
0
    return;
8446
8447
0
  LParen = ArgLoc.getLocWithOffset(-1);
8448
8449
0
  S.Diag(CE->getBeginLoc(), diag::note_remove_move)
8450
0
      << FixItHint::CreateRemoval(SourceRange(CallBegin, LParen))
8451
0
      << FixItHint::CreateRemoval(SourceRange(RParen, RParen));
8452
0
}
8453
8454
0
static void CheckForNullPointerDereference(Sema &S, const Expr *E) {
8455
  // Check to see if we are dereferencing a null pointer.  If so, this is
8456
  // undefined behavior, so warn about it.  This only handles the pattern
8457
  // "*null", which is a very syntactic check.
8458
0
  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
8459
0
    if (UO->getOpcode() == UO_Deref &&
8460
0
        UO->getSubExpr()->IgnoreParenCasts()->
8461
0
        isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) {
8462
0
    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
8463
0
                          S.PDiag(diag::warn_binding_null_to_reference)
8464
0
                            << UO->getSubExpr()->getSourceRange());
8465
0
  }
8466
0
}
8467
8468
MaterializeTemporaryExpr *
8469
Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
8470
0
                                     bool BoundToLvalueReference) {
8471
0
  auto MTE = new (Context)
8472
0
      MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference);
8473
8474
  // Order an ExprWithCleanups for lifetime marks.
8475
  //
8476
  // TODO: It'll be good to have a single place to check the access of the
8477
  // destructor and generate ExprWithCleanups for various uses. Currently these
8478
  // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary,
8479
  // but there may be a chance to merge them.
8480
0
  Cleanup.setExprNeedsCleanups(false);
8481
0
  return MTE;
8482
0
}
8483
8484
0
ExprResult Sema::TemporaryMaterializationConversion(Expr *E) {
8485
  // In C++98, we don't want to implicitly create an xvalue.
8486
  // FIXME: This means that AST consumers need to deal with "prvalues" that
8487
  // denote materialized temporaries. Maybe we should add another ValueKind
8488
  // for "xvalue pretending to be a prvalue" for C++98 support.
8489
0
  if (!E->isPRValue() || !getLangOpts().CPlusPlus11)
8490
0
    return E;
8491
8492
  // C++1z [conv.rval]/1: T shall be a complete type.
8493
  // FIXME: Does this ever matter (can we form a prvalue of incomplete type)?
8494
  // If so, we should check for a non-abstract class type here too.
8495
0
  QualType T = E->getType();
8496
0
  if (RequireCompleteType(E->getExprLoc(), T, diag::err_incomplete_type))
8497
0
    return ExprError();
8498
8499
0
  return CreateMaterializeTemporaryExpr(E->getType(), E, false);
8500
0
}
8501
8502
ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty,
8503
                                                ExprValueKind VK,
8504
0
                                                CheckedConversionKind CCK) {
8505
8506
0
  CastKind CK = CK_NoOp;
8507
8508
0
  if (VK == VK_PRValue) {
8509
0
    auto PointeeTy = Ty->getPointeeType();
8510
0
    auto ExprPointeeTy = E->getType()->getPointeeType();
8511
0
    if (!PointeeTy.isNull() &&
8512
0
        PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace())
8513
0
      CK = CK_AddressSpaceConversion;
8514
0
  } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) {
8515
0
    CK = CK_AddressSpaceConversion;
8516
0
  }
8517
8518
0
  return ImpCastExprToType(E, Ty, CK, VK, /*BasePath=*/nullptr, CCK);
8519
0
}
8520
8521
ExprResult InitializationSequence::Perform(Sema &S,
8522
                                           const InitializedEntity &Entity,
8523
                                           const InitializationKind &Kind,
8524
                                           MultiExprArg Args,
8525
20
                                           QualType *ResultType) {
8526
20
  if (Failed()) {
8527
0
    Diagnose(S, Entity, Kind, Args);
8528
0
    return ExprError();
8529
0
  }
8530
20
  if (!ZeroInitializationFixit.empty()) {
8531
0
    const Decl *D = Entity.getDecl();
8532
0
    const auto *VD = dyn_cast_or_null<VarDecl>(D);
8533
0
    QualType DestType = Entity.getType();
8534
8535
    // The initialization would have succeeded with this fixit. Since the fixit
8536
    // is on the error, we need to build a valid AST in this case, so this isn't
8537
    // handled in the Failed() branch above.
8538
0
    if (!DestType->isRecordType() && VD && VD->isConstexpr()) {
8539
      // Use a more useful diagnostic for constexpr variables.
8540
0
      S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
8541
0
          << VD
8542
0
          << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8543
0
                                        ZeroInitializationFixit);
8544
0
    } else {
8545
0
      unsigned DiagID = diag::err_default_init_const;
8546
0
      if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>())
8547
0
        DiagID = diag::ext_default_init_const;
8548
8549
0
      S.Diag(Kind.getLocation(), DiagID)
8550
0
          << DestType << (bool)DestType->getAs<RecordType>()
8551
0
          << FixItHint::CreateInsertion(ZeroInitializationFixitLoc,
8552
0
                                        ZeroInitializationFixit);
8553
0
    }
8554
0
  }
8555
8556
20
  if (getKind() == DependentSequence) {
8557
    // If the declaration is a non-dependent, incomplete array type
8558
    // that has an initializer, then its type will be completed once
8559
    // the initializer is instantiated.
8560
13
    if (ResultType && !Entity.getType()->isDependentType() &&
8561
13
        Args.size() == 1) {
8562
12
      QualType DeclType = Entity.getType();
8563
12
      if (const IncompleteArrayType *ArrayT
8564
12
                           = S.Context.getAsIncompleteArrayType(DeclType)) {
8565
        // FIXME: We don't currently have the ability to accurately
8566
        // compute the length of an initializer list without
8567
        // performing full type-checking of the initializer list
8568
        // (since we have to determine where braces are implicitly
8569
        // introduced and such).  So, we fall back to making the array
8570
        // type a dependently-sized array type with no specified
8571
        // bound.
8572
0
        if (isa<InitListExpr>((Expr *)Args[0])) {
8573
0
          SourceRange Brackets;
8574
8575
          // Scavange the location of the brackets from the entity, if we can.
8576
0
          if (auto *DD = dyn_cast_or_null<DeclaratorDecl>(Entity.getDecl())) {
8577
0
            if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
8578
0
              TypeLoc TL = TInfo->getTypeLoc();
8579
0
              if (IncompleteArrayTypeLoc ArrayLoc =
8580
0
                      TL.getAs<IncompleteArrayTypeLoc>())
8581
0
                Brackets = ArrayLoc.getBracketsRange();
8582
0
            }
8583
0
          }
8584
8585
0
          *ResultType
8586
0
            = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
8587
0
                                                   /*NumElts=*/nullptr,
8588
0
                                                   ArrayT->getSizeModifier(),
8589
0
                                       ArrayT->getIndexTypeCVRQualifiers(),
8590
0
                                                   Brackets);
8591
0
        }
8592
8593
0
      }
8594
12
    }
8595
13
    if (Kind.getKind() == InitializationKind::IK_Direct &&
8596
13
        !Kind.isExplicitCast()) {
8597
      // Rebuild the ParenListExpr.
8598
0
      SourceRange ParenRange = Kind.getParenOrBraceRange();
8599
0
      return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
8600
0
                                  Args);
8601
0
    }
8602
13
    assert(Kind.getKind() == InitializationKind::IK_Copy ||
8603
13
           Kind.isExplicitCast() ||
8604
13
           Kind.getKind() == InitializationKind::IK_DirectList);
8605
0
    return ExprResult(Args[0]);
8606
13
  }
8607
8608
  // No steps means no initialization.
8609
7
  if (Steps.empty())
8610
0
    return ExprResult((Expr *)nullptr);
8611
8612
7
  if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
8613
7
      Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
8614
7
      !Entity.isParamOrTemplateParamKind()) {
8615
    // Produce a C++98 compatibility warning if we are initializing a reference
8616
    // from an initializer list. For parameters, we produce a better warning
8617
    // elsewhere.
8618
0
    Expr *Init = Args[0];
8619
0
    S.Diag(Init->getBeginLoc(), diag::warn_cxx98_compat_reference_list_init)
8620
0
        << Init->getSourceRange();
8621
0
  }
8622
8623
7
  if (S.getLangOpts().MicrosoftExt && Args.size() == 1 &&
8624
7
      isa<PredefinedExpr>(Args[0]) && Entity.getType()->isArrayType()) {
8625
    // Produce a Microsoft compatibility warning when initializing from a
8626
    // predefined expression since MSVC treats predefined expressions as string
8627
    // literals.
8628
0
    Expr *Init = Args[0];
8629
0
    S.Diag(Init->getBeginLoc(), diag::ext_init_from_predefined) << Init;
8630
0
  }
8631
8632
  // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope
8633
7
  QualType ETy = Entity.getType();
8634
7
  bool HasGlobalAS = ETy.hasAddressSpace() &&
8635
7
                     ETy.getAddressSpace() == LangAS::opencl_global;
8636
8637
7
  if (S.getLangOpts().OpenCLVersion >= 200 &&
8638
7
      ETy->isAtomicType() && !HasGlobalAS &&
8639
7
      Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) {
8640
0
    S.Diag(Args[0]->getBeginLoc(), diag::err_opencl_atomic_init)
8641
0
        << 1
8642
0
        << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc());
8643
0
    return ExprError();
8644
0
  }
8645
8646
7
  QualType DestType = Entity.getType().getNonReferenceType();
8647
  // FIXME: Ugly hack around the fact that Entity.getType() is not
8648
  // the same as Entity.getDecl()->getType() in cases involving type merging,
8649
  //  and we want latter when it makes sense.
8650
7
  if (ResultType)
8651
7
    *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
8652
7
                                     Entity.getType();
8653
8654
7
  ExprResult CurInit((Expr *)nullptr);
8655
7
  SmallVector<Expr*, 4> ArrayLoopCommonExprs;
8656
8657
  // HLSL allows vector initialization to function like list initialization, but
8658
  // use the syntax of a C++-like constructor.
8659
7
  bool IsHLSLVectorInit = S.getLangOpts().HLSL && DestType->isExtVectorType() &&
8660
7
                          isa<InitListExpr>(Args[0]);
8661
7
  (void)IsHLSLVectorInit;
8662
8663
  // For initialization steps that start with a single initializer,
8664
  // grab the only argument out the Args and place it into the "current"
8665
  // initializer.
8666
7
  switch (Steps.front().Kind) {
8667
0
  case SK_ResolveAddressOfOverloadedFunction:
8668
0
  case SK_CastDerivedToBasePRValue:
8669
0
  case SK_CastDerivedToBaseXValue:
8670
0
  case SK_CastDerivedToBaseLValue:
8671
0
  case SK_BindReference:
8672
0
  case SK_BindReferenceToTemporary:
8673
0
  case SK_FinalCopy:
8674
0
  case SK_ExtraneousCopyToTemporary:
8675
0
  case SK_UserConversion:
8676
0
  case SK_QualificationConversionLValue:
8677
0
  case SK_QualificationConversionXValue:
8678
0
  case SK_QualificationConversionPRValue:
8679
0
  case SK_FunctionReferenceConversion:
8680
0
  case SK_AtomicConversion:
8681
0
  case SK_ConversionSequence:
8682
0
  case SK_ConversionSequenceNoNarrowing:
8683
0
  case SK_ListInitialization:
8684
0
  case SK_UnwrapInitList:
8685
0
  case SK_RewrapInitList:
8686
7
  case SK_CAssignment:
8687
7
  case SK_StringInit:
8688
7
  case SK_ObjCObjectConversion:
8689
7
  case SK_ArrayLoopIndex:
8690
7
  case SK_ArrayLoopInit:
8691
7
  case SK_ArrayInit:
8692
7
  case SK_GNUArrayInit:
8693
7
  case SK_ParenthesizedArrayInit:
8694
7
  case SK_PassByIndirectCopyRestore:
8695
7
  case SK_PassByIndirectRestore:
8696
7
  case SK_ProduceObjCObject:
8697
7
  case SK_StdInitializerList:
8698
7
  case SK_OCLSamplerInit:
8699
7
  case SK_OCLZeroOpaqueType: {
8700
7
    assert(Args.size() == 1 || IsHLSLVectorInit);
8701
0
    CurInit = Args[0];
8702
7
    if (!CurInit.get()) return ExprError();
8703
7
    break;
8704
7
  }
8705
8706
7
  case SK_ConstructorInitialization:
8707
0
  case SK_ConstructorInitializationFromList:
8708
0
  case SK_StdInitializerListConstructorCall:
8709
0
  case SK_ZeroInitialization:
8710
0
  case SK_ParenthesizedListInit:
8711
0
    break;
8712
7
  }
8713
8714
  // Promote from an unevaluated context to an unevaluated list context in
8715
  // C++11 list-initialization; we need to instantiate entities usable in
8716
  // constant expressions here in order to perform narrowing checks =(
8717
7
  EnterExpressionEvaluationContext Evaluated(
8718
7
      S, EnterExpressionEvaluationContext::InitList,
8719
7
      CurInit.get() && isa<InitListExpr>(CurInit.get()));
8720
8721
  // C++ [class.abstract]p2:
8722
  //   no objects of an abstract class can be created except as subobjects
8723
  //   of a class derived from it
8724
7
  auto checkAbstractType = [&](QualType T) -> bool {
8725
0
    if (Entity.getKind() == InitializedEntity::EK_Base ||
8726
0
        Entity.getKind() == InitializedEntity::EK_Delegating)
8727
0
      return false;
8728
0
    return S.RequireNonAbstractType(Kind.getLocation(), T,
8729
0
                                    diag::err_allocation_of_abstract_type);
8730
0
  };
8731
8732
  // Walk through the computed steps for the initialization sequence,
8733
  // performing the specified conversions along the way.
8734
7
  bool ConstructorInitRequiresZeroInit = false;
8735
7
  for (step_iterator Step = step_begin(), StepEnd = step_end();
8736
14
       Step != StepEnd; ++Step) {
8737
7
    if (CurInit.isInvalid())
8738
0
      return ExprError();
8739
8740
7
    QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
8741
8742
7
    switch (Step->Kind) {
8743
0
    case SK_ResolveAddressOfOverloadedFunction:
8744
      // Overload resolution determined which function invoke; update the
8745
      // initializer to reflect that choice.
8746
0
      S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
8747
0
      if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
8748
0
        return ExprError();
8749
0
      CurInit = S.FixOverloadedFunctionReference(CurInit,
8750
0
                                                 Step->Function.FoundDecl,
8751
0
                                                 Step->Function.Function);
8752
      // We might get back another placeholder expression if we resolved to a
8753
      // builtin.
8754
0
      if (!CurInit.isInvalid())
8755
0
        CurInit = S.CheckPlaceholderExpr(CurInit.get());
8756
0
      break;
8757
8758
0
    case SK_CastDerivedToBasePRValue:
8759
0
    case SK_CastDerivedToBaseXValue:
8760
0
    case SK_CastDerivedToBaseLValue: {
8761
      // We have a derived-to-base cast that produces either an rvalue or an
8762
      // lvalue. Perform that cast.
8763
8764
0
      CXXCastPath BasePath;
8765
8766
      // Casts to inaccessible base classes are allowed with C-style casts.
8767
0
      bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
8768
0
      if (S.CheckDerivedToBaseConversion(
8769
0
              SourceType, Step->Type, CurInit.get()->getBeginLoc(),
8770
0
              CurInit.get()->getSourceRange(), &BasePath, IgnoreBaseAccess))
8771
0
        return ExprError();
8772
8773
0
      ExprValueKind VK =
8774
0
          Step->Kind == SK_CastDerivedToBaseLValue
8775
0
              ? VK_LValue
8776
0
              : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue
8777
0
                                                          : VK_PRValue);
8778
0
      CurInit = ImplicitCastExpr::Create(S.Context, Step->Type,
8779
0
                                         CK_DerivedToBase, CurInit.get(),
8780
0
                                         &BasePath, VK, FPOptionsOverride());
8781
0
      break;
8782
0
    }
8783
8784
0
    case SK_BindReference:
8785
      // Reference binding does not have any corresponding ASTs.
8786
8787
      // Check exception specifications
8788
0
      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8789
0
        return ExprError();
8790
8791
      // We don't check for e.g. function pointers here, since address
8792
      // availability checks should only occur when the function first decays
8793
      // into a pointer or reference.
8794
0
      if (CurInit.get()->getType()->isFunctionProtoType()) {
8795
0
        if (auto *DRE = dyn_cast<DeclRefExpr>(CurInit.get()->IgnoreParens())) {
8796
0
          if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
8797
0
            if (!S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
8798
0
                                                     DRE->getBeginLoc()))
8799
0
              return ExprError();
8800
0
          }
8801
0
        }
8802
0
      }
8803
8804
0
      CheckForNullPointerDereference(S, CurInit.get());
8805
0
      break;
8806
8807
0
    case SK_BindReferenceToTemporary: {
8808
      // Make sure the "temporary" is actually an rvalue.
8809
0
      assert(CurInit.get()->isPRValue() && "not a temporary");
8810
8811
      // Check exception specifications
8812
0
      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
8813
0
        return ExprError();
8814
8815
0
      QualType MTETy = Step->Type;
8816
8817
      // When this is an incomplete array type (such as when this is
8818
      // initializing an array of unknown bounds from an init list), use THAT
8819
      // type instead so that we propagate the array bounds.
8820
0
      if (MTETy->isIncompleteArrayType() &&
8821
0
          !CurInit.get()->getType()->isIncompleteArrayType() &&
8822
0
          S.Context.hasSameType(
8823
0
              MTETy->getPointeeOrArrayElementType(),
8824
0
              CurInit.get()->getType()->getPointeeOrArrayElementType()))
8825
0
        MTETy = CurInit.get()->getType();
8826
8827
      // Materialize the temporary into memory.
8828
0
      MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
8829
0
          MTETy, CurInit.get(), Entity.getType()->isLValueReferenceType());
8830
0
      CurInit = MTE;
8831
8832
      // If we're extending this temporary to automatic storage duration -- we
8833
      // need to register its cleanup during the full-expression's cleanups.
8834
0
      if (MTE->getStorageDuration() == SD_Automatic &&
8835
0
          MTE->getType().isDestructedType())
8836
0
        S.Cleanup.setExprNeedsCleanups(true);
8837
0
      break;
8838
0
    }
8839
8840
0
    case SK_FinalCopy:
8841
0
      if (checkAbstractType(Step->Type))
8842
0
        return ExprError();
8843
8844
      // If the overall initialization is initializing a temporary, we already
8845
      // bound our argument if it was necessary to do so. If not (if we're
8846
      // ultimately initializing a non-temporary), our argument needs to be
8847
      // bound since it's initializing a function parameter.
8848
      // FIXME: This is a mess. Rationalize temporary destruction.
8849
0
      if (!shouldBindAsTemporary(Entity))
8850
0
        CurInit = S.MaybeBindToTemporary(CurInit.get());
8851
0
      CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8852
0
                           /*IsExtraneousCopy=*/false);
8853
0
      break;
8854
8855
0
    case SK_ExtraneousCopyToTemporary:
8856
0
      CurInit = CopyObject(S, Step->Type, Entity, CurInit,
8857
0
                           /*IsExtraneousCopy=*/true);
8858
0
      break;
8859
8860
0
    case SK_UserConversion: {
8861
      // We have a user-defined conversion that invokes either a constructor
8862
      // or a conversion function.
8863
0
      CastKind CastKind;
8864
0
      FunctionDecl *Fn = Step->Function.Function;
8865
0
      DeclAccessPair FoundFn = Step->Function.FoundDecl;
8866
0
      bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
8867
0
      bool CreatedObject = false;
8868
0
      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
8869
        // Build a call to the selected constructor.
8870
0
        SmallVector<Expr*, 8> ConstructorArgs;
8871
0
        SourceLocation Loc = CurInit.get()->getBeginLoc();
8872
8873
        // Determine the arguments required to actually perform the constructor
8874
        // call.
8875
0
        Expr *Arg = CurInit.get();
8876
0
        if (S.CompleteConstructorCall(Constructor, Step->Type,
8877
0
                                      MultiExprArg(&Arg, 1), Loc,
8878
0
                                      ConstructorArgs))
8879
0
          return ExprError();
8880
8881
        // Build an expression that constructs a temporary.
8882
0
        CurInit = S.BuildCXXConstructExpr(
8883
0
            Loc, Step->Type, FoundFn, Constructor, ConstructorArgs,
8884
0
            HadMultipleCandidates,
8885
0
            /*ListInit*/ false,
8886
0
            /*StdInitListInit*/ false,
8887
0
            /*ZeroInit*/ false, CXXConstructionKind::Complete, SourceRange());
8888
0
        if (CurInit.isInvalid())
8889
0
          return ExprError();
8890
8891
0
        S.CheckConstructorAccess(Kind.getLocation(), Constructor, FoundFn,
8892
0
                                 Entity);
8893
0
        if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8894
0
          return ExprError();
8895
8896
0
        CastKind = CK_ConstructorConversion;
8897
0
        CreatedObject = true;
8898
0
      } else {
8899
        // Build a call to the conversion function.
8900
0
        CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
8901
0
        S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), nullptr,
8902
0
                                    FoundFn);
8903
0
        if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
8904
0
          return ExprError();
8905
8906
0
        CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
8907
0
                                           HadMultipleCandidates);
8908
0
        if (CurInit.isInvalid())
8909
0
          return ExprError();
8910
8911
0
        CastKind = CK_UserDefinedConversion;
8912
0
        CreatedObject = Conversion->getReturnType()->isRecordType();
8913
0
      }
8914
8915
0
      if (CreatedObject && checkAbstractType(CurInit.get()->getType()))
8916
0
        return ExprError();
8917
8918
0
      CurInit = ImplicitCastExpr::Create(
8919
0
          S.Context, CurInit.get()->getType(), CastKind, CurInit.get(), nullptr,
8920
0
          CurInit.get()->getValueKind(), S.CurFPFeatureOverrides());
8921
8922
0
      if (shouldBindAsTemporary(Entity))
8923
        // The overall entity is temporary, so this expression should be
8924
        // destroyed at the end of its full-expression.
8925
0
        CurInit = S.MaybeBindToTemporary(CurInit.getAs<Expr>());
8926
0
      else if (CreatedObject && shouldDestroyEntity(Entity)) {
8927
        // The object outlasts the full-expression, but we need to prepare for
8928
        // a destructor being run on it.
8929
        // FIXME: It makes no sense to do this here. This should happen
8930
        // regardless of how we initialized the entity.
8931
0
        QualType T = CurInit.get()->getType();
8932
0
        if (const RecordType *Record = T->getAs<RecordType>()) {
8933
0
          CXXDestructorDecl *Destructor
8934
0
            = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
8935
0
          S.CheckDestructorAccess(CurInit.get()->getBeginLoc(), Destructor,
8936
0
                                  S.PDiag(diag::err_access_dtor_temp) << T);
8937
0
          S.MarkFunctionReferenced(CurInit.get()->getBeginLoc(), Destructor);
8938
0
          if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getBeginLoc()))
8939
0
            return ExprError();
8940
0
        }
8941
0
      }
8942
0
      break;
8943
0
    }
8944
8945
0
    case SK_QualificationConversionLValue:
8946
0
    case SK_QualificationConversionXValue:
8947
0
    case SK_QualificationConversionPRValue: {
8948
      // Perform a qualification conversion; these can never go wrong.
8949
0
      ExprValueKind VK =
8950
0
          Step->Kind == SK_QualificationConversionLValue
8951
0
              ? VK_LValue
8952
0
              : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue
8953
0
                                                                : VK_PRValue);
8954
0
      CurInit = S.PerformQualificationConversion(CurInit.get(), Step->Type, VK);
8955
0
      break;
8956
0
    }
8957
8958
0
    case SK_FunctionReferenceConversion:
8959
0
      assert(CurInit.get()->isLValue() &&
8960
0
             "function reference should be lvalue");
8961
0
      CurInit =
8962
0
          S.ImpCastExprToType(CurInit.get(), Step->Type, CK_NoOp, VK_LValue);
8963
0
      break;
8964
8965
0
    case SK_AtomicConversion: {
8966
0
      assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic");
8967
0
      CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
8968
0
                                    CK_NonAtomicToAtomic, VK_PRValue);
8969
0
      break;
8970
0
    }
8971
8972
0
    case SK_ConversionSequence:
8973
0
    case SK_ConversionSequenceNoNarrowing: {
8974
0
      if (const auto *FromPtrType =
8975
0
              CurInit.get()->getType()->getAs<PointerType>()) {
8976
0
        if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) {
8977
0
          if (FromPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8978
0
              !ToPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8979
            // Do not check static casts here because they are checked earlier
8980
            // in Sema::ActOnCXXNamedCast()
8981
0
            if (!Kind.isStaticCast()) {
8982
0
              S.Diag(CurInit.get()->getExprLoc(),
8983
0
                     diag::warn_noderef_to_dereferenceable_pointer)
8984
0
                  << CurInit.get()->getSourceRange();
8985
0
            }
8986
0
          }
8987
0
        }
8988
0
      }
8989
8990
0
      Sema::CheckedConversionKind CCK
8991
0
        = Kind.isCStyleCast()? Sema::CCK_CStyleCast
8992
0
        : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
8993
0
        : Kind.isExplicitCast()? Sema::CCK_OtherCast
8994
0
        : Sema::CCK_ImplicitConversion;
8995
0
      ExprResult CurInitExprRes =
8996
0
        S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
8997
0
                                    getAssignmentAction(Entity), CCK);
8998
0
      if (CurInitExprRes.isInvalid())
8999
0
        return ExprError();
9000
9001
0
      S.DiscardMisalignedMemberAddress(Step->Type.getTypePtr(), CurInit.get());
9002
9003
0
      CurInit = CurInitExprRes;
9004
9005
0
      if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
9006
0
          S.getLangOpts().CPlusPlus)
9007
0
        DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
9008
0
                                    CurInit.get());
9009
9010
0
      break;
9011
0
    }
9012
9013
0
    case SK_ListInitialization: {
9014
0
      if (checkAbstractType(Step->Type))
9015
0
        return ExprError();
9016
9017
0
      InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
9018
      // If we're not initializing the top-level entity, we need to create an
9019
      // InitializeTemporary entity for our target type.
9020
0
      QualType Ty = Step->Type;
9021
0
      bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
9022
0
      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
9023
0
      InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
9024
0
      InitListChecker PerformInitList(S, InitEntity,
9025
0
          InitList, Ty, /*VerifyOnly=*/false,
9026
0
          /*TreatUnavailableAsInvalid=*/false);
9027
0
      if (PerformInitList.HadError())
9028
0
        return ExprError();
9029
9030
      // Hack: We must update *ResultType if available in order to set the
9031
      // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
9032
      // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
9033
0
      if (ResultType &&
9034
0
          ResultType->getNonReferenceType()->isIncompleteArrayType()) {
9035
0
        if ((*ResultType)->isRValueReferenceType())
9036
0
          Ty = S.Context.getRValueReferenceType(Ty);
9037
0
        else if ((*ResultType)->isLValueReferenceType())
9038
0
          Ty = S.Context.getLValueReferenceType(Ty,
9039
0
            (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue());
9040
0
        *ResultType = Ty;
9041
0
      }
9042
9043
0
      InitListExpr *StructuredInitList =
9044
0
          PerformInitList.getFullyStructuredList();
9045
0
      CurInit.get();
9046
0
      CurInit = shouldBindAsTemporary(InitEntity)
9047
0
          ? S.MaybeBindToTemporary(StructuredInitList)
9048
0
          : StructuredInitList;
9049
0
      break;
9050
0
    }
9051
9052
0
    case SK_ConstructorInitializationFromList: {
9053
0
      if (checkAbstractType(Step->Type))
9054
0
        return ExprError();
9055
9056
      // When an initializer list is passed for a parameter of type "reference
9057
      // to object", we don't get an EK_Temporary entity, but instead an
9058
      // EK_Parameter entity with reference type.
9059
      // FIXME: This is a hack. What we really should do is create a user
9060
      // conversion step for this case, but this makes it considerably more
9061
      // complicated. For now, this will do.
9062
0
      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
9063
0
                                        Entity.getType().getNonReferenceType());
9064
0
      bool UseTemporary = Entity.getType()->isReferenceType();
9065
0
      assert(Args.size() == 1 && "expected a single argument for list init");
9066
0
      InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9067
0
      S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
9068
0
        << InitList->getSourceRange();
9069
0
      MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
9070
0
      CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
9071
0
                                                                   Entity,
9072
0
                                                 Kind, Arg, *Step,
9073
0
                                               ConstructorInitRequiresZeroInit,
9074
0
                                               /*IsListInitialization*/true,
9075
0
                                               /*IsStdInitListInit*/false,
9076
0
                                               InitList->getLBraceLoc(),
9077
0
                                               InitList->getRBraceLoc());
9078
0
      break;
9079
0
    }
9080
9081
0
    case SK_UnwrapInitList:
9082
0
      CurInit = cast<InitListExpr>(CurInit.get())->getInit(0);
9083
0
      break;
9084
9085
0
    case SK_RewrapInitList: {
9086
0
      Expr *E = CurInit.get();
9087
0
      InitListExpr *Syntactic = Step->WrappingSyntacticList;
9088
0
      InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
9089
0
          Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
9090
0
      ILE->setSyntacticForm(Syntactic);
9091
0
      ILE->setType(E->getType());
9092
0
      ILE->setValueKind(E->getValueKind());
9093
0
      CurInit = ILE;
9094
0
      break;
9095
0
    }
9096
9097
0
    case SK_ConstructorInitialization:
9098
0
    case SK_StdInitializerListConstructorCall: {
9099
0
      if (checkAbstractType(Step->Type))
9100
0
        return ExprError();
9101
9102
      // When an initializer list is passed for a parameter of type "reference
9103
      // to object", we don't get an EK_Temporary entity, but instead an
9104
      // EK_Parameter entity with reference type.
9105
      // FIXME: This is a hack. What we really should do is create a user
9106
      // conversion step for this case, but this makes it considerably more
9107
      // complicated. For now, this will do.
9108
0
      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
9109
0
                                        Entity.getType().getNonReferenceType());
9110
0
      bool UseTemporary = Entity.getType()->isReferenceType();
9111
0
      bool IsStdInitListInit =
9112
0
          Step->Kind == SK_StdInitializerListConstructorCall;
9113
0
      Expr *Source = CurInit.get();
9114
0
      SourceRange Range = Kind.hasParenOrBraceRange()
9115
0
                              ? Kind.getParenOrBraceRange()
9116
0
                              : SourceRange();
9117
0
      CurInit = PerformConstructorInitialization(
9118
0
          S, UseTemporary ? TempEntity : Entity, Kind,
9119
0
          Source ? MultiExprArg(Source) : Args, *Step,
9120
0
          ConstructorInitRequiresZeroInit,
9121
0
          /*IsListInitialization*/ IsStdInitListInit,
9122
0
          /*IsStdInitListInitialization*/ IsStdInitListInit,
9123
0
          /*LBraceLoc*/ Range.getBegin(),
9124
0
          /*RBraceLoc*/ Range.getEnd());
9125
0
      break;
9126
0
    }
9127
9128
0
    case SK_ZeroInitialization: {
9129
0
      step_iterator NextStep = Step;
9130
0
      ++NextStep;
9131
0
      if (NextStep != StepEnd &&
9132
0
          (NextStep->Kind == SK_ConstructorInitialization ||
9133
0
           NextStep->Kind == SK_ConstructorInitializationFromList)) {
9134
        // The need for zero-initialization is recorded directly into
9135
        // the call to the object's constructor within the next step.
9136
0
        ConstructorInitRequiresZeroInit = true;
9137
0
      } else if (Kind.getKind() == InitializationKind::IK_Value &&
9138
0
                 S.getLangOpts().CPlusPlus &&
9139
0
                 !Kind.isImplicitValueInit()) {
9140
0
        TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
9141
0
        if (!TSInfo)
9142
0
          TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
9143
0
                                                    Kind.getRange().getBegin());
9144
9145
0
        CurInit = new (S.Context) CXXScalarValueInitExpr(
9146
0
            Entity.getType().getNonLValueExprType(S.Context), TSInfo,
9147
0
            Kind.getRange().getEnd());
9148
0
      } else {
9149
0
        CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type);
9150
0
      }
9151
0
      break;
9152
0
    }
9153
9154
7
    case SK_CAssignment: {
9155
7
      QualType SourceType = CurInit.get()->getType();
9156
9157
      // Save off the initial CurInit in case we need to emit a diagnostic
9158
7
      ExprResult InitialCurInit = CurInit;
9159
7
      ExprResult Result = CurInit;
9160
7
      Sema::AssignConvertType ConvTy =
9161
7
        S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
9162
7
            Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
9163
7
      if (Result.isInvalid())
9164
0
        return ExprError();
9165
7
      CurInit = Result;
9166
9167
      // If this is a call, allow conversion to a transparent union.
9168
7
      ExprResult CurInitExprRes = CurInit;
9169
7
      if (ConvTy != Sema::Compatible &&
9170
7
          Entity.isParameterKind() &&
9171
7
          S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
9172
0
            == Sema::Compatible)
9173
0
        ConvTy = Sema::Compatible;
9174
7
      if (CurInitExprRes.isInvalid())
9175
0
        return ExprError();
9176
7
      CurInit = CurInitExprRes;
9177
9178
7
      bool Complained;
9179
7
      if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
9180
7
                                     Step->Type, SourceType,
9181
7
                                     InitialCurInit.get(),
9182
7
                                     getAssignmentAction(Entity, true),
9183
7
                                     &Complained)) {
9184
0
        PrintInitLocationNote(S, Entity);
9185
0
        return ExprError();
9186
7
      } else if (Complained)
9187
1
        PrintInitLocationNote(S, Entity);
9188
7
      break;
9189
7
    }
9190
9191
7
    case SK_StringInit: {
9192
0
      QualType Ty = Step->Type;
9193
0
      bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType();
9194
0
      CheckStringInit(CurInit.get(), UpdateType ? *ResultType : Ty,
9195
0
                      S.Context.getAsArrayType(Ty), S);
9196
0
      break;
9197
7
    }
9198
9199
0
    case SK_ObjCObjectConversion:
9200
0
      CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9201
0
                          CK_ObjCObjectLValueCast,
9202
0
                          CurInit.get()->getValueKind());
9203
0
      break;
9204
9205
0
    case SK_ArrayLoopIndex: {
9206
0
      Expr *Cur = CurInit.get();
9207
0
      Expr *BaseExpr = new (S.Context)
9208
0
          OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(),
9209
0
                          Cur->getValueKind(), Cur->getObjectKind(), Cur);
9210
0
      Expr *IndexExpr =
9211
0
          new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType());
9212
0
      CurInit = S.CreateBuiltinArraySubscriptExpr(
9213
0
          BaseExpr, Kind.getLocation(), IndexExpr, Kind.getLocation());
9214
0
      ArrayLoopCommonExprs.push_back(BaseExpr);
9215
0
      break;
9216
7
    }
9217
9218
0
    case SK_ArrayLoopInit: {
9219
0
      assert(!ArrayLoopCommonExprs.empty() &&
9220
0
             "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit");
9221
0
      Expr *Common = ArrayLoopCommonExprs.pop_back_val();
9222
0
      CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common,
9223
0
                                                  CurInit.get());
9224
0
      break;
9225
7
    }
9226
9227
0
    case SK_GNUArrayInit:
9228
      // Okay: we checked everything before creating this step. Note that
9229
      // this is a GNU extension.
9230
0
      S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
9231
0
        << Step->Type << CurInit.get()->getType()
9232
0
        << CurInit.get()->getSourceRange();
9233
0
      updateGNUCompoundLiteralRValue(CurInit.get());
9234
0
      [[fallthrough]];
9235
0
    case SK_ArrayInit:
9236
      // If the destination type is an incomplete array type, update the
9237
      // type accordingly.
9238
0
      if (ResultType) {
9239
0
        if (const IncompleteArrayType *IncompleteDest
9240
0
                           = S.Context.getAsIncompleteArrayType(Step->Type)) {
9241
0
          if (const ConstantArrayType *ConstantSource
9242
0
                 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
9243
0
            *ResultType = S.Context.getConstantArrayType(
9244
0
                IncompleteDest->getElementType(), ConstantSource->getSize(),
9245
0
                ConstantSource->getSizeExpr(), ArraySizeModifier::Normal, 0);
9246
0
          }
9247
0
        }
9248
0
      }
9249
0
      break;
9250
9251
0
    case SK_ParenthesizedArrayInit:
9252
      // Okay: we checked everything before creating this step. Note that
9253
      // this is a GNU extension.
9254
0
      S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
9255
0
        << CurInit.get()->getSourceRange();
9256
0
      break;
9257
9258
0
    case SK_PassByIndirectCopyRestore:
9259
0
    case SK_PassByIndirectRestore:
9260
0
      checkIndirectCopyRestoreSource(S, CurInit.get());
9261
0
      CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr(
9262
0
          CurInit.get(), Step->Type,
9263
0
          Step->Kind == SK_PassByIndirectCopyRestore);
9264
0
      break;
9265
9266
0
    case SK_ProduceObjCObject:
9267
0
      CurInit = ImplicitCastExpr::Create(
9268
0
          S.Context, Step->Type, CK_ARCProduceObject, CurInit.get(), nullptr,
9269
0
          VK_PRValue, FPOptionsOverride());
9270
0
      break;
9271
9272
0
    case SK_StdInitializerList: {
9273
0
      S.Diag(CurInit.get()->getExprLoc(),
9274
0
             diag::warn_cxx98_compat_initializer_list_init)
9275
0
        << CurInit.get()->getSourceRange();
9276
9277
      // Materialize the temporary into memory.
9278
0
      MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr(
9279
0
          CurInit.get()->getType(), CurInit.get(),
9280
0
          /*BoundToLvalueReference=*/false);
9281
9282
      // Wrap it in a construction of a std::initializer_list<T>.
9283
0
      CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE);
9284
9285
      // Bind the result, in case the library has given initializer_list a
9286
      // non-trivial destructor.
9287
0
      if (shouldBindAsTemporary(Entity))
9288
0
        CurInit = S.MaybeBindToTemporary(CurInit.get());
9289
0
      break;
9290
0
    }
9291
9292
0
    case SK_OCLSamplerInit: {
9293
      // Sampler initialization have 5 cases:
9294
      //   1. function argument passing
9295
      //      1a. argument is a file-scope variable
9296
      //      1b. argument is a function-scope variable
9297
      //      1c. argument is one of caller function's parameters
9298
      //   2. variable initialization
9299
      //      2a. initializing a file-scope variable
9300
      //      2b. initializing a function-scope variable
9301
      //
9302
      // For file-scope variables, since they cannot be initialized by function
9303
      // call of __translate_sampler_initializer in LLVM IR, their references
9304
      // need to be replaced by a cast from their literal initializers to
9305
      // sampler type. Since sampler variables can only be used in function
9306
      // calls as arguments, we only need to replace them when handling the
9307
      // argument passing.
9308
0
      assert(Step->Type->isSamplerT() &&
9309
0
             "Sampler initialization on non-sampler type.");
9310
0
      Expr *Init = CurInit.get()->IgnoreParens();
9311
0
      QualType SourceType = Init->getType();
9312
      // Case 1
9313
0
      if (Entity.isParameterKind()) {
9314
0
        if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) {
9315
0
          S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
9316
0
            << SourceType;
9317
0
          break;
9318
0
        } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init)) {
9319
0
          auto Var = cast<VarDecl>(DRE->getDecl());
9320
          // Case 1b and 1c
9321
          // No cast from integer to sampler is needed.
9322
0
          if (!Var->hasGlobalStorage()) {
9323
0
            CurInit = ImplicitCastExpr::Create(
9324
0
                S.Context, Step->Type, CK_LValueToRValue, Init,
9325
0
                /*BasePath=*/nullptr, VK_PRValue, FPOptionsOverride());
9326
0
            break;
9327
0
          }
9328
          // Case 1a
9329
          // For function call with a file-scope sampler variable as argument,
9330
          // get the integer literal.
9331
          // Do not diagnose if the file-scope variable does not have initializer
9332
          // since this has already been diagnosed when parsing the variable
9333
          // declaration.
9334
0
          if (!Var->getInit() || !isa<ImplicitCastExpr>(Var->getInit()))
9335
0
            break;
9336
0
          Init = cast<ImplicitCastExpr>(const_cast<Expr*>(
9337
0
            Var->getInit()))->getSubExpr();
9338
0
          SourceType = Init->getType();
9339
0
        }
9340
0
      } else {
9341
        // Case 2
9342
        // Check initializer is 32 bit integer constant.
9343
        // If the initializer is taken from global variable, do not diagnose since
9344
        // this has already been done when parsing the variable declaration.
9345
0
        if (!Init->isConstantInitializer(S.Context, false))
9346
0
          break;
9347
9348
0
        if (!SourceType->isIntegerType() ||
9349
0
            32 != S.Context.getIntWidth(SourceType)) {
9350
0
          S.Diag(Kind.getLocation(), diag::err_sampler_initializer_not_integer)
9351
0
            << SourceType;
9352
0
          break;
9353
0
        }
9354
9355
0
        Expr::EvalResult EVResult;
9356
0
        Init->EvaluateAsInt(EVResult, S.Context);
9357
0
        llvm::APSInt Result = EVResult.Val.getInt();
9358
0
        const uint64_t SamplerValue = Result.getLimitedValue();
9359
        // 32-bit value of sampler's initializer is interpreted as
9360
        // bit-field with the following structure:
9361
        // |unspecified|Filter|Addressing Mode| Normalized Coords|
9362
        // |31        6|5    4|3             1|                 0|
9363
        // This structure corresponds to enum values of sampler properties
9364
        // defined in SPIR spec v1.2 and also opencl-c.h
9365
0
        unsigned AddressingMode  = (0x0E & SamplerValue) >> 1;
9366
0
        unsigned FilterMode      = (0x30 & SamplerValue) >> 4;
9367
0
        if (FilterMode != 1 && FilterMode != 2 &&
9368
0
            !S.getOpenCLOptions().isAvailableOption(
9369
0
                "cl_intel_device_side_avc_motion_estimation", S.getLangOpts()))
9370
0
          S.Diag(Kind.getLocation(),
9371
0
                 diag::warn_sampler_initializer_invalid_bits)
9372
0
                 << "Filter Mode";
9373
0
        if (AddressingMode > 4)
9374
0
          S.Diag(Kind.getLocation(),
9375
0
                 diag::warn_sampler_initializer_invalid_bits)
9376
0
                 << "Addressing Mode";
9377
0
      }
9378
9379
      // Cases 1a, 2a and 2b
9380
      // Insert cast from integer to sampler.
9381
0
      CurInit = S.ImpCastExprToType(Init, S.Context.OCLSamplerTy,
9382
0
                                      CK_IntToOCLSampler);
9383
0
      break;
9384
0
    }
9385
0
    case SK_OCLZeroOpaqueType: {
9386
0
      assert((Step->Type->isEventT() || Step->Type->isQueueT() ||
9387
0
              Step->Type->isOCLIntelSubgroupAVCType()) &&
9388
0
             "Wrong type for initialization of OpenCL opaque type.");
9389
9390
0
      CurInit = S.ImpCastExprToType(CurInit.get(), Step->Type,
9391
0
                                    CK_ZeroToOCLOpaqueType,
9392
0
                                    CurInit.get()->getValueKind());
9393
0
      break;
9394
0
    }
9395
0
    case SK_ParenthesizedListInit: {
9396
0
      CurInit = nullptr;
9397
0
      TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
9398
0
                                        /*VerifyOnly=*/false, &CurInit);
9399
0
      if (CurInit.get() && ResultType)
9400
0
        *ResultType = CurInit.get()->getType();
9401
0
      if (shouldBindAsTemporary(Entity))
9402
0
        CurInit = S.MaybeBindToTemporary(CurInit.get());
9403
0
      break;
9404
0
    }
9405
7
    }
9406
7
  }
9407
9408
7
  Expr *Init = CurInit.get();
9409
7
  if (!Init)
9410
0
    return ExprError();
9411
9412
  // Check whether the initializer has a shorter lifetime than the initialized
9413
  // entity, and if not, either lifetime-extend or warn as appropriate.
9414
7
  S.checkInitializerLifetime(Entity, Init);
9415
9416
  // Diagnose non-fatal problems with the completed initialization.
9417
7
  if (InitializedEntity::EntityKind EK = Entity.getKind();
9418
7
      (EK == InitializedEntity::EK_Member ||
9419
7
       EK == InitializedEntity::EK_ParenAggInitMember) &&
9420
7
      cast<FieldDecl>(Entity.getDecl())->isBitField())
9421
0
    S.CheckBitFieldInitialization(Kind.getLocation(),
9422
0
                                  cast<FieldDecl>(Entity.getDecl()), Init);
9423
9424
  // Check for std::move on construction.
9425
7
  CheckMoveOnConstruction(S, Init,
9426
7
                          Entity.getKind() == InitializedEntity::EK_Result);
9427
9428
7
  return Init;
9429
7
}
9430
9431
/// Somewhere within T there is an uninitialized reference subobject.
9432
/// Dig it out and diagnose it.
9433
static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
9434
0
                                           QualType T) {
9435
0
  if (T->isReferenceType()) {
9436
0
    S.Diag(Loc, diag::err_reference_without_init)
9437
0
      << T.getNonReferenceType();
9438
0
    return true;
9439
0
  }
9440
9441
0
  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
9442
0
  if (!RD || !RD->hasUninitializedReferenceMember())
9443
0
    return false;
9444
9445
0
  for (const auto *FI : RD->fields()) {
9446
0
    if (FI->isUnnamedBitfield())
9447
0
      continue;
9448
9449
0
    if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
9450
0
      S.Diag(Loc, diag::note_value_initialization_here) << RD;
9451
0
      return true;
9452
0
    }
9453
0
  }
9454
9455
0
  for (const auto &BI : RD->bases()) {
9456
0
    if (DiagnoseUninitializedReference(S, BI.getBeginLoc(), BI.getType())) {
9457
0
      S.Diag(Loc, diag::note_value_initialization_here) << RD;
9458
0
      return true;
9459
0
    }
9460
0
  }
9461
9462
0
  return false;
9463
0
}
9464
9465
9466
//===----------------------------------------------------------------------===//
9467
// Diagnose initialization failures
9468
//===----------------------------------------------------------------------===//
9469
9470
/// Emit notes associated with an initialization that failed due to a
9471
/// "simple" conversion failure.
9472
static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
9473
0
                                   Expr *op) {
9474
0
  QualType destType = entity.getType();
9475
0
  if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
9476
0
      op->getType()->isObjCObjectPointerType()) {
9477
9478
    // Emit a possible note about the conversion failing because the
9479
    // operand is a message send with a related result type.
9480
0
    S.EmitRelatedResultTypeNote(op);
9481
9482
    // Emit a possible note about a return failing because we're
9483
    // expecting a related result type.
9484
0
    if (entity.getKind() == InitializedEntity::EK_Result)
9485
0
      S.EmitRelatedResultTypeNoteForReturn(destType);
9486
0
  }
9487
0
  QualType fromType = op->getType();
9488
0
  QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType();
9489
0
  QualType destPointeeType = destType.getCanonicalType()->getPointeeType();
9490
0
  auto *fromDecl = fromType->getPointeeCXXRecordDecl();
9491
0
  auto *destDecl = destType->getPointeeCXXRecordDecl();
9492
0
  if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord &&
9493
0
      destDecl->getDeclKind() == Decl::CXXRecord &&
9494
0
      !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() &&
9495
0
      !fromDecl->hasDefinition() &&
9496
0
      destPointeeType.getQualifiers().compatiblyIncludes(
9497
0
          fromPointeeType.getQualifiers()))
9498
0
    S.Diag(fromDecl->getLocation(), diag::note_forward_class_conversion)
9499
0
        << S.getASTContext().getTagDeclType(fromDecl)
9500
0
        << S.getASTContext().getTagDeclType(destDecl);
9501
0
}
9502
9503
static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
9504
0
                             InitListExpr *InitList) {
9505
0
  QualType DestType = Entity.getType();
9506
9507
0
  QualType E;
9508
0
  if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
9509
0
    QualType ArrayType = S.Context.getConstantArrayType(
9510
0
        E.withConst(),
9511
0
        llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
9512
0
                    InitList->getNumInits()),
9513
0
        nullptr, clang::ArraySizeModifier::Normal, 0);
9514
0
    InitializedEntity HiddenArray =
9515
0
        InitializedEntity::InitializeTemporary(ArrayType);
9516
0
    return diagnoseListInit(S, HiddenArray, InitList);
9517
0
  }
9518
9519
0
  if (DestType->isReferenceType()) {
9520
    // A list-initialization failure for a reference means that we tried to
9521
    // create a temporary of the inner type (per [dcl.init.list]p3.6) and the
9522
    // inner initialization failed.
9523
0
    QualType T = DestType->castAs<ReferenceType>()->getPointeeType();
9524
0
    diagnoseListInit(S, InitializedEntity::InitializeTemporary(T), InitList);
9525
0
    SourceLocation Loc = InitList->getBeginLoc();
9526
0
    if (auto *D = Entity.getDecl())
9527
0
      Loc = D->getLocation();
9528
0
    S.Diag(Loc, diag::note_in_reference_temporary_list_initializer) << T;
9529
0
    return;
9530
0
  }
9531
9532
0
  InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
9533
0
                                   /*VerifyOnly=*/false,
9534
0
                                   /*TreatUnavailableAsInvalid=*/false);
9535
0
  assert(DiagnoseInitList.HadError() &&
9536
0
         "Inconsistent init list check result.");
9537
0
}
9538
9539
bool InitializationSequence::Diagnose(Sema &S,
9540
                                      const InitializedEntity &Entity,
9541
                                      const InitializationKind &Kind,
9542
0
                                      ArrayRef<Expr *> Args) {
9543
0
  if (!Failed())
9544
0
    return false;
9545
9546
  // When we want to diagnose only one element of a braced-init-list,
9547
  // we need to factor it out.
9548
0
  Expr *OnlyArg;
9549
0
  if (Args.size() == 1) {
9550
0
    auto *List = dyn_cast<InitListExpr>(Args[0]);
9551
0
    if (List && List->getNumInits() == 1)
9552
0
      OnlyArg = List->getInit(0);
9553
0
    else
9554
0
      OnlyArg = Args[0];
9555
0
  }
9556
0
  else
9557
0
    OnlyArg = nullptr;
9558
9559
0
  QualType DestType = Entity.getType();
9560
0
  switch (Failure) {
9561
0
  case FK_TooManyInitsForReference:
9562
    // FIXME: Customize for the initialized entity?
9563
0
    if (Args.empty()) {
9564
      // Dig out the reference subobject which is uninitialized and diagnose it.
9565
      // If this is value-initialization, this could be nested some way within
9566
      // the target type.
9567
0
      assert(Kind.getKind() == InitializationKind::IK_Value ||
9568
0
             DestType->isReferenceType());
9569
0
      bool Diagnosed =
9570
0
        DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
9571
0
      assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
9572
0
      (void)Diagnosed;
9573
0
    } else  // FIXME: diagnostic below could be better!
9574
0
      S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
9575
0
          << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9576
0
    break;
9577
0
  case FK_ParenthesizedListInitForReference:
9578
0
    S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9579
0
      << 1 << Entity.getType() << Args[0]->getSourceRange();
9580
0
    break;
9581
9582
0
  case FK_ArrayNeedsInitList:
9583
0
    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
9584
0
    break;
9585
0
  case FK_ArrayNeedsInitListOrStringLiteral:
9586
0
    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
9587
0
    break;
9588
0
  case FK_ArrayNeedsInitListOrWideStringLiteral:
9589
0
    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
9590
0
    break;
9591
0
  case FK_NarrowStringIntoWideCharArray:
9592
0
    S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
9593
0
    break;
9594
0
  case FK_WideStringIntoCharArray:
9595
0
    S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
9596
0
    break;
9597
0
  case FK_IncompatWideStringIntoWideChar:
9598
0
    S.Diag(Kind.getLocation(),
9599
0
           diag::err_array_init_incompat_wide_string_into_wchar);
9600
0
    break;
9601
0
  case FK_PlainStringIntoUTF8Char:
9602
0
    S.Diag(Kind.getLocation(),
9603
0
           diag::err_array_init_plain_string_into_char8_t);
9604
0
    S.Diag(Args.front()->getBeginLoc(),
9605
0
           diag::note_array_init_plain_string_into_char8_t)
9606
0
        << FixItHint::CreateInsertion(Args.front()->getBeginLoc(), "u8");
9607
0
    break;
9608
0
  case FK_UTF8StringIntoPlainChar:
9609
0
    S.Diag(Kind.getLocation(), diag::err_array_init_utf8_string_into_char)
9610
0
        << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20;
9611
0
    break;
9612
0
  case FK_ArrayTypeMismatch:
9613
0
  case FK_NonConstantArrayInit:
9614
0
    S.Diag(Kind.getLocation(),
9615
0
           (Failure == FK_ArrayTypeMismatch
9616
0
              ? diag::err_array_init_different_type
9617
0
              : diag::err_array_init_non_constant_array))
9618
0
      << DestType.getNonReferenceType()
9619
0
      << OnlyArg->getType()
9620
0
      << Args[0]->getSourceRange();
9621
0
    break;
9622
9623
0
  case FK_VariableLengthArrayHasInitializer:
9624
0
    S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
9625
0
      << Args[0]->getSourceRange();
9626
0
    break;
9627
9628
0
  case FK_AddressOfOverloadFailed: {
9629
0
    DeclAccessPair Found;
9630
0
    S.ResolveAddressOfOverloadedFunction(OnlyArg,
9631
0
                                         DestType.getNonReferenceType(),
9632
0
                                         true,
9633
0
                                         Found);
9634
0
    break;
9635
0
  }
9636
9637
0
  case FK_AddressOfUnaddressableFunction: {
9638
0
    auto *FD = cast<FunctionDecl>(cast<DeclRefExpr>(OnlyArg)->getDecl());
9639
0
    S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9640
0
                                        OnlyArg->getBeginLoc());
9641
0
    break;
9642
0
  }
9643
9644
0
  case FK_ReferenceInitOverloadFailed:
9645
0
  case FK_UserConversionOverloadFailed:
9646
0
    switch (FailedOverloadResult) {
9647
0
    case OR_Ambiguous:
9648
9649
0
      FailedCandidateSet.NoteCandidates(
9650
0
          PartialDiagnosticAt(
9651
0
              Kind.getLocation(),
9652
0
              Failure == FK_UserConversionOverloadFailed
9653
0
                  ? (S.PDiag(diag::err_typecheck_ambiguous_condition)
9654
0
                     << OnlyArg->getType() << DestType
9655
0
                     << Args[0]->getSourceRange())
9656
0
                  : (S.PDiag(diag::err_ref_init_ambiguous)
9657
0
                     << DestType << OnlyArg->getType()
9658
0
                     << Args[0]->getSourceRange())),
9659
0
          S, OCD_AmbiguousCandidates, Args);
9660
0
      break;
9661
9662
0
    case OR_No_Viable_Function: {
9663
0
      auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args);
9664
0
      if (!S.RequireCompleteType(Kind.getLocation(),
9665
0
                                 DestType.getNonReferenceType(),
9666
0
                          diag::err_typecheck_nonviable_condition_incomplete,
9667
0
                               OnlyArg->getType(), Args[0]->getSourceRange()))
9668
0
        S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
9669
0
          << (Entity.getKind() == InitializedEntity::EK_Result)
9670
0
          << OnlyArg->getType() << Args[0]->getSourceRange()
9671
0
          << DestType.getNonReferenceType();
9672
9673
0
      FailedCandidateSet.NoteCandidates(S, Args, Cands);
9674
0
      break;
9675
0
    }
9676
0
    case OR_Deleted: {
9677
0
      S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
9678
0
        << OnlyArg->getType() << DestType.getNonReferenceType()
9679
0
        << Args[0]->getSourceRange();
9680
0
      OverloadCandidateSet::iterator Best;
9681
0
      OverloadingResult Ovl
9682
0
        = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9683
0
      if (Ovl == OR_Deleted) {
9684
0
        S.NoteDeletedFunction(Best->Function);
9685
0
      } else {
9686
0
        llvm_unreachable("Inconsistent overload resolution?");
9687
0
      }
9688
0
      break;
9689
0
    }
9690
9691
0
    case OR_Success:
9692
0
      llvm_unreachable("Conversion did not fail!");
9693
0
    }
9694
0
    break;
9695
9696
0
  case FK_NonConstLValueReferenceBindingToTemporary:
9697
0
    if (isa<InitListExpr>(Args[0])) {
9698
0
      S.Diag(Kind.getLocation(),
9699
0
             diag::err_lvalue_reference_bind_to_initlist)
9700
0
      << DestType.getNonReferenceType().isVolatileQualified()
9701
0
      << DestType.getNonReferenceType()
9702
0
      << Args[0]->getSourceRange();
9703
0
      break;
9704
0
    }
9705
0
    [[fallthrough]];
9706
9707
0
  case FK_NonConstLValueReferenceBindingToUnrelated:
9708
0
    S.Diag(Kind.getLocation(),
9709
0
           Failure == FK_NonConstLValueReferenceBindingToTemporary
9710
0
             ? diag::err_lvalue_reference_bind_to_temporary
9711
0
             : diag::err_lvalue_reference_bind_to_unrelated)
9712
0
      << DestType.getNonReferenceType().isVolatileQualified()
9713
0
      << DestType.getNonReferenceType()
9714
0
      << OnlyArg->getType()
9715
0
      << Args[0]->getSourceRange();
9716
0
    break;
9717
9718
0
  case FK_NonConstLValueReferenceBindingToBitfield: {
9719
    // We don't necessarily have an unambiguous source bit-field.
9720
0
    FieldDecl *BitField = Args[0]->getSourceBitField();
9721
0
    S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
9722
0
      << DestType.isVolatileQualified()
9723
0
      << (BitField ? BitField->getDeclName() : DeclarationName())
9724
0
      << (BitField != nullptr)
9725
0
      << Args[0]->getSourceRange();
9726
0
    if (BitField)
9727
0
      S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
9728
0
    break;
9729
0
  }
9730
9731
0
  case FK_NonConstLValueReferenceBindingToVectorElement:
9732
0
    S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
9733
0
      << DestType.isVolatileQualified()
9734
0
      << Args[0]->getSourceRange();
9735
0
    break;
9736
9737
0
  case FK_NonConstLValueReferenceBindingToMatrixElement:
9738
0
    S.Diag(Kind.getLocation(), diag::err_reference_bind_to_matrix_element)
9739
0
        << DestType.isVolatileQualified() << Args[0]->getSourceRange();
9740
0
    break;
9741
9742
0
  case FK_RValueReferenceBindingToLValue:
9743
0
    S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
9744
0
      << DestType.getNonReferenceType() << OnlyArg->getType()
9745
0
      << Args[0]->getSourceRange();
9746
0
    break;
9747
9748
0
  case FK_ReferenceAddrspaceMismatchTemporary:
9749
0
    S.Diag(Kind.getLocation(), diag::err_reference_bind_temporary_addrspace)
9750
0
        << DestType << Args[0]->getSourceRange();
9751
0
    break;
9752
9753
0
  case FK_ReferenceInitDropsQualifiers: {
9754
0
    QualType SourceType = OnlyArg->getType();
9755
0
    QualType NonRefType = DestType.getNonReferenceType();
9756
0
    Qualifiers DroppedQualifiers =
9757
0
        SourceType.getQualifiers() - NonRefType.getQualifiers();
9758
9759
0
    if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf(
9760
0
            SourceType.getQualifiers()))
9761
0
      S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9762
0
          << NonRefType << SourceType << 1 /*addr space*/
9763
0
          << Args[0]->getSourceRange();
9764
0
    else if (DroppedQualifiers.hasQualifiers())
9765
0
      S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9766
0
          << NonRefType << SourceType << 0 /*cv quals*/
9767
0
          << Qualifiers::fromCVRMask(DroppedQualifiers.getCVRQualifiers())
9768
0
          << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange();
9769
0
    else
9770
      // FIXME: Consider decomposing the type and explaining which qualifiers
9771
      // were dropped where, or on which level a 'const' is missing, etc.
9772
0
      S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
9773
0
          << NonRefType << SourceType << 2 /*incompatible quals*/
9774
0
          << Args[0]->getSourceRange();
9775
0
    break;
9776
0
  }
9777
9778
0
  case FK_ReferenceInitFailed:
9779
0
    S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
9780
0
      << DestType.getNonReferenceType()
9781
0
      << DestType.getNonReferenceType()->isIncompleteType()
9782
0
      << OnlyArg->isLValue()
9783
0
      << OnlyArg->getType()
9784
0
      << Args[0]->getSourceRange();
9785
0
    emitBadConversionNotes(S, Entity, Args[0]);
9786
0
    break;
9787
9788
0
  case FK_ConversionFailed: {
9789
0
    QualType FromType = OnlyArg->getType();
9790
0
    PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
9791
0
      << (int)Entity.getKind()
9792
0
      << DestType
9793
0
      << OnlyArg->isLValue()
9794
0
      << FromType
9795
0
      << Args[0]->getSourceRange();
9796
0
    S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
9797
0
    S.Diag(Kind.getLocation(), PDiag);
9798
0
    emitBadConversionNotes(S, Entity, Args[0]);
9799
0
    break;
9800
0
  }
9801
9802
0
  case FK_ConversionFromPropertyFailed:
9803
    // No-op. This error has already been reported.
9804
0
    break;
9805
9806
0
  case FK_TooManyInitsForScalar: {
9807
0
    SourceRange R;
9808
9809
0
    auto *InitList = dyn_cast<InitListExpr>(Args[0]);
9810
0
    if (InitList && InitList->getNumInits() >= 1) {
9811
0
      R = SourceRange(InitList->getInit(0)->getEndLoc(), InitList->getEndLoc());
9812
0
    } else {
9813
0
      assert(Args.size() > 1 && "Expected multiple initializers!");
9814
0
      R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc());
9815
0
    }
9816
9817
0
    R.setBegin(S.getLocForEndOfToken(R.getBegin()));
9818
0
    if (Kind.isCStyleOrFunctionalCast())
9819
0
      S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
9820
0
        << R;
9821
0
    else
9822
0
      S.Diag(Kind.getLocation(), diag::err_excess_initializers)
9823
0
        << /*scalar=*/2 << R;
9824
0
    break;
9825
0
  }
9826
9827
0
  case FK_ParenthesizedListInitForScalar:
9828
0
    S.Diag(Kind.getLocation(), diag::err_list_init_in_parens)
9829
0
      << 0 << Entity.getType() << Args[0]->getSourceRange();
9830
0
    break;
9831
9832
0
  case FK_ReferenceBindingToInitList:
9833
0
    S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
9834
0
      << DestType.getNonReferenceType() << Args[0]->getSourceRange();
9835
0
    break;
9836
9837
0
  case FK_InitListBadDestinationType:
9838
0
    S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
9839
0
      << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
9840
0
    break;
9841
9842
0
  case FK_ListConstructorOverloadFailed:
9843
0
  case FK_ConstructorOverloadFailed: {
9844
0
    SourceRange ArgsRange;
9845
0
    if (Args.size())
9846
0
      ArgsRange =
9847
0
          SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc());
9848
9849
0
    if (Failure == FK_ListConstructorOverloadFailed) {
9850
0
      assert(Args.size() == 1 &&
9851
0
             "List construction from other than 1 argument.");
9852
0
      InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9853
0
      Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
9854
0
    }
9855
9856
    // FIXME: Using "DestType" for the entity we're printing is probably
9857
    // bad.
9858
0
    switch (FailedOverloadResult) {
9859
0
      case OR_Ambiguous:
9860
0
        FailedCandidateSet.NoteCandidates(
9861
0
            PartialDiagnosticAt(Kind.getLocation(),
9862
0
                                S.PDiag(diag::err_ovl_ambiguous_init)
9863
0
                                    << DestType << ArgsRange),
9864
0
            S, OCD_AmbiguousCandidates, Args);
9865
0
        break;
9866
9867
0
      case OR_No_Viable_Function:
9868
0
        if (Kind.getKind() == InitializationKind::IK_Default &&
9869
0
            (Entity.getKind() == InitializedEntity::EK_Base ||
9870
0
             Entity.getKind() == InitializedEntity::EK_Member ||
9871
0
             Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) &&
9872
0
            isa<CXXConstructorDecl>(S.CurContext)) {
9873
          // This is implicit default initialization of a member or
9874
          // base within a constructor. If no viable function was
9875
          // found, notify the user that they need to explicitly
9876
          // initialize this base/member.
9877
0
          CXXConstructorDecl *Constructor
9878
0
            = cast<CXXConstructorDecl>(S.CurContext);
9879
0
          const CXXRecordDecl *InheritedFrom = nullptr;
9880
0
          if (auto Inherited = Constructor->getInheritedConstructor())
9881
0
            InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass();
9882
0
          if (Entity.getKind() == InitializedEntity::EK_Base) {
9883
0
            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9884
0
              << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9885
0
              << S.Context.getTypeDeclType(Constructor->getParent())
9886
0
              << /*base=*/0
9887
0
              << Entity.getType()
9888
0
              << InheritedFrom;
9889
9890
0
            RecordDecl *BaseDecl
9891
0
              = Entity.getBaseSpecifier()->getType()->castAs<RecordType>()
9892
0
                                                                  ->getDecl();
9893
0
            S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
9894
0
              << S.Context.getTagDeclType(BaseDecl);
9895
0
          } else {
9896
0
            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
9897
0
              << (InheritedFrom ? 2 : Constructor->isImplicit() ? 1 : 0)
9898
0
              << S.Context.getTypeDeclType(Constructor->getParent())
9899
0
              << /*member=*/1
9900
0
              << Entity.getName()
9901
0
              << InheritedFrom;
9902
0
            S.Diag(Entity.getDecl()->getLocation(),
9903
0
                   diag::note_member_declared_at);
9904
9905
0
            if (const RecordType *Record
9906
0
                                 = Entity.getType()->getAs<RecordType>())
9907
0
              S.Diag(Record->getDecl()->getLocation(),
9908
0
                     diag::note_previous_decl)
9909
0
                << S.Context.getTagDeclType(Record->getDecl());
9910
0
          }
9911
0
          break;
9912
0
        }
9913
9914
0
        FailedCandidateSet.NoteCandidates(
9915
0
            PartialDiagnosticAt(
9916
0
                Kind.getLocation(),
9917
0
                S.PDiag(diag::err_ovl_no_viable_function_in_init)
9918
0
                    << DestType << ArgsRange),
9919
0
            S, OCD_AllCandidates, Args);
9920
0
        break;
9921
9922
0
      case OR_Deleted: {
9923
0
        OverloadCandidateSet::iterator Best;
9924
0
        OverloadingResult Ovl
9925
0
          = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
9926
0
        if (Ovl != OR_Deleted) {
9927
0
          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9928
0
              << DestType << ArgsRange;
9929
0
          llvm_unreachable("Inconsistent overload resolution?");
9930
0
          break;
9931
0
        }
9932
9933
        // If this is a defaulted or implicitly-declared function, then
9934
        // it was implicitly deleted. Make it clear that the deletion was
9935
        // implicit.
9936
0
        if (S.isImplicitlyDeleted(Best->Function))
9937
0
          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
9938
0
            << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
9939
0
            << DestType << ArgsRange;
9940
0
        else
9941
0
          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
9942
0
              << DestType << ArgsRange;
9943
9944
0
        S.NoteDeletedFunction(Best->Function);
9945
0
        break;
9946
0
      }
9947
9948
0
      case OR_Success:
9949
0
        llvm_unreachable("Conversion did not fail!");
9950
0
    }
9951
0
  }
9952
0
  break;
9953
9954
0
  case FK_DefaultInitOfConst:
9955
0
    if (Entity.getKind() == InitializedEntity::EK_Member &&
9956
0
        isa<CXXConstructorDecl>(S.CurContext)) {
9957
      // This is implicit default-initialization of a const member in
9958
      // a constructor. Complain that it needs to be explicitly
9959
      // initialized.
9960
0
      CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
9961
0
      S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
9962
0
        << (Constructor->getInheritedConstructor() ? 2 :
9963
0
            Constructor->isImplicit() ? 1 : 0)
9964
0
        << S.Context.getTypeDeclType(Constructor->getParent())
9965
0
        << /*const=*/1
9966
0
        << Entity.getName();
9967
0
      S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
9968
0
        << Entity.getName();
9969
0
    } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Entity.getDecl());
9970
0
               VD && VD->isConstexpr()) {
9971
0
      S.Diag(Kind.getLocation(), diag::err_constexpr_var_requires_const_init)
9972
0
          << VD;
9973
0
    } else {
9974
0
      S.Diag(Kind.getLocation(), diag::err_default_init_const)
9975
0
          << DestType << (bool)DestType->getAs<RecordType>();
9976
0
    }
9977
0
    break;
9978
9979
0
  case FK_Incomplete:
9980
0
    S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
9981
0
                          diag::err_init_incomplete_type);
9982
0
    break;
9983
9984
0
  case FK_ListInitializationFailed: {
9985
    // Run the init list checker again to emit diagnostics.
9986
0
    InitListExpr *InitList = cast<InitListExpr>(Args[0]);
9987
0
    diagnoseListInit(S, Entity, InitList);
9988
0
    break;
9989
0
  }
9990
9991
0
  case FK_PlaceholderType: {
9992
    // FIXME: Already diagnosed!
9993
0
    break;
9994
0
  }
9995
9996
0
  case FK_ExplicitConstructor: {
9997
0
    S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
9998
0
      << Args[0]->getSourceRange();
9999
0
    OverloadCandidateSet::iterator Best;
10000
0
    OverloadingResult Ovl
10001
0
      = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
10002
0
    (void)Ovl;
10003
0
    assert(Ovl == OR_Success && "Inconsistent overload resolution");
10004
0
    CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
10005
0
    S.Diag(CtorDecl->getLocation(),
10006
0
           diag::note_explicit_ctor_deduction_guide_here) << false;
10007
0
    break;
10008
0
  }
10009
10010
0
  case FK_ParenthesizedListInitFailed:
10011
0
    TryOrBuildParenListInitialization(S, Entity, Kind, Args, *this,
10012
0
                                      /*VerifyOnly=*/false);
10013
0
    break;
10014
10015
0
  case FK_DesignatedInitForNonAggregate:
10016
0
    InitListExpr *InitList = cast<InitListExpr>(Args[0]);
10017
0
    S.Diag(Kind.getLocation(), diag::err_designated_init_for_non_aggregate)
10018
0
        << Entity.getType() << InitList->getSourceRange();
10019
0
    break;
10020
0
  }
10021
10022
0
  PrintInitLocationNote(S, Entity);
10023
0
  return true;
10024
0
}
10025
10026
0
void InitializationSequence::dump(raw_ostream &OS) const {
10027
0
  switch (SequenceKind) {
10028
0
  case FailedSequence: {
10029
0
    OS << "Failed sequence: ";
10030
0
    switch (Failure) {
10031
0
    case FK_TooManyInitsForReference:
10032
0
      OS << "too many initializers for reference";
10033
0
      break;
10034
10035
0
    case FK_ParenthesizedListInitForReference:
10036
0
      OS << "parenthesized list init for reference";
10037
0
      break;
10038
10039
0
    case FK_ArrayNeedsInitList:
10040
0
      OS << "array requires initializer list";
10041
0
      break;
10042
10043
0
    case FK_AddressOfUnaddressableFunction:
10044
0
      OS << "address of unaddressable function was taken";
10045
0
      break;
10046
10047
0
    case FK_ArrayNeedsInitListOrStringLiteral:
10048
0
      OS << "array requires initializer list or string literal";
10049
0
      break;
10050
10051
0
    case FK_ArrayNeedsInitListOrWideStringLiteral:
10052
0
      OS << "array requires initializer list or wide string literal";
10053
0
      break;
10054
10055
0
    case FK_NarrowStringIntoWideCharArray:
10056
0
      OS << "narrow string into wide char array";
10057
0
      break;
10058
10059
0
    case FK_WideStringIntoCharArray:
10060
0
      OS << "wide string into char array";
10061
0
      break;
10062
10063
0
    case FK_IncompatWideStringIntoWideChar:
10064
0
      OS << "incompatible wide string into wide char array";
10065
0
      break;
10066
10067
0
    case FK_PlainStringIntoUTF8Char:
10068
0
      OS << "plain string literal into char8_t array";
10069
0
      break;
10070
10071
0
    case FK_UTF8StringIntoPlainChar:
10072
0
      OS << "u8 string literal into char array";
10073
0
      break;
10074
10075
0
    case FK_ArrayTypeMismatch:
10076
0
      OS << "array type mismatch";
10077
0
      break;
10078
10079
0
    case FK_NonConstantArrayInit:
10080
0
      OS << "non-constant array initializer";
10081
0
      break;
10082
10083
0
    case FK_AddressOfOverloadFailed:
10084
0
      OS << "address of overloaded function failed";
10085
0
      break;
10086
10087
0
    case FK_ReferenceInitOverloadFailed:
10088
0
      OS << "overload resolution for reference initialization failed";
10089
0
      break;
10090
10091
0
    case FK_NonConstLValueReferenceBindingToTemporary:
10092
0
      OS << "non-const lvalue reference bound to temporary";
10093
0
      break;
10094
10095
0
    case FK_NonConstLValueReferenceBindingToBitfield:
10096
0
      OS << "non-const lvalue reference bound to bit-field";
10097
0
      break;
10098
10099
0
    case FK_NonConstLValueReferenceBindingToVectorElement:
10100
0
      OS << "non-const lvalue reference bound to vector element";
10101
0
      break;
10102
10103
0
    case FK_NonConstLValueReferenceBindingToMatrixElement:
10104
0
      OS << "non-const lvalue reference bound to matrix element";
10105
0
      break;
10106
10107
0
    case FK_NonConstLValueReferenceBindingToUnrelated:
10108
0
      OS << "non-const lvalue reference bound to unrelated type";
10109
0
      break;
10110
10111
0
    case FK_RValueReferenceBindingToLValue:
10112
0
      OS << "rvalue reference bound to an lvalue";
10113
0
      break;
10114
10115
0
    case FK_ReferenceInitDropsQualifiers:
10116
0
      OS << "reference initialization drops qualifiers";
10117
0
      break;
10118
10119
0
    case FK_ReferenceAddrspaceMismatchTemporary:
10120
0
      OS << "reference with mismatching address space bound to temporary";
10121
0
      break;
10122
10123
0
    case FK_ReferenceInitFailed:
10124
0
      OS << "reference initialization failed";
10125
0
      break;
10126
10127
0
    case FK_ConversionFailed:
10128
0
      OS << "conversion failed";
10129
0
      break;
10130
10131
0
    case FK_ConversionFromPropertyFailed:
10132
0
      OS << "conversion from property failed";
10133
0
      break;
10134
10135
0
    case FK_TooManyInitsForScalar:
10136
0
      OS << "too many initializers for scalar";
10137
0
      break;
10138
10139
0
    case FK_ParenthesizedListInitForScalar:
10140
0
      OS << "parenthesized list init for reference";
10141
0
      break;
10142
10143
0
    case FK_ReferenceBindingToInitList:
10144
0
      OS << "referencing binding to initializer list";
10145
0
      break;
10146
10147
0
    case FK_InitListBadDestinationType:
10148
0
      OS << "initializer list for non-aggregate, non-scalar type";
10149
0
      break;
10150
10151
0
    case FK_UserConversionOverloadFailed:
10152
0
      OS << "overloading failed for user-defined conversion";
10153
0
      break;
10154
10155
0
    case FK_ConstructorOverloadFailed:
10156
0
      OS << "constructor overloading failed";
10157
0
      break;
10158
10159
0
    case FK_DefaultInitOfConst:
10160
0
      OS << "default initialization of a const variable";
10161
0
      break;
10162
10163
0
    case FK_Incomplete:
10164
0
      OS << "initialization of incomplete type";
10165
0
      break;
10166
10167
0
    case FK_ListInitializationFailed:
10168
0
      OS << "list initialization checker failure";
10169
0
      break;
10170
10171
0
    case FK_VariableLengthArrayHasInitializer:
10172
0
      OS << "variable length array has an initializer";
10173
0
      break;
10174
10175
0
    case FK_PlaceholderType:
10176
0
      OS << "initializer expression isn't contextually valid";
10177
0
      break;
10178
10179
0
    case FK_ListConstructorOverloadFailed:
10180
0
      OS << "list constructor overloading failed";
10181
0
      break;
10182
10183
0
    case FK_ExplicitConstructor:
10184
0
      OS << "list copy initialization chose explicit constructor";
10185
0
      break;
10186
10187
0
    case FK_ParenthesizedListInitFailed:
10188
0
      OS << "parenthesized list initialization failed";
10189
0
      break;
10190
10191
0
    case FK_DesignatedInitForNonAggregate:
10192
0
      OS << "designated initializer for non-aggregate type";
10193
0
      break;
10194
0
    }
10195
0
    OS << '\n';
10196
0
    return;
10197
0
  }
10198
10199
0
  case DependentSequence:
10200
0
    OS << "Dependent sequence\n";
10201
0
    return;
10202
10203
0
  case NormalSequence:
10204
0
    OS << "Normal sequence: ";
10205
0
    break;
10206
0
  }
10207
10208
0
  for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
10209
0
    if (S != step_begin()) {
10210
0
      OS << " -> ";
10211
0
    }
10212
10213
0
    switch (S->Kind) {
10214
0
    case SK_ResolveAddressOfOverloadedFunction:
10215
0
      OS << "resolve address of overloaded function";
10216
0
      break;
10217
10218
0
    case SK_CastDerivedToBasePRValue:
10219
0
      OS << "derived-to-base (prvalue)";
10220
0
      break;
10221
10222
0
    case SK_CastDerivedToBaseXValue:
10223
0
      OS << "derived-to-base (xvalue)";
10224
0
      break;
10225
10226
0
    case SK_CastDerivedToBaseLValue:
10227
0
      OS << "derived-to-base (lvalue)";
10228
0
      break;
10229
10230
0
    case SK_BindReference:
10231
0
      OS << "bind reference to lvalue";
10232
0
      break;
10233
10234
0
    case SK_BindReferenceToTemporary:
10235
0
      OS << "bind reference to a temporary";
10236
0
      break;
10237
10238
0
    case SK_FinalCopy:
10239
0
      OS << "final copy in class direct-initialization";
10240
0
      break;
10241
10242
0
    case SK_ExtraneousCopyToTemporary:
10243
0
      OS << "extraneous C++03 copy to temporary";
10244
0
      break;
10245
10246
0
    case SK_UserConversion:
10247
0
      OS << "user-defined conversion via " << *S->Function.Function;
10248
0
      break;
10249
10250
0
    case SK_QualificationConversionPRValue:
10251
0
      OS << "qualification conversion (prvalue)";
10252
0
      break;
10253
10254
0
    case SK_QualificationConversionXValue:
10255
0
      OS << "qualification conversion (xvalue)";
10256
0
      break;
10257
10258
0
    case SK_QualificationConversionLValue:
10259
0
      OS << "qualification conversion (lvalue)";
10260
0
      break;
10261
10262
0
    case SK_FunctionReferenceConversion:
10263
0
      OS << "function reference conversion";
10264
0
      break;
10265
10266
0
    case SK_AtomicConversion:
10267
0
      OS << "non-atomic-to-atomic conversion";
10268
0
      break;
10269
10270
0
    case SK_ConversionSequence:
10271
0
      OS << "implicit conversion sequence (";
10272
0
      S->ICS->dump(); // FIXME: use OS
10273
0
      OS << ")";
10274
0
      break;
10275
10276
0
    case SK_ConversionSequenceNoNarrowing:
10277
0
      OS << "implicit conversion sequence with narrowing prohibited (";
10278
0
      S->ICS->dump(); // FIXME: use OS
10279
0
      OS << ")";
10280
0
      break;
10281
10282
0
    case SK_ListInitialization:
10283
0
      OS << "list aggregate initialization";
10284
0
      break;
10285
10286
0
    case SK_UnwrapInitList:
10287
0
      OS << "unwrap reference initializer list";
10288
0
      break;
10289
10290
0
    case SK_RewrapInitList:
10291
0
      OS << "rewrap reference initializer list";
10292
0
      break;
10293
10294
0
    case SK_ConstructorInitialization:
10295
0
      OS << "constructor initialization";
10296
0
      break;
10297
10298
0
    case SK_ConstructorInitializationFromList:
10299
0
      OS << "list initialization via constructor";
10300
0
      break;
10301
10302
0
    case SK_ZeroInitialization:
10303
0
      OS << "zero initialization";
10304
0
      break;
10305
10306
0
    case SK_CAssignment:
10307
0
      OS << "C assignment";
10308
0
      break;
10309
10310
0
    case SK_StringInit:
10311
0
      OS << "string initialization";
10312
0
      break;
10313
10314
0
    case SK_ObjCObjectConversion:
10315
0
      OS << "Objective-C object conversion";
10316
0
      break;
10317
10318
0
    case SK_ArrayLoopIndex:
10319
0
      OS << "indexing for array initialization loop";
10320
0
      break;
10321
10322
0
    case SK_ArrayLoopInit:
10323
0
      OS << "array initialization loop";
10324
0
      break;
10325
10326
0
    case SK_ArrayInit:
10327
0
      OS << "array initialization";
10328
0
      break;
10329
10330
0
    case SK_GNUArrayInit:
10331
0
      OS << "array initialization (GNU extension)";
10332
0
      break;
10333
10334
0
    case SK_ParenthesizedArrayInit:
10335
0
      OS << "parenthesized array initialization";
10336
0
      break;
10337
10338
0
    case SK_PassByIndirectCopyRestore:
10339
0
      OS << "pass by indirect copy and restore";
10340
0
      break;
10341
10342
0
    case SK_PassByIndirectRestore:
10343
0
      OS << "pass by indirect restore";
10344
0
      break;
10345
10346
0
    case SK_ProduceObjCObject:
10347
0
      OS << "Objective-C object retension";
10348
0
      break;
10349
10350
0
    case SK_StdInitializerList:
10351
0
      OS << "std::initializer_list from initializer list";
10352
0
      break;
10353
10354
0
    case SK_StdInitializerListConstructorCall:
10355
0
      OS << "list initialization from std::initializer_list";
10356
0
      break;
10357
10358
0
    case SK_OCLSamplerInit:
10359
0
      OS << "OpenCL sampler_t from integer constant";
10360
0
      break;
10361
10362
0
    case SK_OCLZeroOpaqueType:
10363
0
      OS << "OpenCL opaque type from zero";
10364
0
      break;
10365
0
    case SK_ParenthesizedListInit:
10366
0
      OS << "initialization from a parenthesized list of values";
10367
0
      break;
10368
0
    }
10369
10370
0
    OS << " [" << S->Type << ']';
10371
0
  }
10372
10373
0
  OS << '\n';
10374
0
}
10375
10376
0
void InitializationSequence::dump() const {
10377
0
  dump(llvm::errs());
10378
0
}
10379
10380
static void DiagnoseNarrowingInInitList(Sema &S,
10381
                                        const ImplicitConversionSequence &ICS,
10382
                                        QualType PreNarrowingType,
10383
                                        QualType EntityType,
10384
0
                                        const Expr *PostInit) {
10385
0
  const StandardConversionSequence *SCS = nullptr;
10386
0
  switch (ICS.getKind()) {
10387
0
  case ImplicitConversionSequence::StandardConversion:
10388
0
    SCS = &ICS.Standard;
10389
0
    break;
10390
0
  case ImplicitConversionSequence::UserDefinedConversion:
10391
0
    SCS = &ICS.UserDefined.After;
10392
0
    break;
10393
0
  case ImplicitConversionSequence::AmbiguousConversion:
10394
0
  case ImplicitConversionSequence::StaticObjectArgumentConversion:
10395
0
  case ImplicitConversionSequence::EllipsisConversion:
10396
0
  case ImplicitConversionSequence::BadConversion:
10397
0
    return;
10398
0
  }
10399
10400
0
  auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID,
10401
0
                      unsigned ConstRefDiagID, unsigned WarnDiagID) {
10402
0
    unsigned DiagID;
10403
0
    auto &L = S.getLangOpts();
10404
0
    if (L.CPlusPlus11 &&
10405
0
        (!L.MicrosoftExt || L.isCompatibleWithMSVC(LangOptions::MSVC2015)))
10406
0
      DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID;
10407
0
    else
10408
0
      DiagID = WarnDiagID;
10409
0
    return S.Diag(PostInit->getBeginLoc(), DiagID)
10410
0
           << PostInit->getSourceRange();
10411
0
  };
10412
10413
  // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
10414
0
  APValue ConstantValue;
10415
0
  QualType ConstantType;
10416
0
  switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
10417
0
                                ConstantType)) {
10418
0
  case NK_Not_Narrowing:
10419
0
  case NK_Dependent_Narrowing:
10420
    // No narrowing occurred.
10421
0
    return;
10422
10423
0
  case NK_Type_Narrowing: {
10424
    // This was a floating-to-integer conversion, which is always considered a
10425
    // narrowing conversion even if the value is a constant and can be
10426
    // represented exactly as an integer.
10427
0
    QualType T = EntityType.getNonReferenceType();
10428
0
    MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing,
10429
0
             diag::ext_init_list_type_narrowing_const_reference,
10430
0
             diag::warn_init_list_type_narrowing)
10431
0
        << PreNarrowingType.getLocalUnqualifiedType()
10432
0
        << T.getLocalUnqualifiedType();
10433
0
    break;
10434
0
  }
10435
10436
0
  case NK_Constant_Narrowing: {
10437
    // A constant value was narrowed.
10438
0
    MakeDiag(EntityType.getNonReferenceType() != EntityType,
10439
0
             diag::ext_init_list_constant_narrowing,
10440
0
             diag::ext_init_list_constant_narrowing_const_reference,
10441
0
             diag::warn_init_list_constant_narrowing)
10442
0
        << ConstantValue.getAsString(S.getASTContext(), ConstantType)
10443
0
        << EntityType.getNonReferenceType().getLocalUnqualifiedType();
10444
0
    break;
10445
0
  }
10446
10447
0
  case NK_Variable_Narrowing: {
10448
    // A variable's value may have been narrowed.
10449
0
    MakeDiag(EntityType.getNonReferenceType() != EntityType,
10450
0
             diag::ext_init_list_variable_narrowing,
10451
0
             diag::ext_init_list_variable_narrowing_const_reference,
10452
0
             diag::warn_init_list_variable_narrowing)
10453
0
        << PreNarrowingType.getLocalUnqualifiedType()
10454
0
        << EntityType.getNonReferenceType().getLocalUnqualifiedType();
10455
0
    break;
10456
0
  }
10457
0
  }
10458
10459
0
  SmallString<128> StaticCast;
10460
0
  llvm::raw_svector_ostream OS(StaticCast);
10461
0
  OS << "static_cast<";
10462
0
  if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
10463
    // It's important to use the typedef's name if there is one so that the
10464
    // fixit doesn't break code using types like int64_t.
10465
    //
10466
    // FIXME: This will break if the typedef requires qualification.  But
10467
    // getQualifiedNameAsString() includes non-machine-parsable components.
10468
0
    OS << *TT->getDecl();
10469
0
  } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
10470
0
    OS << BT->getName(S.getLangOpts());
10471
0
  else {
10472
    // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
10473
    // with a broken cast.
10474
0
    return;
10475
0
  }
10476
0
  OS << ">(";
10477
0
  S.Diag(PostInit->getBeginLoc(), diag::note_init_list_narrowing_silence)
10478
0
      << PostInit->getSourceRange()
10479
0
      << FixItHint::CreateInsertion(PostInit->getBeginLoc(), OS.str())
10480
0
      << FixItHint::CreateInsertion(
10481
0
             S.getLocForEndOfToken(PostInit->getEndLoc()), ")");
10482
0
}
10483
10484
//===----------------------------------------------------------------------===//
10485
// Initialization helper functions
10486
//===----------------------------------------------------------------------===//
10487
bool
10488
Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
10489
0
                                   ExprResult Init) {
10490
0
  if (Init.isInvalid())
10491
0
    return false;
10492
10493
0
  Expr *InitE = Init.get();
10494
0
  assert(InitE && "No initialization expression");
10495
10496
0
  InitializationKind Kind =
10497
0
      InitializationKind::CreateCopy(InitE->getBeginLoc(), SourceLocation());
10498
0
  InitializationSequence Seq(*this, Entity, Kind, InitE);
10499
0
  return !Seq.Failed();
10500
0
}
10501
10502
ExprResult
10503
Sema::PerformCopyInitialization(const InitializedEntity &Entity,
10504
                                SourceLocation EqualLoc,
10505
                                ExprResult Init,
10506
                                bool TopLevelOfInitList,
10507
0
                                bool AllowExplicit) {
10508
0
  if (Init.isInvalid())
10509
0
    return ExprError();
10510
10511
0
  Expr *InitE = Init.get();
10512
0
  assert(InitE && "No initialization expression?");
10513
10514
0
  if (EqualLoc.isInvalid())
10515
0
    EqualLoc = InitE->getBeginLoc();
10516
10517
0
  InitializationKind Kind = InitializationKind::CreateCopy(
10518
0
      InitE->getBeginLoc(), EqualLoc, AllowExplicit);
10519
0
  InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
10520
10521
  // Prevent infinite recursion when performing parameter copy-initialization.
10522
0
  const bool ShouldTrackCopy =
10523
0
      Entity.isParameterKind() && Seq.isConstructorInitialization();
10524
0
  if (ShouldTrackCopy) {
10525
0
    if (llvm::is_contained(CurrentParameterCopyTypes, Entity.getType())) {
10526
0
      Seq.SetOverloadFailure(
10527
0
          InitializationSequence::FK_ConstructorOverloadFailed,
10528
0
          OR_No_Viable_Function);
10529
10530
      // Try to give a meaningful diagnostic note for the problematic
10531
      // constructor.
10532
0
      const auto LastStep = Seq.step_end() - 1;
10533
0
      assert(LastStep->Kind ==
10534
0
             InitializationSequence::SK_ConstructorInitialization);
10535
0
      const FunctionDecl *Function = LastStep->Function.Function;
10536
0
      auto Candidate =
10537
0
          llvm::find_if(Seq.getFailedCandidateSet(),
10538
0
                        [Function](const OverloadCandidate &Candidate) -> bool {
10539
0
                          return Candidate.Viable &&
10540
0
                                 Candidate.Function == Function &&
10541
0
                                 Candidate.Conversions.size() > 0;
10542
0
                        });
10543
0
      if (Candidate != Seq.getFailedCandidateSet().end() &&
10544
0
          Function->getNumParams() > 0) {
10545
0
        Candidate->Viable = false;
10546
0
        Candidate->FailureKind = ovl_fail_bad_conversion;
10547
0
        Candidate->Conversions[0].setBad(BadConversionSequence::no_conversion,
10548
0
                                         InitE,
10549
0
                                         Function->getParamDecl(0)->getType());
10550
0
      }
10551
0
    }
10552
0
    CurrentParameterCopyTypes.push_back(Entity.getType());
10553
0
  }
10554
10555
0
  ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
10556
10557
0
  if (ShouldTrackCopy)
10558
0
    CurrentParameterCopyTypes.pop_back();
10559
10560
0
  return Result;
10561
0
}
10562
10563
/// Determine whether RD is, or is derived from, a specialization of CTD.
10564
static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD,
10565
0
                                              ClassTemplateDecl *CTD) {
10566
0
  auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) {
10567
0
    auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Candidate);
10568
0
    return !CTSD || !declaresSameEntity(CTSD->getSpecializedTemplate(), CTD);
10569
0
  };
10570
0
  return !(NotSpecialization(RD) && RD->forallBases(NotSpecialization));
10571
0
}
10572
10573
QualType Sema::DeduceTemplateSpecializationFromInitializer(
10574
    TypeSourceInfo *TSInfo, const InitializedEntity &Entity,
10575
0
    const InitializationKind &Kind, MultiExprArg Inits) {
10576
0
  auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>(
10577
0
      TSInfo->getType()->getContainedDeducedType());
10578
0
  assert(DeducedTST && "not a deduced template specialization type");
10579
10580
0
  auto TemplateName = DeducedTST->getTemplateName();
10581
0
  if (TemplateName.isDependent())
10582
0
    return SubstAutoTypeDependent(TSInfo->getType());
10583
10584
  // We can only perform deduction for class templates.
10585
0
  auto *Template =
10586
0
      dyn_cast_or_null<ClassTemplateDecl>(TemplateName.getAsTemplateDecl());
10587
0
  if (!Template) {
10588
0
    Diag(Kind.getLocation(),
10589
0
         diag::err_deduced_non_class_template_specialization_type)
10590
0
      << (int)getTemplateNameKindForDiagnostics(TemplateName) << TemplateName;
10591
0
    if (auto *TD = TemplateName.getAsTemplateDecl())
10592
0
      NoteTemplateLocation(*TD);
10593
0
    return QualType();
10594
0
  }
10595
10596
  // Can't deduce from dependent arguments.
10597
0
  if (Expr::hasAnyTypeDependentArguments(Inits)) {
10598
0
    Diag(TSInfo->getTypeLoc().getBeginLoc(),
10599
0
         diag::warn_cxx14_compat_class_template_argument_deduction)
10600
0
        << TSInfo->getTypeLoc().getSourceRange() << 0;
10601
0
    return SubstAutoTypeDependent(TSInfo->getType());
10602
0
  }
10603
10604
  // FIXME: Perform "exact type" matching first, per CWG discussion?
10605
  //        Or implement this via an implied 'T(T) -> T' deduction guide?
10606
10607
  // FIXME: Do we need/want a std::initializer_list<T> special case?
10608
10609
  // Look up deduction guides, including those synthesized from constructors.
10610
  //
10611
  // C++1z [over.match.class.deduct]p1:
10612
  //   A set of functions and function templates is formed comprising:
10613
  //   - For each constructor of the class template designated by the
10614
  //     template-name, a function template [...]
10615
  //  - For each deduction-guide, a function or function template [...]
10616
0
  DeclarationNameInfo NameInfo(
10617
0
      Context.DeclarationNames.getCXXDeductionGuideName(Template),
10618
0
      TSInfo->getTypeLoc().getEndLoc());
10619
0
  LookupResult Guides(*this, NameInfo, LookupOrdinaryName);
10620
0
  LookupQualifiedName(Guides, Template->getDeclContext());
10621
10622
  // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't
10623
  // clear on this, but they're not found by name so access does not apply.
10624
0
  Guides.suppressDiagnostics();
10625
10626
  // Figure out if this is list-initialization.
10627
0
  InitListExpr *ListInit =
10628
0
      (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct)
10629
0
          ? dyn_cast<InitListExpr>(Inits[0])
10630
0
          : nullptr;
10631
10632
  // C++1z [over.match.class.deduct]p1:
10633
  //   Initialization and overload resolution are performed as described in
10634
  //   [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list]
10635
  //   (as appropriate for the type of initialization performed) for an object
10636
  //   of a hypothetical class type, where the selected functions and function
10637
  //   templates are considered to be the constructors of that class type
10638
  //
10639
  // Since we know we're initializing a class type of a type unrelated to that
10640
  // of the initializer, this reduces to something fairly reasonable.
10641
0
  OverloadCandidateSet Candidates(Kind.getLocation(),
10642
0
                                  OverloadCandidateSet::CSK_Normal);
10643
0
  OverloadCandidateSet::iterator Best;
10644
10645
0
  bool AllowExplicit = !Kind.isCopyInit() || ListInit;
10646
10647
  // Return true if the candidate is added successfully, false otherwise.
10648
0
  auto addDeductionCandidate = [&](FunctionTemplateDecl *TD,
10649
0
                                   CXXDeductionGuideDecl *GD,
10650
0
                                   DeclAccessPair FoundDecl,
10651
0
                                   bool OnlyListConstructors,
10652
0
                                   bool AllowAggregateDeductionCandidate) {
10653
    // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class)
10654
    //   For copy-initialization, the candidate functions are all the
10655
    //   converting constructors (12.3.1) of that class.
10656
    // C++ [over.match.copy]p1: (non-list copy-initialization from class)
10657
    //   The converting constructors of T are candidate functions.
10658
0
    if (!AllowExplicit) {
10659
      // Overload resolution checks whether the deduction guide is declared
10660
      // explicit for us.
10661
10662
      // When looking for a converting constructor, deduction guides that
10663
      // could never be called with one argument are not interesting to
10664
      // check or note.
10665
0
      if (GD->getMinRequiredArguments() > 1 ||
10666
0
          (GD->getNumParams() == 0 && !GD->isVariadic()))
10667
0
        return;
10668
0
    }
10669
10670
    // C++ [over.match.list]p1.1: (first phase list initialization)
10671
    //   Initially, the candidate functions are the initializer-list
10672
    //   constructors of the class T
10673
0
    if (OnlyListConstructors && !isInitListConstructor(GD))
10674
0
      return;
10675
10676
0
    if (!AllowAggregateDeductionCandidate &&
10677
0
        GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
10678
0
      return;
10679
10680
    // C++ [over.match.list]p1.2: (second phase list initialization)
10681
    //   the candidate functions are all the constructors of the class T
10682
    // C++ [over.match.ctor]p1: (all other cases)
10683
    //   the candidate functions are all the constructors of the class of
10684
    //   the object being initialized
10685
10686
    // C++ [over.best.ics]p4:
10687
    //   When [...] the constructor [...] is a candidate by
10688
    //    - [over.match.copy] (in all cases)
10689
    // FIXME: The "second phase of [over.match.list] case can also
10690
    // theoretically happen here, but it's not clear whether we can
10691
    // ever have a parameter of the right type.
10692
0
    bool SuppressUserConversions = Kind.isCopyInit();
10693
10694
0
    if (TD) {
10695
0
      SmallVector<Expr *, 8> TmpInits;
10696
0
      for (Expr *E : Inits)
10697
0
        if (auto *DI = dyn_cast<DesignatedInitExpr>(E))
10698
0
          TmpInits.push_back(DI->getInit());
10699
0
        else
10700
0
          TmpInits.push_back(E);
10701
0
      AddTemplateOverloadCandidate(
10702
0
          TD, FoundDecl, /*ExplicitArgs=*/nullptr, TmpInits, Candidates,
10703
0
          SuppressUserConversions,
10704
0
          /*PartialOverloading=*/false, AllowExplicit, ADLCallKind::NotADL,
10705
0
          /*PO=*/{}, AllowAggregateDeductionCandidate);
10706
0
    } else {
10707
0
      AddOverloadCandidate(GD, FoundDecl, Inits, Candidates,
10708
0
                           SuppressUserConversions,
10709
0
                           /*PartialOverloading=*/false, AllowExplicit);
10710
0
    }
10711
0
  };
10712
10713
0
  bool FoundDeductionGuide = false;
10714
10715
0
  auto TryToResolveOverload =
10716
0
      [&](bool OnlyListConstructors) -> OverloadingResult {
10717
0
    Candidates.clear(OverloadCandidateSet::CSK_Normal);
10718
0
    bool HasAnyDeductionGuide = false;
10719
10720
0
    auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) {
10721
0
      auto *RD = cast<CXXRecordDecl>(Template->getTemplatedDecl());
10722
0
      if (!(RD->getDefinition() && RD->isAggregate()))
10723
0
        return;
10724
0
      QualType Ty = Context.getRecordType(RD);
10725
0
      SmallVector<QualType, 8> ElementTypes;
10726
10727
0
      InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes);
10728
0
      if (!CheckInitList.HadError()) {
10729
        // C++ [over.match.class.deduct]p1.8:
10730
        //   if e_i is of array type and x_i is a braced-init-list, T_i is an
10731
        //   rvalue reference to the declared type of e_i and
10732
        // C++ [over.match.class.deduct]p1.9:
10733
        //   if e_i is of array type and x_i is a bstring-literal, T_i is an
10734
        //   lvalue reference to the const-qualified declared type of e_i and
10735
        // C++ [over.match.class.deduct]p1.10:
10736
        //   otherwise, T_i is the declared type of e_i
10737
0
        for (int I = 0, E = ListInit->getNumInits();
10738
0
             I < E && !isa<PackExpansionType>(ElementTypes[I]); ++I)
10739
0
          if (ElementTypes[I]->isArrayType()) {
10740
0
            if (isa<InitListExpr>(ListInit->getInit(I)))
10741
0
              ElementTypes[I] = Context.getRValueReferenceType(ElementTypes[I]);
10742
0
            else if (isa<StringLiteral>(
10743
0
                         ListInit->getInit(I)->IgnoreParenImpCasts()))
10744
0
              ElementTypes[I] =
10745
0
                  Context.getLValueReferenceType(ElementTypes[I].withConst());
10746
0
          }
10747
10748
0
        llvm::FoldingSetNodeID ID;
10749
0
        ID.AddPointer(Template);
10750
0
        for (auto &T : ElementTypes)
10751
0
          T.getCanonicalType().Profile(ID);
10752
0
        unsigned Hash = ID.ComputeHash();
10753
0
        if (AggregateDeductionCandidates.count(Hash) == 0) {
10754
0
          if (FunctionTemplateDecl *TD =
10755
0
                  DeclareImplicitDeductionGuideFromInitList(
10756
0
                      Template, ElementTypes,
10757
0
                      TSInfo->getTypeLoc().getEndLoc())) {
10758
0
            auto *GD = cast<CXXDeductionGuideDecl>(TD->getTemplatedDecl());
10759
0
            GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
10760
0
            AggregateDeductionCandidates[Hash] = GD;
10761
0
            addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10762
0
                                  OnlyListConstructors,
10763
0
                                  /*AllowAggregateDeductionCandidate=*/true);
10764
0
          }
10765
0
        } else {
10766
0
          CXXDeductionGuideDecl *GD = AggregateDeductionCandidates[Hash];
10767
0
          FunctionTemplateDecl *TD = GD->getDescribedFunctionTemplate();
10768
0
          assert(TD && "aggregate deduction candidate is function template");
10769
0
          addDeductionCandidate(TD, GD, DeclAccessPair::make(TD, AS_public),
10770
0
                                OnlyListConstructors,
10771
0
                                /*AllowAggregateDeductionCandidate=*/true);
10772
0
        }
10773
0
        HasAnyDeductionGuide = true;
10774
0
      }
10775
0
    };
10776
10777
0
    for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) {
10778
0
      NamedDecl *D = (*I)->getUnderlyingDecl();
10779
0
      if (D->isInvalidDecl())
10780
0
        continue;
10781
10782
0
      auto *TD = dyn_cast<FunctionTemplateDecl>(D);
10783
0
      auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>(
10784
0
          TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(D));
10785
0
      if (!GD)
10786
0
        continue;
10787
10788
0
      if (!GD->isImplicit())
10789
0
        HasAnyDeductionGuide = true;
10790
10791
0
      addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors,
10792
0
                            /*AllowAggregateDeductionCandidate=*/false);
10793
0
    }
10794
10795
    // C++ [over.match.class.deduct]p1.4:
10796
    //   if C is defined and its definition satisfies the conditions for an
10797
    //   aggregate class ([dcl.init.aggr]) with the assumption that any
10798
    //   dependent base class has no virtual functions and no virtual base
10799
    //   classes, and the initializer is a non-empty braced-init-list or
10800
    //   parenthesized expression-list, and there are no deduction-guides for
10801
    //   C, the set contains an additional function template, called the
10802
    //   aggregate deduction candidate, defined as follows.
10803
0
    if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) {
10804
0
      if (ListInit && ListInit->getNumInits()) {
10805
0
        SynthesizeAggrGuide(ListInit);
10806
0
      } else if (Inits.size()) { // parenthesized expression-list
10807
        // Inits are expressions inside the parentheses. We don't have
10808
        // the parentheses source locations, use the begin/end of Inits as the
10809
        // best heuristic.
10810
0
        InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(),
10811
0
                                  Inits, Inits.back()->getEndLoc());
10812
0
        SynthesizeAggrGuide(&TempListInit);
10813
0
      }
10814
0
    }
10815
10816
0
    FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide;
10817
10818
0
    return Candidates.BestViableFunction(*this, Kind.getLocation(), Best);
10819
0
  };
10820
10821
0
  OverloadingResult Result = OR_No_Viable_Function;
10822
10823
  // C++11 [over.match.list]p1, per DR1467: for list-initialization, first
10824
  // try initializer-list constructors.
10825
0
  if (ListInit) {
10826
0
    bool TryListConstructors = true;
10827
10828
    // Try list constructors unless the list is empty and the class has one or
10829
    // more default constructors, in which case those constructors win.
10830
0
    if (!ListInit->getNumInits()) {
10831
0
      for (NamedDecl *D : Guides) {
10832
0
        auto *FD = dyn_cast<FunctionDecl>(D->getUnderlyingDecl());
10833
0
        if (FD && FD->getMinRequiredArguments() == 0) {
10834
0
          TryListConstructors = false;
10835
0
          break;
10836
0
        }
10837
0
      }
10838
0
    } else if (ListInit->getNumInits() == 1) {
10839
      // C++ [over.match.class.deduct]:
10840
      //   As an exception, the first phase in [over.match.list] (considering
10841
      //   initializer-list constructors) is omitted if the initializer list
10842
      //   consists of a single expression of type cv U, where U is a
10843
      //   specialization of C or a class derived from a specialization of C.
10844
0
      Expr *E = ListInit->getInit(0);
10845
0
      auto *RD = E->getType()->getAsCXXRecordDecl();
10846
0
      if (!isa<InitListExpr>(E) && RD &&
10847
0
          isCompleteType(Kind.getLocation(), E->getType()) &&
10848
0
          isOrIsDerivedFromSpecializationOf(RD, Template))
10849
0
        TryListConstructors = false;
10850
0
    }
10851
10852
0
    if (TryListConstructors)
10853
0
      Result = TryToResolveOverload(/*OnlyListConstructor*/true);
10854
    // Then unwrap the initializer list and try again considering all
10855
    // constructors.
10856
0
    Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits());
10857
0
  }
10858
10859
  // If list-initialization fails, or if we're doing any other kind of
10860
  // initialization, we (eventually) consider constructors.
10861
0
  if (Result == OR_No_Viable_Function)
10862
0
    Result = TryToResolveOverload(/*OnlyListConstructor*/false);
10863
10864
0
  switch (Result) {
10865
0
  case OR_Ambiguous:
10866
    // FIXME: For list-initialization candidates, it'd usually be better to
10867
    // list why they were not viable when given the initializer list itself as
10868
    // an argument.
10869
0
    Candidates.NoteCandidates(
10870
0
        PartialDiagnosticAt(
10871
0
            Kind.getLocation(),
10872
0
            PDiag(diag::err_deduced_class_template_ctor_ambiguous)
10873
0
                << TemplateName),
10874
0
        *this, OCD_AmbiguousCandidates, Inits);
10875
0
    return QualType();
10876
10877
0
  case OR_No_Viable_Function: {
10878
0
    CXXRecordDecl *Primary =
10879
0
        cast<ClassTemplateDecl>(Template)->getTemplatedDecl();
10880
0
    bool Complete =
10881
0
        isCompleteType(Kind.getLocation(), Context.getTypeDeclType(Primary));
10882
0
    Candidates.NoteCandidates(
10883
0
        PartialDiagnosticAt(
10884
0
            Kind.getLocation(),
10885
0
            PDiag(Complete ? diag::err_deduced_class_template_ctor_no_viable
10886
0
                           : diag::err_deduced_class_template_incomplete)
10887
0
                << TemplateName << !Guides.empty()),
10888
0
        *this, OCD_AllCandidates, Inits);
10889
0
    return QualType();
10890
0
  }
10891
10892
0
  case OR_Deleted: {
10893
0
    Diag(Kind.getLocation(), diag::err_deduced_class_template_deleted)
10894
0
      << TemplateName;
10895
0
    NoteDeletedFunction(Best->Function);
10896
0
    return QualType();
10897
0
  }
10898
10899
0
  case OR_Success:
10900
    // C++ [over.match.list]p1:
10901
    //   In copy-list-initialization, if an explicit constructor is chosen, the
10902
    //   initialization is ill-formed.
10903
0
    if (Kind.isCopyInit() && ListInit &&
10904
0
        cast<CXXDeductionGuideDecl>(Best->Function)->isExplicit()) {
10905
0
      bool IsDeductionGuide = !Best->Function->isImplicit();
10906
0
      Diag(Kind.getLocation(), diag::err_deduced_class_template_explicit)
10907
0
          << TemplateName << IsDeductionGuide;
10908
0
      Diag(Best->Function->getLocation(),
10909
0
           diag::note_explicit_ctor_deduction_guide_here)
10910
0
          << IsDeductionGuide;
10911
0
      return QualType();
10912
0
    }
10913
10914
    // Make sure we didn't select an unusable deduction guide, and mark it
10915
    // as referenced.
10916
0
    DiagnoseUseOfDecl(Best->FoundDecl, Kind.getLocation());
10917
0
    MarkFunctionReferenced(Kind.getLocation(), Best->Function);
10918
0
    break;
10919
0
  }
10920
10921
  // C++ [dcl.type.class.deduct]p1:
10922
  //  The placeholder is replaced by the return type of the function selected
10923
  //  by overload resolution for class template deduction.
10924
0
  QualType DeducedType =
10925
0
      SubstAutoType(TSInfo->getType(), Best->Function->getReturnType());
10926
0
  Diag(TSInfo->getTypeLoc().getBeginLoc(),
10927
0
       diag::warn_cxx14_compat_class_template_argument_deduction)
10928
0
      << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType;
10929
10930
  // Warn if CTAD was used on a type that does not have any user-defined
10931
  // deduction guides.
10932
0
  if (!FoundDeductionGuide) {
10933
0
    Diag(TSInfo->getTypeLoc().getBeginLoc(),
10934
0
         diag::warn_ctad_maybe_unsupported)
10935
0
        << TemplateName;
10936
0
    Diag(Template->getLocation(), diag::note_suppress_ctad_maybe_unsupported);
10937
0
  }
10938
10939
0
  return DeducedType;
10940
0
}