Coverage Report

Created: 2022-01-25 06:29

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
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 C++ declarations.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTConsumer.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/ASTLambda.h"
16
#include "clang/AST/ASTMutationListener.h"
17
#include "clang/AST/CXXInheritance.h"
18
#include "clang/AST/CharUnits.h"
19
#include "clang/AST/ComparisonCategories.h"
20
#include "clang/AST/EvaluatedExprVisitor.h"
21
#include "clang/AST/ExprCXX.h"
22
#include "clang/AST/RecordLayout.h"
23
#include "clang/AST/RecursiveASTVisitor.h"
24
#include "clang/AST/StmtVisitor.h"
25
#include "clang/AST/TypeLoc.h"
26
#include "clang/AST/TypeOrdering.h"
27
#include "clang/Basic/AttributeCommonInfo.h"
28
#include "clang/Basic/PartialDiagnostic.h"
29
#include "clang/Basic/Specifiers.h"
30
#include "clang/Basic/TargetInfo.h"
31
#include "clang/Lex/LiteralSupport.h"
32
#include "clang/Lex/Preprocessor.h"
33
#include "clang/Sema/CXXFieldCollector.h"
34
#include "clang/Sema/DeclSpec.h"
35
#include "clang/Sema/Initialization.h"
36
#include "clang/Sema/Lookup.h"
37
#include "clang/Sema/ParsedTemplate.h"
38
#include "clang/Sema/Scope.h"
39
#include "clang/Sema/ScopeInfo.h"
40
#include "clang/Sema/SemaInternal.h"
41
#include "clang/Sema/Template.h"
42
#include "llvm/ADT/ScopeExit.h"
43
#include "llvm/ADT/SmallString.h"
44
#include "llvm/ADT/STLExtras.h"
45
#include "llvm/ADT/StringExtras.h"
46
#include <map>
47
#include <set>
48
49
using namespace clang;
50
51
//===----------------------------------------------------------------------===//
52
// CheckDefaultArgumentVisitor
53
//===----------------------------------------------------------------------===//
54
55
namespace {
56
/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
57
/// the default argument of a parameter to determine whether it
58
/// contains any ill-formed subexpressions. For example, this will
59
/// diagnose the use of local variables or parameters within the
60
/// default argument expression.
61
class CheckDefaultArgumentVisitor
62
    : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
63
  Sema &S;
64
  const Expr *DefaultArg;
65
66
public:
67
  CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
68
80.9k
      : S(S), DefaultArg(DefaultArg) {}
69
70
  bool VisitExpr(const Expr *Node);
71
  bool VisitDeclRefExpr(const DeclRefExpr *DRE);
72
  bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
73
  bool VisitLambdaExpr(const LambdaExpr *Lambda);
74
  bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
75
};
76
77
/// VisitExpr - Visit all of the children of this expression.
78
85.7k
bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
79
85.7k
  bool IsInvalid = false;
80
85.7k
  for (const Stmt *SubStmt : Node->children())
81
34.5k
    IsInvalid |= Visit(SubStmt);
82
85.7k
  return IsInvalid;
83
85.7k
}
84
85
/// VisitDeclRefExpr - Visit a reference to a declaration, to
86
/// determine whether this declaration can be used in the default
87
/// argument expression.
88
29.4k
bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
89
29.4k
  const NamedDecl *Decl = DRE->getDecl();
90
29.4k
  if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
91
    // C++ [dcl.fct.default]p9:
92
    //   [...] parameters of a function shall not be used in default
93
    //   argument expressions, even if they are not evaluated. [...]
94
    //
95
    // C++17 [dcl.fct.default]p9 (by CWG 2082):
96
    //   [...] A parameter shall not appear as a potentially-evaluated
97
    //   expression in a default argument. [...]
98
    //
99
19
    if (DRE->isNonOdrUse() != NOUR_Unevaluated)
100
13
      return S.Diag(DRE->getBeginLoc(),
101
13
                    diag::err_param_default_argument_references_param)
102
13
             << Param->getDeclName() << DefaultArg->getSourceRange();
103
29.3k
  } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
104
    // C++ [dcl.fct.default]p7:
105
    //   Local variables shall not be used in default argument
106
    //   expressions.
107
    //
108
    // C++17 [dcl.fct.default]p7 (by CWG 2082):
109
    //   A local variable shall not appear as a potentially-evaluated
110
    //   expression in a default argument.
111
    //
112
    // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
113
    //   Note: A local variable cannot be odr-used (6.3) in a default argument.
114
    //
115
12.7k
    if (VDecl->isLocalVarDecl() && 
!DRE->isNonOdrUse()13
)
116
5
      return S.Diag(DRE->getBeginLoc(),
117
5
                    diag::err_param_default_argument_references_local)
118
5
             << VDecl->getDeclName() << DefaultArg->getSourceRange();
119
12.7k
  }
120
121
29.3k
  return false;
122
29.4k
}
123
124
/// VisitCXXThisExpr - Visit a C++ "this" expression.
125
7
bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
126
  // C++ [dcl.fct.default]p8:
127
  //   The keyword this shall not be used in a default argument of a
128
  //   member function.
129
7
  return S.Diag(ThisE->getBeginLoc(),
130
7
                diag::err_param_default_argument_references_this)
131
7
         << ThisE->getSourceRange();
132
7
}
133
134
bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
135
1
    const PseudoObjectExpr *POE) {
136
1
  bool Invalid = false;
137
2
  for (const Expr *E : POE->semantics()) {
138
    // Look through bindings.
139
2
    if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
140
1
      E = OVE->getSourceExpr();
141
1
      assert(E && "pseudo-object binding without source expression?");
142
1
    }
143
144
0
    Invalid |= Visit(E);
145
2
  }
146
1
  return Invalid;
147
1
}
148
149
324
bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
150
  // C++11 [expr.lambda.prim]p13:
151
  //   A lambda-expression appearing in a default argument shall not
152
  //   implicitly or explicitly capture any entity.
153
324
  if (Lambda->capture_begin() == Lambda->capture_end())
154
321
    return false;
155
156
3
  return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
157
324
}
158
} // namespace
159
160
void
161
Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
162
66.0k
                                                 const CXXMethodDecl *Method) {
163
  // If we have an MSAny spec already, don't bother.
164
66.0k
  if (!Method || ComputedEST == EST_MSAny)
165
0
    return;
166
167
66.0k
  const FunctionProtoType *Proto
168
66.0k
    = Method->getType()->getAs<FunctionProtoType>();
169
66.0k
  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
170
66.0k
  if (!Proto)
171
1
    return;
172
173
66.0k
  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
174
175
  // If we have a throw-all spec at this point, ignore the function.
176
66.0k
  if (ComputedEST == EST_None)
177
408
    return;
178
179
65.6k
  if (EST == EST_None && 
Method->hasAttr<NoThrowAttr>()1.47k
)
180
0
    EST = EST_BasicNoexcept;
181
182
65.6k
  switch (EST) {
183
0
  case EST_Unparsed:
184
0
  case EST_Uninstantiated:
185
0
  case EST_Unevaluated:
186
0
    llvm_unreachable("should not see unresolved exception specs here");
187
188
  // If this function can throw any exceptions, make a note of that.
189
0
  case EST_MSAny:
190
1.47k
  case EST_None:
191
    // FIXME: Whichever we see last of MSAny and None determines our result.
192
    // We should make a consistent, order-independent choice here.
193
1.47k
    ClearExceptions();
194
1.47k
    ComputedEST = EST;
195
1.47k
    return;
196
281
  case EST_NoexceptFalse:
197
281
    ClearExceptions();
198
281
    ComputedEST = EST_None;
199
281
    return;
200
  // FIXME: If the call to this decl is using any of its default arguments, we
201
  // need to search them for potentially-throwing calls.
202
  // If this function has a basic noexcept, it doesn't affect the outcome.
203
63.1k
  case EST_BasicNoexcept:
204
63.2k
  case EST_NoexceptTrue:
205
63.2k
  case EST_NoThrow:
206
63.2k
    return;
207
  // If we're still at noexcept(true) and there's a throw() callee,
208
  // change to that specification.
209
660
  case EST_DynamicNone:
210
660
    if (ComputedEST == EST_BasicNoexcept)
211
18
      ComputedEST = EST_DynamicNone;
212
660
    return;
213
0
  case EST_DependentNoexcept:
214
0
    llvm_unreachable(
215
0
        "should not generate implicit declarations for dependent cases");
216
24
  case EST_Dynamic:
217
24
    break;
218
65.6k
  }
219
24
  assert(EST == EST_Dynamic && "EST case not considered earlier.");
220
0
  assert(ComputedEST != EST_None &&
221
24
         "Shouldn't collect exceptions when throw-all is guaranteed.");
222
0
  ComputedEST = EST_Dynamic;
223
  // Record the exceptions in this function's exception specification.
224
24
  for (const auto &E : Proto->exceptions())
225
24
    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
226
24
      Exceptions.push_back(E);
227
24
}
228
229
1.34k
void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
230
1.34k
  if (!S || ComputedEST == EST_MSAny)
231
0
    return;
232
233
  // FIXME:
234
  //
235
  // C++0x [except.spec]p14:
236
  //   [An] implicit exception-specification specifies the type-id T if and
237
  // only if T is allowed by the exception-specification of a function directly
238
  // invoked by f's implicit definition; f shall allow all exceptions if any
239
  // function it directly invokes allows all exceptions, and f shall allow no
240
  // exceptions if every function it directly invokes allows no exceptions.
241
  //
242
  // Note in particular that if an implicit exception-specification is generated
243
  // for a function containing a throw-expression, that specification can still
244
  // be noexcept(true).
245
  //
246
  // Note also that 'directly invoked' is not defined in the standard, and there
247
  // is no indication that we should only consider potentially-evaluated calls.
248
  //
249
  // Ultimately we should implement the intent of the standard: the exception
250
  // specification should be the set of exceptions which can be thrown by the
251
  // implicit definition. For now, we assume that any non-nothrow expression can
252
  // throw any exception.
253
254
1.34k
  if (Self->canThrow(S))
255
275
    ComputedEST = EST_None;
256
1.34k
}
257
258
ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
259
81.0k
                                             SourceLocation EqualLoc) {
260
81.0k
  if (RequireCompleteType(Param->getLocation(), Param->getType(),
261
81.0k
                          diag::err_typecheck_decl_incomplete_type))
262
18
    return true;
263
264
  // C++ [dcl.fct.default]p5
265
  //   A default argument expression is implicitly converted (clause
266
  //   4) to the parameter type. The default argument expression has
267
  //   the same semantic constraints as the initializer expression in
268
  //   a declaration of a variable of the parameter type, using the
269
  //   copy-initialization semantics (8.5).
270
80.9k
  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
271
80.9k
                                                                    Param);
272
80.9k
  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273
80.9k
                                                           EqualLoc);
274
80.9k
  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275
80.9k
  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276
80.9k
  if (Result.isInvalid())
277
36
    return true;
278
80.9k
  Arg = Result.getAs<Expr>();
279
280
80.9k
  CheckCompletedExpr(Arg, EqualLoc);
281
80.9k
  Arg = MaybeCreateExprWithCleanups(Arg);
282
283
80.9k
  return Arg;
284
80.9k
}
285
286
void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287
80.9k
                                   SourceLocation EqualLoc) {
288
  // Add the default argument to the parameter
289
80.9k
  Param->setDefaultArg(Arg);
290
291
  // We have already instantiated this parameter; provide each of the
292
  // instantiations with the uninstantiated default argument.
293
80.9k
  UnparsedDefaultArgInstantiationsMap::iterator InstPos
294
80.9k
    = UnparsedDefaultArgInstantiations.find(Param);
295
80.9k
  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296
14
    for (unsigned I = 0, N = InstPos->second.size(); I != N; 
++I9
)
297
9
      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298
299
    // We're done tracking this parameter's instantiations.
300
5
    UnparsedDefaultArgInstantiations.erase(InstPos);
301
5
  }
302
80.9k
}
303
304
/// ActOnParamDefaultArgument - Check whether the default argument
305
/// provided for a function parameter is well-formed. If so, attach it
306
/// to the parameter declaration.
307
void
308
Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
309
80.9k
                                Expr *DefaultArg) {
310
80.9k
  if (!param || !DefaultArg)
311
0
    return;
312
313
80.9k
  ParmVarDecl *Param = cast<ParmVarDecl>(param);
314
80.9k
  UnparsedDefaultArgLocs.erase(Param);
315
316
80.9k
  auto Fail = [&] {
317
101
    Param->setInvalidDecl();
318
101
    Param->setDefaultArg(new (Context) OpaqueValueExpr(
319
101
        EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
320
101
  };
321
322
  // Default arguments are only permitted in C++
323
80.9k
  if (!getLangOpts().CPlusPlus) {
324
1
    Diag(EqualLoc, diag::err_param_default_argument)
325
1
      << DefaultArg->getSourceRange();
326
1
    return Fail();
327
1
  }
328
329
  // Check for unexpanded parameter packs.
330
80.9k
  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331
26
    return Fail();
332
26
  }
333
334
  // C++11 [dcl.fct.default]p3
335
  //   A default argument expression [...] shall not be specified for a
336
  //   parameter pack.
337
80.9k
  if (Param->isParameterPack()) {
338
1
    Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339
1
        << DefaultArg->getSourceRange();
340
    // Recover by discarding the default argument.
341
1
    Param->setDefaultArg(nullptr);
342
1
    return;
343
1
  }
344
345
80.9k
  ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346
80.9k
  if (Result.isInvalid())
347
47
    return Fail();
348
349
80.9k
  DefaultArg = Result.getAs<Expr>();
350
351
  // Check that the default argument is well-formed
352
80.9k
  CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353
80.9k
  if (DefaultArgChecker.Visit(DefaultArg))
354
27
    return Fail();
355
356
80.8k
  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357
80.8k
}
358
359
/// ActOnParamUnparsedDefaultArgument - We've seen a default
360
/// argument for a function parameter, but we can't parse it yet
361
/// because we're inside a class definition. Note that this default
362
/// argument will be parsed later.
363
void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364
                                             SourceLocation EqualLoc,
365
66.2k
                                             SourceLocation ArgLoc) {
366
66.2k
  if (!param)
367
0
    return;
368
369
66.2k
  ParmVarDecl *Param = cast<ParmVarDecl>(param);
370
66.2k
  Param->setUnparsedDefaultArg();
371
66.2k
  UnparsedDefaultArgLocs[Param] = ArgLoc;
372
66.2k
}
373
374
/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375
/// the default argument for the parameter param failed.
376
void Sema::ActOnParamDefaultArgumentError(Decl *param,
377
296
                                          SourceLocation EqualLoc) {
378
296
  if (!param)
379
0
    return;
380
381
296
  ParmVarDecl *Param = cast<ParmVarDecl>(param);
382
296
  Param->setInvalidDecl();
383
296
  UnparsedDefaultArgLocs.erase(Param);
384
296
  Param->setDefaultArg(new (Context) OpaqueValueExpr(
385
296
      EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
386
296
}
387
388
/// CheckExtraCXXDefaultArguments - Check for any extra default
389
/// arguments in the declarator, which is not a function declaration
390
/// or definition and therefore is not permitted to have default
391
/// arguments. This routine should be invoked for every declarator
392
/// that is not a function declaration or definition.
393
45.8M
void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
394
  // C++ [dcl.fct.default]p3
395
  //   A default argument expression shall be specified only in the
396
  //   parameter-declaration-clause of a function declaration or in a
397
  //   template-parameter (14.1). It shall not be specified for a
398
  //   parameter pack. If it is specified in a
399
  //   parameter-declaration-clause, it shall not occur within a
400
  //   declarator or abstract-declarator of a parameter-declaration.
401
45.8M
  bool MightBeFunction = D.isFunctionDeclarationContext();
402
61.0M
  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; 
++i15.1M
) {
403
15.1M
    DeclaratorChunk &chunk = D.getTypeObject(i);
404
15.1M
    if (chunk.Kind == DeclaratorChunk::Function) {
405
10.5M
      if (MightBeFunction) {
406
        // This is a function declaration. It can have default arguments, but
407
        // keep looking in case its return type is a function type with default
408
        // arguments.
409
10.3M
        MightBeFunction = false;
410
10.3M
        continue;
411
10.3M
      }
412
409k
      
for (unsigned argIdx = 0, e = chunk.Fun.NumParams; 156k
argIdx != e;
413
252k
           ++argIdx) {
414
252k
        ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
415
252k
        if (Param->hasUnparsedDefaultArg()) {
416
3
          std::unique_ptr<CachedTokens> Toks =
417
3
              std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
418
3
          SourceRange SR;
419
3
          if (Toks->size() > 1)
420
2
            SR = SourceRange((*Toks)[1].getLocation(),
421
2
                             Toks->back().getLocation());
422
1
          else
423
1
            SR = UnparsedDefaultArgLocs[Param];
424
3
          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
425
3
            << SR;
426
252k
        } else if (Param->getDefaultArg()) {
427
10
          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
428
10
            << Param->getDefaultArg()->getSourceRange();
429
10
          Param->setDefaultArg(nullptr);
430
10
        }
431
252k
      }
432
4.59M
    } else if (chunk.Kind != DeclaratorChunk::Paren) {
433
4.46M
      MightBeFunction = false;
434
4.46M
    }
435
15.1M
  }
436
45.8M
}
437
438
28.8k
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
439
54.3k
  return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
440
54.3k
    return P->hasDefaultArg() && 
!P->hasInheritedDefaultArg()56
;
441
54.3k
  });
442
28.8k
}
443
444
/// MergeCXXFunctionDecl - Merge two declarations of the same C++
445
/// function, once we already know that they have the same
446
/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
447
/// error, false otherwise.
448
bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
449
217k
                                Scope *S) {
450
217k
  bool Invalid = false;
451
452
  // The declaration context corresponding to the scope is the semantic
453
  // parent, unless this is a local function declaration, in which case
454
  // it is that surrounding function.
455
217k
  DeclContext *ScopeDC = New->isLocalExternDecl()
456
217k
                             ? 
New->getLexicalDeclContext()221
457
217k
                             : 
New->getDeclContext()217k
;
458
459
  // Find the previous declaration for the purpose of default arguments.
460
217k
  FunctionDecl *PrevForDefaultArgs = Old;
461
218k
  for (/**/; PrevForDefaultArgs;
462
       // Don't bother looking back past the latest decl if this is a local
463
       // extern declaration; nothing else could work.
464
217k
       
PrevForDefaultArgs = 580
New->isLocalExternDecl()580
465
580
                                ? 
nullptr181
466
217k
                                : 
PrevForDefaultArgs->getPreviousDecl()399
) {
467
    // Ignore hidden declarations.
468
217k
    if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
469
317
      continue;
470
471
217k
    if (S && 
!isDeclInScope(PrevForDefaultArgs, ScopeDC, S)206k
&&
472
217k
        
!New->isCXXClassMember()232
) {
473
      // Ignore default arguments of old decl if they are not in
474
      // the same scope and this is not an out-of-line definition of
475
      // a member function.
476
232
      continue;
477
232
    }
478
479
217k
    if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
480
      // If only one of these is a local function declaration, then they are
481
      // declared in different scopes, even though isDeclInScope may think
482
      // they're in the same scope. (If both are local, the scope check is
483
      // sufficient, and if neither is local, then they are in the same scope.)
484
31
      continue;
485
31
    }
486
487
    // We found the right previous declaration.
488
217k
    break;
489
217k
  }
490
491
  // C++ [dcl.fct.default]p4:
492
  //   For non-template functions, default arguments can be added in
493
  //   later declarations of a function in the same
494
  //   scope. Declarations in different scopes have completely
495
  //   distinct sets of default arguments. That is, declarations in
496
  //   inner scopes do not acquire default arguments from
497
  //   declarations in outer scopes, and vice versa. In a given
498
  //   function declaration, all parameters subsequent to a
499
  //   parameter with a default argument shall have default
500
  //   arguments supplied in this or previous declarations. A
501
  //   default argument shall not be redefined by a later
502
  //   declaration (not even to the same value).
503
  //
504
  // C++ [dcl.fct.default]p6:
505
  //   Except for member functions of class templates, the default arguments
506
  //   in a member function definition that appears outside of the class
507
  //   definition are added to the set of default arguments provided by the
508
  //   member function declaration in the class definition.
509
217k
  for (unsigned p = 0, NumParams = PrevForDefaultArgs
510
217k
                                       ? 
PrevForDefaultArgs->getNumParams()217k
511
217k
                                       : 
0418
;
512
563k
       p < NumParams; 
++p346k
) {
513
346k
    ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
514
346k
    ParmVarDecl *NewParam = New->getParamDecl(p);
515
516
346k
    bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : 
false0
;
517
346k
    bool NewParamHasDfl = NewParam->hasDefaultArg();
518
519
346k
    if (OldParamHasDfl && 
NewParamHasDfl21.1k
) {
520
14
      unsigned DiagDefaultParamID =
521
14
        diag::err_param_default_argument_redefinition;
522
523
      // MSVC accepts that default parameters be redefined for member functions
524
      // of template class. The new default parameter's value is ignored.
525
14
      Invalid = true;
526
14
      if (getLangOpts().MicrosoftExt) {
527
3
        CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
528
3
        if (MD && MD->getParent()->getDescribedClassTemplate()) {
529
          // Merge the old default argument into the new parameter.
530
3
          NewParam->setHasInheritedDefaultArg();
531
3
          if (OldParam->hasUninstantiatedDefaultArg())
532
0
            NewParam->setUninstantiatedDefaultArg(
533
0
                                      OldParam->getUninstantiatedDefaultArg());
534
3
          else
535
3
            NewParam->setDefaultArg(OldParam->getInit());
536
3
          DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
537
3
          Invalid = false;
538
3
        }
539
3
      }
540
541
      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
542
      // hint here. Alternatively, we could walk the type-source information
543
      // for NewParam to find the last source location in the type... but it
544
      // isn't worth the effort right now. This is the kind of test case that
545
      // is hard to get right:
546
      //   int f(int);
547
      //   void g(int (*fp)(int) = f);
548
      //   void g(int (*fp)(int) = &f);
549
14
      Diag(NewParam->getLocation(), DiagDefaultParamID)
550
14
        << NewParam->getDefaultArgRange();
551
552
      // Look for the function declaration where the default argument was
553
      // actually written, which may be a declaration prior to Old.
554
14
      for (auto Older = PrevForDefaultArgs;
555
16
           OldParam->hasInheritedDefaultArg(); /**/) {
556
2
        Older = Older->getPreviousDecl();
557
2
        OldParam = Older->getParamDecl(p);
558
2
      }
559
560
14
      Diag(OldParam->getLocation(), diag::note_previous_definition)
561
14
        << OldParam->getDefaultArgRange();
562
345k
    } else if (OldParamHasDfl) {
563
      // Merge the old default argument into the new parameter unless the new
564
      // function is a friend declaration in a template class. In the latter
565
      // case the default arguments will be inherited when the friend
566
      // declaration will be instantiated.
567
21.1k
      if (New->getFriendObjectKind() == Decl::FOK_None ||
568
21.1k
          
!New->getLexicalDeclContext()->isDependentContext()343
) {
569
        // It's important to use getInit() here;  getDefaultArg()
570
        // strips off any top-level ExprWithCleanups.
571
21.1k
        NewParam->setHasInheritedDefaultArg();
572
21.1k
        if (OldParam->hasUnparsedDefaultArg())
573
7
          NewParam->setUnparsedDefaultArg();
574
21.1k
        else if (OldParam->hasUninstantiatedDefaultArg())
575
31
          NewParam->setUninstantiatedDefaultArg(
576
31
                                       OldParam->getUninstantiatedDefaultArg());
577
21.1k
        else
578
21.1k
          NewParam->setDefaultArg(OldParam->getInit());
579
21.1k
      }
580
324k
    } else if (NewParamHasDfl) {
581
104
      if (New->getDescribedFunctionTemplate()) {
582
        // Paragraph 4, quoted above, only applies to non-template functions.
583
6
        Diag(NewParam->getLocation(),
584
6
             diag::err_param_default_argument_template_redecl)
585
6
          << NewParam->getDefaultArgRange();
586
6
        Diag(PrevForDefaultArgs->getLocation(),
587
6
             diag::note_template_prev_declaration)
588
6
            << false;
589
98
      } else if (New->getTemplateSpecializationKind()
590
98
                   != TSK_ImplicitInstantiation &&
591
98
                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
592
        // C++ [temp.expr.spec]p21:
593
        //   Default function arguments shall not be specified in a declaration
594
        //   or a definition for one of the following explicit specializations:
595
        //     - the explicit specialization of a function template;
596
        //     - the explicit specialization of a member function template;
597
        //     - the explicit specialization of a member function of a class
598
        //       template where the class template specialization to which the
599
        //       member function specialization belongs is implicitly
600
        //       instantiated.
601
2
        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
602
2
          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
603
2
          << New->getDeclName()
604
2
          << NewParam->getDefaultArgRange();
605
96
      } else if (New->getDeclContext()->isDependentContext()) {
606
        // C++ [dcl.fct.default]p6 (DR217):
607
        //   Default arguments for a member function of a class template shall
608
        //   be specified on the initial declaration of the member function
609
        //   within the class template.
610
        //
611
        // Reading the tea leaves a bit in DR217 and its reference to DR205
612
        // leads me to the conclusion that one cannot add default function
613
        // arguments for an out-of-line definition of a member function of a
614
        // dependent type.
615
7
        int WhichKind = 2;
616
7
        if (CXXRecordDecl *Record
617
7
              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
618
7
          if (Record->getDescribedClassTemplate())
619
6
            WhichKind = 0;
620
1
          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
621
0
            WhichKind = 1;
622
1
          else
623
1
            WhichKind = 2;
624
7
        }
625
626
7
        Diag(NewParam->getLocation(),
627
7
             diag::err_param_default_argument_member_template_redecl)
628
7
          << WhichKind
629
7
          << NewParam->getDefaultArgRange();
630
7
      }
631
104
    }
632
346k
  }
633
634
  // DR1344: If a default argument is added outside a class definition and that
635
  // default argument makes the function a special member function, the program
636
  // is ill-formed. This can only happen for constructors.
637
217k
  if (isa<CXXConstructorDecl>(New) &&
638
217k
      
New->getMinRequiredArguments() < Old->getMinRequiredArguments()26.3k
) {
639
7
    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
640
7
                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
641
7
    if (NewSM != OldSM) {
642
7
      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
643
7
      assert(NewParam->hasDefaultArg());
644
0
      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
645
7
        << NewParam->getDefaultArgRange() << NewSM;
646
7
      Diag(Old->getLocation(), diag::note_previous_declaration);
647
7
    }
648
7
  }
649
650
0
  const FunctionDecl *Def;
651
  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
652
  // template has a constexpr specifier then all its declarations shall
653
  // contain the constexpr specifier.
654
217k
  if (New->getConstexprKind() != Old->getConstexprKind()) {
655
97
    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
656
97
        << New << static_cast<int>(New->getConstexprKind())
657
97
        << static_cast<int>(Old->getConstexprKind());
658
97
    Diag(Old->getLocation(), diag::note_previous_declaration);
659
97
    Invalid = true;
660
217k
  } else if (!Old->getMostRecentDecl()->isInlined() && 
New->isInlined()174k
&&
661
217k
             
Old->isDefined(Def)61.8k
&&
662
             // If a friend function is inlined but does not have 'inline'
663
             // specifier, it is a definition. Do not report attribute conflict
664
             // in this case, redefinition will be diagnosed later.
665
217k
             
(21
New->isInlineSpecified()21
||
666
21
              
New->getFriendObjectKind() == Decl::FOK_None2
)) {
667
    // C++11 [dcl.fcn.spec]p4:
668
    //   If the definition of a function appears in a translation unit before its
669
    //   first declaration as inline, the program is ill-formed.
670
19
    Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
671
19
    Diag(Def->getLocation(), diag::note_previous_definition);
672
19
    Invalid = true;
673
19
  }
674
675
  // C++17 [temp.deduct.guide]p3:
676
  //   Two deduction guide declarations in the same translation unit
677
  //   for the same class template shall not have equivalent
678
  //   parameter-declaration-clauses.
679
217k
  if (isa<CXXDeductionGuideDecl>(New) &&
680
217k
      
!New->isFunctionTemplateSpecialization()7
&&
isVisible(Old)3
) {
681
2
    Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
682
2
    Diag(Old->getLocation(), diag::note_previous_declaration);
683
2
  }
684
685
  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
686
  // argument expression, that declaration shall be a definition and shall be
687
  // the only declaration of the function or function template in the
688
  // translation unit.
689
217k
  if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
690
217k
      
functionDeclHasDefaultArgument(Old)1.49k
) {
691
6
    Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
692
6
    Diag(Old->getLocation(), diag::note_previous_declaration);
693
6
    Invalid = true;
694
6
  }
695
696
  // C++11 [temp.friend]p4 (DR329):
697
  //   When a function is defined in a friend function declaration in a class
698
  //   template, the function is instantiated when the function is odr-used.
699
  //   The same restrictions on multiple declarations and definitions that
700
  //   apply to non-template function declarations and definitions also apply
701
  //   to these implicit definitions.
702
217k
  const FunctionDecl *OldDefinition = nullptr;
703
217k
  if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
704
217k
      
Old->isDefined(OldDefinition, true)43
)
705
25
    CheckForFunctionRedefinition(New, OldDefinition);
706
707
217k
  return Invalid;
708
217k
}
709
710
NamedDecl *
711
Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
712
384
                                   MultiTemplateParamsArg TemplateParamLists) {
713
384
  assert(D.isDecompositionDeclarator());
714
0
  const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
715
716
  // The syntax only allows a decomposition declarator as a simple-declaration,
717
  // a for-range-declaration, or a condition in Clang, but we parse it in more
718
  // cases than that.
719
384
  if (!D.mayHaveDecompositionDeclarator()) {
720
2
    Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
721
2
      << Decomp.getSourceRange();
722
2
    return nullptr;
723
2
  }
724
725
382
  if (!TemplateParamLists.empty()) {
726
    // FIXME: There's no rule against this, but there are also no rules that
727
    // would actually make it usable, so we reject it for now.
728
2
    Diag(TemplateParamLists.front()->getTemplateLoc(),
729
2
         diag::err_decomp_decl_template);
730
2
    return nullptr;
731
2
  }
732
733
380
  Diag(Decomp.getLSquareLoc(),
734
380
       !getLangOpts().CPlusPlus17
735
380
           ? 
diag::ext_decomp_decl13
736
380
           : 
D.getContext() == DeclaratorContext::Condition367
737
367
                 ? 
diag::ext_decomp_decl_cond30
738
367
                 : 
diag::warn_cxx14_compat_decomp_decl337
)
739
380
      << Decomp.getSourceRange();
740
741
  // The semantic context is always just the current context.
742
380
  DeclContext *const DC = CurContext;
743
744
  // C++17 [dcl.dcl]/8:
745
  //   The decl-specifier-seq shall contain only the type-specifier auto
746
  //   and cv-qualifiers.
747
  // C++2a [dcl.dcl]/8:
748
  //   If decl-specifier-seq contains any decl-specifier other than static,
749
  //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
750
380
  auto &DS = D.getDeclSpec();
751
380
  {
752
380
    SmallVector<StringRef, 8> BadSpecifiers;
753
380
    SmallVector<SourceLocation, 8> BadSpecifierLocs;
754
380
    SmallVector<StringRef, 8> CPlusPlus20Specifiers;
755
380
    SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
756
380
    if (auto SCS = DS.getStorageClassSpec()) {
757
21
      if (SCS == DeclSpec::SCS_static) {
758
16
        CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
759
16
        CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
760
16
      } else {
761
5
        BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
762
5
        BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
763
5
      }
764
21
    }
765
380
    if (auto TSCS = DS.getThreadStorageClassSpec()) {
766
8
      CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
767
8
      CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
768
8
    }
769
380
    if (DS.hasConstexprSpecifier()) {
770
4
      BadSpecifiers.push_back(
771
4
          DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
772
4
      BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
773
4
    }
774
380
    if (DS.isInlineSpecified()) {
775
4
      BadSpecifiers.push_back("inline");
776
4
      BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
777
4
    }
778
380
    if (!BadSpecifiers.empty()) {
779
11
      auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
780
11
      Err << (int)BadSpecifiers.size()
781
11
          << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
782
      // Don't add FixItHints to remove the specifiers; we do still respect
783
      // them when building the underlying variable.
784
11
      for (auto Loc : BadSpecifierLocs)
785
13
        Err << SourceRange(Loc, Loc);
786
369
    } else if (!CPlusPlus20Specifiers.empty()) {
787
16
      auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
788
16
                         getLangOpts().CPlusPlus20
789
16
                             ? 
diag::warn_cxx17_compat_decomp_decl_spec4
790
16
                             : 
diag::ext_decomp_decl_spec12
);
791
16
      Warn << (int)CPlusPlus20Specifiers.size()
792
16
           << llvm::join(CPlusPlus20Specifiers.begin(),
793
16
                         CPlusPlus20Specifiers.end(), " ");
794
16
      for (auto Loc : CPlusPlus20SpecifierLocs)
795
20
        Warn << SourceRange(Loc, Loc);
796
16
    }
797
    // We can't recover from it being declared as a typedef.
798
380
    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
799
2
      return nullptr;
800
380
  }
801
802
  // C++2a [dcl.struct.bind]p1:
803
  //   A cv that includes volatile is deprecated
804
378
  if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
805
378
      
getLangOpts().CPlusPlus205
)
806
1
    Diag(DS.getVolatileSpecLoc(),
807
1
         diag::warn_deprecated_volatile_structured_binding);
808
809
378
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
810
378
  QualType R = TInfo->getType();
811
812
378
  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
813
378
                                      UPPC_DeclarationType))
814
0
    D.setInvalidType();
815
816
  // The syntax only allows a single ref-qualifier prior to the decomposition
817
  // declarator. No other declarator chunks are permitted. Also check the type
818
  // specifier here.
819
378
  if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
820
378
      
D.hasGroupingParens()361
||
D.getNumTypeObjects() > 1361
||
821
378
      
(361
D.getNumTypeObjects() == 1361
&&
822
361
       
D.getTypeObject(0).Kind != DeclaratorChunk::Reference112
)) {
823
23
    Diag(Decomp.getLSquareLoc(),
824
23
         (D.hasGroupingParens() ||
825
23
          (D.getNumTypeObjects() &&
826
23
           
D.getTypeObject(0).Kind == DeclaratorChunk::Paren6
))
827
23
             ? 
diag::err_decomp_decl_parens2
828
23
             : 
diag::err_decomp_decl_type21
)
829
23
        << R;
830
831
    // In most cases, there's no actual problem with an explicitly-specified
832
    // type, but a function type won't work here, and ActOnVariableDeclarator
833
    // shouldn't be called for such a type.
834
23
    if (R->isFunctionType())
835
0
      D.setInvalidType();
836
23
  }
837
838
  // Build the BindingDecls.
839
378
  SmallVector<BindingDecl*, 8> Bindings;
840
841
  // Build the BindingDecls.
842
691
  for (auto &B : D.getDecompositionDeclarator().bindings()) {
843
    // Check for name conflicts.
844
691
    DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
845
691
    LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
846
691
                          ForVisibleRedeclaration);
847
691
    LookupName(Previous, S,
848
691
               /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
849
850
    // It's not permitted to shadow a template parameter name.
851
691
    if (Previous.isSingleResult() &&
852
691
        
Previous.getFoundDecl()->isTemplateParameter()61
) {
853
0
      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
854
0
                                      Previous.getFoundDecl());
855
0
      Previous.clear();
856
0
    }
857
858
691
    auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859
860
    // Find the shadowed declaration before filtering for scope.
861
691
    NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
862
691
                                  ? getShadowedDeclaration(BD, Previous)
863
691
                                  : 
nullptr0
;
864
865
691
    bool ConsiderLinkage = DC->isFunctionOrMethod() &&
866
691
                           
DS.getStorageClassSpec() == DeclSpec::SCS_extern615
;
867
691
    FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
868
691
                         /*AllowInlineNamespace*/false);
869
870
691
    if (!Previous.empty()) {
871
1
      auto *Old = Previous.getRepresentativeDecl();
872
1
      Diag(B.NameLoc, diag::err_redefinition) << B.Name;
873
1
      Diag(Old->getLocation(), diag::note_previous_definition);
874
690
    } else if (ShadowedDecl && 
!D.isRedeclaration()8
) {
875
8
      CheckShadow(BD, ShadowedDecl, Previous);
876
8
    }
877
691
    PushOnScopeChains(BD, S, true);
878
691
    Bindings.push_back(BD);
879
691
    ParsingInitForAutoVars.insert(BD);
880
691
  }
881
882
  // There are no prior lookup results for the variable itself, because it
883
  // is unnamed.
884
378
  DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
885
378
                               Decomp.getLSquareLoc());
886
378
  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
887
378
                        ForVisibleRedeclaration);
888
889
  // Build the variable that holds the non-decomposed object.
890
378
  bool AddToScope = true;
891
378
  NamedDecl *New =
892
378
      ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
893
378
                              MultiTemplateParamsArg(), AddToScope, Bindings);
894
378
  if (AddToScope) {
895
378
    S->AddDecl(New);
896
378
    CurContext->addHiddenDecl(New);
897
378
  }
898
899
378
  if (isInOpenMPDeclareTargetContext())
900
0
    checkDeclIsAllowedInOpenMPTarget(nullptr, New);
901
902
378
  return New;
903
380
}
904
905
static bool checkSimpleDecomposition(
906
    Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
907
    QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
908
86
    llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
909
86
  if ((int64_t)Bindings.size() != NumElems) {
910
7
    S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
911
7
        << DecompType << (unsigned)Bindings.size()
912
7
        << (unsigned)NumElems.getLimitedValue(UINT_MAX)
913
7
        << toString(NumElems, 10) << (NumElems < Bindings.size());
914
7
    return true;
915
7
  }
916
917
79
  unsigned I = 0;
918
170
  for (auto *B : Bindings) {
919
170
    SourceLocation Loc = B->getLocation();
920
170
    ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
921
170
    if (E.isInvalid())
922
0
      return true;
923
170
    E = GetInit(Loc, E.get(), I++);
924
170
    if (E.isInvalid())
925
0
      return true;
926
170
    B->setBinding(ElemType, E.get());
927
170
  }
928
929
79
  return false;
930
79
}
931
932
static bool checkArrayLikeDecomposition(Sema &S,
933
                                        ArrayRef<BindingDecl *> Bindings,
934
                                        ValueDecl *Src, QualType DecompType,
935
                                        const llvm::APSInt &NumElems,
936
83
                                        QualType ElemType) {
937
83
  return checkSimpleDecomposition(
938
83
      S, Bindings, Src, DecompType, NumElems, ElemType,
939
164
      [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
940
164
        ExprResult E = S.ActOnIntegerConstant(Loc, I);
941
164
        if (E.isInvalid())
942
0
          return ExprError();
943
164
        return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
944
164
      });
945
83
}
946
947
static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
948
                                    ValueDecl *Src, QualType DecompType,
949
81
                                    const ConstantArrayType *CAT) {
950
81
  return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
951
81
                                     llvm::APSInt(CAT->getSize()),
952
81
                                     CAT->getElementType());
953
81
}
954
955
static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
956
                                     ValueDecl *Src, QualType DecompType,
957
2
                                     const VectorType *VT) {
958
2
  return checkArrayLikeDecomposition(
959
2
      S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
960
2
      S.Context.getQualifiedType(VT->getElementType(),
961
2
                                 DecompType.getQualifiers()));
962
2
}
963
964
static bool checkComplexDecomposition(Sema &S,
965
                                      ArrayRef<BindingDecl *> Bindings,
966
                                      ValueDecl *Src, QualType DecompType,
967
3
                                      const ComplexType *CT) {
968
3
  return checkSimpleDecomposition(
969
3
      S, Bindings, Src, DecompType, llvm::APSInt::get(2),
970
3
      S.Context.getQualifiedType(CT->getElementType(),
971
3
                                 DecompType.getQualifiers()),
972
6
      [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
973
6
        return S.CreateBuiltinUnaryOp(Loc, I ? 
UO_Imag3
:
UO_Real3
, Base);
974
6
      });
975
3
}
976
977
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
978
                                     TemplateArgumentListInfo &Args,
979
4
                                     const TemplateParameterList *Params) {
980
4
  SmallString<128> SS;
981
4
  llvm::raw_svector_ostream OS(SS);
982
4
  bool First = true;
983
4
  unsigned I = 0;
984
7
  for (auto &Arg : Args.arguments()) {
985
7
    if (!First)
986
3
      OS << ", ";
987
7
    Arg.getArgument().print(PrintingPolicy, OS,
988
7
                            TemplateParameterList::shouldIncludeTypeForArgument(
989
7
                                PrintingPolicy, Params, I));
990
7
    First = false;
991
7
    I++;
992
7
  }
993
4
  return std::string(OS.str());
994
4
}
995
996
static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
997
                                     SourceLocation Loc, StringRef Trait,
998
                                     TemplateArgumentListInfo &Args,
999
346
                                     unsigned DiagID) {
1000
346
  auto DiagnoseMissing = [&] {
1001
171
    if (DiagID)
1002
1
      S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1003
1
                                               Args, /*Params*/ nullptr);
1004
171
    return true;
1005
171
  };
1006
1007
  // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1008
346
  NamespaceDecl *Std = S.getStdNamespace();
1009
346
  if (!Std)
1010
155
    return DiagnoseMissing();
1011
1012
  // Look up the trait itself, within namespace std. We can diagnose various
1013
  // problems with this lookup even if we've been asked to not diagnose a
1014
  // missing specialization, because this can only fail if the user has been
1015
  // declaring their own names in namespace std or we don't support the
1016
  // standard library implementation in use.
1017
191
  LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1018
191
                      Loc, Sema::LookupOrdinaryName);
1019
191
  if (!S.LookupQualifiedName(Result, Std))
1020
16
    return DiagnoseMissing();
1021
175
  if (Result.isAmbiguous())
1022
0
    return true;
1023
1024
175
  ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1025
175
  if (!TraitTD) {
1026
0
    Result.suppressDiagnostics();
1027
0
    NamedDecl *Found = *Result.begin();
1028
0
    S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1029
0
    S.Diag(Found->getLocation(), diag::note_declared_at);
1030
0
    return true;
1031
0
  }
1032
1033
  // Build the template-id.
1034
175
  QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1035
175
  if (TraitTy.isNull())
1036
0
    return true;
1037
175
  if (!S.isCompleteType(Loc, TraitTy)) {
1038
36
    if (DiagID)
1039
2
      S.RequireCompleteType(
1040
2
          Loc, TraitTy, DiagID,
1041
2
          printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1042
2
                            TraitTD->getTemplateParameters()));
1043
36
    return true;
1044
36
  }
1045
1046
139
  CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1047
139
  assert(RD && "specialization of class template is not a class?");
1048
1049
  // Look up the member of the trait type.
1050
0
  S.LookupQualifiedName(TraitMemberLookup, RD);
1051
139
  return TraitMemberLookup.isAmbiguous();
1052
175
}
1053
1054
static TemplateArgumentLoc
1055
getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1056
169
                                   uint64_t I) {
1057
169
  TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1058
169
  return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1059
169
}
1060
1061
static TemplateArgumentLoc
1062
346
getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1063
346
  return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1064
346
}
1065
1066
namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1067
1068
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1069
263
                               llvm::APSInt &Size) {
1070
263
  EnterExpressionEvaluationContext ContextRAII(
1071
263
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1072
1073
263
  DeclarationName Value = S.PP.getIdentifierInfo("value");
1074
263
  LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1075
1076
  // Form template argument list for tuple_size<T>.
1077
263
  TemplateArgumentListInfo Args(Loc, Loc);
1078
263
  Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1079
1080
  // If there's no tuple_size specialization or the lookup of 'value' is empty,
1081
  // it's not tuple-like.
1082
263
  if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1083
263
      
R.empty()59
)
1084
206
    return IsTupleLike::NotTupleLike;
1085
1086
  // If we get this far, we've committed to the tuple interpretation, but
1087
  // we can still fail if there actually isn't a usable ::value.
1088
1089
57
  struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1090
57
    LookupResult &R;
1091
57
    TemplateArgumentListInfo &Args;
1092
57
    ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1093
57
        : R(R), Args(Args) {}
1094
57
    Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1095
57
                                               SourceLocation Loc) override {
1096
1
      return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1097
1
             << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1098
1
                                  /*Params*/ nullptr);
1099
1
    }
1100
57
  } Diagnoser(R, Args);
1101
1102
57
  ExprResult E =
1103
57
      S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1104
57
  if (E.isInvalid())
1105
0
    return IsTupleLike::Error;
1106
1107
57
  E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1108
57
  if (E.isInvalid())
1109
1
    return IsTupleLike::Error;
1110
1111
56
  return IsTupleLike::TupleLike;
1112
57
}
1113
1114
/// \return std::tuple_element<I, T>::type.
1115
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1116
83
                                        unsigned I, QualType T) {
1117
  // Form template argument list for tuple_element<I, T>.
1118
83
  TemplateArgumentListInfo Args(Loc, Loc);
1119
83
  Args.addArgument(
1120
83
      getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1121
83
  Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1122
1123
83
  DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1124
83
  LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1125
83
  if (lookupStdTypeTraitMember(
1126
83
          S, R, Loc, "tuple_element", Args,
1127
83
          diag::err_decomp_decl_std_tuple_element_not_specialized))
1128
3
    return QualType();
1129
1130
80
  auto *TD = R.getAsSingle<TypeDecl>();
1131
80
  if (!TD) {
1132
0
    R.suppressDiagnostics();
1133
0
    S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1134
0
        << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1135
0
                             /*Params*/ nullptr);
1136
0
    if (!R.empty())
1137
0
      S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1138
0
    return QualType();
1139
0
  }
1140
1141
80
  return S.Context.getTypeDeclType(TD);
1142
80
}
1143
1144
namespace {
1145
struct InitializingBinding {
1146
  Sema &S;
1147
86
  InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1148
86
    Sema::CodeSynthesisContext Ctx;
1149
86
    Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1150
86
    Ctx.PointOfInstantiation = BD->getLocation();
1151
86
    Ctx.Entity = BD;
1152
86
    S.pushCodeSynthesisContext(Ctx);
1153
86
  }
1154
86
  ~InitializingBinding() {
1155
86
    S.popCodeSynthesisContext();
1156
86
  }
1157
};
1158
}
1159
1160
static bool checkTupleLikeDecomposition(Sema &S,
1161
                                        ArrayRef<BindingDecl *> Bindings,
1162
                                        VarDecl *Src, QualType DecompType,
1163
56
                                        const llvm::APSInt &TupleSize) {
1164
56
  if ((int64_t)Bindings.size() != TupleSize) {
1165
3
    S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1166
3
        << DecompType << (unsigned)Bindings.size()
1167
3
        << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1168
3
        << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1169
3
    return true;
1170
3
  }
1171
1172
53
  if (Bindings.empty())
1173
0
    return false;
1174
1175
53
  DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1176
1177
  // [dcl.decomp]p3:
1178
  //   The unqualified-id get is looked up in the scope of E by class member
1179
  //   access lookup ...
1180
53
  LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1181
53
  bool UseMemberGet = false;
1182
53
  if (S.isCompleteType(Src->getLocation(), DecompType)) {
1183
53
    if (auto *RD = DecompType->getAsCXXRecordDecl())
1184
53
      S.LookupQualifiedName(MemberGet, RD);
1185
53
    if (MemberGet.isAmbiguous())
1186
1
      return true;
1187
    //   ... and if that finds at least one declaration that is a function
1188
    //   template whose first template parameter is a non-type parameter ...
1189
52
    for (NamedDecl *D : MemberGet) {
1190
35
      if (FunctionTemplateDecl *FTD =
1191
35
              dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1192
31
        TemplateParameterList *TPL = FTD->getTemplateParameters();
1193
31
        if (TPL->size() != 0 &&
1194
31
            isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1195
          //   ... the initializer is e.get<i>().
1196
29
          UseMemberGet = true;
1197
29
          break;
1198
29
        }
1199
31
      }
1200
35
    }
1201
52
  }
1202
1203
52
  unsigned I = 0;
1204
86
  for (auto *B : Bindings) {
1205
86
    InitializingBinding InitContext(S, B);
1206
86
    SourceLocation Loc = B->getLocation();
1207
1208
86
    ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1209
86
    if (E.isInvalid())
1210
0
      return true;
1211
1212
    //   e is an lvalue if the type of the entity is an lvalue reference and
1213
    //   an xvalue otherwise
1214
86
    if (!Src->getType()->isLValueReferenceType())
1215
66
      E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1216
66
                                   E.get(), nullptr, VK_XValue,
1217
66
                                   FPOptionsOverride());
1218
1219
86
    TemplateArgumentListInfo Args(Loc, Loc);
1220
86
    Args.addArgument(
1221
86
        getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1222
1223
86
    if (UseMemberGet) {
1224
      //   if [lookup of member get] finds at least one declaration, the
1225
      //   initializer is e.get<i-1>().
1226
37
      E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1227
37
                                     CXXScopeSpec(), SourceLocation(), nullptr,
1228
37
                                     MemberGet, &Args, nullptr);
1229
37
      if (E.isInvalid())
1230
0
        return true;
1231
1232
37
      E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1233
49
    } else {
1234
      //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1235
      //   in the associated namespaces.
1236
49
      Expr *Get = UnresolvedLookupExpr::Create(
1237
49
          S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1238
49
          DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1239
49
          UnresolvedSetIterator(), UnresolvedSetIterator());
1240
1241
49
      Expr *Arg = E.get();
1242
49
      E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1243
49
    }
1244
86
    if (E.isInvalid())
1245
3
      return true;
1246
83
    Expr *Init = E.get();
1247
1248
    //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1249
83
    QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1250
83
    if (T.isNull())
1251
3
      return true;
1252
1253
    //   each vi is a variable of type "reference to T" initialized with the
1254
    //   initializer, where the reference is an lvalue reference if the
1255
    //   initializer is an lvalue and an rvalue reference otherwise
1256
80
    QualType RefType =
1257
80
        S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1258
80
    if (RefType.isNull())
1259
0
      return true;
1260
80
    auto *RefVD = VarDecl::Create(
1261
80
        S.Context, Src->getDeclContext(), Loc, Loc,
1262
80
        B->getDeclName().getAsIdentifierInfo(), RefType,
1263
80
        S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1264
80
    RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1265
80
    RefVD->setTSCSpec(Src->getTSCSpec());
1266
80
    RefVD->setImplicit();
1267
80
    if (Src->isInlineSpecified())
1268
0
      RefVD->setInlineSpecified();
1269
80
    RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1270
1271
80
    InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1272
80
    InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1273
80
    InitializationSequence Seq(S, Entity, Kind, Init);
1274
80
    E = Seq.Perform(S, Entity, Kind, Init);
1275
80
    if (E.isInvalid())
1276
2
      return true;
1277
78
    E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1278
78
    if (E.isInvalid())
1279
0
      return true;
1280
78
    RefVD->setInit(E.get());
1281
78
    S.CheckCompleteVariableDeclaration(RefVD);
1282
1283
78
    E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1284
78
                                   DeclarationNameInfo(B->getDeclName(), Loc),
1285
78
                                   RefVD);
1286
78
    if (E.isInvalid())
1287
0
      return true;
1288
1289
78
    B->setBinding(T, E.get());
1290
78
    I++;
1291
78
  }
1292
1293
44
  return false;
1294
52
}
1295
1296
/// Find the base class to decompose in a built-in decomposition of a class type.
1297
/// This base class search is, unfortunately, not quite like any other that we
1298
/// perform anywhere else in C++.
1299
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1300
                                                const CXXRecordDecl *RD,
1301
199
                                                CXXCastPath &BasePath) {
1302
199
  auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1303
199
                          CXXBasePath &Path) {
1304
33
    return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1305
33
  };
1306
1307
199
  const CXXRecordDecl *ClassWithFields = nullptr;
1308
199
  AccessSpecifier AS = AS_public;
1309
199
  if (RD->hasDirectFields())
1310
    // [dcl.decomp]p4:
1311
    //   Otherwise, all of E's non-static data members shall be public direct
1312
    //   members of E ...
1313
174
    ClassWithFields = RD;
1314
25
  else {
1315
    //   ... or of ...
1316
25
    CXXBasePaths Paths;
1317
25
    Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1318
25
    if (!RD->lookupInBases(BaseHasFields, Paths)) {
1319
      // If no classes have fields, just decompose RD itself. (This will work
1320
      // if and only if zero bindings were provided.)
1321
7
      return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1322
7
    }
1323
1324
18
    CXXBasePath *BestPath = nullptr;
1325
22
    for (auto &P : Paths) {
1326
22
      if (!BestPath)
1327
18
        BestPath = &P;
1328
4
      else if (!S.Context.hasSameType(P.back().Base->getType(),
1329
4
                                      BestPath->back().Base->getType())) {
1330
        //   ... the same ...
1331
1
        S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1332
1
          << false << RD << BestPath->back().Base->getType()
1333
1
          << P.back().Base->getType();
1334
1
        return DeclAccessPair();
1335
3
      } else if (P.Access < BestPath->Access) {
1336
0
        BestPath = &P;
1337
0
      }
1338
22
    }
1339
1340
    //   ... unambiguous ...
1341
17
    QualType BaseType = BestPath->back().Base->getType();
1342
17
    if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1343
2
      S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1344
2
        << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1345
2
      return DeclAccessPair();
1346
2
    }
1347
1348
    //   ... [accessible, implied by other rules] base class of E.
1349
15
    S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1350
15
                           *BestPath, diag::err_decomp_decl_inaccessible_base);
1351
15
    AS = BestPath->Access;
1352
1353
15
    ClassWithFields = BaseType->getAsCXXRecordDecl();
1354
15
    S.BuildBasePathArray(Paths, BasePath);
1355
15
  }
1356
1357
  // The above search did not check whether the selected class itself has base
1358
  // classes with fields, so check that now.
1359
189
  CXXBasePaths Paths;
1360
189
  if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1361
2
    S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1362
2
      << (ClassWithFields == RD) << RD << ClassWithFields
1363
2
      << Paths.front().back().Base->getType();
1364
2
    return DeclAccessPair();
1365
2
  }
1366
1367
187
  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1368
189
}
1369
1370
static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1371
                                     ValueDecl *Src, QualType DecompType,
1372
199
                                     const CXXRecordDecl *OrigRD) {
1373
199
  if (S.RequireCompleteType(Src->getLocation(), DecompType,
1374
199
                            diag::err_incomplete_type))
1375
0
    return true;
1376
1377
199
  CXXCastPath BasePath;
1378
199
  DeclAccessPair BasePair =
1379
199
      findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1380
199
  const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1381
199
  if (!RD)
1382
5
    return true;
1383
194
  QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1384
194
                                                 DecompType.getQualifiers());
1385
1386
194
  auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1387
8
    unsigned NumFields = llvm::count_if(
1388
10
        RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1389
8
    assert(Bindings.size() != NumFields);
1390
0
    S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1391
8
        << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1392
8
        << (NumFields < Bindings.size());
1393
8
    return true;
1394
8
  };
1395
1396
  //   all of E's non-static data members shall be [...] well-formed
1397
  //   when named as e.name in the context of the structured binding,
1398
  //   E shall not have an anonymous union member, ...
1399
194
  unsigned I = 0;
1400
354
  for (auto *FD : RD->fields()) {
1401
354
    if (FD->isUnnamedBitfield())
1402
2
      continue;
1403
1404
    // All the non-static data members are required to be nameable, so they
1405
    // must all have names.
1406
352
    if (!FD->getDeclName()) {
1407
4
      if (RD->isLambda()) {
1408
2
        S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1409
2
        S.Diag(RD->getLocation(), diag::note_lambda_decl);
1410
2
        return true;
1411
2
      }
1412
1413
2
      if (FD->isAnonymousStructOrUnion()) {
1414
2
        S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1415
2
          << DecompType << FD->getType()->isUnionType();
1416
2
        S.Diag(FD->getLocation(), diag::note_declared_at);
1417
2
        return true;
1418
2
      }
1419
1420
      // FIXME: Are there any other ways we could have an anonymous member?
1421
2
    }
1422
1423
    // We have a real field to bind.
1424
348
    if (I >= Bindings.size())
1425
2
      return DiagnoseBadNumberOfBindings();
1426
346
    auto *B = Bindings[I++];
1427
346
    SourceLocation Loc = B->getLocation();
1428
1429
    // The field must be accessible in the context of the structured binding.
1430
    // We already checked that the base class is accessible.
1431
    // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1432
    // const_cast here.
1433
346
    S.CheckStructuredBindingMemberAccess(
1434
346
        Loc, const_cast<CXXRecordDecl *>(OrigRD),
1435
346
        DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1436
346
                                     BasePair.getAccess(), FD->getAccess())));
1437
1438
    // Initialize the binding to Src.FD.
1439
346
    ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1440
346
    if (E.isInvalid())
1441
0
      return true;
1442
346
    E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1443
346
                            VK_LValue, &BasePath);
1444
346
    if (E.isInvalid())
1445
0
      return true;
1446
346
    E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1447
346
                                  CXXScopeSpec(), FD,
1448
346
                                  DeclAccessPair::make(FD, FD->getAccess()),
1449
346
                                  DeclarationNameInfo(FD->getDeclName(), Loc));
1450
346
    if (E.isInvalid())
1451
0
      return true;
1452
1453
    // If the type of the member is T, the referenced type is cv T, where cv is
1454
    // the cv-qualification of the decomposition expression.
1455
    //
1456
    // FIXME: We resolve a defect here: if the field is mutable, we do not add
1457
    // 'const' to the type of the field.
1458
346
    Qualifiers Q = DecompType.getQualifiers();
1459
346
    if (FD->isMutable())
1460
11
      Q.removeConst();
1461
346
    B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1462
346
  }
1463
1464
188
  if (I != Bindings.size())
1465
6
    return DiagnoseBadNumberOfBindings();
1466
1467
182
  return false;
1468
188
}
1469
1470
368
void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1471
368
  QualType DecompType = DD->getType();
1472
1473
  // If the type of the decomposition is dependent, then so is the type of
1474
  // each binding.
1475
368
  if (DecompType->isDependentType()) {
1476
19
    for (auto *B : DD->bindings())
1477
34
      B->setType(Context.DependentTy);
1478
19
    return;
1479
19
  }
1480
1481
349
  DecompType = DecompType.getNonReferenceType();
1482
349
  ArrayRef<BindingDecl*> Bindings = DD->bindings();
1483
1484
  // C++1z [dcl.decomp]/2:
1485
  //   If E is an array type [...]
1486
  // As an extension, we also support decomposition of built-in complex and
1487
  // vector types.
1488
349
  if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1489
81
    if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1490
7
      DD->setInvalidDecl();
1491
81
    return;
1492
81
  }
1493
268
  if (auto *VT = DecompType->getAs<VectorType>()) {
1494
2
    if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1495
0
      DD->setInvalidDecl();
1496
2
    return;
1497
2
  }
1498
266
  if (auto *CT = DecompType->getAs<ComplexType>()) {
1499
3
    if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1500
0
      DD->setInvalidDecl();
1501
3
    return;
1502
3
  }
1503
1504
  // C++1z [dcl.decomp]/3:
1505
  //   if the expression std::tuple_size<E>::value is a well-formed integral
1506
  //   constant expression, [...]
1507
263
  llvm::APSInt TupleSize(32);
1508
263
  switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1509
1
  case IsTupleLike::Error:
1510
1
    DD->setInvalidDecl();
1511
1
    return;
1512
1513
56
  case IsTupleLike::TupleLike:
1514
56
    if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1515
12
      DD->setInvalidDecl();
1516
56
    return;
1517
1518
206
  case IsTupleLike::NotTupleLike:
1519
206
    break;
1520
263
  }
1521
1522
  // C++1z [dcl.dcl]/8:
1523
  //   [E shall be of array or non-union class type]
1524
206
  CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1525
206
  if (!RD || 
RD->isUnion()199
) {
1526
7
    Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1527
7
        << DD << !RD << DecompType;
1528
7
    DD->setInvalidDecl();
1529
7
    return;
1530
7
  }
1531
1532
  // C++1z [dcl.decomp]/4:
1533
  //   all of E's non-static data members shall be [...] direct members of
1534
  //   E or of the same unambiguous public base class of E, ...
1535
199
  if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1536
17
    DD->setInvalidDecl();
1537
199
}
1538
1539
/// Merge the exception specifications of two variable declarations.
1540
///
1541
/// This is called when there's a redeclaration of a VarDecl. The function
1542
/// checks if the redeclaration might have an exception specification and
1543
/// validates compatibility and merges the specs if necessary.
1544
61.2k
void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1545
  // Shortcut if exceptions are disabled.
1546
61.2k
  if (!getLangOpts().CXXExceptions)
1547
4.99k
    return;
1548
1549
56.2k
  assert(Context.hasSameType(New->getType(), Old->getType()) &&
1550
56.2k
         "Should only be called if types are otherwise the same.");
1551
1552
0
  QualType NewType = New->getType();
1553
56.2k
  QualType OldType = Old->getType();
1554
1555
  // We're only interested in pointers and references to functions, as well
1556
  // as pointers to member functions.
1557
56.2k
  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1558
16
    NewType = R->getPointeeType();
1559
16
    OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1560
56.2k
  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1561
239
    NewType = P->getPointeeType();
1562
239
    OldType = OldType->castAs<PointerType>()->getPointeeType();
1563
55.9k
  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1564
0
    NewType = M->getPointeeType();
1565
0
    OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1566
0
  }
1567
1568
56.2k
  if (!NewType->isFunctionProtoType())
1569
56.2k
    return;
1570
1571
  // There's lots of special cases for functions. For function pointers, system
1572
  // libraries are hopefully not as broken so that we don't need these
1573
  // workarounds.
1574
24
  if (CheckEquivalentExceptionSpec(
1575
24
        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1576
24
        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1577
7
    New->setInvalidDecl();
1578
7
  }
1579
24
}
1580
1581
/// CheckCXXDefaultArguments - Verify that the default arguments for a
1582
/// function declaration are well-formed according to C++
1583
/// [dcl.fct.default].
1584
9.67M
void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1585
9.67M
  unsigned NumParams = FD->getNumParams();
1586
9.67M
  unsigned ParamIdx = 0;
1587
1588
  // This checking doesn't make sense for explicit specializations; their
1589
  // default arguments are determined by the declaration we're specializing,
1590
  // not by FD.
1591
9.67M
  if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1592
4.70k
    return;
1593
9.67M
  if (auto *FTD = FD->getDescribedFunctionTemplate())
1594
457k
    if (FTD->isMemberSpecialization())
1595
61
      return;
1596
1597
  // Find first parameter with a default argument
1598
34.7M
  
for (; 9.67M
ParamIdx < NumParams;
++ParamIdx25.0M
) {
1599
25.1M
    ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1600
25.1M
    if (Param->hasDefaultArg())
1601
101k
      break;
1602
25.1M
  }
1603
1604
  // C++20 [dcl.fct.default]p4:
1605
  //   In a given function declaration, each parameter subsequent to a parameter
1606
  //   with a default argument shall have a default argument supplied in this or
1607
  //   a previous declaration, unless the parameter was expanded from a
1608
  //   parameter pack, or shall be a function parameter pack.
1609
9.78M
  for (; ParamIdx < NumParams; 
++ParamIdx112k
) {
1610
112k
    ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1611
112k
    if (!Param->hasDefaultArg() && 
!Param->isParameterPack()125
&&
1612
112k
        
!(75
CurrentInstantiationScope75
&&
1613
75
          
CurrentInstantiationScope->isLocalPackExpansion(Param)55
)) {
1614
20
      if (Param->isInvalidDecl())
1615
0
        /* We already complained about this parameter. */;
1616
20
      else if (Param->getIdentifier())
1617
12
        Diag(Param->getLocation(),
1618
12
             diag::err_param_default_argument_missing_name)
1619
12
          << Param->getIdentifier();
1620
8
      else
1621
8
        Diag(Param->getLocation(),
1622
8
             diag::err_param_default_argument_missing);
1623
20
    }
1624
112k
  }
1625
9.67M
}
1626
1627
/// Check that the given type is a literal type. Issue a diagnostic if not,
1628
/// if Kind is Diagnose.
1629
/// \return \c true if a problem has been found (and optionally diagnosed).
1630
template <typename... Ts>
1631
static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1632
                             SourceLocation Loc, QualType T, unsigned DiagID,
1633
252k
                             Ts &&...DiagArgs) {
1634
252k
  if (T->isDependentType())
1635
135k
    return false;
1636
1637
117k
  switch (Kind) {
1638
115k
  case Sema::CheckConstexprKind::Diagnose:
1639
115k
    return SemaRef.RequireLiteralType(Loc, T, DiagID,
1640
115k
                                      std::forward<Ts>(DiagArgs)...);
1641
1642
2.07k
  case Sema::CheckConstexprKind::CheckValid:
1643
2.07k
    return !T->isLiteralType(SemaRef.Context);
1644
117k
  }
1645
1646
0
  llvm_unreachable("unknown CheckConstexprKind");
1647
0
}
SemaDeclCXX.cpp:bool CheckLiteralType<bool>(clang::Sema&, clang::Sema::CheckConstexprKind, clang::SourceLocation, clang::QualType, unsigned int, bool&&)
Line
Count
Source
1633
132k
                             Ts &&...DiagArgs) {
1634
132k
  if (T->isDependentType())
1635
62.2k
    return false;
1636
1637
69.8k
  switch (Kind) {
1638
68.1k
  case Sema::CheckConstexprKind::Diagnose:
1639
68.1k
    return SemaRef.RequireLiteralType(Loc, T, DiagID,
1640
68.1k
                                      std::forward<Ts>(DiagArgs)...);
1641
1642
1.74k
  case Sema::CheckConstexprKind::CheckValid:
1643
1.74k
    return !T->isLiteralType(SemaRef.Context);
1644
69.8k
  }
1645
1646
0
  llvm_unreachable("unknown CheckConstexprKind");
1647
0
}
SemaDeclCXX.cpp:bool CheckLiteralType<unsigned int, clang::SourceRange, bool, bool>(clang::Sema&, clang::Sema::CheckConstexprKind, clang::SourceLocation, clang::QualType, unsigned int, unsigned int&&, clang::SourceRange&&, bool&&, bool&&)
Line
Count
Source
1633
120k
                             Ts &&...DiagArgs) {
1634
120k
  if (T->isDependentType())
1635
73.4k
    return false;
1636
1637
47.2k
  switch (Kind) {
1638
46.9k
  case Sema::CheckConstexprKind::Diagnose:
1639
46.9k
    return SemaRef.RequireLiteralType(Loc, T, DiagID,
1640
46.9k
                                      std::forward<Ts>(DiagArgs)...);
1641
1642
336
  case Sema::CheckConstexprKind::CheckValid:
1643
336
    return !T->isLiteralType(SemaRef.Context);
1644
47.2k
  }
1645
1646
0
  llvm_unreachable("unknown CheckConstexprKind");
1647
0
}
1648
1649
/// Determine whether a destructor cannot be constexpr due to
1650
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1651
                                               const CXXDestructorDecl *DD,
1652
2
                                               Sema::CheckConstexprKind Kind) {
1653
2
  auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1654
2
    const CXXRecordDecl *RD =
1655
2
        T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1656
2
    if (!RD || RD->hasConstexprDestructor())
1657
0
      return true;
1658
1659
2
    if (Kind == Sema::CheckConstexprKind::Diagnose) {
1660
2
      SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1661
2
          << static_cast<int>(DD->getConstexprKind()) << !FD
1662
2
          << (FD ? 
FD->getDeclName()1
:
DeclarationName()1
) << T;
1663
2
      SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1664
2
          << !FD << (FD ? 
FD->getDeclName()1
:
DeclarationName()1
) << T;
1665
2
    }
1666
2
    return false;
1667
2
  };
1668
1669
2
  const CXXRecordDecl *RD = DD->getParent();
1670
2
  for (const CXXBaseSpecifier &B : RD->bases())
1671
1
    if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1672
1
      return false;
1673
1
  for (const FieldDecl *FD : RD->fields())
1674
1
    if (!Check(FD->getLocation(), FD->getType(), FD))
1675
1
      return false;
1676
0
  return true;
1677
1
}
1678
1679
/// Check whether a function's parameter types are all literal types. If so,
1680
/// return true. If not, produce a suitable diagnostic and return false.
1681
static bool CheckConstexprParameterTypes(Sema &SemaRef,
1682
                                         const FunctionDecl *FD,
1683
153k
                                         Sema::CheckConstexprKind Kind) {
1684
153k
  unsigned ArgIndex = 0;
1685
153k
  const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1686
153k
  for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1687
153k
                                              e = FT->param_type_end();
1688
274k
       i != e; 
++i, ++ArgIndex120k
) {
1689
120k
    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1690
120k
    SourceLocation ParamLoc = PD->getLocation();
1691
120k
    if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1692
120k
                         diag::err_constexpr_non_literal_param, ArgIndex + 1,
1693
120k
                         PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1694
120k
                         FD->isConsteval()))
1695
56
      return false;
1696
120k
  }
1697
153k
  return true;
1698
153k
}
1699
1700
/// Check whether a function's return type is a literal type. If so, return
1701
/// true. If not, produce a suitable diagnostic and return false.
1702
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1703
129k
                                     Sema::CheckConstexprKind Kind) {
1704
129k
  if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1705
129k
                       diag::err_constexpr_non_literal_return,
1706
129k
                       FD->isConsteval()))
1707
23
    return false;
1708
129k
  return true;
1709
129k
}
1710
1711
/// Get diagnostic %select index for tag kind for
1712
/// record diagnostic message.
1713
/// WARNING: Indexes apply to particular diagnostics only!
1714
///
1715
/// \returns diagnostic %select index.
1716
24
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1717
24
  switch (Tag) {
1718
19
  case TTK_Struct: return 0;
1719
1
  case TTK_Interface: return 1;
1720
4
  case TTK_Class:  return 2;
1721
0
  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1722
24
  }
1723
24
}
1724
1725
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1726
                                       Stmt *Body,
1727
                                       Sema::CheckConstexprKind Kind);
1728
1729
// Check whether a function declaration satisfies the requirements of a
1730
// constexpr function definition or a constexpr constructor definition. If so,
1731
// return true. If not, produce appropriate diagnostics (unless asked not to by
1732
// Kind) and return false.
1733
//
1734
// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1735
bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1736
153k
                                            CheckConstexprKind Kind) {
1737
153k
  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1738
153k
  if (MD && 
MD->isInstance()110k
) {
1739
    // C++11 [dcl.constexpr]p4:
1740
    //  The definition of a constexpr constructor shall satisfy the following
1741
    //  constraints:
1742
    //  - the class shall not have any virtual base classes;
1743
    //
1744
    // FIXME: This only applies to constructors and destructors, not arbitrary
1745
    // member functions.
1746
42.5k
    const CXXRecordDecl *RD = MD->getParent();
1747
42.5k
    if (RD->getNumVBases()) {
1748
13
      if (Kind == CheckConstexprKind::CheckValid)
1749
0
        return false;
1750
1751
13
      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1752
13
        << isa<CXXConstructorDecl>(NewFD)
1753
13
        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1754
13
      for (const auto &I : RD->vbases())
1755
13
        Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1756
13
            << I.getSourceRange();
1757
13
      return false;
1758
13
    }
1759
42.5k
  }
1760
1761
153k
  if (!isa<CXXConstructorDecl>(NewFD)) {
1762
    // C++11 [dcl.constexpr]p3:
1763
    //  The definition of a constexpr function shall satisfy the following
1764
    //  constraints:
1765
    // - it shall not be virtual; (removed in C++20)
1766
129k
    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1767
129k
    if (Method && 
Method->isVirtual()86.2k
) {
1768
41
      if (getLangOpts().CPlusPlus20) {
1769
28
        if (Kind == CheckConstexprKind::Diagnose)
1770
28
          Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1771
28
      } else {
1772
13
        if (Kind == CheckConstexprKind::CheckValid)
1773
0
          return false;
1774
1775
13
        Method = Method->getCanonicalDecl();
1776
13
        Diag(Method->getLocation(), diag::err_constexpr_virtual);
1777
1778
        // If it's not obvious why this function is virtual, find an overridden
1779
        // function which uses the 'virtual' keyword.
1780
13
        const CXXMethodDecl *WrittenVirtual = Method;
1781
20
        while (!WrittenVirtual->isVirtualAsWritten())
1782
7
          WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1783
13
        if (WrittenVirtual != Method)
1784
5
          Diag(WrittenVirtual->getLocation(),
1785
5
               diag::note_overridden_virtual_function);
1786
13
        return false;
1787
13
      }
1788
41
    }
1789
1790
    // - its return type shall be a literal type;
1791
129k
    if (!CheckConstexprReturnType(*this, NewFD, Kind))
1792
23
      return false;
1793
129k
  }
1794
1795
153k
  if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1796
    // A destructor can be constexpr only if the defaulted destructor could be;
1797
    // we don't need to check the members and bases if we already know they all
1798
    // have constexpr destructors.
1799
63
    if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1800
2
      if (Kind == CheckConstexprKind::CheckValid)
1801
0
        return false;
1802
2
      if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1803
2
        return false;
1804
2
    }
1805
63
  }
1806
1807
  // - each of its parameter types shall be a literal type;
1808
153k
  if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1809
56
    return false;
1810
1811
153k
  Stmt *Body = NewFD->getBody();
1812
153k
  assert(Body &&
1813
153k
         "CheckConstexprFunctionDefinition called on function with no body");
1814
0
  return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1815
153k
}
1816
1817
/// Check the given declaration statement is legal within a constexpr function
1818
/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1819
///
1820
/// \return true if the body is OK (maybe only as an extension), false if we
1821
///         have diagnosed a problem.
1822
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1823
                                   DeclStmt *DS, SourceLocation &Cxx1yLoc,
1824
16.3k
                                   Sema::CheckConstexprKind Kind) {
1825
  // C++11 [dcl.constexpr]p3 and p4:
1826
  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1827
  //  contain only
1828
16.4k
  for (const auto *DclIt : DS->decls()) {
1829
16.4k
    switch (DclIt->getKind()) {
1830
5.03k
    case Decl::StaticAssert:
1831
5.13k
    case Decl::Using:
1832
5.13k
    case Decl::UsingShadow:
1833
5.14k
    case Decl::UsingDirective:
1834
5.14k
    case Decl::UnresolvedUsingTypename:
1835
5.14k
    case Decl::UnresolvedUsingValue:
1836
5.14k
    case Decl::UsingEnum:
1837
      //   - static_assert-declarations
1838
      //   - using-declarations,
1839
      //   - using-directives,
1840
      //   - using-enum-declaration
1841
5.14k
      continue;
1842
1843
8.28k
    case Decl::Typedef:
1844
8.34k
    case Decl::TypeAlias: {
1845
      //   - typedef declarations and alias-declarations that do not define
1846
      //     classes or enumerations,
1847
8.34k
      const auto *TN = cast<TypedefNameDecl>(DclIt);
1848
8.34k
      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1849
        // Don't allow variably-modified types in constexpr functions.
1850
0
        if (Kind == Sema::CheckConstexprKind::Diagnose) {
1851
0
          TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1852
0
          SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1853
0
            << TL.getSourceRange() << TL.getType()
1854
0
            << isa<CXXConstructorDecl>(Dcl);
1855
0
        }
1856
0
        return false;
1857
0
      }
1858
8.34k
      continue;
1859
8.34k
    }
1860
1861
8.34k
    case Decl::Enum:
1862
107
    case Decl::CXXRecord:
1863
      // C++1y allows types to be defined, not just declared.
1864
107
      if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1865
93
        if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866
69
          SemaRef.Diag(DS->getBeginLoc(),
1867
69
                       SemaRef.getLangOpts().CPlusPlus14
1868
69
                           ? 
diag::warn_cxx11_compat_constexpr_type_definition63
1869
69
                           : 
diag::ext_constexpr_type_definition6
)
1870
69
              << isa<CXXConstructorDecl>(Dcl);
1871
69
        } else 
if (24
!SemaRef.getLangOpts().CPlusPlus1424
) {
1872
0
          return false;
1873
0
        }
1874
93
      }
1875
107
      continue;
1876
1877
107
    case Decl::EnumConstant:
1878
0
    case Decl::IndirectField:
1879
0
    case Decl::ParmVar:
1880
      // These can only appear with other declarations which are banned in
1881
      // C++11 and permitted in C++1y, so ignore them.
1882
0
      continue;
1883
1884
2.77k
    case Decl::Var:
1885
2.78k
    case Decl::Decomposition: {
1886
      // C++1y [dcl.constexpr]p3 allows anything except:
1887
      //   a definition of a variable of non-literal type or of static or
1888
      //   thread storage duration or [before C++2a] for which no
1889
      //   initialization is performed.
1890
2.78k
      const auto *VD = cast<VarDecl>(DclIt);
1891
2.78k
      if (VD->isThisDeclarationADefinition()) {
1892
2.74k
        if (VD->isStaticLocal()) {
1893
20
          if (Kind == Sema::CheckConstexprKind::Diagnose) {
1894
17
            SemaRef.Diag(VD->getLocation(),
1895
17
                         diag::err_constexpr_local_var_static)
1896
17
              << isa<CXXConstructorDecl>(Dcl)
1897
17
              << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1898
17
          }
1899
20
          return false;
1900
20
        }
1901
2.72k
        if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1902
2.72k
                             diag::err_constexpr_local_var_non_literal_type,
1903
2.72k
                             isa<CXXConstructorDecl>(Dcl)))
1904
19
          return false;
1905
2.70k
        if (!VD->getType()->isDependentType() &&
1906
2.70k
            
!VD->hasInit()1.43k
&&
!VD->isCXXForRangeDecl()65
) {
1907
63
          if (Kind == Sema::CheckConstexprKind::Diagnose) {
1908
28
            SemaRef.Diag(
1909
28
                VD->getLocation(),
1910
28
                SemaRef.getLangOpts().CPlusPlus20
1911
28
                    ? 
diag::warn_cxx17_compat_constexpr_local_var_no_init22
1912
28
                    : 
diag::ext_constexpr_local_var_no_init6
)
1913
28
                << isa<CXXConstructorDecl>(Dcl);
1914
35
          } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1915
7
            return false;
1916
7
          }
1917
56
          continue;
1918
63
        }
1919
2.70k
      }
1920
2.68k
      if (Kind == Sema::CheckConstexprKind::Diagnose) {
1921
2.35k
        SemaRef.Diag(VD->getLocation(),
1922
2.35k
                     SemaRef.getLangOpts().CPlusPlus14
1923
2.35k
                      ? 
diag::warn_cxx11_compat_constexpr_local_var2.34k
1924
2.35k
                      : 
diag::ext_constexpr_local_var6
)
1925
2.35k
          << isa<CXXConstructorDecl>(Dcl);
1926
2.35k
      } else 
if (333
!SemaRef.getLangOpts().CPlusPlus14333
) {
1927
0
        return false;
1928
0
      }
1929
2.68k
      continue;
1930
2.68k
    }
1931
1932
2.68k
    case Decl::NamespaceAlias:
1933
21
    case Decl::Function:
1934
      // These are disallowed in C++11 and permitted in C++1y. Allow them
1935
      // everywhere as an extension.
1936
21
      if (!Cxx1yLoc.isValid())
1937
21
        Cxx1yLoc = DS->getBeginLoc();
1938
21
      continue;
1939
1940
0
    default:
1941
0
      if (Kind == Sema::CheckConstexprKind::Diagnose) {
1942
0
        SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1943
0
            << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1944
0
      }
1945
0
      return false;
1946
16.4k
    }
1947
16.4k
  }
1948
1949
16.3k
  return true;
1950
16.3k
}
1951
1952
/// Check that the given field is initialized within a constexpr constructor.
1953
///
1954
/// \param Dcl The constexpr constructor being checked.
1955
/// \param Field The field being checked. This may be a member of an anonymous
1956
///        struct or union nested within the class being checked.
1957
/// \param Inits All declarations, including anonymous struct/union members and
1958
///        indirect members, for which any initialization was provided.
1959
/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1960
///        multiple notes for different members to the same error.
1961
/// \param Kind Whether we're diagnosing a constructor as written or determining
1962
///        whether the formal requirements are satisfied.
1963
/// \return \c false if we're checking for validity and the constructor does
1964
///         not satisfy the requirements on a constexpr constructor.
1965
static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1966
                                          const FunctionDecl *Dcl,
1967
                                          FieldDecl *Field,
1968
                                          llvm::SmallSet<Decl*, 16> &Inits,
1969
                                          bool &Diagnosed,
1970
434
                                          Sema::CheckConstexprKind Kind) {
1971
  // In C++20 onwards, there's nothing to check for validity.
1972
434
  if (Kind == Sema::CheckConstexprKind::CheckValid &&
1973
434
      
SemaRef.getLangOpts().CPlusPlus200
)
1974
0
    return true;
1975
1976
434
  if (Field->isInvalidDecl())
1977
2
    return true;
1978
1979
432
  if (Field->isUnnamedBitfield())
1980
8
    return true;
1981
1982
  // Anonymous unions with no variant members and empty anonymous structs do not
1983
  // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1984
  // indirect fields don't need initializing.
1985
424
  if (Field->isAnonymousStructOrUnion() &&
1986
424
      
(196
Field->getType()->isUnionType()196
1987
196
           ? 
!Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()139
1988
196
           : 
Field->getType()->getAsCXXRecordDecl()->isEmpty()57
))
1989
6
    return true;
1990
1991
418
  if (!Inits.count(Field)) {
1992
40
    if (Kind == Sema::CheckConstexprKind::Diagnose) {
1993
40
      if (!Diagnosed) {
1994
25
        SemaRef.Diag(Dcl->getLocation(),
1995
25
                     SemaRef.getLangOpts().CPlusPlus20
1996
25
                         ? 
diag::warn_cxx17_compat_constexpr_ctor_missing_init9
1997
25
                         : 
diag::ext_constexpr_ctor_missing_init16
);
1998
25
        Diagnosed = true;
1999
25
      }
2000
40
      SemaRef.Diag(Field->getLocation(),
2001
40
                   diag::note_constexpr_ctor_missing_init);
2002
40
    } else 
if (0
!SemaRef.getLangOpts().CPlusPlus200
) {
2003
0
      return false;
2004
0
    }
2005
378
  } else if (Field->isAnonymousStructOrUnion()) {
2006
167
    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2007
167
    for (auto *I : RD->fields())
2008
      // If an anonymous union contains an anonymous struct of which any member
2009
      // is initialized, all members must be initialized.
2010
365
      if (!RD->isUnion() || 
Inits.count(I)251
)
2011
230
        if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2012
230
                                           Kind))
2013
0
          return false;
2014
167
  }
2015
418
  return true;
2016
418
}
2017
2018
/// Check the provided statement is allowed in a constexpr function
2019
/// definition.
2020
static bool
2021
CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2022
                           SmallVectorImpl<SourceLocation> &ReturnStmts,
2023
                           SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2024
158k
                           Sema::CheckConstexprKind Kind) {
2025
  // - its function-body shall be [...] a compound-statement that contains only
2026
158k
  switch (S->getStmtClass()) {
2027
79
  case Stmt::NullStmtClass:
2028
    //   - null statements,
2029
79
    return true;
2030
2031
16.3k
  case Stmt::DeclStmtClass:
2032
    //   - static_assert-declarations
2033
    //   - using-declarations,
2034
    //   - using-directives,
2035
    //   - typedef declarations and alias-declarations that do not define
2036
    //     classes or enumerations,
2037
16.3k
    if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2038
46
      return false;
2039
16.3k
    return true;
2040
2041
129k
  case Stmt::ReturnStmtClass:
2042
    //   - and exactly one return statement;
2043
129k
    if (isa<CXXConstructorDecl>(Dcl)) {
2044
      // C++1y allows return statements in constexpr constructors.
2045
3
      if (!Cxx1yLoc.isValid())
2046
3
        Cxx1yLoc = S->getBeginLoc();
2047
3
      return true;
2048
3
    }
2049
2050
129k
    ReturnStmts.push_back(S->getBeginLoc());
2051
129k
    return true;
2052
2053
1
  case Stmt::AttributedStmtClass:
2054
    // Attributes on a statement don't affect its formal kind and hence don't
2055
    // affect its validity in a constexpr function.
2056
1
    return CheckConstexprFunctionStmt(SemaRef, Dcl,
2057
1
                                      cast<AttributedStmt>(S)->getSubStmt(),
2058
1
                                      ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind);
2059
2060
1.78k
  case Stmt::CompoundStmtClass: {
2061
    // C++1y allows compound-statements.
2062
1.78k
    if (!Cxx1yLoc.isValid())
2063
34
      Cxx1yLoc = S->getBeginLoc();
2064
2065
1.78k
    CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2066
4.38k
    for (auto *BodyIt : CompStmt->body()) {
2067
4.38k
      if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2068
4.38k
                                      Cxx1yLoc, Cxx2aLoc, Kind))
2069
3
        return false;
2070
4.38k
    }
2071
1.78k
    return true;
2072
1.78k
  }
2073
2074
3.00k
  case Stmt::IfStmtClass: {
2075
    // C++1y allows if-statements.
2076
3.00k
    if (!Cxx1yLoc.isValid())
2077
869
      Cxx1yLoc = S->getBeginLoc();
2078
2079
3.00k
    IfStmt *If = cast<IfStmt>(S);
2080
3.00k
    if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2081
3.00k
                                    Cxx1yLoc, Cxx2aLoc, Kind))
2082
0
      return false;
2083
3.00k
    if (If->getElse() &&
2084
3.00k
        !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2085
461
                                    Cxx1yLoc, Cxx2aLoc, Kind))
2086
0
      return false;
2087
3.00k
    return true;
2088
3.00k
  }
2089
2090
501
  case Stmt::WhileStmtClass:
2091
557
  case Stmt::DoStmtClass:
2092
866
  case Stmt::ForStmtClass:
2093
887
  case Stmt::CXXForRangeStmtClass:
2094
916
  case Stmt::ContinueStmtClass:
2095
    // C++1y allows all of these. We don't allow them as extensions in C++11,
2096
    // because they don't make sense without variable mutation.
2097
916
    if (!SemaRef.getLangOpts().CPlusPlus14)
2098
3
      break;
2099
913
    if (!Cxx1yLoc.isValid())
2100
241
      Cxx1yLoc = S->getBeginLoc();
2101
913
    for (Stmt *SubStmt : S->children())
2102
2.82k
      if (SubStmt &&
2103
2.82k
          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2104
2.28k
                                      Cxx1yLoc, Cxx2aLoc, Kind))
2105
0
        return false;
2106
913
    return true;
2107
2108
63
  case Stmt::SwitchStmtClass:
2109
291
  case Stmt::CaseStmtClass:
2110
300
  case Stmt::DefaultStmtClass:
2111
619
  case Stmt::BreakStmtClass:
2112
    // C++1y allows switch-statements, and since they don't need variable
2113
    // mutation, we can reasonably allow them in C++11 as an extension.
2114
619
    if (!Cxx1yLoc.isValid())
2115
37
      Cxx1yLoc = S->getBeginLoc();
2116
619
    for (Stmt *SubStmt : S->children())
2117
599
      if (SubStmt &&
2118
599
          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2119
599
                                      Cxx1yLoc, Cxx2aLoc, Kind))
2120
0
        return false;
2121
619
    return true;
2122
2123
12
  case Stmt::GCCAsmStmtClass:
2124
12
  case Stmt::MSAsmStmtClass:
2125
    // C++2a allows inline assembly statements.
2126
21
  case Stmt::CXXTryStmtClass:
2127
21
    if (Cxx2aLoc.isInvalid())
2128
21
      Cxx2aLoc = S->getBeginLoc();
2129
21
    for (Stmt *SubStmt : S->children()) {
2130
18
      if (SubStmt &&
2131
18
          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2132
18
                                      Cxx1yLoc, Cxx2aLoc, Kind))
2133
3
        return false;
2134
18
    }
2135
18
    return true;
2136
2137
16
  case Stmt::CXXCatchStmtClass:
2138
    // Do not bother checking the language mode (already covered by the
2139
    // try block check).
2140
16
    if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2141
16
                                    cast<CXXCatchStmt>(S)->getHandlerBlock(),
2142
16
                                    ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2143
3
      return false;
2144
13
    return true;
2145
2146
6.39k
  default:
2147
6.39k
    if (!isa<Expr>(S))
2148
8
      break;
2149
2150
    // C++1y allows expression-statements.
2151
6.39k
    if (!Cxx1yLoc.isValid())
2152
2.02k
      Cxx1yLoc = S->getBeginLoc();
2153
6.39k
    return true;
2154
158k
  }
2155
2156
11
  if (Kind == Sema::CheckConstexprKind::Diagnose) {
2157
11
    SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2158
11
        << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2159
11
  }
2160
11
  return false;
2161
158k
}
2162
2163
/// Check the body for the given constexpr function declaration only contains
2164
/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2165
///
2166
/// \return true if the body is OK, false if we have found or diagnosed a
2167
/// problem.
2168
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2169
                                       Stmt *Body,
2170
153k
                                       Sema::CheckConstexprKind Kind) {
2171
153k
  SmallVector<SourceLocation, 4> ReturnStmts;
2172
2173
153k
  if (isa<CXXTryStmt>(Body)) {
2174
    // C++11 [dcl.constexpr]p3:
2175
    //  The definition of a constexpr function shall satisfy the following
2176
    //  constraints: [...]
2177
    // - its function-body shall be = delete, = default, or a
2178
    //   compound-statement
2179
    //
2180
    // C++11 [dcl.constexpr]p4:
2181
    //  In the definition of a constexpr constructor, [...]
2182
    // - its function-body shall not be a function-try-block;
2183
    //
2184
    // This restriction is lifted in C++2a, as long as inner statements also
2185
    // apply the general constexpr rules.
2186
7
    switch (Kind) {
2187
0
    case Sema::CheckConstexprKind::CheckValid:
2188
0
      if (!SemaRef.getLangOpts().CPlusPlus20)
2189
0
        return false;
2190
0
      break;
2191
2192
7
    case Sema::CheckConstexprKind::Diagnose:
2193
7
      SemaRef.Diag(Body->getBeginLoc(),
2194
7
           !SemaRef.getLangOpts().CPlusPlus20
2195
7
               ? 
diag::ext_constexpr_function_try_block_cxx205
2196
7
               : 
diag::warn_cxx17_compat_constexpr_function_try_block2
)
2197
7
          << isa<CXXConstructorDecl>(Dcl);
2198
7
      break;
2199
7
    }
2200
7
  }
2201
2202
  // - its function-body shall be [...] a compound-statement that contains only
2203
  //   [... list of cases ...]
2204
  //
2205
  // Note that walking the children here is enough to properly check for
2206
  // CompoundStmt and CXXTryStmt body.
2207
153k
  SourceLocation Cxx1yLoc, Cxx2aLoc;
2208
153k
  for (Stmt *SubStmt : Body->children()) {
2209
147k
    if (SubStmt &&
2210
147k
        !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2211
147k
                                    Cxx1yLoc, Cxx2aLoc, Kind))
2212
57
      return false;
2213
147k
  }
2214
2215
153k
  if (Kind == Sema::CheckConstexprKind::CheckValid) {
2216
    // If this is only valid as an extension, report that we don't satisfy the
2217
    // constraints of the current language.
2218
2.01k
    if ((Cxx2aLoc.isValid() && 
!SemaRef.getLangOpts().CPlusPlus209
) ||
2219
2.01k
        
(2.00k
Cxx1yLoc.isValid()2.00k
&&
!SemaRef.getLangOpts().CPlusPlus17505
))
2220
6
      return false;
2221
151k
  } else if (Cxx2aLoc.isValid()) {
2222
9
    SemaRef.Diag(Cxx2aLoc,
2223
9
         SemaRef.getLangOpts().CPlusPlus20
2224
9
           ? 
diag::warn_cxx17_compat_constexpr_body_invalid_stmt3
2225
9
           : 
diag::ext_constexpr_body_invalid_stmt_cxx206
)
2226
9
      << isa<CXXConstructorDecl>(Dcl);
2227
151k
  } else if (Cxx1yLoc.isValid()) {
2228
2.70k
    SemaRef.Diag(Cxx1yLoc,
2229
2.70k
         SemaRef.getLangOpts().CPlusPlus14
2230
2.70k
           ? 
diag::warn_cxx11_compat_constexpr_body_invalid_stmt2.69k
2231
2.70k
           : 
diag::ext_constexpr_body_invalid_stmt7
)
2232
2.70k
      << isa<CXXConstructorDecl>(Dcl);
2233
2.70k
  }
2234
2235
153k
  if (const CXXConstructorDecl *Constructor
2236
153k
        = dyn_cast<CXXConstructorDecl>(Dcl)) {
2237
24.4k
    const CXXRecordDecl *RD = Constructor->getParent();
2238
    // DR1359:
2239
    // - every non-variant non-static data member and base class sub-object
2240
    //   shall be initialized;
2241
    // DR1460:
2242
    // - if the class is a union having variant members, exactly one of them
2243
    //   shall be initialized;
2244
24.4k
    if (RD->isUnion()) {
2245
125
      if (Constructor->getNumCtorInitializers() == 0 &&
2246
125
          
RD->hasVariantMembers()9
) {
2247
2
        if (Kind == Sema::CheckConstexprKind::Diagnose) {
2248
2
          SemaRef.Diag(
2249
2
              Dcl->getLocation(),
2250
2
              SemaRef.getLangOpts().CPlusPlus20
2251
2
                  ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2252
2
                  : 
diag::ext_constexpr_union_ctor_no_init0
);
2253
2
        } else 
if (0
!SemaRef.getLangOpts().CPlusPlus200
) {
2254
0
          return false;
2255
0
        }
2256
2
      }
2257
24.3k
    } else if (!Constructor->isDependentContext() &&
2258
24.3k
               
!Constructor->isDelegatingConstructor()3.06k
) {
2259
3.05k
      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2260
2261
      // Skip detailed checking if we have enough initializers, and we would
2262
      // allow at most one initializer per member.
2263
0
      bool AnyAnonStructUnionMembers = false;
2264
3.05k
      unsigned Fields = 0;
2265
3.05k
      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2266
9.12k
           E = RD->field_end(); I != E; 
++I, ++Fields6.06k
) {
2267
6.14k
        if (I->isAnonymousStructOrUnion()) {
2268
79
          AnyAnonStructUnionMembers = true;
2269
79
          break;
2270
79
        }
2271
6.14k
      }
2272
      // DR1460:
2273
      // - if the class is a union-like class, but is not a union, for each of
2274
      //   its anonymous union members having variant members, exactly one of
2275
      //   them shall be initialized;
2276
3.05k
      if (AnyAnonStructUnionMembers ||
2277
3.05k
          
Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields2.97k
) {
2278
        // Check initialization of non-static data members. Base classes are
2279
        // always initialized so do not need to be checked. Dependent bases
2280
        // might not have initializers in the member initializer list.
2281
94
        llvm::SmallSet<Decl*, 16> Inits;
2282
212
        for (const auto *I: Constructor->inits()) {
2283
212
          if (FieldDecl *FD = I->getMember())
2284
44
            Inits.insert(FD);
2285
168
          else if (IndirectFieldDecl *ID = I->getIndirectMember())
2286
167
            Inits.insert(ID->chain_begin(), ID->chain_end());
2287
212
        }
2288
2289
94
        bool Diagnosed = false;
2290
94
        for (auto *I : RD->fields())
2291
204
          if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2292
204
                                             Kind))
2293
0
            return false;
2294
94
      }
2295
3.05k
    }
2296
129k
  } else {
2297
129k
    if (ReturnStmts.empty()) {
2298
      // C++1y doesn't require constexpr functions to contain a 'return'
2299
      // statement. We still do, unless the return type might be void, because
2300
      // otherwise if there's no return statement, the function cannot
2301
      // be used in a core constant expression.
2302
1.74k
      bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2303
1.74k
                
(1.74k
Dcl->getReturnType()->isVoidType()1.74k
||
2304
1.74k
                 
Dcl->getReturnType()->isDependentType()381
);
2305
1.74k
      switch (Kind) {
2306
726
      case Sema::CheckConstexprKind::Diagnose:
2307
726
        SemaRef.Diag(Dcl->getLocation(),
2308
726
                     OK ? 
diag::warn_cxx11_compat_constexpr_body_no_return706
2309
726
                        : 
diag::err_constexpr_body_no_return20
)
2310
726
            << Dcl->isConsteval();
2311
726
        if (!OK)
2312
20
          return false;
2313
706
        break;
2314
2315
1.01k
      case Sema::CheckConstexprKind::CheckValid:
2316
        // The formal requirements don't include this rule in C++14, even
2317
        // though the "must be able to produce a constant expression" rules
2318
        // still imply it in some cases.
2319
1.01k
        if (!SemaRef.getLangOpts().CPlusPlus14)
2320
0
          return false;
2321
1.01k
        break;
2322
1.74k
      }
2323
127k
    } else if (ReturnStmts.size() > 1) {
2324
814
      switch (Kind) {
2325
784
      case Sema::CheckConstexprKind::Diagnose:
2326
784
        SemaRef.Diag(
2327
784
            ReturnStmts.back(),
2328
784
            SemaRef.getLangOpts().CPlusPlus14
2329
784
                ? 
diag::warn_cxx11_compat_constexpr_body_multiple_return783
2330
784
                : 
diag::ext_constexpr_body_multiple_return1
);
2331
2.49k
        for (unsigned I = 0; I < ReturnStmts.size() - 1; 
++I1.70k
)
2332
1.70k
          SemaRef.Diag(ReturnStmts[I],
2333
1.70k
                       diag::note_constexpr_body_previous_return);
2334
784
        break;
2335
2336
30
      case Sema::CheckConstexprKind::CheckValid:
2337
30
        if (!SemaRef.getLangOpts().CPlusPlus14)
2338
0
          return false;
2339
30
        break;
2340
814
      }
2341
814
    }
2342
129k
  }
2343
2344
  // C++11 [dcl.constexpr]p5:
2345
  //   if no function argument values exist such that the function invocation
2346
  //   substitution would produce a constant expression, the program is
2347
  //   ill-formed; no diagnostic required.
2348
  // C++11 [dcl.constexpr]p3:
2349
  //   - every constructor call and implicit conversion used in initializing the
2350
  //     return value shall be one of those allowed in a constant expression.
2351
  // C++11 [dcl.constexpr]p4:
2352
  //   - every constructor involved in initializing non-static data members and
2353
  //     base class sub-objects shall be a constexpr constructor.
2354
  //
2355
  // Note that this rule is distinct from the "requirements for a constexpr
2356
  // function", so is not checked in CheckValid mode.
2357
153k
  SmallVector<PartialDiagnosticAt, 8> Diags;
2358
153k
  if (Kind == Sema::CheckConstexprKind::Diagnose &&
2359
153k
      
!Expr::isPotentialConstantExpr(Dcl, Diags)151k
) {
2360
313
    SemaRef.Diag(Dcl->getLocation(),
2361
313
                 diag::ext_constexpr_function_never_constant_expr)
2362
313
        << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2363
687
    for (size_t I = 0, N = Diags.size(); I != N; 
++I374
)
2364
374
      SemaRef.Diag(Diags[I].first, Diags[I].second);
2365
    // Don't return false here: we allow this for compatibility in
2366
    // system headers.
2367
313
  }
2368
2369
153k
  return true;
2370
153k
}
2371
2372
/// Get the class that is directly named by the current context. This is the
2373
/// class for which an unqualified-id in this scope could name a constructor
2374
/// or destructor.
2375
///
2376
/// If the scope specifier denotes a class, this will be that class.
2377
/// If the scope specifier is empty, this will be the class whose
2378
/// member-specification we are currently within. Otherwise, there
2379
/// is no such class.
2380
2.50M
CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2381
2.50M
  assert(getLangOpts().CPlusPlus && "No class names in C!");
2382
2383
2.50M
  if (SS && 
SS->isInvalid()960k
)
2384
40
    return nullptr;
2385
2386
2.50M
  if (SS && 
SS->isNotEmpty()960k
) {
2387
434k
    DeclContext *DC = computeDeclContext(*SS, true);
2388
434k
    return dyn_cast_or_null<CXXRecordDecl>(DC);
2389
434k
  }
2390
2391
2.07M
  return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2392
2.50M
}
2393
2394
/// isCurrentClassName - Determine whether the identifier II is the
2395
/// name of the class type currently being defined. In the case of
2396
/// nested classes, this will only return true if II is the name of
2397
/// the innermost class.
2398
bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2399
2.22M
                              const CXXScopeSpec *SS) {
2400
2.22M
  CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2401
2.22M
  return CurDecl && 
&II == CurDecl->getIdentifier()1.89M
;
2402
2.22M
}
2403
2404
/// Determine whether the identifier II is a typo for the name of
2405
/// the class type currently being defined. If so, update it to the identifier
2406
/// that should have been used.
2407
45
bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2408
45
  assert(getLangOpts().CPlusPlus && "No class names in C!");
2409
2410
45
  if (!getLangOpts().SpellChecking)
2411
0
    return false;
2412
2413
45
  CXXRecordDecl *CurDecl;
2414
45
  if (SS && 
SS->isSet()29
&&
!SS->isInvalid()19
) {
2415
19
    DeclContext *DC = computeDeclContext(*SS, true);
2416
19
    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2417
19
  } else
2418
26
    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2419
2420
45
  if (CurDecl && 
CurDecl->getIdentifier()40
&&
II != CurDecl->getIdentifier()35
&&
2421
45
      3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2422
35
          < II->getLength()) {
2423
10
    II = CurDecl->getIdentifier();
2424
10
    return true;
2425
10
  }
2426
2427
35
  return false;
2428
45
}
2429
2430
/// Determine whether the given class is a base class of the given
2431
/// class, including looking at dependent bases.
2432
static bool findCircularInheritance(const CXXRecordDecl *Class,
2433
24
                                    const CXXRecordDecl *Current) {
2434
24
  SmallVector<const CXXRecordDecl*, 8> Queue;
2435
2436
24
  Class = Class->getCanonicalDecl();
2437
26
  while (true) {
2438
26
    for (const auto &I : Current->bases()) {
2439
8
      CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2440
8
      if (!Base)
2441
5
        continue;
2442
2443
3
      Base = Base->getDefinition();
2444
3
      if (!Base)
2445
0
        continue;
2446
2447
3
      if (Base->getCanonicalDecl() == Class)
2448
1
        return true;
2449
2450
2
      Queue.push_back(Base);
2451
2
    }
2452
2453
25
    if (Queue.empty())
2454
23
      return false;
2455
2456
2
    Current = Queue.pop_back_val();
2457
2
  }
2458
2459
0
  return false;
2460
24
}
2461
2462
/// Check the validity of a C++ base class specifier.
2463
///
2464
/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2465
/// and returns NULL otherwise.
2466
CXXBaseSpecifier *
2467
Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2468
                         SourceRange SpecifierRange,
2469
                         bool Virtual, AccessSpecifier Access,
2470
                         TypeSourceInfo *TInfo,
2471
462k
                         SourceLocation EllipsisLoc) {
2472
462k
  QualType BaseType = TInfo->getType();
2473
462k
  if (BaseType->containsErrors()) {
2474
    // Already emitted a diagnostic when parsing the error type.
2475
3
    return nullptr;
2476
3
  }
2477
  // C++ [class.union]p1:
2478
  //   A union shall not have base classes.
2479
462k
  if (Class->isUnion()) {
2480
1
    Diag(Class->getLocation(), diag::err_base_clause_on_union)
2481
1
      << SpecifierRange;
2482
1
    return nullptr;
2483
1
  }
2484
2485
462k
  if (EllipsisLoc.isValid() &&
2486
462k
      
!TInfo->getType()->containsUnexpandedParameterPack()491
) {
2487
2
    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2488
2
      << TInfo->getTypeLoc().getSourceRange();
2489
2
    EllipsisLoc = SourceLocation();
2490
2
  }
2491
2492
462k
  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2493
2494
462k
  if (BaseType->isDependentType()) {
2495
    // Make sure that we don't have circular inheritance among our dependent
2496
    // bases. For non-dependent bases, the check for completeness below handles
2497
    // this.
2498
120k
    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2499
35
      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2500
35
          
(33
(BaseDecl = BaseDecl->getDefinition())33
&&
2501
33
           
findCircularInheritance(Class, BaseDecl)24
)) {
2502
3
        Diag(BaseLoc, diag::err_circular_inheritance)
2503
3
          << BaseType << Context.getTypeDeclType(Class);
2504
2505
3
        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2506
1
          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2507
1
            << BaseType;
2508
2509
3
        return nullptr;
2510
3
      }
2511
35
    }
2512
2513
    // Make sure that we don't make an ill-formed AST where the type of the
2514
    // Class is non-dependent and its attached base class specifier is an
2515
    // dependent type, which violates invariants in many clang code paths (e.g.
2516
    // constexpr evaluator). If this case happens (in errory-recovery mode), we
2517
    // explicitly mark the Class decl invalid. The diagnostic was already
2518
    // emitted.
2519
120k
    if (!Class->getTypeForDecl()->isDependentType())
2520
2
      Class->setInvalidDecl();
2521
120k
    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2522
120k
                                          Class->getTagKind() == TTK_Class,
2523
120k
                                          Access, TInfo, EllipsisLoc);
2524
120k
  }
2525
2526
  // Base specifiers must be record types.
2527
341k
  if (!BaseType->isRecordType()) {
2528
114
    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2529
114
    return nullptr;
2530
114
  }
2531
2532
  // C++ [class.union]p1:
2533
  //   A union shall not be used as a base class.
2534
341k
  if (BaseType->isUnionType()) {
2535
1
    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2536
1
    return nullptr;
2537
1
  }
2538
2539
  // For the MS ABI, propagate DLL attributes to base class templates.
2540
341k
  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2541
4.14k
    if (Attr *ClassAttr = getDLLAttr(Class)) {
2542
297
      if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2543
297
              BaseType->getAsCXXRecordDecl())) {
2544
241
        propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2545
241
                                            BaseLoc);
2546
241
      }
2547
297
    }
2548
4.14k
  }
2549
2550
  // C++ [class.derived]p2:
2551
  //   The class-name in a base-specifier shall not be an incompletely
2552
  //   defined class.
2553
341k
  if (RequireCompleteType(BaseLoc, BaseType,
2554
341k
                          diag::err_incomplete_base_class, SpecifierRange)) {
2555
1.10k
    Class->setInvalidDecl();
2556
1.10k
    return nullptr;
2557
1.10k
  }
2558
2559
  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2560
340k
  RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2561
340k
  assert(BaseDecl && "Record type has no declaration");
2562
0
  BaseDecl = BaseDecl->getDefinition();
2563
340k
  assert(BaseDecl && "Base type is not incomplete, but has no definition");
2564
0
  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2565
340k
  assert(CXXBaseDecl && "Base type is not a C++ type");
2566
2567
  // Microsoft docs say:
2568
  // "If a base-class has a code_seg attribute, derived classes must have the
2569
  // same attribute."
2570
0
  const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2571
340k
  const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2572
340k
  if ((DerivedCSA || 
BaseCSA340k
) &&
2573
340k
      
(34
!BaseCSA34
||
!DerivedCSA30
||
BaseCSA->getName() != DerivedCSA->getName()26
)) {
2574
19
    Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2575
19
    Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2576
19
      << CXXBaseDecl;
2577
19
    return nullptr;
2578
19
  }
2579
2580
  // A class which contains a flexible array member is not suitable for use as a
2581
  // base class:
2582
  //   - If the layout determines that a base comes before another base,
2583
  //     the flexible array member would index into the subsequent base.
2584
  //   - If the layout determines that base comes before the derived class,
2585
  //     the flexible array member would index into the derived class.
2586
340k
  if (CXXBaseDecl->hasFlexibleArrayMember()) {
2587
1
    Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2588
1
      << CXXBaseDecl->getDeclName();
2589
1
    return nullptr;
2590
1
  }
2591
2592
  // C++ [class]p3:
2593
  //   If a class is marked final and it appears as a base-type-specifier in
2594
  //   base-clause, the program is ill-formed.
2595
340k
  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2596
11
    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2597
11
      << CXXBaseDecl->getDeclName()
2598
11
      << FA->isSpelledAsSealed();
2599
11
    Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2600
11
        << CXXBaseDecl->getDeclName() << FA->getRange();
2601
11
    return nullptr;
2602
11
  }
2603
2604
340k
  if (BaseDecl->isInvalidDecl())
2605
51
    Class->setInvalidDecl();
2606
2607
  // Create the base specifier.
2608
340k
  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2609
340k
                                        Class->getTagKind() == TTK_Class,
2610
340k
                                        Access, TInfo, EllipsisLoc);
2611
340k
}
2612
2613
/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2614
/// one entry in the base class list of a class specifier, for
2615
/// example:
2616
///    class foo : public bar, virtual private baz {
2617
/// 'public bar' and 'virtual private baz' are each base-specifiers.
2618
BaseResult
2619
Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2620
                         ParsedAttributes &Attributes,
2621
                         bool Virtual, AccessSpecifier Access,
2622
                         ParsedType basetype, SourceLocation BaseLoc,
2623
217k
                         SourceLocation EllipsisLoc) {
2624
217k
  if (!classdecl)
2625
53
    return true;
2626
2627
217k
  AdjustDeclIfTemplate(classdecl);
2628
217k
  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2629
217k
  if (!Class)
2630
0
    return true;
2631
2632
  // We haven't yet attached the base specifiers.
2633
217k
  Class->setIsParsingBaseSpecifiers();
2634
2635
  // We do not support any C++11 attributes on base-specifiers yet.
2636
  // Diagnose any attributes we see.
2637
217k
  for (const ParsedAttr &AL : Attributes) {
2638
18
    if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2639
0
      continue;
2640
18
    Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2641
18
                          ? 
(unsigned)diag::warn_unknown_attribute_ignored17
2642
18
                          : 
(unsigned)diag::err_base_specifier_attribute1
)
2643
18
        << AL << AL.getRange();
2644
18
  }
2645
2646
217k
  TypeSourceInfo *TInfo = nullptr;
2647
217k
  GetTypeFromParser(basetype, &TInfo);
2648
2649
217k
  if (EllipsisLoc.isInvalid() &&
2650
217k
      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2651
216k
                                      UPPC_BaseType))
2652
1
    return true;
2653
2654
217k
  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2655
217k
                                                      Virtual, Access, TInfo,
2656
217k
                                                      EllipsisLoc))
2657
216k
    return BaseSpec;
2658
186
  else
2659
186
    Class->setInvalidDecl();
2660
2661
186
  return true;
2662
217k
}
2663
2664
/// Use small set to collect indirect bases.  As this is only used
2665
/// locally, there's no need to abstract the small size parameter.
2666
typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2667
2668
/// Recursively add the bases of Type.  Don't add Type itself.
2669
static void
2670
NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2671
                  const QualType &Type)
2672
31.8k
{
2673
  // Even though the incoming type is a base, it might not be
2674
  // a class -- it could be a template parm, for instance.
2675
31.8k
  if (auto Rec = Type->getAs<RecordType>()) {
2676
31.8k
    auto Decl = Rec->getAsCXXRecordDecl();
2677
2678
    // Iterate over its bases.
2679
31.8k
    for (const auto &BaseSpec : Decl->bases()) {
2680
11.8k
      QualType Base = Context.getCanonicalType(BaseSpec.getType())
2681
11.8k
        .getUnqualifiedType();
2682
11.8k
      if (Set.insert(Base).second)
2683
        // If we've not already seen it, recurse.
2684
11.0k
        NoteIndirectBases(Context, Set, Base);
2685
11.8k
    }
2686
31.8k
  }
2687
31.8k
}
2688
2689
/// Performs the actual work of attaching the given base class
2690
/// specifiers to a C++ class.
2691
bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2692
977k
                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2693
977k
 if (Bases.empty())
2694
469k
    return false;
2695
2696
  // Used to keep track of which base types we have already seen, so
2697
  // that we can properly diagnose redundant direct base types. Note
2698
  // that the key is always the unqualified canonical type of the base
2699
  // class.
2700
507k
  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2701
2702
  // Used to track indirect bases so we can see if a direct base is
2703
  // ambiguous.
2704
507k
  IndirectBaseSet IndirectBaseTypes;
2705
2706
  // Copy non-redundant base specifiers into permanent storage.
2707
507k
  unsigned NumGoodBases = 0;
2708
507k
  bool Invalid = false;
2709
1.02M
  for (unsigned idx = 0; idx < Bases.size(); 
++idx521k
) {
2710
521k
    QualType NewBaseType
2711
521k
      = Context.getCanonicalType(Bases[idx]->getType());
2712
521k
    NewBaseType = NewBaseType.getLocalUnqualifiedType();
2713
2714
521k
    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2715
521k
    if (KnownBase) {
2716
      // C++ [class.mi]p3:
2717
      //   A class shall not be specified as a direct base class of a
2718
      //   derived class more than once.
2719
2
      Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2720
2
          << KnownBase->getType() << Bases[idx]->getSourceRange();
2721
2722
      // Delete the duplicate base class specifier; we're going to
2723
      // overwrite its pointer later.
2724
2
      Context.Deallocate(Bases[idx]);
2725
2726
2
      Invalid = true;
2727
521k
    } else {
2728
      // Okay, add this new base class.
2729
521k
      KnownBase = Bases[idx];
2730
521k
      Bases[NumGoodBases++] = Bases[idx];
2731
2732
521k
      if (NewBaseType->isDependentType())
2733
120k
        continue;
2734
      // Note this base's direct & indirect bases, if there could be ambiguity.
2735
401k
      if (Bases.size() > 1)
2736
20.7k
        NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2737
2738
401k
      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2739
401k
        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2740
401k
        if (Class->isInterface() &&
2741
401k
              
(25
!RD->isInterfaceLike()25
||
2742
25
               
KnownBase->getAccessSpecifier() != AS_public15
)) {
2743
          // The Microsoft extension __interface does not permit bases that
2744
          // are not themselves public interfaces.
2745
11
          Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2746
11
              << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2747
11
              << RD->getSourceRange();
2748
11
          Invalid = true;
2749
11
        }
2750
401k
        if (RD->hasAttr<WeakAttr>())
2751
4
          Class->addAttr(WeakAttr::CreateImplicit(Context));
2752
401k
      }
2753
401k
    }
2754
521k
  }
2755
2756
  // Attach the remaining base class specifiers to the derived class.
2757
507k
  Class->setBases(Bases.data(), NumGoodBases);
2758
2759
  // Check that the only base classes that are duplicate are virtual.
2760
1.02M
  for (unsigned idx = 0; idx < NumGoodBases; 
++idx521k
) {
2761
    // Check whether this direct base is inaccessible due to ambiguity.
2762
521k
    QualType BaseType = Bases[idx]->getType();
2763
2764
    // Skip all dependent types in templates being used as base specifiers.
2765
    // Checks below assume that the base specifier is a CXXRecord.
2766
521k
    if (BaseType->isDependentType())
2767
120k
      continue;
2768
2769
401k
    CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2770
401k
      .getUnqualifiedType();
2771
2772
401k
    if (IndirectBaseTypes.count(CanonicalBase)) {
2773
361
      CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2774
361
                         /*DetectVirtual=*/true);
2775
361
      bool found
2776
361
        = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2777
361
      assert(found);
2778
0
      (void)found;
2779
2780
361
      if (Paths.isAmbiguous(CanonicalBase))
2781
252
        Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2782
252
            << BaseType << getAmbiguousPathsDisplayString(Paths)
2783
252
            << Bases[idx]->getSourceRange();
2784
109
      else
2785
109
        assert(Bases[idx]->isVirtual());
2786
361
    }
2787
2788
    // Delete the base class specifier, since its data has been copied
2789
    // into the CXXRecordDecl.
2790
0
    Context.Deallocate(Bases[idx]);
2791
401k
  }
2792
2793
507k
  return Invalid;
2794
977k
}
2795
2796
/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2797
/// class, after checking whether there are any duplicate base
2798
/// classes.
2799
void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2800
210k
                               MutableArrayRef<CXXBaseSpecifier *> Bases) {
2801
210k
  if (!ClassDecl || 
Bases.empty()210k
)
2802
471
    return;
2803
2804
210k
  AdjustDeclIfTemplate(ClassDecl);
2805
210k
  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2806
210k
}
2807
2808
/// Determine whether the type \p Derived is a C++ class that is
2809
/// derived from the type \p Base.
2810
5.48M
bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2811
5.48M
  if (!getLangOpts().CPlusPlus)
2812
673
    return false;
2813
2814
5.48M
  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2815
5.48M
  if (!DerivedRD)
2816
1.17M
    return false;
2817
2818
4.31M
  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2819
4.31M
  if (!BaseRD)
2820
3.84M
    return false;
2821
2822
  // If either the base or the derived type is invalid, don't try to
2823
  // check whether one is derived from the other.
2824
474k
  if (BaseRD->isInvalidDecl() || 
DerivedRD->isInvalidDecl()474k
)
2825
13
    return false;
2826
2827
  // FIXME: In a modules build, do we need the entire path to be visible for us
2828
  // to be able to use the inheritance relationship?
2829
474k
  if (!isCompleteType(Loc, Derived) && 
!DerivedRD->isBeingDefined()7.00k
)
2830
6.33k
    return false;
2831
2832
467k
  return DerivedRD->isDerivedFrom(BaseRD);
2833
474k
}
2834
2835
/// Determine whether the type \p Derived is a C++ class that is
2836
/// derived from the type \p Base.
2837
bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2838
99.2k
                         CXXBasePaths &Paths) {
2839
99.2k
  if (!getLangOpts().CPlusPlus)
2840
196
    return false;
2841
2842
99.0k
  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2843
99.0k
  if (!DerivedRD)
2844
0
    return false;
2845
2846
99.0k
  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2847
99.0k
  if (!BaseRD)
2848
1
    return false;
2849
2850
99.0k
  if (!isCompleteType(Loc, Derived) && 
!DerivedRD->isBeingDefined()69
)
2851
1
    return false;
2852
2853
99.0k
  return DerivedRD->isDerivedFrom(BaseRD, Paths);
2854
99.0k
}
2855
2856
static void BuildBasePathArray(const CXXBasePath &Path,
2857
41.1k
                               CXXCastPath &BasePathArray) {
2858
  // We first go backward and check if we have a virtual base.
2859
  // FIXME: It would be better if CXXBasePath had the base specifier for
2860
  // the nearest virtual base.
2861
41.1k
  unsigned Start = 0;
2862
87.6k
  for (unsigned I = Path.size(); I != 0; 
--I46.5k
) {
2863
47.2k
    if (Path[I - 1].Base->isVirtual()) {
2864
702
      Start = I - 1;
2865
702
      break;
2866
702
    }
2867
47.2k
  }
2868
2869
  // Now add all bases.
2870
88.3k
  for (unsigned I = Start, E = Path.size(); I != E; 
++I47.2k
)
2871
47.2k
    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2872
41.1k
}
2873
2874
2875
void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2876
1.59k
                              CXXCastPath &BasePathArray) {
2877
1.59k
  assert(BasePathArray.empty() && "Base path array must be empty!");
2878
0
  assert(Paths.isRecordingPaths() && "Must record paths!");
2879
0
  return ::BuildBasePathArray(Paths.front(), BasePathArray);
2880
1.59k
}
2881
/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2882
/// conversion (where Derived and Base are class types) is
2883
/// well-formed, meaning that the conversion is unambiguous (and
2884
/// that all of the base classes are accessible). Returns true
2885
/// and emits a diagnostic if the code is ill-formed, returns false
2886
/// otherwise. Loc is the location where this routine should point to
2887
/// if there is an error, and Range is the source range to highlight
2888
/// if there is an error.
2889
///
2890
/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2891
/// diagnostic for the respective type of error will be suppressed, but the
2892
/// check for ill-formed code will still be performed.
2893
bool
2894
Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2895
                                   unsigned InaccessibleBaseID,
2896
                                   unsigned AmbiguousBaseConvID,
2897
                                   SourceLocation Loc, SourceRange Range,
2898
                                   DeclarationName Name,
2899
                                   CXXCastPath *BasePath,
2900
40.1k
                                   bool IgnoreAccess) {
2901
  // First, determine whether the path from Derived to Base is
2902
  // ambiguous. This is slightly more expensive than checking whether
2903
  // the Derived to Base conversion exists, because here we need to
2904
  // explore multiple paths to determine if there is an ambiguity.
2905
40.1k
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2906
40.1k
                     /*DetectVirtual=*/false);
2907
40.1k
  bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2908
40.1k
  if (!DerivationOkay)
2909
1
    return true;
2910
2911
40.1k
  const CXXBasePath *Path = nullptr;
2912
40.1k
  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2913
40.0k
    Path = &Paths.front();
2914
2915
  // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2916
  // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2917
  // user to access such bases.
2918
40.1k
  if (!Path && 
getLangOpts().MSVCCompat62
) {
2919
9
    for (const CXXBasePath &PossiblePath : Paths) {
2920
9
      if (PossiblePath.size() == 1) {
2921
5
        Path = &PossiblePath;
2922
5
        if (AmbiguousBaseConvID)
2923
5
          Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2924
5
              << Base << Derived << Range;
2925
5
        break;
2926
5
      }
2927
9
    }
2928
5
  }
2929
2930
40.1k
  if (Path) {
2931
40.0k
    if (!IgnoreAccess) {
2932
      // Check that the base class can be accessed.
2933
24.2k
      switch (
2934
24.2k
          CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2935
55
      case AR_inaccessible:
2936
55
        return true;
2937
24.1k
      case AR_accessible:
2938
24.1k
      case AR_dependent:
2939
24.1k
      case AR_delayed:
2940
24.1k
        break;
2941
24.2k
      }
2942
24.2k
    }
2943
2944
    // Build a base path if necessary.
2945
40.0k
    if (BasePath)
2946
39.5k
      ::BuildBasePathArray(*Path, *BasePath);
2947
40.0k
    return false;
2948
40.0k
  }
2949
2950
57
  if (AmbiguousBaseConvID) {
2951
    // We know that the derived-to-base conversion is ambiguous, and
2952
    // we're going to produce a diagnostic. Perform the derived-to-base
2953
    // search just one more time to compute all of the possible paths so
2954
    // that we can print them out. This is more expensive than any of
2955
    // the previous derived-to-base checks we've done, but at this point
2956
    // performance isn't as much of an issue.
2957
53
    Paths.clear();
2958
53
    Paths.setRecordingPaths(true);
2959
53
    bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2960
53
    assert(StillOkay && "Can only be used with a derived-to-base conversion");
2961
0
    (void)StillOkay;
2962
2963
    // Build up a textual representation of the ambiguous paths, e.g.,
2964
    // D -> B -> A, that will be used to illustrate the ambiguous
2965
    // conversions in the diagnostic. We only print one of the paths
2966
    // to each base class subobject.
2967
53
    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2968
2969
53
    Diag(Loc, AmbiguousBaseConvID)
2970
53
    << Derived << Base << PathDisplayStr << Range << Name;
2971
53
  }
2972
0
  return true;
2973
40.1k
}
2974
2975
bool
2976
Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2977
                                   SourceLocation Loc, SourceRange Range,
2978
                                   CXXCastPath *BasePath,
2979
34.0k
                                   bool IgnoreAccess) {
2980
34.0k
  return CheckDerivedToBaseConversion(
2981
34.0k
      Derived, Base, diag::err_upcast_to_inaccessible_base,
2982
34.0k
      diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2983
34.0k
      BasePath, IgnoreAccess);
2984
34.0k
}
2985
2986
2987
/// Builds a string representing ambiguous paths from a
2988
/// specific derived class to different subobjects of the same base
2989
/// class.
2990
///
2991
/// This function builds a string that can be used in error messages
2992
/// to show the different paths that one can take through the
2993
/// inheritance hierarchy to go from the derived class to different
2994
/// subobjects of a base class. The result looks something like this:
2995
/// @code
2996
/// struct D -> struct B -> struct A
2997
/// struct D -> struct C -> struct A
2998
/// @endcode
2999
337
std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3000
337
  std::string PathDisplayStr;
3001
337
  std::set<unsigned> DisplayedPaths;
3002
337
  for (CXXBasePaths::paths_iterator Path = Paths.begin();
3003
1.19k
       Path != Paths.end(); 
++Path856
) {
3004
856
    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3005
      // We haven't displayed a path to this particular base
3006
      // class subobject yet.
3007
792
      PathDisplayStr += "\n    ";
3008
792
      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3009
792
      for (CXXBasePath::const_iterator Element = Path->begin();
3010
2.42k
           Element != Path->end(); 
++Element1.63k
)
3011
1.63k
        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3012
792
    }
3013
856
  }
3014
3015
337
  return PathDisplayStr;
3016
337
}
3017
3018
//===----------------------------------------------------------------------===//
3019
// C++ class member Handling
3020
//===----------------------------------------------------------------------===//
3021
3022
/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3023
bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3024
                                SourceLocation ColonLoc,
3025
155k
                                const ParsedAttributesView &Attrs) {
3026
155k
  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3027
0
  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3028
155k
                                                  ASLoc, ColonLoc);
3029
155k
  CurContext->addHiddenDecl(ASDecl);
3030
155k
  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3031
155k
}
3032
3033
/// CheckOverrideControl - Check C++11 override control semantics.
3034
3.58M
void Sema::CheckOverrideControl(NamedDecl *D) {
3035
3.58M
  if (D->isInvalidDecl())
3036
1.03k
    return;
3037
3038
  // We only care about "override" and "final" declarations.
3039
3.57M
  if (!D->hasAttr<OverrideAttr>() && 
!D->hasAttr<FinalAttr>()3.57M
)
3040
3.57M
    return;
3041
3042
547
  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3043
3044
  // We can't check dependent instance methods.
3045
547
  if (MD && 
MD->isInstance()545
&&
3046
547
      
(544
MD->getParent()->hasAnyDependentBases()544
||
3047
544
       
MD->getType()->isDependentType()526
))
3048
24
    return;
3049
3050
523
  if (MD && 
!MD->isVirtual()521
) {
3051
    // If we have a non-virtual method, check if if hides a virtual method.
3052
    // (In that case, it's most likely the method has the wrong type.)
3053
18
    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3054
18
    FindHiddenVirtualMethods(MD, OverloadedMethods);
3055
3056
18
    if (!OverloadedMethods.empty()) {
3057
4
      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3058
3
        Diag(OA->getLocation(),
3059
3
             diag::override_keyword_hides_virtual_member_function)
3060
3
          << "override" << (OverloadedMethods.size() > 1);
3061
3
      } else 
if (FinalAttr *1
FA1
= D->getAttr<FinalAttr>()) {
3062
1
        Diag(FA->getLocation(),
3063
1
             diag::override_keyword_hides_virtual_member_function)
3064
1
          << (FA->isSpelledAsSealed() ? 
"sealed"0
: "final")
3065
1
          << (OverloadedMethods.size() > 1);
3066
1
      }
3067
4
      NoteHiddenVirtualMethods(MD, OverloadedMethods);
3068
4
      MD->setInvalidDecl();
3069
4
      return;
3070
4
    }
3071
    // Fall through into the general case diagnostic.
3072
    // FIXME: We might want to attempt typo correction here.
3073
18
  }
3074
3075
519
  if (!MD || 
!MD->isVirtual()517
) {
3076
16
    if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3077
10
      Diag(OA->getLocation(),
3078
10
           diag::override_keyword_only_allowed_on_virtual_member_functions)
3079
10
        << "override" << FixItHint::CreateRemoval(OA->getLocation());
3080
10
      D->dropAttr<OverrideAttr>();
3081
10
    }
3082
16
    if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3083
6
      Diag(FA->getLocation(),
3084
6
           diag::override_keyword_only_allowed_on_virtual_member_functions)
3085
6
        << (FA->isSpelledAsSealed() ? 
"sealed"0
: "final")
3086
6
        << FixItHint::CreateRemoval(FA->getLocation());
3087
6
      D->dropAttr<FinalAttr>();
3088
6
    }
3089
16
    return;
3090
16
  }
3091
3092
  // C++11 [class.virtual]p5:
3093
  //   If a function is marked with the virt-specifier override and
3094
  //   does not override a member function of a base class, the program is
3095
  //   ill-formed.
3096
503
  bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3097
503
  if (MD->hasAttr<OverrideAttr>() && 
!HasOverriddenMethods431
)
3098
4
    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3099
4
      << MD->getDeclName();
3100
503
}
3101
3102
141k
void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3103
141k
  if (D->isInvalidDecl() || 
D->hasAttr<OverrideAttr>()141k
)
3104
39
    return;
3105
141k
  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3106
141k
  if (!MD || MD->isImplicit() || 
MD->hasAttr<FinalAttr>()110k
)
3107
31.5k
    return;
3108
3109
110k
  SourceLocation Loc = MD->getLocation();
3110
110k
  SourceLocation SpellingLoc = Loc;
3111
110k
  if (getSourceManager().isMacroArgExpansion(Loc))
3112
1
    SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3113
110k
  SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3114
110k
  if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3115
107k
      return;
3116
3117
2.84k
  if (MD->size_overridden_methods() > 0) {
3118
1.84k
    auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3119
1.84k
      unsigned DiagID =
3120
1.84k
          Inconsistent && 
!Diags.isIgnored(DiagInconsistent, MD->getLocation())6
3121
1.84k
              ? 
DiagInconsistent4
3122
1.84k
              : 
DiagSuggest1.83k
;
3123
1.84k
      Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3124
1.84k
      const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3125
1.84k
      Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3126
1.84k
    };
3127
1.84k
    if (isa<CXXDestructorDecl>(MD))
3128
374
      EmitDiag(
3129
374
          diag::warn_inconsistent_destructor_marked_not_override_overriding,
3130
374
          diag::warn_suggest_destructor_marked_not_override_overriding);
3131
1.46k
    else
3132
1.46k
      EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3133
1.46k
               diag::warn_suggest_function_marked_not_override_overriding);
3134
1.84k
  }
3135
2.84k
}
3136
3137
/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3138
/// function overrides a virtual member function marked 'final', according to
3139
/// C++11 [class.virtual]p4.
3140
bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3141
32.8k
                                                  const CXXMethodDecl *Old) {
3142
32.8k
  FinalAttr *FA = Old->getAttr<FinalAttr>();
3143
32.8k
  if (!FA)
3144
32.8k
    return false;
3145
3146
7
  Diag(New->getLocation(), diag::err_final_function_overridden)
3147
7
    << New->getDeclName()
3148
7
    << FA->isSpelledAsSealed();
3149
7
  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3150
7
  return true;
3151
32.8k
}
3152
3153
195
static bool InitializationHasSideEffects(const FieldDecl &FD) {
3154
195
  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3155
  // FIXME: Destruction of ObjC lifetime types has side-effects.
3156
195
  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3157
38
    return !RD->isCompleteDefinition() ||
3158
38
           !RD->hasTrivialDefaultConstructor() ||
3159
38
           
!RD->hasTrivialDestructor()32
;
3160
157
  return false;
3161
195
}
3162
3163
2.59M
static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3164
2.59M
  ParsedAttributesView::const_iterator Itr =
3165
2.59M
      llvm::find_if(list, [](const ParsedAttr &AL) {
3166
1.22M
        return AL.isDeclspecPropertyAttribute();
3167
1.22M
      });
3168
2.59M
  if (Itr != list.end())
3169
99
    return &*Itr;
3170
2.59M
  return nullptr;
3171
2.59M
}
3172
3173
// Check if there is a field shadowing.
3174
void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3175
                                      DeclarationName FieldName,
3176
                                      const CXXRecordDecl *RD,
3177
1.96M
                                      bool DeclIsField) {
3178
1.96M
  if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3179
1.96M
    return;
3180
3181
  // To record a shadowed field in a base
3182
56
  std::map<CXXRecordDecl*, NamedDecl*> Bases;
3183
56
  auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3184
83
                           CXXBasePath &Path) {
3185
83
    const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3186
    // Record an ambiguous path directly
3187
83
    if (Bases.find(Base) != Bases.end())
3188
10
      return true;
3189
73
    for (const auto Field : Base->lookup(FieldName)) {
3190
23
      if ((isa<FieldDecl>(Field) || 
isa<IndirectFieldDecl>(Field)3
) &&
3191
23
          
Field->getAccess() != AS_private21
) {
3192
15
        assert(Field->getAccess() != AS_none);
3193
0
        assert(Bases.find(Base) == Bases.end());
3194
0
        Bases[Base] = Field;
3195
15
        return true;
3196
15
      }
3197
23
    }
3198
58
    return false;
3199
73
  };
3200
3201
56
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3202
56
                     /*DetectVirtual=*/true);
3203
56
  if (!RD->lookupInBases(FieldShadowed, Paths))
3204
43
    return;
3205
3206
25
  
for (const auto &P : Paths)13
{
3207
25
    auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3208
25
    auto It = Bases.find(Base);
3209
    // Skip duplicated bases
3210
25
    if (It == Bases.end())
3211
7
      continue;
3212
18
    auto BaseField = It->second;
3213
18
    assert(BaseField->getAccess() != AS_private);
3214
18
    if (AS_none !=
3215
18
        CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3216
14
      Diag(Loc, diag::warn_shadow_field)
3217
14
        << FieldName << RD << Base << DeclIsField;
3218
14
      Diag(BaseField->getLocation(), diag::note_shadow_field);
3219
14
      Bases.erase(It);
3220
14
    }
3221
18
  }
3222
13
}
3223
3224
/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3225
/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3226
/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3227
/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3228
/// present (but parsing it has been deferred).
3229
NamedDecl *
3230
Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3231
                               MultiTemplateParamsArg TemplateParameterLists,
3232
                               Expr *BW, const VirtSpecifiers &VS,
3233
2.59M
                               InClassInitStyle InitStyle) {
3234
2.59M
  const DeclSpec &DS = D.getDeclSpec();
3235
2.59M
  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3236
2.59M
  DeclarationName Name = NameInfo.getName();
3237
2.59M
  SourceLocation Loc = NameInfo.getLoc();
3238
3239
  // For anonymous bitfields, the location should point to the type.
3240
2.59M
  if (Loc.isInvalid())
3241
1
    Loc = D.getBeginLoc();
3242
3243
2.59M
  Expr *BitWidth = static_cast<Expr*>(BW);
3244
3245
2.59M
  assert(isa<CXXRecordDecl>(CurContext));
3246
0
  assert(!DS.isFriendSpecified());
3247
3248
0
  bool isFunc = D.isDeclarationOfFunction();
3249
2.59M
  const ParsedAttr *MSPropertyAttr =
3250
2.59M
      getMSPropertyAttr(D.getDeclSpec().getAttributes());
3251
3252
2.59M
  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3253
    // The Microsoft extension __interface only permits public member functions
3254
    // and prohibits constructors, destructors, operators, non-public member
3255
    // functions, static methods and data members.
3256
23
    unsigned InvalidDecl;
3257
23
    bool ShowDeclName = true;
3258
23
    if (!isFunc &&
3259
23
        
(3
DS.getStorageClassSpec() == DeclSpec::SCS_typedef3
||
MSPropertyAttr2
))
3260
2
      InvalidDecl = 0;
3261
21
    else if (!isFunc)
3262
1
      InvalidDecl = 1;
3263
20
    else if (AS != AS_public)
3264
2
      InvalidDecl = 2;
3265
18
    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3266
1
      InvalidDecl = 3;
3267
17
    else switch (Name.getNameKind()) {
3268
1
      case DeclarationName::CXXConstructorName:
3269
1
        InvalidDecl = 4;
3270
1
        ShowDeclName = false;
3271
1
        break;
3272
3273
1
      case DeclarationName::CXXDestructorName:
3274
1
        InvalidDecl = 5;
3275
1
        ShowDeclName = false;
3276
1
        break;
3277
3278
1
      case DeclarationName::CXXOperatorName:
3279
2
      case DeclarationName::CXXConversionFunctionName:
3280
2
        InvalidDecl = 6;
3281
2
        break;
3282
3283
13
      default:
3284
13
        InvalidDecl = 0;
3285
13
        break;
3286
17
    }
3287
3288
23
    if (InvalidDecl) {
3289
8
      if (ShowDeclName)
3290
6
        Diag(Loc, diag::err_invalid_member_in_interface)
3291
6
          << (InvalidDecl-1) << Name;
3292
2
      else
3293
2
        Diag(Loc, diag::err_invalid_member_in_interface)
3294
2
          << (InvalidDecl-1) << "";
3295
8
      return nullptr;
3296
8
    }
3297
23
  }
3298
3299
  // C++ 9.2p6: A member shall not be declared to have automatic storage
3300
  // duration (auto, register) or with the extern storage-class-specifier.
3301
  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3302
  // data members and cannot be applied to names declared const or static,
3303
  // and cannot be applied to reference members.
3304
2.59M
  switch (DS.getStorageClassSpec()) {
3305
1.92M
  case DeclSpec::SCS_unspecified:
3306
2.26M
  case DeclSpec::SCS_typedef:
3307
2.58M
  case DeclSpec::SCS_static:
3308
2.58M
    break;
3309
3.05k
  case DeclSpec::SCS_mutable:
3310
3.05k
    if (isFunc) {
3311
4
      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3312
3313
      // FIXME: It would be nicer if the keyword was ignored only for this
3314
      // declarator. Otherwise we could get follow-up errors.
3315
4
      D.getMutableDeclSpec().ClearStorageClassSpecs();
3316
4
    }
3317
3.05k
    break;
3318
19
  default:
3319
19
    Diag(DS.getStorageClassSpecLoc(),
3320
19
         diag::err_storageclass_invalid_for_member);
3321
19
    D.getMutableDeclSpec().ClearStorageClassSpecs();
3322
19
    break;
3323
2.59M
  }
3324
3325
2.59M
  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3326
2.59M
                       
DS.getStorageClassSpec() == DeclSpec::SCS_mutable671k
) &&
3327
2.59M
                      
!isFunc1.92M
);
3328
3329
2.59M
  if (DS.hasConstexprSpecifier() && 
isInstField227k
) {
3330
24
    SemaDiagnosticBuilder B =
3331
24
        Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3332
24
    SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3333
24
    if (InitStyle == ICIS_NoInit) {
3334
13
      B << 0 << 0;
3335
13
      if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3336
2
        B << FixItHint::CreateRemoval(ConstexprLoc);
3337
11
      else {
3338
11
        B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3339
11
        D.getMutableDeclSpec().ClearConstexprSpec();
3340
11
        const char *PrevSpec;
3341
11
        unsigned DiagID;
3342
11
        bool Failed = D.getMutableDeclSpec().SetTypeQual(
3343
11
            DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3344
11
        (void)Failed;
3345
11
        assert(!Failed && "Making a constexpr member const shouldn't fail");
3346
11
      }
3347
13
    } else {
3348
11
      B << 1;
3349
11
      const char *PrevSpec;
3350
11
      unsigned DiagID;
3351
11
      if (D.getMutableDeclSpec().SetStorageClassSpec(
3352
11
          *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3353
11
          Context.getPrintingPolicy())) {
3354
5
        assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3355
5
               "This is the only DeclSpec that should fail to be applied");
3356
0
        B << 1;
3357
6
      } else {
3358
6
        B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3359
6
        isInstField = false;
3360
6
      }
3361
11
    }
3362
24
  }
3363
3364
0
  NamedDecl *Member;
3365
2.59M
  if (isInstField) {
3366
1.03M
    CXXScopeSpec &SS = D.getCXXScopeSpec();
3367
3368
    // Data members must have identifiers for names.
3369
1.03M
    if (!Name.isIdentifier()) {
3370
9
      Diag(Loc, diag::err_bad_variable_name)
3371
9
        << Name;
3372
9
      return nullptr;
3373
9
    }
3374
3375
1.03M
    IdentifierInfo *II = Name.getAsIdentifierInfo();
3376
3377
    // Member field could not be with "template" keyword.
3378
    // So TemplateParameterLists should be empty in this case.
3379
1.03M
    if (TemplateParameterLists.size()) {
3380
22
      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3381
22
      if (TemplateParams->size()) {
3382
        // There is no such thing as a member field template.
3383
21
        Diag(D.getIdentifierLoc(), diag::err_template_member)
3384
21
            << II
3385
21
            << SourceRange(TemplateParams->getTemplateLoc(),
3386
21
                TemplateParams->getRAngleLoc());
3387
21
      } else {
3388
        // There is an extraneous 'template<>' for this member.
3389
1
        Diag(TemplateParams->getTemplateLoc(),
3390
1
            diag::err_template_member_noparams)
3391
1
            << II
3392
1
            << SourceRange(TemplateParams->getTemplateLoc(),
3393
1
                TemplateParams->getRAngleLoc());
3394
1
      }
3395
22
      return nullptr;
3396
22
    }
3397
3398
1.03M
    if (SS.isSet() && 
!SS.isInvalid()6
) {
3399
      // The user provided a superfluous scope specifier inside a class
3400
      // definition:
3401
      //
3402
      // class X {
3403
      //   int X::member;
3404
      // };
3405
6
      if (DeclContext *DC = computeDeclContext(SS, false))
3406
2
        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3407
2
                                     D.getName().getKind() ==
3408
2
                                         UnqualifiedIdKind::IK_TemplateId);
3409
4
      else
3410
4
        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3411
4
          << Name << SS.getRange();
3412
3413
6
      SS.clear();
3414
6
    }
3415
3416
1.03M
    if (MSPropertyAttr) {
3417
99
      Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3418
99
                                BitWidth, InitStyle, AS, *MSPropertyAttr);
3419
99
      if (!Member)
3420
3
        return nullptr;
3421
96
      isInstField = false;
3422
1.03M
    } else {
3423
1.03M
      Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3424
1.03M
                                BitWidth, InitStyle, AS);
3425
1.03M
      if (!Member)
3426
8
        return nullptr;
3427
1.03M
    }
3428
3429
1.03M
    CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3430
1.55M
  } else {
3431
1.55M
    Member = HandleDeclarator(S, D, TemplateParameterLists);
3432
1.55M
    if (!Member)
3433
122
      return nullptr;
3434
3435
    // Non-instance-fields can't have a bitfield.
3436
1.55M
    if (BitWidth) {
3437
9
      if (Member->isInvalidDecl()) {
3438
        // don't emit another diagnostic.
3439
9
      } else if (isa<VarDecl>(Member) || 
isa<VarTemplateDecl>(Member)7
) {
3440
        // C++ 9.6p3: A bit-field shall not be a static member.
3441
        // "static member 'A' cannot be a bit-field"
3442
5
        Diag(Loc, diag::err_static_not_bitfield)
3443
5
          << Name << BitWidth->getSourceRange();
3444
5
      } else 
if (4
isa<TypedefDecl>(Member)4
) {
3445
        // "typedef member 'x' cannot be a bit-field"
3446
2
        Diag(Loc, diag::err_typedef_not_bitfield)
3447
2
          << Name << BitWidth->getSourceRange();
3448
2
      } else {
3449
        // A function typedef ("typedef int f(); f a;").
3450
        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3451
2
        Diag(Loc, diag::err_not_integral_type_bitfield)
3452
2
          << Name << cast<ValueDecl>(Member)->getType()
3453
2
          << BitWidth->getSourceRange();
3454
2
      }
3455
3456
9
      BitWidth = nullptr;
3457
9
      Member->setInvalidDecl();
3458
9
    }
3459
3460
1.55M
    NamedDecl *NonTemplateMember = Member;
3461
1.55M
    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3462
158k
      NonTemplateMember = FunTmpl->getTemplatedDecl();
3463
1.39M
    else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3464
505
      NonTemplateMember = VarTmpl->getTemplatedDecl();
3465
3466
1.55M
    Member->setAccess(AS);
3467
3468
    // If we have declared a member function template or static data member
3469
    // template, set the access of the templated declaration as well.
3470
1.55M
    if (NonTemplateMember != Member)
3471
158k
      NonTemplateMember->setAccess(AS);
3472
3473
    // C++ [temp.deduct.guide]p3:
3474
    //   A deduction guide [...] for a member class template [shall be
3475
    //   declared] with the same access [as the template].
3476
1.55M
    if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3477
46
      auto *TD = DG->getDeducedTemplate();
3478
      // Access specifiers are only meaningful if both the template and the
3479
      // deduction guide are from the same scope.
3480
46
      if (AS != TD->getAccess() &&
3481
46
          TD->getDeclContext()->getRedeclContext()->Equals(
3482
7
              DG->getDeclContext()->getRedeclContext())) {
3483
4
        Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3484
4
        Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3485
4
            << TD->getAccess();
3486
4
        const AccessSpecDecl *LastAccessSpec = nullptr;
3487
62
        for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3488
62
          if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3489
9
            LastAccessSpec = AccessSpec;
3490
62
        }
3491
4
        assert(LastAccessSpec && "differing access with no access specifier");
3492
0
        Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3493
4
            << AS;
3494
4
      }
3495
46
    }
3496
1.55M
  }
3497
3498
2.59M
  if (VS.isOverrideSpecified())
3499
447
    Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3500
447
                                         AttributeCommonInfo::AS_Keyword));
3501
2.59M
  if (VS.isFinalSpecified())
3502
90
    Member->addAttr(FinalAttr::Create(
3503
90
        Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3504
90
        static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3505
3506
2.59M
  if (VS.getLastLocation().isValid()) {
3507
    // Update the end location of a method that has a virt-specifiers.
3508
535
    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3509
533
      MD->setRangeEnd(VS.getLastLocation());
3510
535
  }
3511
3512
2.59M
  CheckOverrideControl(Member);
3513
3514
2.59M
  assert((Name || isInstField) && "No identifier for non-field ?");
3515
3516
2.59M
  if (isInstField) {
3517
1.03M
    FieldDecl *FD = cast<FieldDecl>(Member);
3518
1.03M
    FieldCollector->Add(FD);
3519
3520
1.03M
    if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3521
      // Remember all explicit private FieldDecls that have a name, no side
3522
      // effects and are not part of a dependent type declaration.
3523
612
      if (!FD->isImplicit() && FD->getDeclName() &&
3524
612
          
FD->getAccess() == AS_private597
&&
3525
612
          
!FD->hasAttr<UnusedAttr>()223
&&
3526
612
          
!FD->getParent()->isDependentContext()214
&&
3527
612
          
!InitializationHasSideEffects(*FD)195
)
3528
183
        UnusedPrivateFields.insert(FD);
3529
612
    }
3530
1.03M
  }
3531
3532
2.59M
  return Member;
3533
2.59M
}
3534
3535
namespace {
3536
  class UninitializedFieldVisitor
3537
      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3538
    Sema &S;
3539
    // List of Decls to generate a warning on.  Also remove Decls that become
3540
    // initialized.
3541
    llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3542
    // List of base classes of the record.  Classes are removed after their
3543
    // initializers.
3544
    llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3545
    // Vector of decls to be removed from the Decl set prior to visiting the
3546
    // nodes.  These Decls may have been initialized in the prior initializer.
3547
    llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3548
    // If non-null, add a note to the warning pointing back to the constructor.
3549
    const CXXConstructorDecl *Constructor;
3550
    // Variables to hold state when processing an initializer list.  When
3551
    // InitList is true, special case initialization of FieldDecls matching
3552
    // InitListFieldDecl.
3553
    bool InitList;
3554
    FieldDecl *InitListFieldDecl;
3555
    llvm::SmallVector<unsigned, 4> InitFieldIndex;
3556
3557
  public:
3558
    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3559
    UninitializedFieldVisitor(Sema &S,
3560
                              llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3561
                              llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3562
      : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3563
34.0k
        Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3564
3565
    // Returns true if the use of ME is not an uninitialized use.
3566
    bool IsInitListMemberExprInitialized(MemberExpr *ME,
3567
65
                                         bool CheckReferenceOnly) {
3568
65
      llvm::SmallVector<FieldDecl*, 4> Fields;
3569
65
      bool ReferenceField = false;
3570
227
      while (ME) {
3571
162
        FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3572
162
        if (!FD)
3573
0
          return false;
3574
162
        Fields.push_back(FD);
3575
162
        if (FD->getType()->isReferenceType())
3576
12
          ReferenceField = true;
3577
162
        ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3578
162
      }
3579
3580
      // Binding a reference to an uninitialized field is not an
3581
      // uninitialized use.
3582
65
      if (CheckReferenceOnly && 
!ReferenceField12
)
3583
6
        return true;
3584
3585
59
      llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3586
      // Discard the first field since it is the field decl that is being
3587
      // initialized.
3588
59
      for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3589
91
        UsedFieldIndex.push_back(FD->getFieldIndex());
3590
3591
59
      for (auto UsedIter = UsedFieldIndex.begin(),
3592
59
                UsedEnd = UsedFieldIndex.end(),
3593
59
                OrigIter = InitFieldIndex.begin(),
3594
59
                OrigEnd = InitFieldIndex.end();
3595
95
           UsedIter != UsedEnd && 
OrigIter != OrigEnd75
;
++UsedIter, ++OrigIter36
) {
3596
75
        if (*UsedIter < *OrigIter)
3597
18
          return true;
3598
57
        if (*UsedIter > *OrigIter)
3599
21
          break;
3600
57
      }
3601
3602
41
      return false;
3603
59
    }
3604
3605
    void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3606
5.34k
                          bool AddressOf) {
3607
5.34k
      if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3608
9
        return;
3609
3610
      // FieldME is the inner-most MemberExpr that is not an anonymous struct
3611
      // or union.
3612
5.33k
      MemberExpr *FieldME = ME;
3613
3614
5.33k
      bool AllPODFields = FieldME->getType().isPODType(S.Context);
3615
3616
5.33k
      Expr *Base = ME;
3617
10.8k
      while (MemberExpr *SubME =
3618
5.53k
                 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3619
3620
5.53k
        if (isa<VarDecl>(SubME->getMemberDecl()))
3621
8
          return;
3622
3623
5.52k
        if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3624
5.41k
          if (!FD->isAnonymousStructOrUnion())
3625
5.39k
            FieldME = SubME;
3626
3627
5.52k
        if (!FieldME->getType().isPODType(S.Context))
3628
320
          AllPODFields = false;
3629
3630
5.52k
        Base = SubME->getBase();
3631
5.52k
      }
3632
3633
5.33k
      if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3634
4.76k
        Visit(Base);
3635
4.76k
        return;
3636
4.76k
      }
3637
3638
562
      if (AddressOf && 
AllPODFields3
)
3639
2
        return;
3640
3641
560
      ValueDecl* FoundVD = FieldME->getMemberDecl();
3642
3643
560
      if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3644
16
        while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3645
0
          BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3646
0
        }
3647
3648
16
        if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3649
13
          QualType T = BaseCast->getType();
3650
13
          if (T->isPointerType() &&
3651
13
              BaseClasses.count(T->getPointeeType())) {
3652
4
            S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3653
4
                << T->getPointeeType() << FoundVD;
3654
4
          }
3655
13
        }
3656
16
      }
3657
3658
560
      if (!Decls.count(FoundVD))
3659
217
        return;
3660
3661
343
      const bool IsReference = FoundVD->getType()->isReferenceType();
3662
3663
343
      if (InitList && 
!AddressOf70
&&
FoundVD == InitListFieldDecl70
) {
3664
        // Special checking for initializer lists.
3665
65
        if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3666
24
          return;
3667
24
        }
3668
278
      } else {
3669
        // Prevent double warnings on use of unbounded references.
3670
278
        if (CheckReferenceOnly && 
!IsReference85
)
3671
81
          return;
3672
278
      }
3673
3674
238
      unsigned diag = IsReference
3675
238
          ? 
diag::warn_reference_field_is_uninit5
3676
238
          : 
diag::warn_field_is_uninit233
;
3677
238
      S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3678
238
      if (Constructor)
3679
45
        S.Diag(Constructor->getLocation(),
3680
45
               diag::note_uninit_in_this_constructor)
3681
45
          << (Constructor->isDefaultConstructor() && 
Constructor->isImplicit()44
);
3682
3683
238
    }
3684
3685
14.0k
    void HandleValue(Expr *E, bool AddressOf) {
3686
14.0k
      E = E->IgnoreParens();
3687
3688
14.0k
      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3689
5.16k
        HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3690
5.16k
                         AddressOf /*AddressOf*/);
3691
5.16k
        return;
3692
5.16k
      }
3693
3694
8.92k
      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3695
16
        Visit(CO->getCond());
3696
16
        HandleValue(CO->getTrueExpr(), AddressOf);
3697
16
        HandleValue(CO->getFalseExpr(), AddressOf);
3698
16
        return;
3699
16
      }
3700
3701
8.90k
      if (BinaryConditionalOperator *BCO =
3702
8.90k
              dyn_cast<BinaryConditionalOperator>(E)) {
3703
8
        Visit(BCO->getCond());
3704
8
        HandleValue(BCO->getFalseExpr(), AddressOf);
3705
8
        return;
3706
8
      }
3707
3708
8.89k
      if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3709
8
        HandleValue(OVE->getSourceExpr(), AddressOf);
3710
8
        return;
3711
8
      }
3712
3713
8.88k
      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3714
37
        switch (BO->getOpcode()) {
3715
18
        default:
3716
18
          break;
3717
18
        case(BO_PtrMemD):
3718
4
        case(BO_PtrMemI):
3719
4
          HandleValue(BO->getLHS(), AddressOf);
3720
4
          Visit(BO->getRHS());
3721
4
          return;
3722
15
        case(BO_Comma):
3723
15
          Visit(BO->getLHS());
3724
15
          HandleValue(BO->getRHS(), AddressOf);
3725
15
          return;
3726
37
        }
3727
37
      }
3728
3729
8.87k
      Visit(E);
3730
8.87k
    }
3731
3732
291
    void CheckInitListExpr(InitListExpr *ILE) {
3733
291
      InitFieldIndex.push_back(0);
3734
760
      for (auto Child : ILE->children()) {
3735
760
        if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3736
89
          CheckInitListExpr(SubList);
3737
671
        } else {
3738
671
          Visit(Child);
3739
671
        }
3740
760
        ++InitFieldIndex.back();
3741
760
      }
3742
291
      InitFieldIndex.pop_back();
3743
291
    }
3744
3745
    void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3746
32.4k
                          FieldDecl *Field, const Type *BaseClass) {
3747
      // Remove Decls that may have been initialized in the previous
3748
      // initializer.
3749
32.4k
      for (ValueDecl* VD : DeclsToRemove)
3750
9
        Decls.erase(VD);
3751
32.4k
      DeclsToRemove.clear();
3752
3753
32.4k
      Constructor = FieldConstructor;
3754
32.4k
      InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3755
3756
32.4k
      if (ILE && 
Field219
) {
3757
202
        InitList = true;
3758
202
        InitListFieldDecl = Field;
3759
202
        InitFieldIndex.clear();
3760
202
        CheckInitListExpr(ILE);
3761
32.2k
      } else {
3762
32.2k
        InitList = false;
3763
32.2k
        Visit(E);
3764
32.2k
      }
3765
3766
32.4k
      if (Field)
3767
24.1k
        Decls.erase(Field);
3768
32.4k
      if (BaseClass)
3769
8.16k
        BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3770
32.4k
    }
3771
3772
186
    void VisitMemberExpr(MemberExpr *ME) {
3773
      // All uses of unbounded reference fields will warn.
3774
186
      HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3775
186
    }
3776
3777
16.0k
    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3778
16.0k
      if (E->getCastKind() == CK_LValueToRValue) {
3779
13.4k
        HandleValue(E->getSubExpr(), false /*AddressOf*/);
3780
13.4k
        return;
3781
13.4k
      }
3782
3783
2.66k
      Inherited::VisitImplicitCastExpr(E);
3784
2.66k
    }
3785
3786
11.6k
    void VisitCXXConstructExpr(CXXConstructExpr *E) {
3787
11.6k
      if (E->getConstructor()->isCopyConstructor()) {
3788
281
        Expr *ArgExpr = E->getArg(0);
3789
281
        if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3790
3
          if (ILE->getNumInits() == 1)
3791
3
            ArgExpr = ILE->getInit(0);
3792
281
        if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3793
219
          if (ICE->getCastKind() == CK_NoOp)
3794
196
            ArgExpr = ICE->getSubExpr();
3795
281
        HandleValue(ArgExpr, false /*AddressOf*/);
3796
281
        return;
3797
281
      }
3798
11.4k
      Inherited::VisitCXXConstructExpr(E);
3799
11.4k
    }
3800
3801
97
    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3802
97
      Expr *Callee = E->getCallee();
3803
97
      if (isa<MemberExpr>(Callee)) {
3804
97
        HandleValue(Callee, false /*AddressOf*/);
3805
97
        for (auto Arg : E->arguments())
3806
3
          Visit(Arg);
3807
97
        return;
3808
97
      }
3809
3810
0
      Inherited::VisitCXXMemberCallExpr(E);
3811
0
    }
3812
3813
260
    void VisitCallExpr(CallExpr *E) {
3814
      // Treat std::move as a use.
3815
260
      if (E->isCallToStdMove()) {
3816
36
        HandleValue(E->getArg(0), /*AddressOf=*/false);
3817
36
        return;
3818
36
      }
3819
3820
224
      Inherited::VisitCallExpr(E);
3821
224
    }
3822
3823
49
    void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3824
49
      Expr *Callee = E->getCallee();
3825
3826
49
      if (isa<UnresolvedLookupExpr>(Callee))
3827
0
        return Inherited::VisitCXXOperatorCallExpr(E);
3828
3829
49
      Visit(Callee);
3830
49
      for (auto Arg : E->arguments())
3831
81
        HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3832
49
    }
3833
3834
1.87k
    void VisitBinaryOperator(BinaryOperator *E) {
3835
      // If a field assignment is detected, remove the field from the
3836
      // uninitiailized field set.
3837
1.87k
      if (E->getOpcode() == BO_Assign)
3838
18
        if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3839
17
          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3840
17
            if (!FD->getType()->isReferenceType())
3841
16
              DeclsToRemove.push_back(FD);
3842
3843
1.87k
      if (E->isCompoundAssignmentOp()) {
3844
3
        HandleValue(E->getLHS(), false /*AddressOf*/);
3845
3
        Visit(E->getRHS());
3846
3
        return;
3847
3
      }
3848
3849
1.87k
      Inherited::VisitBinaryOperator(E);
3850
1.87k
    }
3851
3852
186
    void VisitUnaryOperator(UnaryOperator *E) {
3853
186
      if (E->isIncrementDecrementOp()) {
3854
37
        HandleValue(E->getSubExpr(), false /*AddressOf*/);
3855
37
        return;
3856
37
      }
3857
149
      if (E->getOpcode() == UO_AddrOf) {
3858
118
        if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3859
56
          HandleValue(ME->getBase(), true /*AddressOf*/);
3860
56
          return;
3861
56
        }
3862
118
      }
3863
3864
93
      Inherited::VisitUnaryOperator(E);
3865
93
    }
3866
  };
3867
3868
  // Diagnose value-uses of fields to initialize themselves, e.g.
3869
  //   foo(foo)
3870
  // where foo is not also a parameter to the constructor.
3871
  // Also diagnose across field uninitialized use such as
3872
  //   x(y), y(x)
3873
  // TODO: implement -Wuninitialized and fold this into that framework.
3874
  static void DiagnoseUninitializedFields(
3875
238k
      Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3876
3877
238k
    if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3878
238k
                                           Constructor->getLocation())) {
3879
187k
      return;
3880
187k
    }
3881
3882
51.0k
    if (Constructor->isInvalidDecl())
3883
51
      return;
3884
3885
51.0k
    const CXXRecordDecl *RD = Constructor->getParent();
3886
3887
51.0k
    if (RD->isDependentContext())
3888
4.61k
      return;
3889
3890
    // Holds fields that are uninitialized.
3891
46.4k
    llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3892
3893
    // At the beginning, all fields are uninitialized.
3894
302k
    for (auto *I : RD->decls()) {
3895
302k
      if (auto *FD = dyn_cast<FieldDecl>(I)) {
3896
41.9k
        UninitializedFields.insert(FD);
3897
260k
      } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3898
681
        UninitializedFields.insert(IFD->getAnonField());
3899
681
      }
3900
302k
    }
3901
3902
46.4k
    llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3903
46.4k
    for (auto I : RD->bases())
3904
7.74k
      UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3905
3906
46.4k
    if (UninitializedFields.empty() && 
UninitializedBaseClasses.empty()17.1k
)
3907
12.3k
      return;
3908
3909
34.0k
    UninitializedFieldVisitor UninitializedChecker(SemaRef,
3910
34.0k
                                                   UninitializedFields,
3911
34.0k
                                                   UninitializedBaseClasses);
3912
3913
34.0k
    for (const auto *FieldInit : Constructor->inits()) {
3914
32.4k
      if (UninitializedFields.empty() && 
UninitializedBaseClasses.empty()5.62k
)
3915
10
        break;
3916
3917
32.4k
      Expr *InitExpr = FieldInit->getInit();
3918
32.4k
      if (!InitExpr)
3919
0
        continue;
3920
3921
32.4k
      if (CXXDefaultInitExpr *Default =
3922
32.4k
              dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3923
1.32k
        InitExpr = Default->getExpr();
3924
1.32k
        if (!InitExpr)
3925
0
          continue;
3926
        // In class initializers will point to the constructor.
3927
1.32k
        UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3928
1.32k
                                              FieldInit->getAnyMember(),
3929
1.32k
                                              FieldInit->getBaseClass());
3930
31.0k
      } else {
3931
31.0k
        UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3932
31.0k
                                              FieldInit->getAnyMember(),
3933
31.0k
                                              FieldInit->getBaseClass());
3934
31.0k
      }
3935
32.4k
    }
3936
34.0k
  }
3937
} // namespace
3938
3939
/// Enter a new C++ default initializer scope. After calling this, the
3940
/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3941
/// parsing or instantiating the initializer failed.
3942
3.59k
void Sema::ActOnStartCXXInClassMemberInitializer() {
3943
  // Create a synthetic function scope to represent the call to the constructor
3944
  // that notionally surrounds a use of this initializer.
3945
3.59k
  PushFunctionScope();
3946
3.59k
}
3947
3948
152
void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3949
152
  if (!D.isFunctionDeclarator())
3950
4
    return;
3951
148
  auto &FTI = D.getFunctionTypeInfo();
3952
148
  if (!FTI.Params)
3953
85
    return;
3954
63
  for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3955
71
                                                          FTI.NumParams)) {
3956
71
    auto *ParamDecl = cast<NamedDecl>(Param.Param);
3957
71
    if (ParamDecl->getDeclName())
3958
42
      PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3959
71
  }
3960
63
}
3961
3962
152
ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3963
152
  return ActOnRequiresClause(ConstraintExpr);
3964
152
}
3965
3966
483
ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
3967
483
  if (ConstraintExpr.isInvalid())
3968
18
    return ExprError();
3969
3970
465
  ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
3971
465
  if (ConstraintExpr.isInvalid())
3972
0
    return ExprError();
3973
3974
465
  if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
3975
465
                                      UPPC_RequiresClause))
3976
2
    return ExprError();
3977
3978
463
  return ConstraintExpr;
3979
465
}
3980
3981
/// This is invoked after parsing an in-class initializer for a
3982
/// non-static C++ class member, and after instantiating an in-class initializer
3983
/// in a class template. Such actions are deferred until the class is complete.
3984
void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3985
                                                  SourceLocation InitLoc,
3986
3.59k
                                                  Expr *InitExpr) {
3987
  // Pop the notional constructor scope we created earlier.
3988
3.59k
  PopFunctionScopeInfo(nullptr, D);
3989
3990
3.59k
  FieldDecl *FD = dyn_cast<FieldDecl>(D);
3991
3.59k
  assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3992
3.59k
         "must set init style when field is created");
3993
3994
3.59k
  if (!InitExpr) {
3995
29
    D->setInvalidDecl();
3996
29
    if (FD)
3997
28
      FD->removeInClassInitializer();
3998
29
    return;
3999
29
  }
4000
4001
3.56k
  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4002
1
    FD->setInvalidDecl();
4003
1
    FD->removeInClassInitializer();
4004
1
    return;
4005
1
  }
4006
4007
3.56k
  ExprResult Init = InitExpr;
4008
3.56k
  if (!FD->getType()->isDependentType() && 
!InitExpr->isTypeDependent()3.37k
) {
4009
3.28k
    InitializedEntity Entity =
4010
3.28k
        InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4011
3.28k
    InitializationKind Kind =
4012
3.28k
        FD->getInClassInitStyle() == ICIS_ListInit
4013
3.28k
            ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4014
89
                                                   InitExpr->getBeginLoc(),
4015
89
                                                   InitExpr->getEndLoc())
4016
3.28k
            : 
InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc)3.19k
;
4017
3.28k
    InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4018
3.28k
    Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4019
3.28k
    if (Init.isInvalid()) {
4020
34
      FD->setInvalidDecl();
4021
34
      return;
4022
34
    }
4023
3.28k
  }
4024
4025
  // C++11 [class.base.init]p7:
4026
  //   The initialization of each base and member constitutes a
4027
  //   full-expression.
4028
3.52k
  Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4029
3.52k
  if (Init.isInvalid()) {
4030
0
    FD->setInvalidDecl();
4031
0
    return;
4032
0
  }
4033
4034
3.52k
  InitExpr = Init.get();
4035
4036
3.52k
  FD->setInClassInitializer(InitExpr);
4037
3.52k
}
4038
4039
/// Find the direct and/or virtual base specifiers that
4040
/// correspond to the given base type, for use in base initialization
4041
/// within a constructor.
4042
static bool FindBaseInitializer(Sema &SemaRef,
4043
                                CXXRecordDecl *ClassDecl,
4044
                                QualType BaseType,
4045
                                const CXXBaseSpecifier *&DirectBaseSpec,
4046
18.8k
                                const CXXBaseSpecifier *&VirtualBaseSpec) {
4047
  // First, check for a direct base class.
4048
18.8k
  DirectBaseSpec = nullptr;
4049
22.7k
  for (const auto &Base : ClassDecl->bases()) {
4050
22.7k
    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4051
      // We found a direct base of this type. That's what we're
4052
      // initializing.
4053
18.7k
      DirectBaseSpec = &Base;
4054
18.7k
      break;
4055
18.7k
    }
4056
22.7k
  }
4057
4058
  // Check for a virtual base class.
4059
  // FIXME: We might be able to short-circuit this if we know in advance that
4060
  // there are no virtual bases.
4061
18.8k
  VirtualBaseSpec = nullptr;
4062
18.8k
  if (!DirectBaseSpec || 
!DirectBaseSpec->isVirtual()18.7k
) {
4063
    // We haven't found a base yet; search the class hierarchy for a
4064
    // virtual base class.
4065
18.7k
    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4066
18.7k
                       /*DetectVirtual=*/false);
4067
18.7k
    if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4068
18.7k
                              SemaRef.Context.getTypeDeclType(ClassDecl),
4069
18.7k
                              BaseType, Paths)) {
4070
18.7k
      for (CXXBasePaths::paths_iterator Path = Paths.begin();
4071
37.4k
           Path != Paths.end(); 
++Path18.7k
) {
4072
18.7k
        if (Path->back().Base->isVirtual()) {
4073
53
          VirtualBaseSpec = Path->back().Base;
4074
53
          break;
4075
53
        }
4076
18.7k
      }
4077
18.7k
    }
4078
18.7k
  }
4079
4080
18.8k
  return DirectBaseSpec || 
VirtualBaseSpec85
;
4081
18.8k
}
4082
4083
/// Handle a C++ member initializer using braced-init-list syntax.
4084
MemInitResult
4085
Sema::ActOnMemInitializer(Decl *ConstructorD,
4086
                          Scope *S,
4087
                          CXXScopeSpec &SS,
4088
                          IdentifierInfo *MemberOrBase,
4089
                          ParsedType TemplateTypeTy,
4090
                          const DeclSpec &DS,
4091
                          SourceLocation IdLoc,
4092
                          Expr *InitList,
4093
361
                          SourceLocation EllipsisLoc) {
4094
361
  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4095
361
                             DS, IdLoc, InitList,
4096
361
                             EllipsisLoc);
4097
361
}
4098
4099
/// Handle a C++ member initializer using parentheses syntax.
4100
MemInitResult
4101
Sema::ActOnMemInitializer(Decl *ConstructorD,
4102
                          Scope *S,
4103
                          CXXScopeSpec &SS,
4104
                          IdentifierInfo *MemberOrBase,
4105
                          ParsedType TemplateTypeTy,
4106
                          const DeclSpec &DS,
4107
                          SourceLocation IdLoc,
4108
                          SourceLocation LParenLoc,
4109
                          ArrayRef<Expr *> Args,
4110
                          SourceLocation RParenLoc,
4111
215k
                          SourceLocation EllipsisLoc) {
4112
215k
  Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4113
215k
  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4114
215k
                             DS, IdLoc, List, EllipsisLoc);
4115
215k
}
4116
4117
namespace {
4118
4119
// Callback to only accept typo corrections that can be a valid C++ member
4120
// initializer: either a non-static field member or a base class.
4121
class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4122
public:
4123
  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4124
57
      : ClassDecl(ClassDecl) {}
4125
4126
12
  bool ValidateCandidate(const TypoCorrection &candidate) override {
4127
12
    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4128
8
      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4129
2
        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4130
6
      return isa<TypeDecl>(ND);
4131
8
    }
4132
4
    return false;
4133
12
  }
4134
4135
23
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
4136
23
    return std::make_unique<MemInitializerValidatorCCC>(*this);
4137
23
  }
4138
4139
private:
4140
  CXXRecordDecl *ClassDecl;
4141
};
4142
4143
}
4144
4145
ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4146
                                             CXXScopeSpec &SS,
4147
                                             ParsedType TemplateTypeTy,
4148
216k
                                             IdentifierInfo *MemberOrBase) {
4149
216k
  if (SS.getScopeRep() || 
TemplateTypeTy214k
)
4150
6.63k
    return nullptr;
4151
209k
  for (auto *D : ClassDecl->lookup(MemberOrBase))
4152
198k
    if (isa<FieldDecl>(D) || 
isa<IndirectFieldDecl>(D)11.0k
)
4153
187k
      return cast<ValueDecl>(D);
4154
22.2k
  return nullptr;
4155
209k
}
4156
4157
/// Handle a C++ member initializer.
4158
MemInitResult
4159
Sema::BuildMemInitializer(Decl *ConstructorD,
4160
                          Scope *S,
4161
                          CXXScopeSpec &SS,
4162
                          IdentifierInfo *MemberOrBase,
4163
                          ParsedType TemplateTypeTy,
4164
                          const DeclSpec &DS,
4165
                          SourceLocation IdLoc,
4166
                          Expr *Init,
4167
216k
                          SourceLocation EllipsisLoc) {
4168
216k
  ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4169
216k
                                             /*RecoverUncorrectedTypos=*/true);
4170
216k
  if (!Res.isUsable())
4171
4
    return true;
4172
216k
  Init = Res.get();
4173
4174
216k
  if (!ConstructorD)
4175
0
    return true;
4176
4177
216k
  AdjustDeclIfTemplate(ConstructorD);
4178
4179
216k
  CXXConstructorDecl *Constructor
4180
216k
    = dyn_cast<CXXConstructorDecl>(ConstructorD);
4181
216k
  if (!Constructor) {
4182
    // The user wrote a constructor initializer on a function that is
4183
    // not a C++ constructor. Ignore the error for now, because we may
4184
    // have more member initializers coming; we'll diagnose it just
4185
    // once in ActOnMemInitializers.
4186
5
    return true;
4187
5
  }
4188
4189
216k
  CXXRecordDecl *ClassDecl = Constructor->getParent();
4190
4191
  // C++ [class.base.init]p2:
4192
  //   Names in a mem-initializer-id are looked up in the scope of the
4193
  //   constructor's class and, if not found in that scope, are looked
4194
  //   up in the scope containing the constructor's definition.
4195
  //   [Note: if the constructor's class contains a member with the
4196
  //   same name as a direct or virtual base class of the class, a
4197
  //   mem-initializer-id naming the member or base class and composed
4198
  //   of a single identifier refers to the class member. A
4199
  //   mem-initializer-id for the hidden base class may be specified
4200
  //   using a qualified name. ]
4201
4202
  // Look for a member, first.
4203
216k
  if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4204
216k
          ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4205
187k
    if (EllipsisLoc.isValid())
4206
2
      Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4207
2
          << MemberOrBase
4208
2
          << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4209
4210
187k
    return BuildMemberInitializer(Member, Init, IdLoc);
4211
187k
  }
4212
  // It didn't name a member, so see if it names a class.
4213
28.8k
  QualType BaseType;
4214
28.8k
  TypeSourceInfo *TInfo = nullptr;
4215
4216
28.8k
  if (TemplateTypeTy) {
4217
5.03k
    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4218
5.03k
    if (BaseType.isNull())
4219
0
      return true;
4220
23.8k
  } else if (DS.getTypeSpecType() == TST_decltype) {
4221
4
    BaseType = BuildDecltypeType(DS.getRepAsExpr());
4222
23.8k
  } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4223
6
    Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4224
6
    return true;
4225
23.8k
  } else {
4226
23.8k
    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4227
23.8k
    LookupParsedName(R, S, &SS);
4228
4229
23.8k
    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4230
23.8k
    if (!TyD) {
4231
57
      if (R.isAmbiguous()) 
return true0
;
4232
4233
      // We don't want access-control diagnostics here.
4234
57
      R.suppressDiagnostics();
4235
4236
57
      if (SS.isSet() && 
isDependentScopeSpecifier(SS)30
) {
4237
24
        bool NotUnknownSpecialization = false;
4238
24
        DeclContext *DC = computeDeclContext(SS, false);
4239
24
        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4240
0
          NotUnknownSpecialization = !Record->hasAnyDependentBases();
4241
4242
24
        if (!NotUnknownSpecialization) {
4243
          // When the scope specifier can refer to a member of an unknown
4244
          // specialization, we take it as a type name.
4245
24
          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4246
24
                                       SS.getWithLocInContext(Context),
4247
24
                                       *MemberOrBase, IdLoc);
4248
24
          if (BaseType.isNull())
4249
0
            return true;
4250
4251
24
          TInfo = Context.CreateTypeSourceInfo(BaseType);
4252
24
          DependentNameTypeLoc TL =
4253
24
              TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4254
24
          if (!TL.isNull()) {
4255
24
            TL.setNameLoc(IdLoc);
4256
24
            TL.setElaboratedKeywordLoc(SourceLocation());
4257
24
            TL.setQualifierLoc(SS.getWithLocInContext(Context));
4258
24
          }
4259
4260
24
          R.clear();
4261
24
          R.setLookupName(MemberOrBase);
4262
24
        }
4263
24
      }
4264
4265
      // If no results were found, try to correct typos.
4266
57
      TypoCorrection Corr;
4267
57
      MemInitializerValidatorCCC CCC(ClassDecl);
4268
57
      if (R.empty() && 
BaseType.isNull()50
&&
4269
57
          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4270
26
                              CCC, CTK_ErrorRecovery, ClassDecl))) {
4271
6
        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4272
          // We have found a non-static data member with a similar
4273
          // name to what was typed; complain and initialize that
4274
          // member.
4275
2
          diagnoseTypo(Corr,
4276
2
                       PDiag(diag::err_mem_init_not_member_or_class_suggest)
4277
2
                         << MemberOrBase << true);
4278
2
          return BuildMemberInitializer(Member, Init, IdLoc);
4279
4
        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4280
4
          const CXXBaseSpecifier *DirectBaseSpec;
4281
4
          const CXXBaseSpecifier *VirtualBaseSpec;
4282
4
          if (FindBaseInitializer(*this, ClassDecl,
4283
4
                                  Context.getTypeDeclType(Type),
4284
4
                                  DirectBaseSpec, VirtualBaseSpec)) {
4285
            // We have found a direct or virtual base class with a
4286
            // similar name to what was typed; complain and initialize
4287
            // that base class.
4288
4
            diagnoseTypo(Corr,
4289
4
                         PDiag(diag::err_mem_init_not_member_or_class_suggest)
4290
4
                           << MemberOrBase << false,
4291
4
                         PDiag() /*Suppress note, we provide our own.*/);
4292
4293
4
            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4294
4
                                                              : 
VirtualBaseSpec0
;
4295
4
            Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4296
4
                << BaseSpec->getType() << BaseSpec->getSourceRange();
4297
4298
4
            TyD = Type;
4299
4
          }
4300
4
        }
4301
6
      }
4302
4303
55
      if (!TyD && 
BaseType.isNull()51
) {
4304
27
        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4305
27
          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4306
27
        return true;
4307
27
      }
4308
55
    }
4309
4310
23.8k
    if (BaseType.isNull()) {
4311
23.7k
      BaseType = Context.getTypeDeclType(TyD);
4312
23.7k
      MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4313
23.7k
      if (SS.isSet()) {
4314
1.56k
        BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4315
1.56k
                                             BaseType);
4316
1.56k
        TInfo = Context.CreateTypeSourceInfo(BaseType);
4317
1.56k
        ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4318
1.56k
        TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4319
1.56k
        TL.setElaboratedKeywordLoc(SourceLocation());
4320
1.56k
        TL.setQualifierLoc(SS.getWithLocInContext(Context));
4321
1.56k
      }
4322
23.7k
    }
4323
23.8k
  }
4324
4325
28.8k
  if (!TInfo)
4326
22.2k
    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4327
4328
28.8k
  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4329
28.8k
}
4330
4331
MemInitResult
4332
Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4333
212k
                             SourceLocation IdLoc) {
4334
212k
  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4335
212k
  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4336
212k
  assert((DirectMember || IndirectMember) &&
4337
212k
         "Member must be a FieldDecl or IndirectFieldDecl");
4338
4339
212k
  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4340
1
    return true;
4341
4342
212k
  if (Member->isInvalidDecl())
4343
3
    return true;
4344
4345
212k
  MultiExprArg Args;
4346
212k
  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4347
210k
    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4348
210k
  } else 
if (InitListExpr *1.31k
InitList1.31k
= dyn_cast<InitListExpr>(Init)) {
4349
376
    Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4350
941
  } else {
4351
    // Template instantiation doesn't reconstruct ParenListExprs for us.
4352
941
    Args = Init;
4353
941
  }
4354
4355
212k
  SourceRange InitRange = Init->getSourceRange();
4356
4357
212k
  if (Member->getType()->isDependentType() || 
Init->isTypeDependent()72.8k
) {
4358
    // Can't check initialization for a member of dependent type or when
4359
    // any of the arguments are type-dependent expressions.
4360
148k
    DiscardCleanupsInEvaluationContext();
4361
148k
  } else {
4362
63.8k
    bool InitList = false;
4363
63.8k
    if (isa<InitListExpr>(Init)) {
4364
172
      InitList = true;
4365
172
      Args = Init;
4366
172
    }
4367
4368
    // Initialize the member.
4369
63.8k
    InitializedEntity MemberEntity =
4370
63.8k
      DirectMember ? 
InitializedEntity::InitializeMember(DirectMember, nullptr)63.6k
4371
63.8k
                   : InitializedEntity::InitializeMember(IndirectMember,
4372
245
                                                         nullptr);
4373
63.8k
    InitializationKind Kind =
4374
63.8k
        InitList ? InitializationKind::CreateDirectList(
4375
172
                       IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4376
63.8k
                 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4377
63.7k
                                                    InitRange.getEnd());
4378
4379
63.8k
    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4380
63.8k
    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4381
63.8k
                                            nullptr);
4382
63.8k
    if (!MemberInit.isInvalid()) {
4383
      // C++11 [class.base.init]p7:
4384
      //   The initialization of each base and member constitutes a
4385
      //   full-expression.
4386
63.8k
      MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4387
63.8k
                                       /*DiscardedValue*/ false);
4388
63.8k
    }
4389
4390
63.8k
    if (MemberInit.isInvalid()) {
4391
      // Args were sensible expressions but we couldn't initialize the member
4392
      // from them. Preserve them in a RecoveryExpr instead.
4393
41
      Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4394
41
                                Member->getType())
4395
41
                 .get();
4396
41
      if (!Init)
4397
1
        return true;
4398
63.8k
    } else {
4399
63.8k
      Init = MemberInit.get();
4400
63.8k
    }
4401
63.8k
  }
4402
4403
212k
  if (DirectMember) {
4404
211k
    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4405
211k
                                            InitRange.getBegin(), Init,
4406
211k
                                            InitRange.getEnd());
4407
211k
  } else {
4408
261
    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4409
261
                                            InitRange.getBegin(), Init,
4410
261
                                            InitRange.getEnd());
4411
261
  }
4412
212k
}
4413
4414
MemInitResult
4415
Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4416
441
                                 CXXRecordDecl *ClassDecl) {
4417
441
  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4418
441
  if (!LangOpts.CPlusPlus11)
4419
1
    return Diag(NameLoc, diag::err_delegating_ctor)
4420
1
      << TInfo->getTypeLoc().getLocalSourceRange();
4421
440
  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4422
4423
440
  bool InitList = true;
4424
440
  MultiExprArg Args = Init;
4425
440
  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4426
440
    InitList = false;
4427
440
    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4428
440
  }
4429
4430
440
  SourceRange InitRange = Init->getSourceRange();
4431
  // Initialize the object.
4432
440
  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4433
440
                                     QualType(ClassDecl->getTypeForDecl(), 0));
4434
440
  InitializationKind Kind =
4435
440
      InitList ? InitializationKind::CreateDirectList(
4436
0
                     NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4437
440
               : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4438
440
                                                  InitRange.getEnd());
4439
440
  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4440
440
  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4441
440
                                              Args, nullptr);
4442
440
  if (!DelegationInit.isInvalid()) {
4443
437
    assert((DelegationInit.get()->containsErrors() ||
4444
437
            cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4445
437
           "Delegating constructor with no target?");
4446
4447
    // C++11 [class.base.init]p7:
4448
    //   The initialization of each base and member constitutes a
4449
    //   full-expression.
4450
0
    DelegationInit = ActOnFinishFullExpr(
4451
437
        DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4452
437
  }
4453
4454
440
  if (DelegationInit.isInvalid()) {
4455
3
    DelegationInit =
4456
3
        CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4457
3
                           QualType(ClassDecl->getTypeForDecl(), 0));
4458
3
    if (DelegationInit.isInvalid())
4459
1
      return true;
4460
437
  } else {
4461
    // If we are in a dependent context, template instantiation will
4462
    // perform this type-checking again. Just save the arguments that we
4463
    // received in a ParenListExpr.
4464
    // FIXME: This isn't quite ideal, since our ASTs don't capture all
4465
    // of the information that we have about the base
4466
    // initializer. However, deconstructing the ASTs is a dicey process,
4467
    // and this approach is far more likely to get the corner cases right.
4468
437
    if (CurContext->isDependentContext())
4469
2
      DelegationInit = Init;
4470
437
  }
4471
4472
439
  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4473
439
                                          DelegationInit.getAs<Expr>(),
4474
439
                                          InitRange.getEnd());
4475
440
}
4476
4477
MemInitResult
4478
Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4479
                           Expr *Init, CXXRecordDecl *ClassDecl,
4480
37.7k
                           SourceLocation EllipsisLoc) {
4481
37.7k
  SourceLocation BaseLoc
4482
37.7k
    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4483
4484
37.7k
  if (!BaseType->isDependentType() && 
!BaseType->isRecordType()19.3k
)
4485
10
    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4486
10
             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4487
4488
  // C++ [class.base.init]p2:
4489
  //   [...] Unless the mem-initializer-id names a nonstatic data
4490
  //   member of the constructor's class or a direct or virtual base
4491
  //   of that class, the mem-initializer is ill-formed. A
4492
  //   mem-initializer-list can initialize a base class using any
4493
  //   name that denotes that base class type.
4494
4495
  // We can store the initializers in "as-written" form and delay analysis until
4496
  // instantiation if the constructor is dependent. But not for dependent
4497
  // (broken) code in a non-template! SetCtorInitializers does not expect this.
4498
37.7k
  bool Dependent = CurContext->isDependentContext() &&
4499
37.7k
                   
(19.6k
BaseType->isDependentType()19.6k
||
Init->isTypeDependent()1.16k
);
4500
4501
37.7k
  SourceRange InitRange = Init->getSourceRange();
4502
37.7k
  if (EllipsisLoc.isValid()) {
4503
    // This is a pack expansion.
4504
2.62k
    if (!BaseType->containsUnexpandedParameterPack())  {
4505
0
      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4506
0
        << SourceRange(BaseLoc, InitRange.getEnd());
4507
4508
0
      EllipsisLoc = SourceLocation();
4509
0
    }
4510
35.1k
  } else {
4511
    // Check for any unexpanded parameter packs.
4512
35.1k
    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4513
1
      return true;
4514
4515
35.1k
    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4516
0
      return true;
4517
35.1k
  }
4518
4519
  // Check for direct and virtual base classes.
4520
37.7k
  const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4521
37.7k
  const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4522
37.7k
  if (!Dependent) {
4523
19.2k
    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4524
19.2k
                                       BaseType))
4525
439
      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4526
4527
18.8k
    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4528
18.8k
                        VirtualBaseSpec);
4529
4530
    // C++ [base.class.init]p2:
4531
    // Unless the mem-initializer-id names a nonstatic data member of the
4532
    // constructor's class or a direct or virtual base of that class, the
4533
    // mem-initializer is ill-formed.
4534
18.8k
    if (!DirectBaseSpec && 
!VirtualBaseSpec85
) {
4535
      // If the class has any dependent bases, then it's possible that
4536
      // one of those types will resolve to the same type as
4537
      // BaseType. Therefore, just treat this as a dependent base
4538
      // class initialization.  FIXME: Should we try to check the
4539
      // initialization anyway? It seems odd.
4540
35
      if (ClassDecl->hasAnyDependentBases())
4541
20
        Dependent = true;
4542
15
      else
4543
15
        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4544
15
          << BaseType << Context.getTypeDeclType(ClassDecl)
4545
15
          << BaseTInfo->getTypeLoc().getLocalSourceRange();
4546
35
    }
4547
18.8k
  }
4548
4549
37.3k
  if (Dependent) {
4550
18.4k
    DiscardCleanupsInEvaluationContext();
4551
4552
18.4k
    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4553
18.4k
                                            /*IsVirtual=*/false,
4554
18.4k
                                            InitRange.getBegin(), Init,
4555
18.4k
                                            InitRange.getEnd(), EllipsisLoc);
4556
18.4k
  }
4557
4558
  // C++ [base.class.init]p2:
4559
  //   If a mem-initializer-id is ambiguous because it designates both
4560
  //   a direct non-virtual base class and an inherited virtual base
4561
  //   class, the mem-initializer is ill-formed.
4562
18.8k
  if (DirectBaseSpec && 
VirtualBaseSpec18.7k
)
4563
3
    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4564
3
      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4565
4566
18.8k
  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4567
18.8k
  if (!BaseSpec)
4568
50
    BaseSpec = VirtualBaseSpec;
4569
4570
  // Initialize the base.
4571
18.8k
  bool InitList = true;
4572
18.8k
  MultiExprArg Args = Init;
4573
18.8k
  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4574
18.7k
    InitList = false;
4575
18.7k
    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4576
18.7k
  }
4577
4578
18.8k
  InitializedEntity BaseEntity =
4579
18.8k
    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4580
18.8k
  InitializationKind Kind =
4581
18.8k
      InitList ? 
InitializationKind::CreateDirectList(BaseLoc)28
4582
18.8k
               : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4583
18.7k
                                                  InitRange.getEnd());
4584
18.8k
  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4585
18.8k
  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4586
18.8k
  if (!BaseInit.isInvalid()) {
4587
    // C++11 [class.base.init]p7:
4588
    //   The initialization of each base and member constitutes a
4589
    //   full-expression.
4590
18.8k
    BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4591
18.8k
                                   /*DiscardedValue*/ false);
4592
18.8k
  }
4593
4594
18.8k
  if (BaseInit.isInvalid()) {
4595
21
    BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4596
21
                                  Args, BaseType);
4597
21
    if (BaseInit.isInvalid())
4598
1
      return true;
4599
18.8k
  } else {
4600
    // If we are in a dependent context, template instantiation will
4601
    // perform this type-checking again. Just save the arguments that we
4602
    // received in a ParenListExpr.
4603
    // FIXME: This isn't quite ideal, since our ASTs don't capture all
4604
    // of the information that we have about the base
4605
    // initializer. However, deconstructing the ASTs is a dicey process,
4606
    // and this approach is far more likely to get the corner cases right.
4607
18.8k
    if (CurContext->isDependentContext())
4608
1.13k
      BaseInit = Init;
4609
18.8k
  }
4610
4611
18.8k
  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4612
18.8k
                                          BaseSpec->isVirtual(),
4613
18.8k
                                          InitRange.getBegin(),
4614
18.8k
                                          BaseInit.getAs<Expr>(),
4615
18.8k
                                          InitRange.getEnd(), EllipsisLoc);
4616
18.8k
}
4617
4618
// Create a static_cast\<T&&>(expr).
4619
23.7k
static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4620
23.7k
  if (T.isNull()) T = E->getType();
4621
23.7k
  QualType TargetType = SemaRef.BuildReferenceType(
4622
23.7k
      T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4623
23.7k
  SourceLocation ExprLoc = E->getBeginLoc();
4624
23.7k
  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4625
23.7k
      TargetType, ExprLoc);
4626
4627
23.7k
  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4628
23.7k
                                   SourceRange(ExprLoc, ExprLoc),
4629
23.7k
                                   E->getSourceRange()).get();
4630
23.7k
}
4631
4632
/// ImplicitInitializerKind - How an implicit base or member initializer should
4633
/// initialize its base or member.
4634
enum ImplicitInitializerKind {
4635
  IIK_Default,
4636
  IIK_Copy,
4637
  IIK_Move,
4638
  IIK_Inherit
4639
};
4640
4641
static bool
4642
BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4643
                             ImplicitInitializerKind ImplicitInitKind,
4644
                             CXXBaseSpecifier *BaseSpec,
4645
                             bool IsInheritedVirtualBase,
4646
22.5k
                             CXXCtorInitializer *&CXXBaseInit) {
4647
22.5k
  InitializedEntity InitEntity
4648
22.5k
    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4649
22.5k
                                        IsInheritedVirtualBase);
4650
4651
22.5k
  ExprResult BaseInit;
4652
4653
22.5k
  switch (ImplicitInitKind) {
4654
40
  case IIK_Inherit:
4655
13.7k
  case IIK_Default: {
4656
13.7k
    InitializationKind InitKind
4657
13.7k
      = InitializationKind::CreateDefault(Constructor->getLocation());
4658
13.7k
    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4659
13.7k
    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4660
13.7k
    break;
4661
40
  }
4662
4663
2.75k
  case IIK_Move:
4664
8.80k
  case IIK_Copy: {
4665
8.80k
    bool Moving = ImplicitInitKind == IIK_Move;
4666
8.80k
    ParmVarDecl *Param = Constructor->getParamDecl(0);
4667
8.80k
    QualType ParamType = Param->getType().getNonReferenceType();
4668
4669
8.80k
    Expr *CopyCtorArg =
4670
8.80k
      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4671
8.80k
                          SourceLocation(), Param, false,
4672
8.80k
                          Constructor->getLocation(), ParamType,
4673
8.80k
                          VK_LValue, nullptr);
4674
4675
8.80k
    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4676
4677
    // Cast to the base class to avoid ambiguities.
4678
8.80k
    QualType ArgTy =
4679
8.80k
      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4680
8.80k
                                       ParamType.getQualifiers());
4681
4682
8.80k
    if (Moving) {
4683
2.75k
      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4684
2.75k
    }
4685
4686
8.80k
    CXXCastPath BasePath;
4687
8.80k
    BasePath.push_back(BaseSpec);
4688
8.80k
    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4689
8.80k
                                            CK_UncheckedDerivedToBase,
4690
8.80k
                                            Moving ? 
VK_XValue2.75k
:
VK_LValue6.04k
,
4691
8.80k
                                            &BasePath).get();
4692
4693
8.80k
    InitializationKind InitKind
4694
8.80k
      = InitializationKind::CreateDirect(Constructor->getLocation(),
4695
8.80k
                                         SourceLocation(), SourceLocation());
4696
8.80k
    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4697
8.80k
    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4698
8.80k
    break;
4699
2.75k
  }
4700
22.5k
  }
4701
4702
22.5k
  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4703
22.5k
  if (BaseInit.isInvalid())
4704
21
    return true;
4705
4706
22.5k
  CXXBaseInit =
4707
22.5k
    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4708
22.5k
               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4709
22.5k
                                                        SourceLocation()),
4710
22.5k
                                             BaseSpec->isVirtual(),
4711
22.5k
                                             SourceLocation(),
4712
22.5k
                                             BaseInit.getAs<Expr>(),
4713
22.5k
                                             SourceLocation(),
4714
22.5k
                                             SourceLocation());
4715
4716
22.5k
  return false;
4717
22.5k
}
4718
4719
29.4k
static bool RefersToRValueRef(Expr *MemRef) {
4720
29.4k
  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4721
29.4k
  return Referenced->getType()->isRValueReferenceType();
4722
29.4k
}
4723
4724
static bool
4725
BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4726
                               ImplicitInitializerKind ImplicitInitKind,
4727
                               FieldDecl *Field, IndirectFieldDecl *Indirect,
4728
57.9k
                               CXXCtorInitializer *&CXXMemberInit) {
4729
57.9k
  if (Field->isInvalidDecl())
4730
0
    return true;
4731
4732
57.9k
  SourceLocation Loc = Constructor->getLocation();
4733
4734
57.9k
  if (ImplicitInitKind == IIK_Copy || 
ImplicitInitKind == IIK_Move47.6k
) {
4735
29.4k
    bool Moving = ImplicitInitKind == IIK_Move;
4736
29.4k
    ParmVarDecl *Param = Constructor->getParamDecl(0);
4737
29.4k
    QualType ParamType = Param->getType().getNonReferenceType();
4738
4739
    // Suppress copying zero-width bitfields.
4740
29.4k
    if (Field->isZeroLengthBitField(SemaRef.Context))
4741
0
      return false;
4742
4743
29.4k
    Expr *MemberExprBase =
4744
29.4k
      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4745
29.4k
                          SourceLocation(), Param, false,
4746
29.4k
                          Loc, ParamType, VK_LValue, nullptr);
4747
4748
29.4k
    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4749
4750
29.4k
    if (Moving) {
4751
19.1k
      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4752
19.1k
    }
4753
4754
    // Build a reference to this field within the parameter.
4755
29.4k
    CXXScopeSpec SS;
4756
29.4k
    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4757
29.4k
                              Sema::LookupMemberName);
4758
29.4k
    MemberLookup.addDecl(Indirect ? 
cast<ValueDecl>(Indirect)0
4759
29.4k
                                  : cast<ValueDecl>(Field), AS_public);
4760
29.4k
    MemberLookup.resolveKind();
4761
29.4k
    ExprResult CtorArg
4762
29.4k
      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4763
29.4k
                                         ParamType, Loc,
4764
29.4k
                                         /*IsArrow=*/false,
4765
29.4k
                                         SS,
4766
29.4k
                                         /*TemplateKWLoc=*/SourceLocation(),
4767
29.4k
                                         /*FirstQualifierInScope=*/nullptr,
4768
29.4k
                                         MemberLookup,
4769
29.4k
                                         /*TemplateArgs=*/nullptr,
4770
29.4k
                                         /*S*/nullptr);
4771
29.4k
    if (CtorArg.isInvalid())
4772
0
      return true;
4773
4774
    // C++11 [class.copy]p15:
4775
    //   - if a member m has rvalue reference type T&&, it is direct-initialized
4776
    //     with static_cast<T&&>(x.m);
4777
29.4k
    if (RefersToRValueRef(CtorArg.get())) {
4778
100
      CtorArg = CastForMoving(SemaRef, CtorArg.get());
4779
100
    }
4780
4781
29.4k
    InitializedEntity Entity =
4782
29.4k
        Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4783
0
                                                       /*Implicit*/ true)
4784
29.4k
                 : InitializedEntity::InitializeMember(Field, nullptr,
4785
29.4k
                                                       /*Implicit*/ true);
4786
4787
    // Direct-initialize to use the copy constructor.
4788
29.4k
    InitializationKind InitKind =
4789
29.4k
      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4790
4791
29.4k
    Expr *CtorArgE = CtorArg.getAs<Expr>();
4792
29.4k
    InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4793
29.4k
    ExprResult MemberInit =
4794
29.4k
        InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4795
29.4k
    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4796
29.4k
    if (MemberInit.isInvalid())
4797
0
      return true;
4798
4799
29.4k
    if (Indirect)
4800
0
      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4801
0
          SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4802
29.4k
    else
4803
29.4k
      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4804
29.4k
          SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4805
29.4k
    return false;
4806
29.4k
  }
4807
4808
28.5k
  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4809
28.5k
         "Unhandled implicit init kind!");
4810
4811
0
  QualType FieldBaseElementType =
4812
28.5k
    SemaRef.Context.getBaseElementType(Field->getType());
4813
4814
28.5k
  if (FieldBaseElementType->isRecordType()) {
4815
3.90k
    InitializedEntity InitEntity =
4816
3.90k
        Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4817
8
                                                       /*Implicit*/ true)
4818
3.90k
                 : InitializedEntity::InitializeMember(Field, nullptr,
4819
3.89k
                                                       /*Implicit*/ true);
4820
3.90k
    InitializationKind InitKind =
4821
3.90k
      InitializationKind::CreateDefault(Loc);
4822
4823
3.90k
    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4824
3.90k
    ExprResult MemberInit =
4825
3.90k
      InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4826
4827
3.90k
    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4828
3.90k
    if (MemberInit.isInvalid())
4829
18
      return true;
4830
4831
3.88k
    if (Indirect)
4832
8
      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4833
8
                                                               Indirect, Loc,
4834
8
                                                               Loc,
4835
8
                                                               MemberInit.get(),
4836
8
                                                               Loc);
4837
3.87k
    else
4838
3.87k
      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4839
3.87k
                                                               Field, Loc, Loc,
4840
3.87k
                                                               MemberInit.get(),
4841
3.87k
                                                               Loc);
4842
3.88k
    return false;
4843
3.90k
  }
4844
4845
24.5k
  if (!Field->getParent()->isUnion()) {
4846
24.5k
    if (FieldBaseElementType->isReferenceType()) {
4847
9
      SemaRef.Diag(Constructor->getLocation(),
4848
9
                   diag::err_uninitialized_member_in_ctor)
4849
9
      << (int)Constructor->isImplicit()
4850
9
      << SemaRef.Context.getTagDeclType(Constructor->getParent())
4851
9
      << 0 << Field->getDeclName();
4852
9
      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4853
9
      return true;
4854
9
    }
4855
4856
24.5k
    if (FieldBaseElementType.isConstQualified()) {
4857
3
      SemaRef.Diag(Constructor->getLocation(),
4858
3
                   diag::err_uninitialized_member_in_ctor)
4859
3
      << (int)Constructor->isImplicit()
4860
3
      << SemaRef.Context.getTagDeclType(Constructor->getParent())
4861
3
      << 1 << Field->getDeclName();
4862
3
      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4863
3
      return true;
4864
3
    }
4865
24.5k
  }
4866
4867
24.5k
  if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4868
    // ARC and Weak:
4869
    //   Default-initialize Objective-C pointers to NULL.
4870
40
    CXXMemberInit
4871
40
      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4872
40
                                                 Loc, Loc,
4873
40
                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4874
40
                                                 Loc);
4875
40
    return false;
4876
40
  }
4877
4878
  // Nothing to initialize.
4879
24.5k
  CXXMemberInit = nullptr;
4880
24.5k
  return false;
4881
24.5k
}
4882
4883
namespace {
4884
struct BaseAndFieldInfo {
4885
  Sema &S;
4886
  CXXConstructorDecl *Ctor;
4887
  bool AnyErrorsInInits;
4888
  ImplicitInitializerKind IIK;
4889
  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4890
  SmallVector<CXXCtorInitializer*, 8> AllToInit;
4891
  llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4892
4893
  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4894
139k
    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4895
139k
    bool Generated = Ctor->isImplicit() || 
Ctor->isDefaulted()78.1k
;
4896
139k
    if (Ctor->getInheritedConstructor())
4897
310
      IIK = IIK_Inherit;
4898
139k
    else if (Generated && 
Ctor->isCopyConstructor()70.4k
)
4899
15.1k
      IIK = IIK_Copy;
4900
124k
    else if (Generated && 
Ctor->isMoveConstructor()55.3k
)
4901
24.5k
      IIK = IIK_Move;
4902
99.8k
    else
4903
99.8k
      IIK = IIK_Default;
4904
139k
  }
4905
4906
1.85M
  bool isImplicitCopyOrMove() const {
4907
1.85M
    switch (IIK) {
4908
139k
    case IIK_Copy:
4909
418k
    case IIK_Move:
4910
418k
      return true;
4911
4912
1.43M
    case IIK_Default:
4913
1.43M
    case IIK_Inherit:
4914
1.43M
      return false;
4915
1.85M
    }
4916
4917
0
    llvm_unreachable("Invalid ImplicitInitializerKind!");
4918
0
  }
4919
4920
88.9k
  bool addFieldInitializer(CXXCtorInitializer *Init) {
4921
88.9k
    AllToInit.push_back(Init);
4922
4923
    // Check whether this initializer makes the field "used".
4924
88.9k
    if (Init->getInit()->HasSideEffects(S.Context))
4925
18.0k
      S.UnusedPrivateFields.remove(Init->getAnyMember());
4926
4927
88.9k
    return false;
4928
88.9k
  }
4929
4930
72.5k
  bool isInactiveUnionMember(FieldDecl *Field) {
4931
72.5k
    RecordDecl *Record = Field->getParent();
4932
72.5k
    if (!Record->isUnion())
4933
61.3k
      return false;
4934
4935
11.2k
    if (FieldDecl *Active =
4936
11.2k
            ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4937
256
      return Active != Field->getCanonicalDecl();
4938
4939
    // In an implicit copy or move constructor, ignore any in-class initializer.
4940
10.9k
    if (isImplicitCopyOrMove())
4941
1.43k
      return true;
4942
4943
    // If there's no explicit initialization, the field is active only if it
4944
    // has an in-class initializer...
4945
9.51k
    if (Field->hasInClassInitializer())
4946
85
      return false;
4947
    // ... or it's an anonymous struct or union whose class has an in-class
4948
    // initializer.
4949
9.43k
    if (!Field->isAnonymousStructOrUnion())
4950
9.37k
      return true;
4951
55
    CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4952
55
    return !FieldRD->hasInClassInitializer();
4953
9.43k
  }
4954
4955
  /// Determine whether the given field is, or is within, a union member
4956
  /// that is inactive (because there was an initializer given for a different
4957
  /// member of the union, or because the union was not initialized at all).
4958
  bool isWithinInactiveUnionMember(FieldDecl *Field,
4959
70.9k
                                   IndirectFieldDecl *Indirect) {
4960
70.9k
    if (!Indirect)
4961
69.4k
      return isInactiveUnionMember(Field);
4962
4963
3.07k
    
for (auto *C : Indirect->chain())1.50k
{
4964
3.07k
      FieldDecl *Field = dyn_cast<FieldDecl>(C);
4965
3.07k
      if (Field && isInactiveUnionMember(Field))
4966
1.37k
        return true;
4967
3.07k
    }
4968
130
    return false;
4969
1.50k
  }
4970
};
4971
}
4972
4973
/// Determine whether the given type is an incomplete or zero-lenfgth
4974
/// array type.
4975
166k
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4976
166k
  if (T->isIncompleteArrayType())
4977
39
    return true;
4978
4979
177k
  
while (const ConstantArrayType *166k
ArrayT = Context.getAsConstantArrayType(T)) {
4980
11.3k
    if (!ArrayT->getSize())
4981
68
      return true;
4982
4983
11.2k
    T = ArrayT->getElementType();
4984
11.2k
  }
4985
4986
166k
  return false;
4987
166k
}
4988
4989
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4990
                                    FieldDecl *Field,
4991
124k
                                    IndirectFieldDecl *Indirect = nullptr) {
4992
124k
  if (Field->isInvalidDecl())
4993
100
    return false;
4994
4995
  // Overwhelmingly common case: we have a direct initializer for this field.
4996
124k
  if (CXXCtorInitializer *Init =
4997
124k
          Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4998
53.7k
    return Info.addFieldInitializer(Init);
4999
5000
  // C++11 [class.base.init]p8:
5001
  //   if the entity is a non-static data member that has a
5002
  //   brace-or-equal-initializer and either
5003
  //   -- the constructor's class is a union and no other variant member of that
5004
  //      union is designated by a mem-initializer-id or
5005
  //   -- the constructor's class is not a union, and, if the entity is a member
5006
  //      of an anonymous union, no other member of that union is designated by
5007
  //      a mem-initializer-id,
5008
  //   the entity is initialized as specified in [dcl.init].
5009
  //
5010
  // We also apply the same rules to handle anonymous structs within anonymous
5011
  // unions.
5012
70.9k
  if (Info.isWithinInactiveUnionMember(Field, Indirect))
5013
11.1k
    return false;
5014
5015
59.8k
  if (Field->hasInClassInitializer() && 
!Info.isImplicitCopyOrMove()1.97k
) {
5016
1.80k
    ExprResult DIE =
5017
1.80k
        SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5018
1.80k
    if (DIE.isInvalid())
5019
2
      return true;
5020
5021
1.79k
    auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5022
1.79k
    SemaRef.checkInitializerLifetime(Entity, DIE.get());
5023
5024
1.79k
    CXXCtorInitializer *Init;
5025
1.79k
    if (Indirect)
5026
71
      Init = new (SemaRef.Context)
5027
71
          CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5028
71
                             SourceLocation(), DIE.get(), SourceLocation());
5029
1.72k
    else
5030
1.72k
      Init = new (SemaRef.Context)
5031
1.72k
          CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5032
1.72k
                             SourceLocation(), DIE.get(), SourceLocation());
5033
1.79k
    return Info.addFieldInitializer(Init);
5034
1.80k
  }
5035
5036
  // Don't initialize incomplete or zero-length arrays.
5037
58.0k
  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5038
73
    return false;
5039
5040
  // Don't try to build an implicit initializer if there were semantic
5041
  // errors in any of the initializers (and therefore we might be
5042
  // missing some that the user actually wrote).
5043
57.9k
  if (Info.AnyErrorsInInits)
5044
19
    return false;
5045
5046
57.9k
  CXXCtorInitializer *Init = nullptr;
5047
57.9k
  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5048
57.9k
                                     Indirect, Init))
5049
30
    return true;
5050
5051
57.9k
  if (!Init)
5052
24.5k
    return false;
5053
5054
33.3k
  return Info.addFieldInitializer(Init);
5055
57.9k
}
5056
5057
bool
5058
Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5059
439
                               CXXCtorInitializer *Initializer) {
5060
439
  assert(Initializer->isDelegatingInitializer());
5061
0
  Constructor->setNumCtorInitializers(1);
5062
439
  CXXCtorInitializer **initializer =
5063
439
    new (Context) CXXCtorInitializer*[1];
5064
439
  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5065
439
  Constructor->setCtorInitializers(initializer);
5066
5067
439
  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5068
439
    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5069
439
    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5070
439
  }
5071
5072
439
  DelegatingCtorDecls.push_back(Constructor);
5073
5074
439
  DiagnoseUninitializedFields(*this, Constructor);
5075
5076
439
  return false;
5077
439
}
5078
5079
bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5080
277k
                               ArrayRef<CXXCtorInitializer *> Initializers) {
5081
277k
  if (Constructor->isDependentContext()) {
5082
    // Just store the initializers as written, they will be checked during
5083
    // instantiation.
5084
138k
    if (!Initializers.empty()) {
5085
127k
      Constructor->setNumCtorInitializers(Initializers.size());
5086
127k
      CXXCtorInitializer **baseOrMemberInitializers =
5087
127k
        new (Context) CXXCtorInitializer*[Initializers.size()];
5088
127k
      memcpy(baseOrMemberInitializers, Initializers.data(),
5089
127k
             Initializers.size() * sizeof(CXXCtorInitializer*));
5090
127k
      Constructor->setCtorInitializers(baseOrMemberInitializers);
5091
127k
    }
5092
5093
    // Let template instantiation know whether we had errors.
5094
138k
    if (AnyErrors)
5095
41
      Constructor->setInvalidDecl();
5096
5097
138k
    return false;
5098
138k
  }
5099
5100
139k
  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5101
5102
  // We need to build the initializer AST according to order of construction
5103
  // and not what user specified in the Initializers list.
5104
139k
  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5105
139k
  if (!ClassDecl)
5106
0
    return true;
5107
5108
139k
  bool HadError = false;
5109
5110
211k
  for (unsigned i = 0; i < Initializers.size(); 
i++71.8k
) {
5111
71.8k
    CXXCtorInitializer *Member = Initializers[i];
5112
5113
71.8k
    if (Member->isBaseInitializer())
5114
18.0k
      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5115
53.7k
    else {
5116
53.7k
      Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5117
5118
53.7k
      if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5119
499
        for (auto *C : F->chain()) {
5120
499
          FieldDecl *FD = dyn_cast<FieldDecl>(C);
5121
499
          if (FD && FD->getParent()->isUnion())
5122
147
            Info.ActiveUnionMember.insert(std::make_pair(
5123
147
                FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5124
499
        }
5125
53.5k
      } else if (FieldDecl *FD = Member->getMember()) {
5126
53.5k
        if (FD->getParent()->isUnion())
5127
78
          Info.ActiveUnionMember.insert(std::make_pair(
5128
78
              FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5129
53.5k
      }
5130
53.7k
    }
5131
71.8k
  }
5132
5133
  // Keep track of the direct virtual bases.
5134
139k
  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5135
139k
  for (auto &I : ClassDecl->bases()) {
5136
39.9k
    if (I.isVirtual())
5137
1.34k
      DirectVBases.insert(&I);
5138