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/TargetInfo.h"
30#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaInternal.h"
40#include "clang/Sema/Template.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringExtras.h"
45#include <map>
46#include <set>
47
48using namespace clang;
49
50//===----------------------------------------------------------------------===//
51// CheckDefaultArgumentVisitor
52//===----------------------------------------------------------------------===//
53
54namespace {
55/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56/// the default argument of a parameter to determine whether it
57/// contains any ill-formed subexpressions. For example, this will
58/// diagnose the use of local variables or parameters within the
59/// default argument expression.
60class CheckDefaultArgumentVisitor
61    : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62  Sema &S;
63  const Expr *DefaultArg;
64
65public:
66  CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67      : S(S), DefaultArg(DefaultArg) {}
68
69  bool VisitExpr(const Expr *Node);
70  bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71  bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72  bool VisitLambdaExpr(const LambdaExpr *Lambda);
73  bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74};
75
76/// VisitExpr - Visit all of the children of this expression.
77bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78  bool IsInvalid = false;
79  for (const Stmt *SubStmt : Node->children())
80    IsInvalid |= Visit(SubStmt);
81  return IsInvalid;
82}
83
84/// VisitDeclRefExpr - Visit a reference to a declaration, to
85/// determine whether this declaration can be used in the default
86/// argument expression.
87bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88  const NamedDecl *Decl = DRE->getDecl();
89  if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90    // C++ [dcl.fct.default]p9:
91    //   [...] parameters of a function shall not be used in default
92    //   argument expressions, even if they are not evaluated. [...]
93    //
94    // C++17 [dcl.fct.default]p9 (by CWG 2082):
95    //   [...] A parameter shall not appear as a potentially-evaluated
96    //   expression in a default argument. [...]
97    //
98    if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99      return S.Diag(DRE->getBeginLoc(),
100                    diag::err_param_default_argument_references_param)
101             << Param->getDeclName() << DefaultArg->getSourceRange();
102  } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103    // C++ [dcl.fct.default]p7:
104    //   Local variables shall not be used in default argument
105    //   expressions.
106    //
107    // C++17 [dcl.fct.default]p7 (by CWG 2082):
108    //   A local variable shall not appear as a potentially-evaluated
109    //   expression in a default argument.
110    //
111    // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112    //   Note: A local variable cannot be odr-used (6.3) in a default argument.
113    //
114    if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115      return S.Diag(DRE->getBeginLoc(),
116                    diag::err_param_default_argument_references_local)
117             << VDecl->getDeclName() << DefaultArg->getSourceRange();
118  }
119
120  return false;
121}
122
123/// VisitCXXThisExpr - Visit a C++ "this" expression.
124bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125  // C++ [dcl.fct.default]p8:
126  //   The keyword this shall not be used in a default argument of a
127  //   member function.
128  return S.Diag(ThisE->getBeginLoc(),
129                diag::err_param_default_argument_references_this)
130         << ThisE->getSourceRange();
131}
132
133bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134    const PseudoObjectExpr *POE) {
135  bool Invalid = false;
136  for (const Expr *E : POE->semantics()) {
137    // Look through bindings.
138    if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139      E = OVE->getSourceExpr();
140      assert(E && "pseudo-object binding without source expression?");
141    }
142
143    Invalid |= Visit(E);
144  }
145  return Invalid;
146}
147
148bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149  // C++11 [expr.lambda.prim]p13:
150  //   A lambda-expression appearing in a default argument shall not
151  //   implicitly or explicitly capture any entity.
152  if (Lambda->capture_begin() == Lambda->capture_end())
153    return false;
154
155  return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156}
157} // namespace
158
159void
160Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161                                                 const CXXMethodDecl *Method) {
162  // If we have an MSAny spec already, don't bother.
163  if (!Method || ComputedEST == EST_MSAny)
164    return;
165
166  const FunctionProtoType *Proto
167    = Method->getType()->getAs<FunctionProtoType>();
168  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169  if (!Proto)
170    return;
171
172  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173
174  // If we have a throw-all spec at this point, ignore the function.
175  if (ComputedEST == EST_None)
176    return;
177
178  if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179    EST = EST_BasicNoexcept;
180
181  switch (EST) {
182  case EST_Unparsed:
183  case EST_Uninstantiated:
184  case EST_Unevaluated:
185    llvm_unreachable("should not see unresolved exception specs here");
186
187  // If this function can throw any exceptions, make a note of that.
188  case EST_MSAny:
189  case EST_None:
190    // FIXME: Whichever we see last of MSAny and None determines our result.
191    // We should make a consistent, order-independent choice here.
192    ClearExceptions();
193    ComputedEST = EST;
194    return;
195  case EST_NoexceptFalse:
196    ClearExceptions();
197    ComputedEST = EST_None;
198    return;
199  // FIXME: If the call to this decl is using any of its default arguments, we
200  // need to search them for potentially-throwing calls.
201  // If this function has a basic noexcept, it doesn't affect the outcome.
202  case EST_BasicNoexcept:
203  case EST_NoexceptTrue:
204  case EST_NoThrow:
205    return;
206  // If we're still at noexcept(true) and there's a throw() callee,
207  // change to that specification.
208  case EST_DynamicNone:
209    if (ComputedEST == EST_BasicNoexcept)
210      ComputedEST = EST_DynamicNone;
211    return;
212  case EST_DependentNoexcept:
213    llvm_unreachable(
214        "should not generate implicit declarations for dependent cases");
215  case EST_Dynamic:
216    break;
217  }
218  assert(EST == EST_Dynamic && "EST case not considered earlier.");
219  assert(ComputedEST != EST_None &&
220         "Shouldn't collect exceptions when throw-all is guaranteed.");
221  ComputedEST = EST_Dynamic;
222  // Record the exceptions in this function's exception specification.
223  for (const auto &E : Proto->exceptions())
224    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225      Exceptions.push_back(E);
226}
227
228void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229  if (!S || ComputedEST == EST_MSAny)
230    return;
231
232  // FIXME:
233  //
234  // C++0x [except.spec]p14:
235  //   [An] implicit exception-specification specifies the type-id T if and
236  // only if T is allowed by the exception-specification of a function directly
237  // invoked by f's implicit definition; f shall allow all exceptions if any
238  // function it directly invokes allows all exceptions, and f shall allow no
239  // exceptions if every function it directly invokes allows no exceptions.
240  //
241  // Note in particular that if an implicit exception-specification is generated
242  // for a function containing a throw-expression, that specification can still
243  // be noexcept(true).
244  //
245  // Note also that 'directly invoked' is not defined in the standard, and there
246  // is no indication that we should only consider potentially-evaluated calls.
247  //
248  // Ultimately we should implement the intent of the standard: the exception
249  // specification should be the set of exceptions which can be thrown by the
250  // implicit definition. For now, we assume that any non-nothrow expression can
251  // throw any exception.
252
253  if (Self->canThrow(S))
254    ComputedEST = EST_None;
255}
256
257ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param,
258                                             Expr *Arg,
259                                             SourceLocation EqualLoc) {
260  if (RequireCompleteType(Param->getLocation(), Param->getType(),
261                          diag::err_typecheck_decl_incomplete_type))
262    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  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
271                                                                    Param);
272  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273                                                           EqualLoc);
274  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276  if (Result.isInvalid())
277    return true;
278  Arg = Result.getAs<Expr>();
279
280  CheckCompletedExpr(Arg, EqualLoc);
281  Arg = MaybeCreateExprWithCleanups(Arg);
282
283  return Arg;
284}
285
286void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287                                   SourceLocation EqualLoc) {
288  // Add the default argument to the parameter
289  Param->setDefaultArg(Arg);
290
291  // We have already instantiated this parameter; provide each of the
292  // instantiations with the uninstantiated default argument.
293  UnparsedDefaultArgInstantiationsMap::iterator InstPos
294    = UnparsedDefaultArgInstantiations.find(Param);
295  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298
299    // We're done tracking this parameter's instantiations.
300    UnparsedDefaultArgInstantiations.erase(InstPos);
301  }
302}
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.
307void
308Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
309                                Expr *DefaultArg) {
310  if (!param || !DefaultArg)
311    return;
312
313  ParmVarDecl *Param = cast<ParmVarDecl>(param);
314  UnparsedDefaultArgLocs.erase(Param);
315
316  auto Fail = [&] {
317    Param->setInvalidDecl();
318    Param->setDefaultArg(new (Context) OpaqueValueExpr(
319        EqualLoc, Param->getType().getNonReferenceType(), VK_RValue));
320  };
321
322  // Default arguments are only permitted in C++
323  if (!getLangOpts().CPlusPlus) {
324    Diag(EqualLoc, diag::err_param_default_argument)
325      << DefaultArg->getSourceRange();
326    return Fail();
327  }
328
329  // Check for unexpanded parameter packs.
330  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331    return Fail();
332  }
333
334  // C++11 [dcl.fct.default]p3
335  //   A default argument expression [...] shall not be specified for a
336  //   parameter pack.
337  if (Param->isParameterPack()) {
338    Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339        << DefaultArg->getSourceRange();
340    // Recover by discarding the default argument.
341    Param->setDefaultArg(nullptr);
342    return;
343  }
344
345  ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346  if (Result.isInvalid())
347    return Fail();
348
349  DefaultArg = Result.getAs<Expr>();
350
351  // Check that the default argument is well-formed
352  CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353  if (DefaultArgChecker.Visit(DefaultArg))
354    return Fail();
355
356  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357}
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.
363void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364                                             SourceLocation EqualLoc,
365                                             SourceLocation ArgLoc) {
366  if (!param)
367    return;
368
369  ParmVarDecl *Param = cast<ParmVarDecl>(param);
370  Param->setUnparsedDefaultArg();
371  UnparsedDefaultArgLocs[Param] = ArgLoc;
372}
373
374/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375/// the default argument for the parameter param failed.
376void Sema::ActOnParamDefaultArgumentError(Decl *param,
377                                          SourceLocation EqualLoc) {
378  if (!param)
379    return;
380
381  ParmVarDecl *Param = cast<ParmVarDecl>(param);
382  Param->setInvalidDecl();
383  UnparsedDefaultArgLocs.erase(Param);
384  Param->setDefaultArg(new(Context)
385                       OpaqueValueExpr(EqualLoc,
386                                       Param->getType().getNonReferenceType(),
387                                       VK_RValue));
388}
389
390/// CheckExtraCXXDefaultArguments - Check for any extra default
391/// arguments in the declarator, which is not a function declaration
392/// or definition and therefore is not permitted to have default
393/// arguments. This routine should be invoked for every declarator
394/// that is not a function declaration or definition.
395void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
396  // C++ [dcl.fct.default]p3
397  //   A default argument expression shall be specified only in the
398  //   parameter-declaration-clause of a function declaration or in a
399  //   template-parameter (14.1). It shall not be specified for a
400  //   parameter pack. If it is specified in a
401  //   parameter-declaration-clause, it shall not occur within a
402  //   declarator or abstract-declarator of a parameter-declaration.
403  bool MightBeFunction = D.isFunctionDeclarationContext();
404  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
405    DeclaratorChunk &chunk = D.getTypeObject(i);
406    if (chunk.Kind == DeclaratorChunk::Function) {
407      if (MightBeFunction) {
408        // This is a function declaration. It can have default arguments, but
409        // keep looking in case its return type is a function type with default
410        // arguments.
411        MightBeFunction = false;
412        continue;
413      }
414      for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
415           ++argIdx) {
416        ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
417        if (Param->hasUnparsedDefaultArg()) {
418          std::unique_ptr<CachedTokens> Toks =
419              std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
420          SourceRange SR;
421          if (Toks->size() > 1)
422            SR = SourceRange((*Toks)[1].getLocation(),
423                             Toks->back().getLocation());
424          else
425            SR = UnparsedDefaultArgLocs[Param];
426          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
427            << SR;
428        } else if (Param->getDefaultArg()) {
429          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
430            << Param->getDefaultArg()->getSourceRange();
431          Param->setDefaultArg(nullptr);
432        }
433      }
434    } else if (chunk.Kind != DeclaratorChunk::Paren) {
435      MightBeFunction = false;
436    }
437  }
438}
439
440static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
441  return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
442    return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
443  });
444}
445
446/// MergeCXXFunctionDecl - Merge two declarations of the same C++
447/// function, once we already know that they have the same
448/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
449/// error, false otherwise.
450bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
451                                Scope *S) {
452  bool Invalid = false;
453
454  // The declaration context corresponding to the scope is the semantic
455  // parent, unless this is a local function declaration, in which case
456  // it is that surrounding function.
457  DeclContext *ScopeDC = New->isLocalExternDecl()
458                             ? New->getLexicalDeclContext()
459                             : New->getDeclContext();
460
461  // Find the previous declaration for the purpose of default arguments.
462  FunctionDecl *PrevForDefaultArgs = Old;
463  for (/**/; PrevForDefaultArgs;
464       // Don't bother looking back past the latest decl if this is a local
465       // extern declaration; nothing else could work.
466       PrevForDefaultArgs = New->isLocalExternDecl()
467                                ? nullptr
468                                : PrevForDefaultArgs->getPreviousDecl()) {
469    // Ignore hidden declarations.
470    if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
471      continue;
472
473    if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
474        !New->isCXXClassMember()) {
475      // Ignore default arguments of old decl if they are not in
476      // the same scope and this is not an out-of-line definition of
477      // a member function.
478      continue;
479    }
480
481    if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
482      // If only one of these is a local function declaration, then they are
483      // declared in different scopes, even though isDeclInScope may think
484      // they're in the same scope. (If both are local, the scope check is
485      // sufficient, and if neither is local, then they are in the same scope.)
486      continue;
487    }
488
489    // We found the right previous declaration.
490    break;
491  }
492
493  // C++ [dcl.fct.default]p4:
494  //   For non-template functions, default arguments can be added in
495  //   later declarations of a function in the same
496  //   scope. Declarations in different scopes have completely
497  //   distinct sets of default arguments. That is, declarations in
498  //   inner scopes do not acquire default arguments from
499  //   declarations in outer scopes, and vice versa. In a given
500  //   function declaration, all parameters subsequent to a
501  //   parameter with a default argument shall have default
502  //   arguments supplied in this or previous declarations. A
503  //   default argument shall not be redefined by a later
504  //   declaration (not even to the same value).
505  //
506  // C++ [dcl.fct.default]p6:
507  //   Except for member functions of class templates, the default arguments
508  //   in a member function definition that appears outside of the class
509  //   definition are added to the set of default arguments provided by the
510  //   member function declaration in the class definition.
511  for (unsigned p = 0, NumParams = PrevForDefaultArgs
512                                       ? PrevForDefaultArgs->getNumParams()
513                                       : 0;
514       p < NumParams; ++p) {
515    ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
516    ParmVarDecl *NewParam = New->getParamDecl(p);
517
518    bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
519    bool NewParamHasDfl = NewParam->hasDefaultArg();
520
521    if (OldParamHasDfl && NewParamHasDfl) {
522      unsigned DiagDefaultParamID =
523        diag::err_param_default_argument_redefinition;
524
525      // MSVC accepts that default parameters be redefined for member functions
526      // of template class. The new default parameter's value is ignored.
527      Invalid = true;
528      if (getLangOpts().MicrosoftExt) {
529        CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
530        if (MD && MD->getParent()->getDescribedClassTemplate()) {
531          // Merge the old default argument into the new parameter.
532          NewParam->setHasInheritedDefaultArg();
533          if (OldParam->hasUninstantiatedDefaultArg())
534            NewParam->setUninstantiatedDefaultArg(
535                                      OldParam->getUninstantiatedDefaultArg());
536          else
537            NewParam->setDefaultArg(OldParam->getInit());
538          DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
539          Invalid = false;
540        }
541      }
542
543      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
544      // hint here. Alternatively, we could walk the type-source information
545      // for NewParam to find the last source location in the type... but it
546      // isn't worth the effort right now. This is the kind of test case that
547      // is hard to get right:
548      //   int f(int);
549      //   void g(int (*fp)(int) = f);
550      //   void g(int (*fp)(int) = &f);
551      Diag(NewParam->getLocation(), DiagDefaultParamID)
552        << NewParam->getDefaultArgRange();
553
554      // Look for the function declaration where the default argument was
555      // actually written, which may be a declaration prior to Old.
556      for (auto Older = PrevForDefaultArgs;
557           OldParam->hasInheritedDefaultArg(); /**/) {
558        Older = Older->getPreviousDecl();
559        OldParam = Older->getParamDecl(p);
560      }
561
562      Diag(OldParam->getLocation(), diag::note_previous_definition)
563        << OldParam->getDefaultArgRange();
564    } else if (OldParamHasDfl) {
565      // Merge the old default argument into the new parameter unless the new
566      // function is a friend declaration in a template class. In the latter
567      // case the default arguments will be inherited when the friend
568      // declaration will be instantiated.
569      if (New->getFriendObjectKind() == Decl::FOK_None ||
570          !New->getLexicalDeclContext()->isDependentContext()) {
571        // It's important to use getInit() here;  getDefaultArg()
572        // strips off any top-level ExprWithCleanups.
573        NewParam->setHasInheritedDefaultArg();
574        if (OldParam->hasUnparsedDefaultArg())
575          NewParam->setUnparsedDefaultArg();
576        else if (OldParam->hasUninstantiatedDefaultArg())
577          NewParam->setUninstantiatedDefaultArg(
578                                       OldParam->getUninstantiatedDefaultArg());
579        else
580          NewParam->setDefaultArg(OldParam->getInit());
581      }
582    } else if (NewParamHasDfl) {
583      if (New->getDescribedFunctionTemplate()) {
584        // Paragraph 4, quoted above, only applies to non-template functions.
585        Diag(NewParam->getLocation(),
586             diag::err_param_default_argument_template_redecl)
587          << NewParam->getDefaultArgRange();
588        Diag(PrevForDefaultArgs->getLocation(),
589             diag::note_template_prev_declaration)
590            << false;
591      } else if (New->getTemplateSpecializationKind()
592                   != TSK_ImplicitInstantiation &&
593                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
594        // C++ [temp.expr.spec]p21:
595        //   Default function arguments shall not be specified in a declaration
596        //   or a definition for one of the following explicit specializations:
597        //     - the explicit specialization of a function template;
598        //     - the explicit specialization of a member function template;
599        //     - the explicit specialization of a member function of a class
600        //       template where the class template specialization to which the
601        //       member function specialization belongs is implicitly
602        //       instantiated.
603        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
604          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
605          << New->getDeclName()
606          << NewParam->getDefaultArgRange();
607      } else if (New->getDeclContext()->isDependentContext()) {
608        // C++ [dcl.fct.default]p6 (DR217):
609        //   Default arguments for a member function of a class template shall
610        //   be specified on the initial declaration of the member function
611        //   within the class template.
612        //
613        // Reading the tea leaves a bit in DR217 and its reference to DR205
614        // leads me to the conclusion that one cannot add default function
615        // arguments for an out-of-line definition of a member function of a
616        // dependent type.
617        int WhichKind = 2;
618        if (CXXRecordDecl *Record
619              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
620          if (Record->getDescribedClassTemplate())
621            WhichKind = 0;
622          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
623            WhichKind = 1;
624          else
625            WhichKind = 2;
626        }
627
628        Diag(NewParam->getLocation(),
629             diag::err_param_default_argument_member_template_redecl)
630          << WhichKind
631          << NewParam->getDefaultArgRange();
632      }
633    }
634  }
635
636  // DR1344: If a default argument is added outside a class definition and that
637  // default argument makes the function a special member function, the program
638  // is ill-formed. This can only happen for constructors.
639  if (isa<CXXConstructorDecl>(New) &&
640      New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
641    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
642                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
643    if (NewSM != OldSM) {
644      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
645      assert(NewParam->hasDefaultArg());
646      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
647        << NewParam->getDefaultArgRange() << NewSM;
648      Diag(Old->getLocation(), diag::note_previous_declaration);
649    }
650  }
651
652  const FunctionDecl *Def;
653  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
654  // template has a constexpr specifier then all its declarations shall
655  // contain the constexpr specifier.
656  if (New->getConstexprKind() != Old->getConstexprKind()) {
657    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
658        << New << New->getConstexprKind() << Old->getConstexprKind();
659    Diag(Old->getLocation(), diag::note_previous_declaration);
660    Invalid = true;
661  } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
662             Old->isDefined(Def) &&
663             // If a friend function is inlined but does not have 'inline'
664             // specifier, it is a definition. Do not report attribute conflict
665             // in this case, redefinition will be diagnosed later.
666             (New->isInlineSpecified() ||
667              New->getFriendObjectKind() == Decl::FOK_None)) {
668    // C++11 [dcl.fcn.spec]p4:
669    //   If the definition of a function appears in a translation unit before its
670    //   first declaration as inline, the program is ill-formed.
671    Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
672    Diag(Def->getLocation(), diag::note_previous_definition);
673    Invalid = true;
674  }
675
676  // C++17 [temp.deduct.guide]p3:
677  //   Two deduction guide declarations in the same translation unit
678  //   for the same class template shall not have equivalent
679  //   parameter-declaration-clauses.
680  if (isa<CXXDeductionGuideDecl>(New) &&
681      !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
682    Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
683    Diag(Old->getLocation(), diag::note_previous_declaration);
684  }
685
686  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
687  // argument expression, that declaration shall be a definition and shall be
688  // the only declaration of the function or function template in the
689  // translation unit.
690  if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
691      functionDeclHasDefaultArgument(Old)) {
692    Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
693    Diag(Old->getLocation(), diag::note_previous_declaration);
694    Invalid = true;
695  }
696
697  return Invalid;
698}
699
700NamedDecl *
701Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
702                                   MultiTemplateParamsArg TemplateParamLists) {
703  assert(D.isDecompositionDeclarator());
704  const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
705
706  // The syntax only allows a decomposition declarator as a simple-declaration,
707  // a for-range-declaration, or a condition in Clang, but we parse it in more
708  // cases than that.
709  if (!D.mayHaveDecompositionDeclarator()) {
710    Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
711      << Decomp.getSourceRange();
712    return nullptr;
713  }
714
715  if (!TemplateParamLists.empty()) {
716    // FIXME: There's no rule against this, but there are also no rules that
717    // would actually make it usable, so we reject it for now.
718    Diag(TemplateParamLists.front()->getTemplateLoc(),
719         diag::err_decomp_decl_template);
720    return nullptr;
721  }
722
723  Diag(Decomp.getLSquareLoc(),
724       !getLangOpts().CPlusPlus17
725           ? diag::ext_decomp_decl
726           : D.getContext() == DeclaratorContext::ConditionContext
727                 ? diag::ext_decomp_decl_cond
728                 : diag::warn_cxx14_compat_decomp_decl)
729      << Decomp.getSourceRange();
730
731  // The semantic context is always just the current context.
732  DeclContext *const DC = CurContext;
733
734  // C++17 [dcl.dcl]/8:
735  //   The decl-specifier-seq shall contain only the type-specifier auto
736  //   and cv-qualifiers.
737  // C++2a [dcl.dcl]/8:
738  //   If decl-specifier-seq contains any decl-specifier other than static,
739  //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
740  auto &DS = D.getDeclSpec();
741  {
742    SmallVector<StringRef, 8> BadSpecifiers;
743    SmallVector<SourceLocation, 8> BadSpecifierLocs;
744    SmallVector<StringRef, 8> CPlusPlus20Specifiers;
745    SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
746    if (auto SCS = DS.getStorageClassSpec()) {
747      if (SCS == DeclSpec::SCS_static) {
748        CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
749        CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
750      } else {
751        BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
752        BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
753      }
754    }
755    if (auto TSCS = DS.getThreadStorageClassSpec()) {
756      CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
757      CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
758    }
759    if (DS.hasConstexprSpecifier()) {
760      BadSpecifiers.push_back(
761          DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
762      BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
763    }
764    if (DS.isInlineSpecified()) {
765      BadSpecifiers.push_back("inline");
766      BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
767    }
768    if (!BadSpecifiers.empty()) {
769      auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
770      Err << (int)BadSpecifiers.size()
771          << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
772      // Don't add FixItHints to remove the specifiers; we do still respect
773      // them when building the underlying variable.
774      for (auto Loc : BadSpecifierLocs)
775        Err << SourceRange(Loc, Loc);
776    } else if (!CPlusPlus20Specifiers.empty()) {
777      auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
778                         getLangOpts().CPlusPlus20
779                             ? diag::warn_cxx17_compat_decomp_decl_spec
780                             : diag::ext_decomp_decl_spec);
781      Warn << (int)CPlusPlus20Specifiers.size()
782           << llvm::join(CPlusPlus20Specifiers.begin(),
783                         CPlusPlus20Specifiers.end(), " ");
784      for (auto Loc : CPlusPlus20SpecifierLocs)
785        Warn << SourceRange(Loc, Loc);
786    }
787    // We can't recover from it being declared as a typedef.
788    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
789      return nullptr;
790  }
791
792  // C++2a [dcl.struct.bind]p1:
793  //   A cv that includes volatile is deprecated
794  if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
795      getLangOpts().CPlusPlus20)
796    Diag(DS.getVolatileSpecLoc(),
797         diag::warn_deprecated_volatile_structured_binding);
798
799  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
800  QualType R = TInfo->getType();
801
802  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
803                                      UPPC_DeclarationType))
804    D.setInvalidType();
805
806  // The syntax only allows a single ref-qualifier prior to the decomposition
807  // declarator. No other declarator chunks are permitted. Also check the type
808  // specifier here.
809  if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
810      D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
811      (D.getNumTypeObjects() == 1 &&
812       D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
813    Diag(Decomp.getLSquareLoc(),
814         (D.hasGroupingParens() ||
815          (D.getNumTypeObjects() &&
816           D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
817             ? diag::err_decomp_decl_parens
818             : diag::err_decomp_decl_type)
819        << R;
820
821    // In most cases, there's no actual problem with an explicitly-specified
822    // type, but a function type won't work here, and ActOnVariableDeclarator
823    // shouldn't be called for such a type.
824    if (R->isFunctionType())
825      D.setInvalidType();
826  }
827
828  // Build the BindingDecls.
829  SmallVector<BindingDecl*, 8> Bindings;
830
831  // Build the BindingDecls.
832  for (auto &B : D.getDecompositionDeclarator().bindings()) {
833    // Check for name conflicts.
834    DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
835    LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
836                          ForVisibleRedeclaration);
837    LookupName(Previous, S,
838               /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
839
840    // It's not permitted to shadow a template parameter name.
841    if (Previous.isSingleResult() &&
842        Previous.getFoundDecl()->isTemplateParameter()) {
843      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
844                                      Previous.getFoundDecl());
845      Previous.clear();
846    }
847
848    bool ConsiderLinkage = DC->isFunctionOrMethod() &&
849                           DS.getStorageClassSpec() == DeclSpec::SCS_extern;
850    FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
851                         /*AllowInlineNamespace*/false);
852    if (!Previous.empty()) {
853      auto *Old = Previous.getRepresentativeDecl();
854      Diag(B.NameLoc, diag::err_redefinition) << B.Name;
855      Diag(Old->getLocation(), diag::note_previous_definition);
856    }
857
858    auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859    PushOnScopeChains(BD, S, true);
860    Bindings.push_back(BD);
861    ParsingInitForAutoVars.insert(BD);
862  }
863
864  // There are no prior lookup results for the variable itself, because it
865  // is unnamed.
866  DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
867                               Decomp.getLSquareLoc());
868  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
869                        ForVisibleRedeclaration);
870
871  // Build the variable that holds the non-decomposed object.
872  bool AddToScope = true;
873  NamedDecl *New =
874      ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
875                              MultiTemplateParamsArg(), AddToScope, Bindings);
876  if (AddToScope) {
877    S->AddDecl(New);
878    CurContext->addHiddenDecl(New);
879  }
880
881  if (isInOpenMPDeclareTargetContext())
882    checkDeclIsAllowedInOpenMPTarget(nullptr, New);
883
884  return New;
885}
886
887static bool checkSimpleDecomposition(
888    Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
889    QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
890    llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
891  if ((int64_t)Bindings.size() != NumElems) {
892    S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
893        << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
894        << (NumElems < Bindings.size());
895    return true;
896  }
897
898  unsigned I = 0;
899  for (auto *B : Bindings) {
900    SourceLocation Loc = B->getLocation();
901    ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
902    if (E.isInvalid())
903      return true;
904    E = GetInit(Loc, E.get(), I++);
905    if (E.isInvalid())
906      return true;
907    B->setBinding(ElemType, E.get());
908  }
909
910  return false;
911}
912
913static bool checkArrayLikeDecomposition(Sema &S,
914                                        ArrayRef<BindingDecl *> Bindings,
915                                        ValueDecl *Src, QualType DecompType,
916                                        const llvm::APSInt &NumElems,
917                                        QualType ElemType) {
918  return checkSimpleDecomposition(
919      S, Bindings, Src, DecompType, NumElems, ElemType,
920      [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
921        ExprResult E = S.ActOnIntegerConstant(Loc, I);
922        if (E.isInvalid())
923          return ExprError();
924        return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
925      });
926}
927
928static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
929                                    ValueDecl *Src, QualType DecompType,
930                                    const ConstantArrayType *CAT) {
931  return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
932                                     llvm::APSInt(CAT->getSize()),
933                                     CAT->getElementType());
934}
935
936static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
937                                     ValueDecl *Src, QualType DecompType,
938                                     const VectorType *VT) {
939  return checkArrayLikeDecomposition(
940      S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
941      S.Context.getQualifiedType(VT->getElementType(),
942                                 DecompType.getQualifiers()));
943}
944
945static bool checkComplexDecomposition(Sema &S,
946                                      ArrayRef<BindingDecl *> Bindings,
947                                      ValueDecl *Src, QualType DecompType,
948                                      const ComplexType *CT) {
949  return checkSimpleDecomposition(
950      S, Bindings, Src, DecompType, llvm::APSInt::get(2),
951      S.Context.getQualifiedType(CT->getElementType(),
952                                 DecompType.getQualifiers()),
953      [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
954        return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
955      });
956}
957
958static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
959                                     TemplateArgumentListInfo &Args) {
960  SmallString<128> SS;
961  llvm::raw_svector_ostream OS(SS);
962  bool First = true;
963  for (auto &Arg : Args.arguments()) {
964    if (!First)
965      OS << ", ";
966    Arg.getArgument().print(PrintingPolicy, OS);
967    First = false;
968  }
969  return std::string(OS.str());
970}
971
972static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
973                                     SourceLocation Loc, StringRef Trait,
974                                     TemplateArgumentListInfo &Args,
975                                     unsigned DiagID) {
976  auto DiagnoseMissing = [&] {
977    if (DiagID)
978      S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
979                                               Args);
980    return true;
981  };
982
983  // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
984  NamespaceDecl *Std = S.getStdNamespace();
985  if (!Std)
986    return DiagnoseMissing();
987
988  // Look up the trait itself, within namespace std. We can diagnose various
989  // problems with this lookup even if we've been asked to not diagnose a
990  // missing specialization, because this can only fail if the user has been
991  // declaring their own names in namespace std or we don't support the
992  // standard library implementation in use.
993  LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
994                      Loc, Sema::LookupOrdinaryName);
995  if (!S.LookupQualifiedName(Result, Std))
996    return DiagnoseMissing();
997  if (Result.isAmbiguous())
998    return true;
999
1000  ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1001  if (!TraitTD) {
1002    Result.suppressDiagnostics();
1003    NamedDecl *Found = *Result.begin();
1004    S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1005    S.Diag(Found->getLocation(), diag::note_declared_at);
1006    return true;
1007  }
1008
1009  // Build the template-id.
1010  QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1011  if (TraitTy.isNull())
1012    return true;
1013  if (!S.isCompleteType(Loc, TraitTy)) {
1014    if (DiagID)
1015      S.RequireCompleteType(
1016          Loc, TraitTy, DiagID,
1017          printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1018    return true;
1019  }
1020
1021  CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1022  assert(RD && "specialization of class template is not a class?");
1023
1024  // Look up the member of the trait type.
1025  S.LookupQualifiedName(TraitMemberLookup, RD);
1026  return TraitMemberLookup.isAmbiguous();
1027}
1028
1029static TemplateArgumentLoc
1030getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1031                                   uint64_t I) {
1032  TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1033  return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1034}
1035
1036static TemplateArgumentLoc
1037getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1038  return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1039}
1040
1041namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1042
1043static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1044                               llvm::APSInt &Size) {
1045  EnterExpressionEvaluationContext ContextRAII(
1046      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1047
1048  DeclarationName Value = S.PP.getIdentifierInfo("value");
1049  LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1050
1051  // Form template argument list for tuple_size<T>.
1052  TemplateArgumentListInfo Args(Loc, Loc);
1053  Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1054
1055  // If there's no tuple_size specialization or the lookup of 'value' is empty,
1056  // it's not tuple-like.
1057  if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1058      R.empty())
1059    return IsTupleLike::NotTupleLike;
1060
1061  // If we get this far, we've committed to the tuple interpretation, but
1062  // we can still fail if there actually isn't a usable ::value.
1063
1064  struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1065    LookupResult &R;
1066    TemplateArgumentListInfo &Args;
1067    ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1068        : R(R), Args(Args) {}
1069    void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1070      S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1071          << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1072    }
1073  } Diagnoser(R, Args);
1074
1075  ExprResult E =
1076      S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1077  if (E.isInvalid())
1078    return IsTupleLike::Error;
1079
1080  E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1081  if (E.isInvalid())
1082    return IsTupleLike::Error;
1083
1084  return IsTupleLike::TupleLike;
1085}
1086
1087/// \return std::tuple_element<I, T>::type.
1088static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1089                                        unsigned I, QualType T) {
1090  // Form template argument list for tuple_element<I, T>.
1091  TemplateArgumentListInfo Args(Loc, Loc);
1092  Args.addArgument(
1093      getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1094  Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1095
1096  DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1097  LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1098  if (lookupStdTypeTraitMember(
1099          S, R, Loc, "tuple_element", Args,
1100          diag::err_decomp_decl_std_tuple_element_not_specialized))
1101    return QualType();
1102
1103  auto *TD = R.getAsSingle<TypeDecl>();
1104  if (!TD) {
1105    R.suppressDiagnostics();
1106    S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1107      << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1108    if (!R.empty())
1109      S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1110    return QualType();
1111  }
1112
1113  return S.Context.getTypeDeclType(TD);
1114}
1115
1116namespace {
1117struct InitializingBinding {
1118  Sema &S;
1119  InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1120    Sema::CodeSynthesisContext Ctx;
1121    Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1122    Ctx.PointOfInstantiation = BD->getLocation();
1123    Ctx.Entity = BD;
1124    S.pushCodeSynthesisContext(Ctx);
1125  }
1126  ~InitializingBinding() {
1127    S.popCodeSynthesisContext();
1128  }
1129};
1130}
1131
1132static bool checkTupleLikeDecomposition(Sema &S,
1133                                        ArrayRef<BindingDecl *> Bindings,
1134                                        VarDecl *Src, QualType DecompType,
1135                                        const llvm::APSInt &TupleSize) {
1136  if ((int64_t)Bindings.size() != TupleSize) {
1137    S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1138        << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1139        << (TupleSize < Bindings.size());
1140    return true;
1141  }
1142
1143  if (Bindings.empty())
1144    return false;
1145
1146  DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1147
1148  // [dcl.decomp]p3:
1149  //   The unqualified-id get is looked up in the scope of E by class member
1150  //   access lookup ...
1151  LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1152  bool UseMemberGet = false;
1153  if (S.isCompleteType(Src->getLocation(), DecompType)) {
1154    if (auto *RD = DecompType->getAsCXXRecordDecl())
1155      S.LookupQualifiedName(MemberGet, RD);
1156    if (MemberGet.isAmbiguous())
1157      return true;
1158    //   ... and if that finds at least one declaration that is a function
1159    //   template whose first template parameter is a non-type parameter ...
1160    for (NamedDecl *D : MemberGet) {
1161      if (FunctionTemplateDecl *FTD =
1162              dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1163        TemplateParameterList *TPL = FTD->getTemplateParameters();
1164        if (TPL->size() != 0 &&
1165            isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1166          //   ... the initializer is e.get<i>().
1167          UseMemberGet = true;
1168          break;
1169        }
1170      }
1171    }
1172  }
1173
1174  unsigned I = 0;
1175  for (auto *B : Bindings) {
1176    InitializingBinding InitContext(S, B);
1177    SourceLocation Loc = B->getLocation();
1178
1179    ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1180    if (E.isInvalid())
1181      return true;
1182
1183    //   e is an lvalue if the type of the entity is an lvalue reference and
1184    //   an xvalue otherwise
1185    if (!Src->getType()->isLValueReferenceType())
1186      E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1187                                   E.get(), nullptr, VK_XValue);
1188
1189    TemplateArgumentListInfo Args(Loc, Loc);
1190    Args.addArgument(
1191        getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1192
1193    if (UseMemberGet) {
1194      //   if [lookup of member get] finds at least one declaration, the
1195      //   initializer is e.get<i-1>().
1196      E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1197                                     CXXScopeSpec(), SourceLocation(), nullptr,
1198                                     MemberGet, &Args, nullptr);
1199      if (E.isInvalid())
1200        return true;
1201
1202      E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1203    } else {
1204      //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1205      //   in the associated namespaces.
1206      Expr *Get = UnresolvedLookupExpr::Create(
1207          S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1208          DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1209          UnresolvedSetIterator(), UnresolvedSetIterator());
1210
1211      Expr *Arg = E.get();
1212      E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1213    }
1214    if (E.isInvalid())
1215      return true;
1216    Expr *Init = E.get();
1217
1218    //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1219    QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1220    if (T.isNull())
1221      return true;
1222
1223    //   each vi is a variable of type "reference to T" initialized with the
1224    //   initializer, where the reference is an lvalue reference if the
1225    //   initializer is an lvalue and an rvalue reference otherwise
1226    QualType RefType =
1227        S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1228    if (RefType.isNull())
1229      return true;
1230    auto *RefVD = VarDecl::Create(
1231        S.Context, Src->getDeclContext(), Loc, Loc,
1232        B->getDeclName().getAsIdentifierInfo(), RefType,
1233        S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1234    RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1235    RefVD->setTSCSpec(Src->getTSCSpec());
1236    RefVD->setImplicit();
1237    if (Src->isInlineSpecified())
1238      RefVD->setInlineSpecified();
1239    RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1240
1241    InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1242    InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1243    InitializationSequence Seq(S, Entity, Kind, Init);
1244    E = Seq.Perform(S, Entity, Kind, Init);
1245    if (E.isInvalid())
1246      return true;
1247    E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1248    if (E.isInvalid())
1249      return true;
1250    RefVD->setInit(E.get());
1251    if (!E.get()->isValueDependent())
1252      RefVD->checkInitIsICE();
1253
1254    E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1255                                   DeclarationNameInfo(B->getDeclName(), Loc),
1256                                   RefVD);
1257    if (E.isInvalid())
1258      return true;
1259
1260    B->setBinding(T, E.get());
1261    I++;
1262  }
1263
1264  return false;
1265}
1266
1267/// Find the base class to decompose in a built-in decomposition of a class type.
1268/// This base class search is, unfortunately, not quite like any other that we
1269/// perform anywhere else in C++.
1270static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1271                                                const CXXRecordDecl *RD,
1272                                                CXXCastPath &BasePath) {
1273  auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1274                          CXXBasePath &Path) {
1275    return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1276  };
1277
1278  const CXXRecordDecl *ClassWithFields = nullptr;
1279  AccessSpecifier AS = AS_public;
1280  if (RD->hasDirectFields())
1281    // [dcl.decomp]p4:
1282    //   Otherwise, all of E's non-static data members shall be public direct
1283    //   members of E ...
1284    ClassWithFields = RD;
1285  else {
1286    //   ... or of ...
1287    CXXBasePaths Paths;
1288    Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1289    if (!RD->lookupInBases(BaseHasFields, Paths)) {
1290      // If no classes have fields, just decompose RD itself. (This will work
1291      // if and only if zero bindings were provided.)
1292      return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1293    }
1294
1295    CXXBasePath *BestPath = nullptr;
1296    for (auto &P : Paths) {
1297      if (!BestPath)
1298        BestPath = &P;
1299      else if (!S.Context.hasSameType(P.back().Base->getType(),
1300                                      BestPath->back().Base->getType())) {
1301        //   ... the same ...
1302        S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1303          << false << RD << BestPath->back().Base->getType()
1304          << P.back().Base->getType();
1305        return DeclAccessPair();
1306      } else if (P.Access < BestPath->Access) {
1307        BestPath = &P;
1308      }
1309    }
1310
1311    //   ... unambiguous ...
1312    QualType BaseType = BestPath->back().Base->getType();
1313    if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1314      S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1315        << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1316      return DeclAccessPair();
1317    }
1318
1319    //   ... [accessible, implied by other rules] base class of E.
1320    S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1321                           *BestPath, diag::err_decomp_decl_inaccessible_base);
1322    AS = BestPath->Access;
1323
1324    ClassWithFields = BaseType->getAsCXXRecordDecl();
1325    S.BuildBasePathArray(Paths, BasePath);
1326  }
1327
1328  // The above search did not check whether the selected class itself has base
1329  // classes with fields, so check that now.
1330  CXXBasePaths Paths;
1331  if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1332    S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1333      << (ClassWithFields == RD) << RD << ClassWithFields
1334      << Paths.front().back().Base->getType();
1335    return DeclAccessPair();
1336  }
1337
1338  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1339}
1340
1341static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1342                                     ValueDecl *Src, QualType DecompType,
1343                                     const CXXRecordDecl *OrigRD) {
1344  if (S.RequireCompleteType(Src->getLocation(), DecompType,
1345                            diag::err_incomplete_type))
1346    return true;
1347
1348  CXXCastPath BasePath;
1349  DeclAccessPair BasePair =
1350      findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1351  const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1352  if (!RD)
1353    return true;
1354  QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1355                                                 DecompType.getQualifiers());
1356
1357  auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1358    unsigned NumFields =
1359        std::count_if(RD->field_begin(), RD->field_end(),
1360                      [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1361    assert(Bindings.size() != NumFields);
1362    S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1363        << DecompType << (unsigned)Bindings.size() << NumFields
1364        << (NumFields < Bindings.size());
1365    return true;
1366  };
1367
1368  //   all of E's non-static data members shall be [...] well-formed
1369  //   when named as e.name in the context of the structured binding,
1370  //   E shall not have an anonymous union member, ...
1371  unsigned I = 0;
1372  for (auto *FD : RD->fields()) {
1373    if (FD->isUnnamedBitfield())
1374      continue;
1375
1376    if (FD->isAnonymousStructOrUnion()) {
1377      S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1378        << DecompType << FD->getType()->isUnionType();
1379      S.Diag(FD->getLocation(), diag::note_declared_at);
1380      return true;
1381    }
1382
1383    // We have a real field to bind.
1384    if (I >= Bindings.size())
1385      return DiagnoseBadNumberOfBindings();
1386    auto *B = Bindings[I++];
1387    SourceLocation Loc = B->getLocation();
1388
1389    // The field must be accessible in the context of the structured binding.
1390    // We already checked that the base class is accessible.
1391    // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1392    // const_cast here.
1393    S.CheckStructuredBindingMemberAccess(
1394        Loc, const_cast<CXXRecordDecl *>(OrigRD),
1395        DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1396                                     BasePair.getAccess(), FD->getAccess())));
1397
1398    // Initialize the binding to Src.FD.
1399    ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1400    if (E.isInvalid())
1401      return true;
1402    E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1403                            VK_LValue, &BasePath);
1404    if (E.isInvalid())
1405      return true;
1406    E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1407                                  CXXScopeSpec(), FD,
1408                                  DeclAccessPair::make(FD, FD->getAccess()),
1409                                  DeclarationNameInfo(FD->getDeclName(), Loc));
1410    if (E.isInvalid())
1411      return true;
1412
1413    // If the type of the member is T, the referenced type is cv T, where cv is
1414    // the cv-qualification of the decomposition expression.
1415    //
1416    // FIXME: We resolve a defect here: if the field is mutable, we do not add
1417    // 'const' to the type of the field.
1418    Qualifiers Q = DecompType.getQualifiers();
1419    if (FD->isMutable())
1420      Q.removeConst();
1421    B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1422  }
1423
1424  if (I != Bindings.size())
1425    return DiagnoseBadNumberOfBindings();
1426
1427  return false;
1428}
1429
1430void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1431  QualType DecompType = DD->getType();
1432
1433  // If the type of the decomposition is dependent, then so is the type of
1434  // each binding.
1435  if (DecompType->isDependentType()) {
1436    for (auto *B : DD->bindings())
1437      B->setType(Context.DependentTy);
1438    return;
1439  }
1440
1441  DecompType = DecompType.getNonReferenceType();
1442  ArrayRef<BindingDecl*> Bindings = DD->bindings();
1443
1444  // C++1z [dcl.decomp]/2:
1445  //   If E is an array type [...]
1446  // As an extension, we also support decomposition of built-in complex and
1447  // vector types.
1448  if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1449    if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1450      DD->setInvalidDecl();
1451    return;
1452  }
1453  if (auto *VT = DecompType->getAs<VectorType>()) {
1454    if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1455      DD->setInvalidDecl();
1456    return;
1457  }
1458  if (auto *CT = DecompType->getAs<ComplexType>()) {
1459    if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1460      DD->setInvalidDecl();
1461    return;
1462  }
1463
1464  // C++1z [dcl.decomp]/3:
1465  //   if the expression std::tuple_size<E>::value is a well-formed integral
1466  //   constant expression, [...]
1467  llvm::APSInt TupleSize(32);
1468  switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1469  case IsTupleLike::Error:
1470    DD->setInvalidDecl();
1471    return;
1472
1473  case IsTupleLike::TupleLike:
1474    if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1475      DD->setInvalidDecl();
1476    return;
1477
1478  case IsTupleLike::NotTupleLike:
1479    break;
1480  }
1481
1482  // C++1z [dcl.dcl]/8:
1483  //   [E shall be of array or non-union class type]
1484  CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1485  if (!RD || RD->isUnion()) {
1486    Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1487        << DD << !RD << DecompType;
1488    DD->setInvalidDecl();
1489    return;
1490  }
1491
1492  // C++1z [dcl.decomp]/4:
1493  //   all of E's non-static data members shall be [...] direct members of
1494  //   E or of the same unambiguous public base class of E, ...
1495  if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1496    DD->setInvalidDecl();
1497}
1498
1499/// Merge the exception specifications of two variable declarations.
1500///
1501/// This is called when there's a redeclaration of a VarDecl. The function
1502/// checks if the redeclaration might have an exception specification and
1503/// validates compatibility and merges the specs if necessary.
1504void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1505  // Shortcut if exceptions are disabled.
1506  if (!getLangOpts().CXXExceptions)
1507    return;
1508
1509  assert(Context.hasSameType(New->getType(), Old->getType()) &&
1510         "Should only be called if types are otherwise the same.");
1511
1512  QualType NewType = New->getType();
1513  QualType OldType = Old->getType();
1514
1515  // We're only interested in pointers and references to functions, as well
1516  // as pointers to member functions.
1517  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1518    NewType = R->getPointeeType();
1519    OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1520  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1521    NewType = P->getPointeeType();
1522    OldType = OldType->castAs<PointerType>()->getPointeeType();
1523  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1524    NewType = M->getPointeeType();
1525    OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1526  }
1527
1528  if (!NewType->isFunctionProtoType())
1529    return;
1530
1531  // There's lots of special cases for functions. For function pointers, system
1532  // libraries are hopefully not as broken so that we don't need these
1533  // workarounds.
1534  if (CheckEquivalentExceptionSpec(
1535        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1536        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1537    New->setInvalidDecl();
1538  }
1539}
1540
1541/// CheckCXXDefaultArguments - Verify that the default arguments for a
1542/// function declaration are well-formed according to C++
1543/// [dcl.fct.default].
1544void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1545  unsigned NumParams = FD->getNumParams();
1546  unsigned ParamIdx = 0;
1547
1548  // This checking doesn't make sense for explicit specializations; their
1549  // default arguments are determined by the declaration we're specializing,
1550  // not by FD.
1551  if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1552    return;
1553  if (auto *FTD = FD->getDescribedFunctionTemplate())
1554    if (FTD->isMemberSpecialization())
1555      return;
1556
1557  // Find first parameter with a default argument
1558  for (; ParamIdx < NumParams; ++ParamIdx) {
1559    ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1560    if (Param->hasDefaultArg())
1561      break;
1562  }
1563
1564  // C++20 [dcl.fct.default]p4:
1565  //   In a given function declaration, each parameter subsequent to a parameter
1566  //   with a default argument shall have a default argument supplied in this or
1567  //   a previous declaration, unless the parameter was expanded from a
1568  //   parameter pack, or shall be a function parameter pack.
1569  for (; ParamIdx < NumParams; ++ParamIdx) {
1570    ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1571    if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1572        !(CurrentInstantiationScope &&
1573          CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1574      if (Param->isInvalidDecl())
1575        /* We already complained about this parameter. */;
1576      else if (Param->getIdentifier())
1577        Diag(Param->getLocation(),
1578             diag::err_param_default_argument_missing_name)
1579          << Param->getIdentifier();
1580      else
1581        Diag(Param->getLocation(),
1582             diag::err_param_default_argument_missing);
1583    }
1584  }
1585}
1586
1587/// Check that the given type is a literal type. Issue a diagnostic if not,
1588/// if Kind is Diagnose.
1589/// \return \c true if a problem has been found (and optionally diagnosed).
1590template <typename... Ts>
1591static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1592                             SourceLocation Loc, QualType T, unsigned DiagID,
1593                             Ts &&...DiagArgs) {
1594  if (T->isDependentType())
1595    return false;
1596
1597  switch (Kind) {
1598  case Sema::CheckConstexprKind::Diagnose:
1599    return SemaRef.RequireLiteralType(Loc, T, DiagID,
1600                                      std::forward<Ts>(DiagArgs)...);
1601
1602  case Sema::CheckConstexprKind::CheckValid:
1603    return !T->isLiteralType(SemaRef.Context);
1604  }
1605
1606  llvm_unreachable("unknown CheckConstexprKind");
1607}
1608
1609/// Determine whether a destructor cannot be constexpr due to
1610static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1611                                               const CXXDestructorDecl *DD,
1612                                               Sema::CheckConstexprKind Kind) {
1613  auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1614    const CXXRecordDecl *RD =
1615        T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1616    if (!RD || RD->hasConstexprDestructor())
1617      return true;
1618
1619    if (Kind == Sema::CheckConstexprKind::Diagnose) {
1620      SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1621          << DD->getConstexprKind() << !FD
1622          << (FD ? FD->getDeclName() : DeclarationName()) << T;
1623      SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1624          << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1625    }
1626    return false;
1627  };
1628
1629  const CXXRecordDecl *RD = DD->getParent();
1630  for (const CXXBaseSpecifier &B : RD->bases())
1631    if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1632      return false;
1633  for (const FieldDecl *FD : RD->fields())
1634    if (!Check(FD->getLocation(), FD->getType(), FD))
1635      return false;
1636  return true;
1637}
1638
1639/// Check whether a function's parameter types are all literal types. If so,
1640/// return true. If not, produce a suitable diagnostic and return false.
1641static bool CheckConstexprParameterTypes(Sema &SemaRef,
1642                                         const FunctionDecl *FD,
1643                                         Sema::CheckConstexprKind Kind) {
1644  unsigned ArgIndex = 0;
1645  const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1646  for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1647                                              e = FT->param_type_end();
1648       i != e; ++i, ++ArgIndex) {
1649    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1650    SourceLocation ParamLoc = PD->getLocation();
1651    if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1652                         diag::err_constexpr_non_literal_param, ArgIndex + 1,
1653                         PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1654                         FD->isConsteval()))
1655      return false;
1656  }
1657  return true;
1658}
1659
1660/// Check whether a function's return type is a literal type. If so, return
1661/// true. If not, produce a suitable diagnostic and return false.
1662static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1663                                     Sema::CheckConstexprKind Kind) {
1664  if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1665                       diag::err_constexpr_non_literal_return,
1666                       FD->isConsteval()))
1667    return false;
1668  return true;
1669}
1670
1671/// Get diagnostic %select index for tag kind for
1672/// record diagnostic message.
1673/// WARNING: Indexes apply to particular diagnostics only!
1674///
1675/// \returns diagnostic %select index.
1676static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1677  switch (Tag) {
1678  case TTK_Struct: return 0;
1679  case TTK_Interface: return 1;
1680  case TTK_Class:  return 2;
1681  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1682  }
1683}
1684
1685static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1686                                       Stmt *Body,
1687                                       Sema::CheckConstexprKind Kind);
1688
1689// Check whether a function declaration satisfies the requirements of a
1690// constexpr function definition or a constexpr constructor definition. If so,
1691// return true. If not, produce appropriate diagnostics (unless asked not to by
1692// Kind) and return false.
1693//
1694// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1695bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1696                                            CheckConstexprKind Kind) {
1697  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1698  if (MD && MD->isInstance()) {
1699    // C++11 [dcl.constexpr]p4:
1700    //  The definition of a constexpr constructor shall satisfy the following
1701    //  constraints:
1702    //  - the class shall not have any virtual base classes;
1703    //
1704    // FIXME: This only applies to constructors and destructors, not arbitrary
1705    // member functions.
1706    const CXXRecordDecl *RD = MD->getParent();
1707    if (RD->getNumVBases()) {
1708      if (Kind == CheckConstexprKind::CheckValid)
1709        return false;
1710
1711      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1712        << isa<CXXConstructorDecl>(NewFD)
1713        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1714      for (const auto &I : RD->vbases())
1715        Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1716            << I.getSourceRange();
1717      return false;
1718    }
1719  }
1720
1721  if (!isa<CXXConstructorDecl>(NewFD)) {
1722    // C++11 [dcl.constexpr]p3:
1723    //  The definition of a constexpr function shall satisfy the following
1724    //  constraints:
1725    // - it shall not be virtual; (removed in C++20)
1726    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1727    if (Method && Method->isVirtual()) {
1728      if (getLangOpts().CPlusPlus20) {
1729        if (Kind == CheckConstexprKind::Diagnose)
1730          Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1731      } else {
1732        if (Kind == CheckConstexprKind::CheckValid)
1733          return false;
1734
1735        Method = Method->getCanonicalDecl();
1736        Diag(Method->getLocation(), diag::err_constexpr_virtual);
1737
1738        // If it's not obvious why this function is virtual, find an overridden
1739        // function which uses the 'virtual' keyword.
1740        const CXXMethodDecl *WrittenVirtual = Method;
1741        while (!WrittenVirtual->isVirtualAsWritten())
1742          WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1743        if (WrittenVirtual != Method)
1744          Diag(WrittenVirtual->getLocation(),
1745               diag::note_overridden_virtual_function);
1746        return false;
1747      }
1748    }
1749
1750    // - its return type shall be a literal type;
1751    if (!CheckConstexprReturnType(*this, NewFD, Kind))
1752      return false;
1753  }
1754
1755  if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1756    // A destructor can be constexpr only if the defaulted destructor could be;
1757    // we don't need to check the members and bases if we already know they all
1758    // have constexpr destructors.
1759    if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1760      if (Kind == CheckConstexprKind::CheckValid)
1761        return false;
1762      if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1763        return false;
1764    }
1765  }
1766
1767  // - each of its parameter types shall be a literal type;
1768  if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1769    return false;
1770
1771  Stmt *Body = NewFD->getBody();
1772  assert(Body &&
1773         "CheckConstexprFunctionDefinition called on function with no body");
1774  return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1775}
1776
1777/// Check the given declaration statement is legal within a constexpr function
1778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1779///
1780/// \return true if the body is OK (maybe only as an extension), false if we
1781///         have diagnosed a problem.
1782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1783                                   DeclStmt *DS, SourceLocation &Cxx1yLoc,
1784                                   Sema::CheckConstexprKind Kind) {
1785  // C++11 [dcl.constexpr]p3 and p4:
1786  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1787  //  contain only
1788  for (const auto *DclIt : DS->decls()) {
1789    switch (DclIt->getKind()) {
1790    case Decl::StaticAssert:
1791    case Decl::Using:
1792    case Decl::UsingShadow:
1793    case Decl::UsingDirective:
1794    case Decl::UnresolvedUsingTypename:
1795    case Decl::UnresolvedUsingValue:
1796      //   - static_assert-declarations
1797      //   - using-declarations,
1798      //   - using-directives,
1799      continue;
1800
1801    case Decl::Typedef:
1802    case Decl::TypeAlias: {
1803      //   - typedef declarations and alias-declarations that do not define
1804      //     classes or enumerations,
1805      const auto *TN = cast<TypedefNameDecl>(DclIt);
1806      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1807        // Don't allow variably-modified types in constexpr functions.
1808        if (Kind == Sema::CheckConstexprKind::Diagnose) {
1809          TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1810          SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1811            << TL.getSourceRange() << TL.getType()
1812            << isa<CXXConstructorDecl>(Dcl);
1813        }
1814        return false;
1815      }
1816      continue;
1817    }
1818
1819    case Decl::Enum:
1820    case Decl::CXXRecord:
1821      // C++1y allows types to be defined, not just declared.
1822      if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1823        if (Kind == Sema::CheckConstexprKind::Diagnose) {
1824          SemaRef.Diag(DS->getBeginLoc(),
1825                       SemaRef.getLangOpts().CPlusPlus14
1826                           ? diag::warn_cxx11_compat_constexpr_type_definition
1827                           : diag::ext_constexpr_type_definition)
1828              << isa<CXXConstructorDecl>(Dcl);
1829        } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1830          return false;
1831        }
1832      }
1833      continue;
1834
1835    case Decl::EnumConstant:
1836    case Decl::IndirectField:
1837    case Decl::ParmVar:
1838      // These can only appear with other declarations which are banned in
1839      // C++11 and permitted in C++1y, so ignore them.
1840      continue;
1841
1842    case Decl::Var:
1843    case Decl::Decomposition: {
1844      // C++1y [dcl.constexpr]p3 allows anything except:
1845      //   a definition of a variable of non-literal type or of static or
1846      //   thread storage duration or [before C++2a] for which no
1847      //   initialization is performed.
1848      const auto *VD = cast<VarDecl>(DclIt);
1849      if (VD->isThisDeclarationADefinition()) {
1850        if (VD->isStaticLocal()) {
1851          if (Kind == Sema::CheckConstexprKind::Diagnose) {
1852            SemaRef.Diag(VD->getLocation(),
1853                         diag::err_constexpr_local_var_static)
1854              << isa<CXXConstructorDecl>(Dcl)
1855              << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1856          }
1857          return false;
1858        }
1859        if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1860                             diag::err_constexpr_local_var_non_literal_type,
1861                             isa<CXXConstructorDecl>(Dcl)))
1862          return false;
1863        if (!VD->getType()->isDependentType() &&
1864            !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1865          if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866            SemaRef.Diag(
1867                VD->getLocation(),
1868                SemaRef.getLangOpts().CPlusPlus20
1869                    ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1870                    : diag::ext_constexpr_local_var_no_init)
1871                << isa<CXXConstructorDecl>(Dcl);
1872          } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1873            return false;
1874          }
1875          continue;
1876        }
1877      }
1878      if (Kind == Sema::CheckConstexprKind::Diagnose) {
1879        SemaRef.Diag(VD->getLocation(),
1880                     SemaRef.getLangOpts().CPlusPlus14
1881                      ? diag::warn_cxx11_compat_constexpr_local_var
1882                      : diag::ext_constexpr_local_var)
1883          << isa<CXXConstructorDecl>(Dcl);
1884      } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1885        return false;
1886      }
1887      continue;
1888    }
1889
1890    case Decl::NamespaceAlias:
1891    case Decl::Function:
1892      // These are disallowed in C++11 and permitted in C++1y. Allow them
1893      // everywhere as an extension.
1894      if (!Cxx1yLoc.isValid())
1895        Cxx1yLoc = DS->getBeginLoc();
1896      continue;
1897
1898    default:
1899      if (Kind == Sema::CheckConstexprKind::Diagnose) {
1900        SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1901            << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1902      }
1903      return false;
1904    }
1905  }
1906
1907  return true;
1908}
1909
1910/// Check that the given field is initialized within a constexpr constructor.
1911///
1912/// \param Dcl The constexpr constructor being checked.
1913/// \param Field The field being checked. This may be a member of an anonymous
1914///        struct or union nested within the class being checked.
1915/// \param Inits All declarations, including anonymous struct/union members and
1916///        indirect members, for which any initialization was provided.
1917/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1918///        multiple notes for different members to the same error.
1919/// \param Kind Whether we're diagnosing a constructor as written or determining
1920///        whether the formal requirements are satisfied.
1921/// \return \c false if we're checking for validity and the constructor does
1922///         not satisfy the requirements on a constexpr constructor.
1923static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1924                                          const FunctionDecl *Dcl,
1925                                          FieldDecl *Field,
1926                                          llvm::SmallSet<Decl*, 16> &Inits,
1927                                          bool &Diagnosed,
1928                                          Sema::CheckConstexprKind Kind) {
1929  // In C++20 onwards, there's nothing to check for validity.
1930  if (Kind == Sema::CheckConstexprKind::CheckValid &&
1931      SemaRef.getLangOpts().CPlusPlus20)
1932    return true;
1933
1934  if (Field->isInvalidDecl())
1935    return true;
1936
1937  if (Field->isUnnamedBitfield())
1938    return true;
1939
1940  // Anonymous unions with no variant members and empty anonymous structs do not
1941  // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1942  // indirect fields don't need initializing.
1943  if (Field->isAnonymousStructOrUnion() &&
1944      (Field->getType()->isUnionType()
1945           ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1946           : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1947    return true;
1948
1949  if (!Inits.count(Field)) {
1950    if (Kind == Sema::CheckConstexprKind::Diagnose) {
1951      if (!Diagnosed) {
1952        SemaRef.Diag(Dcl->getLocation(),
1953                     SemaRef.getLangOpts().CPlusPlus20
1954                         ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1955                         : diag::ext_constexpr_ctor_missing_init);
1956        Diagnosed = true;
1957      }
1958      SemaRef.Diag(Field->getLocation(),
1959                   diag::note_constexpr_ctor_missing_init);
1960    } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1961      return false;
1962    }
1963  } else if (Field->isAnonymousStructOrUnion()) {
1964    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1965    for (auto *I : RD->fields())
1966      // If an anonymous union contains an anonymous struct of which any member
1967      // is initialized, all members must be initialized.
1968      if (!RD->isUnion() || Inits.count(I))
1969        if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1970                                           Kind))
1971          return false;
1972  }
1973  return true;
1974}
1975
1976/// Check the provided statement is allowed in a constexpr function
1977/// definition.
1978static bool
1979CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1980                           SmallVectorImpl<SourceLocation> &ReturnStmts,
1981                           SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1982                           Sema::CheckConstexprKind Kind) {
1983  // - its function-body shall be [...] a compound-statement that contains only
1984  switch (S->getStmtClass()) {
1985  case Stmt::NullStmtClass:
1986    //   - null statements,
1987    return true;
1988
1989  case Stmt::DeclStmtClass:
1990    //   - static_assert-declarations
1991    //   - using-declarations,
1992    //   - using-directives,
1993    //   - typedef declarations and alias-declarations that do not define
1994    //     classes or enumerations,
1995    if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1996      return false;
1997    return true;
1998
1999  case Stmt::ReturnStmtClass:
2000    //   - and exactly one return statement;
2001    if (isa<CXXConstructorDecl>(Dcl)) {
2002      // C++1y allows return statements in constexpr constructors.
2003      if (!Cxx1yLoc.isValid())
2004        Cxx1yLoc = S->getBeginLoc();
2005      return true;
2006    }
2007
2008    ReturnStmts.push_back(S->getBeginLoc());
2009    return true;
2010
2011  case Stmt::CompoundStmtClass: {
2012    // C++1y allows compound-statements.
2013    if (!Cxx1yLoc.isValid())
2014      Cxx1yLoc = S->getBeginLoc();
2015
2016    CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2017    for (auto *BodyIt : CompStmt->body()) {
2018      if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2019                                      Cxx1yLoc, Cxx2aLoc, Kind))
2020        return false;
2021    }
2022    return true;
2023  }
2024
2025  case Stmt::AttributedStmtClass:
2026    if (!Cxx1yLoc.isValid())
2027      Cxx1yLoc = S->getBeginLoc();
2028    return true;
2029
2030  case Stmt::IfStmtClass: {
2031    // C++1y allows if-statements.
2032    if (!Cxx1yLoc.isValid())
2033      Cxx1yLoc = S->getBeginLoc();
2034
2035    IfStmt *If = cast<IfStmt>(S);
2036    if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2037                                    Cxx1yLoc, Cxx2aLoc, Kind))
2038      return false;
2039    if (If->getElse() &&
2040        !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2041                                    Cxx1yLoc, Cxx2aLoc, Kind))
2042      return false;
2043    return true;
2044  }
2045
2046  case Stmt::WhileStmtClass:
2047  case Stmt::DoStmtClass:
2048  case Stmt::ForStmtClass:
2049  case Stmt::CXXForRangeStmtClass:
2050  case Stmt::ContinueStmtClass:
2051    // C++1y allows all of these. We don't allow them as extensions in C++11,
2052    // because they don't make sense without variable mutation.
2053    if (!SemaRef.getLangOpts().CPlusPlus14)
2054      break;
2055    if (!Cxx1yLoc.isValid())
2056      Cxx1yLoc = S->getBeginLoc();
2057    for (Stmt *SubStmt : S->children())
2058      if (SubStmt &&
2059          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2060                                      Cxx1yLoc, Cxx2aLoc, Kind))
2061        return false;
2062    return true;
2063
2064  case Stmt::SwitchStmtClass:
2065  case Stmt::CaseStmtClass:
2066  case Stmt::DefaultStmtClass:
2067  case Stmt::BreakStmtClass:
2068    // C++1y allows switch-statements, and since they don't need variable
2069    // mutation, we can reasonably allow them in C++11 as an extension.
2070    if (!Cxx1yLoc.isValid())
2071      Cxx1yLoc = S->getBeginLoc();
2072    for (Stmt *SubStmt : S->children())
2073      if (SubStmt &&
2074          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2075                                      Cxx1yLoc, Cxx2aLoc, Kind))
2076        return false;
2077    return true;
2078
2079  case Stmt::GCCAsmStmtClass:
2080  case Stmt::MSAsmStmtClass:
2081    // C++2a allows inline assembly statements.
2082  case Stmt::CXXTryStmtClass:
2083    if (Cxx2aLoc.isInvalid())
2084      Cxx2aLoc = S->getBeginLoc();
2085    for (Stmt *SubStmt : S->children()) {
2086      if (SubStmt &&
2087          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2088                                      Cxx1yLoc, Cxx2aLoc, Kind))
2089        return false;
2090    }
2091    return true;
2092
2093  case Stmt::CXXCatchStmtClass:
2094    // Do not bother checking the language mode (already covered by the
2095    // try block check).
2096    if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2097                                    cast<CXXCatchStmt>(S)->getHandlerBlock(),
2098                                    ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2099      return false;
2100    return true;
2101
2102  default:
2103    if (!isa<Expr>(S))
2104      break;
2105
2106    // C++1y allows expression-statements.
2107    if (!Cxx1yLoc.isValid())
2108      Cxx1yLoc = S->getBeginLoc();
2109    return true;
2110  }
2111
2112  if (Kind == Sema::CheckConstexprKind::Diagnose) {
2113    SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2114        << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2115  }
2116  return false;
2117}
2118
2119/// Check the body for the given constexpr function declaration only contains
2120/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2121///
2122/// \return true if the body is OK, false if we have found or diagnosed a
2123/// problem.
2124static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2125                                       Stmt *Body,
2126                                       Sema::CheckConstexprKind Kind) {
2127  SmallVector<SourceLocation, 4> ReturnStmts;
2128
2129  if (isa<CXXTryStmt>(Body)) {
2130    // C++11 [dcl.constexpr]p3:
2131    //  The definition of a constexpr function shall satisfy the following
2132    //  constraints: [...]
2133    // - its function-body shall be = delete, = default, or a
2134    //   compound-statement
2135    //
2136    // C++11 [dcl.constexpr]p4:
2137    //  In the definition of a constexpr constructor, [...]
2138    // - its function-body shall not be a function-try-block;
2139    //
2140    // This restriction is lifted in C++2a, as long as inner statements also
2141    // apply the general constexpr rules.
2142    switch (Kind) {
2143    case Sema::CheckConstexprKind::CheckValid:
2144      if (!SemaRef.getLangOpts().CPlusPlus20)
2145        return false;
2146      break;
2147
2148    case Sema::CheckConstexprKind::Diagnose:
2149      SemaRef.Diag(Body->getBeginLoc(),
2150           !SemaRef.getLangOpts().CPlusPlus20
2151               ? diag::ext_constexpr_function_try_block_cxx20
2152               : diag::warn_cxx17_compat_constexpr_function_try_block)
2153          << isa<CXXConstructorDecl>(Dcl);
2154      break;
2155    }
2156  }
2157
2158  // - its function-body shall be [...] a compound-statement that contains only
2159  //   [... list of cases ...]
2160  //
2161  // Note that walking the children here is enough to properly check for
2162  // CompoundStmt and CXXTryStmt body.
2163  SourceLocation Cxx1yLoc, Cxx2aLoc;
2164  for (Stmt *SubStmt : Body->children()) {
2165    if (SubStmt &&
2166        !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2167                                    Cxx1yLoc, Cxx2aLoc, Kind))
2168      return false;
2169  }
2170
2171  if (Kind == Sema::CheckConstexprKind::CheckValid) {
2172    // If this is only valid as an extension, report that we don't satisfy the
2173    // constraints of the current language.
2174    if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2175        (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2176      return false;
2177  } else if (Cxx2aLoc.isValid()) {
2178    SemaRef.Diag(Cxx2aLoc,
2179         SemaRef.getLangOpts().CPlusPlus20
2180           ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2181           : diag::ext_constexpr_body_invalid_stmt_cxx20)
2182      << isa<CXXConstructorDecl>(Dcl);
2183  } else if (Cxx1yLoc.isValid()) {
2184    SemaRef.Diag(Cxx1yLoc,
2185         SemaRef.getLangOpts().CPlusPlus14
2186           ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2187           : diag::ext_constexpr_body_invalid_stmt)
2188      << isa<CXXConstructorDecl>(Dcl);
2189  }
2190
2191  if (const CXXConstructorDecl *Constructor
2192        = dyn_cast<CXXConstructorDecl>(Dcl)) {
2193    const CXXRecordDecl *RD = Constructor->getParent();
2194    // DR1359:
2195    // - every non-variant non-static data member and base class sub-object
2196    //   shall be initialized;
2197    // DR1460:
2198    // - if the class is a union having variant members, exactly one of them
2199    //   shall be initialized;
2200    if (RD->isUnion()) {
2201      if (Constructor->getNumCtorInitializers() == 0 &&
2202          RD->hasVariantMembers()) {
2203        if (Kind == Sema::CheckConstexprKind::Diagnose) {
2204          SemaRef.Diag(
2205              Dcl->getLocation(),
2206              SemaRef.getLangOpts().CPlusPlus20
2207                  ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2208                  : diag::ext_constexpr_union_ctor_no_init);
2209        } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2210          return false;
2211        }
2212      }
2213    } else if (!Constructor->isDependentContext() &&
2214               !Constructor->isDelegatingConstructor()) {
2215      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2216
2217      // Skip detailed checking if we have enough initializers, and we would
2218      // allow at most one initializer per member.
2219      bool AnyAnonStructUnionMembers = false;
2220      unsigned Fields = 0;
2221      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2222           E = RD->field_end(); I != E; ++I, ++Fields) {
2223        if (I->isAnonymousStructOrUnion()) {
2224          AnyAnonStructUnionMembers = true;
2225          break;
2226        }
2227      }
2228      // DR1460:
2229      // - if the class is a union-like class, but is not a union, for each of
2230      //   its anonymous union members having variant members, exactly one of
2231      //   them shall be initialized;
2232      if (AnyAnonStructUnionMembers ||
2233          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2234        // Check initialization of non-static data members. Base classes are
2235        // always initialized so do not need to be checked. Dependent bases
2236        // might not have initializers in the member initializer list.
2237        llvm::SmallSet<Decl*, 16> Inits;
2238        for (const auto *I: Constructor->inits()) {
2239          if (FieldDecl *FD = I->getMember())
2240            Inits.insert(FD);
2241          else if (IndirectFieldDecl *ID = I->getIndirectMember())
2242            Inits.insert(ID->chain_begin(), ID->chain_end());
2243        }
2244
2245        bool Diagnosed = false;
2246        for (auto *I : RD->fields())
2247          if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2248                                             Kind))
2249            return false;
2250      }
2251    }
2252  } else {
2253    if (ReturnStmts.empty()) {
2254      // C++1y doesn't require constexpr functions to contain a 'return'
2255      // statement. We still do, unless the return type might be void, because
2256      // otherwise if there's no return statement, the function cannot
2257      // be used in a core constant expression.
2258      bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2259                (Dcl->getReturnType()->isVoidType() ||
2260                 Dcl->getReturnType()->isDependentType());
2261      switch (Kind) {
2262      case Sema::CheckConstexprKind::Diagnose:
2263        SemaRef.Diag(Dcl->getLocation(),
2264                     OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2265                        : diag::err_constexpr_body_no_return)
2266            << Dcl->isConsteval();
2267        if (!OK)
2268          return false;
2269        break;
2270
2271      case Sema::CheckConstexprKind::CheckValid:
2272        // The formal requirements don't include this rule in C++14, even
2273        // though the "must be able to produce a constant expression" rules
2274        // still imply it in some cases.
2275        if (!SemaRef.getLangOpts().CPlusPlus14)
2276          return false;
2277        break;
2278      }
2279    } else if (ReturnStmts.size() > 1) {
2280      switch (Kind) {
2281      case Sema::CheckConstexprKind::Diagnose:
2282        SemaRef.Diag(
2283            ReturnStmts.back(),
2284            SemaRef.getLangOpts().CPlusPlus14
2285                ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2286                : diag::ext_constexpr_body_multiple_return);
2287        for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2288          SemaRef.Diag(ReturnStmts[I],
2289                       diag::note_constexpr_body_previous_return);
2290        break;
2291
2292      case Sema::CheckConstexprKind::CheckValid:
2293        if (!SemaRef.getLangOpts().CPlusPlus14)
2294          return false;
2295        break;
2296      }
2297    }
2298  }
2299
2300  // C++11 [dcl.constexpr]p5:
2301  //   if no function argument values exist such that the function invocation
2302  //   substitution would produce a constant expression, the program is
2303  //   ill-formed; no diagnostic required.
2304  // C++11 [dcl.constexpr]p3:
2305  //   - every constructor call and implicit conversion used in initializing the
2306  //     return value shall be one of those allowed in a constant expression.
2307  // C++11 [dcl.constexpr]p4:
2308  //   - every constructor involved in initializing non-static data members and
2309  //     base class sub-objects shall be a constexpr constructor.
2310  //
2311  // Note that this rule is distinct from the "requirements for a constexpr
2312  // function", so is not checked in CheckValid mode.
2313  SmallVector<PartialDiagnosticAt, 8> Diags;
2314  if (Kind == Sema::CheckConstexprKind::Diagnose &&
2315      !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2316    SemaRef.Diag(Dcl->getLocation(),
2317                 diag::ext_constexpr_function_never_constant_expr)
2318        << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2319    for (size_t I = 0, N = Diags.size(); I != N; ++I)
2320      SemaRef.Diag(Diags[I].first, Diags[I].second);
2321    // Don't return false here: we allow this for compatibility in
2322    // system headers.
2323  }
2324
2325  return true;
2326}
2327
2328/// Get the class that is directly named by the current context. This is the
2329/// class for which an unqualified-id in this scope could name a constructor
2330/// or destructor.
2331///
2332/// If the scope specifier denotes a class, this will be that class.
2333/// If the scope specifier is empty, this will be the class whose
2334/// member-specification we are currently within. Otherwise, there
2335/// is no such class.
2336CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2337  assert(getLangOpts().CPlusPlus && "No class names in C!");
2338
2339  if (SS && SS->isInvalid())
2340    return nullptr;
2341
2342  if (SS && SS->isNotEmpty()) {
2343    DeclContext *DC = computeDeclContext(*SS, true);
2344    return dyn_cast_or_null<CXXRecordDecl>(DC);
2345  }
2346
2347  return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2348}
2349
2350/// isCurrentClassName - Determine whether the identifier II is the
2351/// name of the class type currently being defined. In the case of
2352/// nested classes, this will only return true if II is the name of
2353/// the innermost class.
2354bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2355                              const CXXScopeSpec *SS) {
2356  CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2357  return CurDecl && &II == CurDecl->getIdentifier();
2358}
2359
2360/// Determine whether the identifier II is a typo for the name of
2361/// the class type currently being defined. If so, update it to the identifier
2362/// that should have been used.
2363bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2364  assert(getLangOpts().CPlusPlus && "No class names in C!");
2365
2366  if (!getLangOpts().SpellChecking)
2367    return false;
2368
2369  CXXRecordDecl *CurDecl;
2370  if (SS && SS->isSet() && !SS->isInvalid()) {
2371    DeclContext *DC = computeDeclContext(*SS, true);
2372    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2373  } else
2374    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2375
2376  if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2377      3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2378          < II->getLength()) {
2379    II = CurDecl->getIdentifier();
2380    return true;
2381  }
2382
2383  return false;
2384}
2385
2386/// Determine whether the given class is a base class of the given
2387/// class, including looking at dependent bases.
2388static bool findCircularInheritance(const CXXRecordDecl *Class,
2389                                    const CXXRecordDecl *Current) {
2390  SmallVector<const CXXRecordDecl*, 8> Queue;
2391
2392  Class = Class->getCanonicalDecl();
2393  while (true) {
2394    for (const auto &I : Current->bases()) {
2395      CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2396      if (!Base)
2397        continue;
2398
2399      Base = Base->getDefinition();
2400      if (!Base)
2401        continue;
2402
2403      if (Base->getCanonicalDecl() == Class)
2404        return true;
2405
2406      Queue.push_back(Base);
2407    }
2408
2409    if (Queue.empty())
2410      return false;
2411
2412    Current = Queue.pop_back_val();
2413  }
2414
2415  return false;
2416}
2417
2418/// Check the validity of a C++ base class specifier.
2419///
2420/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2421/// and returns NULL otherwise.
2422CXXBaseSpecifier *
2423Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2424                         SourceRange SpecifierRange,
2425                         bool Virtual, AccessSpecifier Access,
2426                         TypeSourceInfo *TInfo,
2427                         SourceLocation EllipsisLoc) {
2428  QualType BaseType = TInfo->getType();
2429  if (BaseType->containsErrors()) {
2430    // Already emitted a diagnostic when parsing the error type.
2431    return nullptr;
2432  }
2433  // C++ [class.union]p1:
2434  //   A union shall not have base classes.
2435  if (Class->isUnion()) {
2436    Diag(Class->getLocation(), diag::err_base_clause_on_union)
2437      << SpecifierRange;
2438    return nullptr;
2439  }
2440
2441  if (EllipsisLoc.isValid() &&
2442      !TInfo->getType()->containsUnexpandedParameterPack()) {
2443    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2444      << TInfo->getTypeLoc().getSourceRange();
2445    EllipsisLoc = SourceLocation();
2446  }
2447
2448  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2449
2450  if (BaseType->isDependentType()) {
2451    // Make sure that we don't have circular inheritance among our dependent
2452    // bases. For non-dependent bases, the check for completeness below handles
2453    // this.
2454    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2455      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2456          ((BaseDecl = BaseDecl->getDefinition()) &&
2457           findCircularInheritance(Class, BaseDecl))) {
2458        Diag(BaseLoc, diag::err_circular_inheritance)
2459          << BaseType << Context.getTypeDeclType(Class);
2460
2461        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2462          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2463            << BaseType;
2464
2465        return nullptr;
2466      }
2467    }
2468
2469    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2470                                          Class->getTagKind() == TTK_Class,
2471                                          Access, TInfo, EllipsisLoc);
2472  }
2473
2474  // Base specifiers must be record types.
2475  if (!BaseType->isRecordType()) {
2476    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2477    return nullptr;
2478  }
2479
2480  // C++ [class.union]p1:
2481  //   A union shall not be used as a base class.
2482  if (BaseType->isUnionType()) {
2483    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2484    return nullptr;
2485  }
2486
2487  // For the MS ABI, propagate DLL attributes to base class templates.
2488  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2489    if (Attr *ClassAttr = getDLLAttr(Class)) {
2490      if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2491              BaseType->getAsCXXRecordDecl())) {
2492        propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2493                                            BaseLoc);
2494      }
2495    }
2496  }
2497
2498  // C++ [class.derived]p2:
2499  //   The class-name in a base-specifier shall not be an incompletely
2500  //   defined class.
2501  if (RequireCompleteType(BaseLoc, BaseType,
2502                          diag::err_incomplete_base_class, SpecifierRange)) {
2503    Class->setInvalidDecl();
2504    return nullptr;
2505  }
2506
2507  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2508  RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2509  assert(BaseDecl && "Record type has no declaration");
2510  BaseDecl = BaseDecl->getDefinition();
2511  assert(BaseDecl && "Base type is not incomplete, but has no definition");
2512  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2513  assert(CXXBaseDecl && "Base type is not a C++ type");
2514
2515  // Microsoft docs say:
2516  // "If a base-class has a code_seg attribute, derived classes must have the
2517  // same attribute."
2518  const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2519  const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2520  if ((DerivedCSA || BaseCSA) &&
2521      (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2522    Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2523    Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2524      << CXXBaseDecl;
2525    return nullptr;
2526  }
2527
2528  // A class which contains a flexible array member is not suitable for use as a
2529  // base class:
2530  //   - If the layout determines that a base comes before another base,
2531  //     the flexible array member would index into the subsequent base.
2532  //   - If the layout determines that base comes before the derived class,
2533  //     the flexible array member would index into the derived class.
2534  if (CXXBaseDecl->hasFlexibleArrayMember()) {
2535    Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2536      << CXXBaseDecl->getDeclName();
2537    return nullptr;
2538  }
2539
2540  // C++ [class]p3:
2541  //   If a class is marked final and it appears as a base-type-specifier in
2542  //   base-clause, the program is ill-formed.
2543  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2544    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2545      << CXXBaseDecl->getDeclName()
2546      << FA->isSpelledAsSealed();
2547    Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2548        << CXXBaseDecl->getDeclName() << FA->getRange();
2549    return nullptr;
2550  }
2551
2552  if (BaseDecl->isInvalidDecl())
2553    Class->setInvalidDecl();
2554
2555  // Create the base specifier.
2556  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2557                                        Class->getTagKind() == TTK_Class,
2558                                        Access, TInfo, EllipsisLoc);
2559}
2560
2561/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2562/// one entry in the base class list of a class specifier, for
2563/// example:
2564///    class foo : public bar, virtual private baz {
2565/// 'public bar' and 'virtual private baz' are each base-specifiers.
2566BaseResult
2567Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2568                         ParsedAttributes &Attributes,
2569                         bool Virtual, AccessSpecifier Access,
2570                         ParsedType basetype, SourceLocation BaseLoc,
2571                         SourceLocation EllipsisLoc) {
2572  if (!classdecl)
2573    return true;
2574
2575  AdjustDeclIfTemplate(classdecl);
2576  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2577  if (!Class)
2578    return true;
2579
2580  // We haven't yet attached the base specifiers.
2581  Class->setIsParsingBaseSpecifiers();
2582
2583  // We do not support any C++11 attributes on base-specifiers yet.
2584  // Diagnose any attributes we see.
2585  for (const ParsedAttr &AL : Attributes) {
2586    if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2587      continue;
2588    Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2589                          ? (unsigned)diag::warn_unknown_attribute_ignored
2590                          : (unsigned)diag::err_base_specifier_attribute)
2591        << AL;
2592  }
2593
2594  TypeSourceInfo *TInfo = nullptr;
2595  GetTypeFromParser(basetype, &TInfo);
2596
2597  if (EllipsisLoc.isInvalid() &&
2598      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2599                                      UPPC_BaseType))
2600    return true;
2601
2602  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2603                                                      Virtual, Access, TInfo,
2604                                                      EllipsisLoc))
2605    return BaseSpec;
2606  else
2607    Class->setInvalidDecl();
2608
2609  return true;
2610}
2611
2612/// Use small set to collect indirect bases.  As this is only used
2613/// locally, there's no need to abstract the small size parameter.
2614typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2615
2616/// Recursively add the bases of Type.  Don't add Type itself.
2617static void
2618NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2619                  const QualType &Type)
2620{
2621  // Even though the incoming type is a base, it might not be
2622  // a class -- it could be a template parm, for instance.
2623  if (auto Rec = Type->getAs<RecordType>()) {
2624    auto Decl = Rec->getAsCXXRecordDecl();
2625
2626    // Iterate over its bases.
2627    for (const auto &BaseSpec : Decl->bases()) {
2628      QualType Base = Context.getCanonicalType(BaseSpec.getType())
2629        .getUnqualifiedType();
2630      if (Set.insert(Base).second)
2631        // If we've not already seen it, recurse.
2632        NoteIndirectBases(Context, Set, Base);
2633    }
2634  }
2635}
2636
2637/// Performs the actual work of attaching the given base class
2638/// specifiers to a C++ class.
2639bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2640                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2641 if (Bases.empty())
2642    return false;
2643
2644  // Used to keep track of which base types we have already seen, so
2645  // that we can properly diagnose redundant direct base types. Note
2646  // that the key is always the unqualified canonical type of the base
2647  // class.
2648  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2649
2650  // Used to track indirect bases so we can see if a direct base is
2651  // ambiguous.
2652  IndirectBaseSet IndirectBaseTypes;
2653
2654  // Copy non-redundant base specifiers into permanent storage.
2655  unsigned NumGoodBases = 0;
2656  bool Invalid = false;
2657  for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2658    QualType NewBaseType
2659      = Context.getCanonicalType(Bases[idx]->getType());
2660    NewBaseType = NewBaseType.getLocalUnqualifiedType();
2661
2662    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2663    if (KnownBase) {
2664      // C++ [class.mi]p3:
2665      //   A class shall not be specified as a direct base class of a
2666      //   derived class more than once.
2667      Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2668          << KnownBase->getType() << Bases[idx]->getSourceRange();
2669
2670      // Delete the duplicate base class specifier; we're going to
2671      // overwrite its pointer later.
2672      Context.Deallocate(Bases[idx]);
2673
2674      Invalid = true;
2675    } else {
2676      // Okay, add this new base class.
2677      KnownBase = Bases[idx];
2678      Bases[NumGoodBases++] = Bases[idx];
2679
2680      // Note this base's direct & indirect bases, if there could be ambiguity.
2681      if (Bases.size() > 1)
2682        NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2683
2684      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2685        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2686        if (Class->isInterface() &&
2687              (!RD->isInterfaceLike() ||
2688               KnownBase->getAccessSpecifier() != AS_public)) {
2689          // The Microsoft extension __interface does not permit bases that
2690          // are not themselves public interfaces.
2691          Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2692              << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2693              << RD->getSourceRange();
2694          Invalid = true;
2695        }
2696        if (RD->hasAttr<WeakAttr>())
2697          Class->addAttr(WeakAttr::CreateImplicit(Context));
2698      }
2699    }
2700  }
2701
2702  // Attach the remaining base class specifiers to the derived class.
2703  Class->setBases(Bases.data(), NumGoodBases);
2704
2705  // Check that the only base classes that are duplicate are virtual.
2706  for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2707    // Check whether this direct base is inaccessible due to ambiguity.
2708    QualType BaseType = Bases[idx]->getType();
2709
2710    // Skip all dependent types in templates being used as base specifiers.
2711    // Checks below assume that the base specifier is a CXXRecord.
2712    if (BaseType->isDependentType())
2713      continue;
2714
2715    CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2716      .getUnqualifiedType();
2717
2718    if (IndirectBaseTypes.count(CanonicalBase)) {
2719      CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2720                         /*DetectVirtual=*/true);
2721      bool found
2722        = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2723      assert(found);
2724      (void)found;
2725
2726      if (Paths.isAmbiguous(CanonicalBase))
2727        Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2728            << BaseType << getAmbiguousPathsDisplayString(Paths)
2729            << Bases[idx]->getSourceRange();
2730      else
2731        assert(Bases[idx]->isVirtual());
2732    }
2733
2734    // Delete the base class specifier, since its data has been copied
2735    // into the CXXRecordDecl.
2736    Context.Deallocate(Bases[idx]);
2737  }
2738
2739  return Invalid;
2740}
2741
2742/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2743/// class, after checking whether there are any duplicate base
2744/// classes.
2745void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2746                               MutableArrayRef<CXXBaseSpecifier *> Bases) {
2747  if (!ClassDecl || Bases.empty())
2748    return;
2749
2750  AdjustDeclIfTemplate(ClassDecl);
2751  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2752}
2753
2754/// Determine whether the type \p Derived is a C++ class that is
2755/// derived from the type \p Base.
2756bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2757  if (!getLangOpts().CPlusPlus)
2758    return false;
2759
2760  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2761  if (!DerivedRD)
2762    return false;
2763
2764  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2765  if (!BaseRD)
2766    return false;
2767
2768  // If either the base or the derived type is invalid, don't try to
2769  // check whether one is derived from the other.
2770  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2771    return false;
2772
2773  // FIXME: In a modules build, do we need the entire path to be visible for us
2774  // to be able to use the inheritance relationship?
2775  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2776    return false;
2777
2778  return DerivedRD->isDerivedFrom(BaseRD);
2779}
2780
2781/// Determine whether the type \p Derived is a C++ class that is
2782/// derived from the type \p Base.
2783bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2784                         CXXBasePaths &Paths) {
2785  if (!getLangOpts().CPlusPlus)
2786    return false;
2787
2788  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2789  if (!DerivedRD)
2790    return false;
2791
2792  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2793  if (!BaseRD)
2794    return false;
2795
2796  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2797    return false;
2798
2799  return DerivedRD->isDerivedFrom(BaseRD, Paths);
2800}
2801
2802static void BuildBasePathArray(const CXXBasePath &Path,
2803                               CXXCastPath &BasePathArray) {
2804  // We first go backward and check if we have a virtual base.
2805  // FIXME: It would be better if CXXBasePath had the base specifier for
2806  // the nearest virtual base.
2807  unsigned Start = 0;
2808  for (unsigned I = Path.size(); I != 0; --I) {
2809    if (Path[I - 1].Base->isVirtual()) {
2810      Start = I - 1;
2811      break;
2812    }
2813  }
2814
2815  // Now add all bases.
2816  for (unsigned I = Start, E = Path.size(); I != E; ++I)
2817    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2818}
2819
2820
2821void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2822                              CXXCastPath &BasePathArray) {
2823  assert(BasePathArray.empty() && "Base path array must be empty!");
2824  assert(Paths.isRecordingPaths() && "Must record paths!");
2825  return ::BuildBasePathArray(Paths.front(), BasePathArray);
2826}
2827/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2828/// conversion (where Derived and Base are class types) is
2829/// well-formed, meaning that the conversion is unambiguous (and
2830/// that all of the base classes are accessible). Returns true
2831/// and emits a diagnostic if the code is ill-formed, returns false
2832/// otherwise. Loc is the location where this routine should point to
2833/// if there is an error, and Range is the source range to highlight
2834/// if there is an error.
2835///
2836/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2837/// diagnostic for the respective type of error will be suppressed, but the
2838/// check for ill-formed code will still be performed.
2839bool
2840Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2841                                   unsigned InaccessibleBaseID,
2842                                   unsigned AmbiguousBaseConvID,
2843                                   SourceLocation Loc, SourceRange Range,
2844                                   DeclarationName Name,
2845                                   CXXCastPath *BasePath,
2846                                   bool IgnoreAccess) {
2847  // First, determine whether the path from Derived to Base is
2848  // ambiguous. This is slightly more expensive than checking whether
2849  // the Derived to Base conversion exists, because here we need to
2850  // explore multiple paths to determine if there is an ambiguity.
2851  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2852                     /*DetectVirtual=*/false);
2853  bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2854  if (!DerivationOkay)
2855    return true;
2856
2857  const CXXBasePath *Path = nullptr;
2858  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2859    Path = &Paths.front();
2860
2861  // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2862  // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2863  // user to access such bases.
2864  if (!Path && getLangOpts().MSVCCompat) {
2865    for (const CXXBasePath &PossiblePath : Paths) {
2866      if (PossiblePath.size() == 1) {
2867        Path = &PossiblePath;
2868        if (AmbiguousBaseConvID)
2869          Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2870              << Base << Derived << Range;
2871        break;
2872      }
2873    }
2874  }
2875
2876  if (Path) {
2877    if (!IgnoreAccess) {
2878      // Check that the base class can be accessed.
2879      switch (
2880          CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2881      case AR_inaccessible:
2882        return true;
2883      case AR_accessible:
2884      case AR_dependent:
2885      case AR_delayed:
2886        break;
2887      }
2888    }
2889
2890    // Build a base path if necessary.
2891    if (BasePath)
2892      ::BuildBasePathArray(*Path, *BasePath);
2893    return false;
2894  }
2895
2896  if (AmbiguousBaseConvID) {
2897    // We know that the derived-to-base conversion is ambiguous, and
2898    // we're going to produce a diagnostic. Perform the derived-to-base
2899    // search just one more time to compute all of the possible paths so
2900    // that we can print them out. This is more expensive than any of
2901    // the previous derived-to-base checks we've done, but at this point
2902    // performance isn't as much of an issue.
2903    Paths.clear();
2904    Paths.setRecordingPaths(true);
2905    bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2906    assert(StillOkay && "Can only be used with a derived-to-base conversion");
2907    (void)StillOkay;
2908
2909    // Build up a textual representation of the ambiguous paths, e.g.,
2910    // D -> B -> A, that will be used to illustrate the ambiguous
2911    // conversions in the diagnostic. We only print one of the paths
2912    // to each base class subobject.
2913    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2914
2915    Diag(Loc, AmbiguousBaseConvID)
2916    << Derived << Base << PathDisplayStr << Range << Name;
2917  }
2918  return true;
2919}
2920
2921bool
2922Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2923                                   SourceLocation Loc, SourceRange Range,
2924                                   CXXCastPath *BasePath,
2925                                   bool IgnoreAccess) {
2926  return CheckDerivedToBaseConversion(
2927      Derived, Base, diag::err_upcast_to_inaccessible_base,
2928      diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2929      BasePath, IgnoreAccess);
2930}
2931
2932
2933/// Builds a string representing ambiguous paths from a
2934/// specific derived class to different subobjects of the same base
2935/// class.
2936///
2937/// This function builds a string that can be used in error messages
2938/// to show the different paths that one can take through the
2939/// inheritance hierarchy to go from the derived class to different
2940/// subobjects of a base class. The result looks something like this:
2941/// @code
2942/// struct D -> struct B -> struct A
2943/// struct D -> struct C -> struct A
2944/// @endcode
2945std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2946  std::string PathDisplayStr;
2947  std::set<unsigned> DisplayedPaths;
2948  for (CXXBasePaths::paths_iterator Path = Paths.begin();
2949       Path != Paths.end(); ++Path) {
2950    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2951      // We haven't displayed a path to this particular base
2952      // class subobject yet.
2953      PathDisplayStr += "\n    ";
2954      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2955      for (CXXBasePath::const_iterator Element = Path->begin();
2956           Element != Path->end(); ++Element)
2957        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2958    }
2959  }
2960
2961  return PathDisplayStr;
2962}
2963
2964//===----------------------------------------------------------------------===//
2965// C++ class member Handling
2966//===----------------------------------------------------------------------===//
2967
2968/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2969bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2970                                SourceLocation ColonLoc,
2971                                const ParsedAttributesView &Attrs) {
2972  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2973  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2974                                                  ASLoc, ColonLoc);
2975  CurContext->addHiddenDecl(ASDecl);
2976  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2977}
2978
2979/// CheckOverrideControl - Check C++11 override control semantics.
2980void Sema::CheckOverrideControl(NamedDecl *D) {
2981  if (D->isInvalidDecl())
2982    return;
2983
2984  // We only care about "override" and "final" declarations.
2985  if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2986    return;
2987
2988  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2989
2990  // We can't check dependent instance methods.
2991  if (MD && MD->isInstance() &&
2992      (MD->getParent()->hasAnyDependentBases() ||
2993       MD->getType()->isDependentType()))
2994    return;
2995
2996  if (MD && !MD->isVirtual()) {
2997    // If we have a non-virtual method, check if if hides a virtual method.
2998    // (In that case, it's most likely the method has the wrong type.)
2999    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3000    FindHiddenVirtualMethods(MD, OverloadedMethods);
3001
3002    if (!OverloadedMethods.empty()) {
3003      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3004        Diag(OA->getLocation(),
3005             diag::override_keyword_hides_virtual_member_function)
3006          << "override" << (OverloadedMethods.size() > 1);
3007      } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3008        Diag(FA->getLocation(),
3009             diag::override_keyword_hides_virtual_member_function)
3010          << (FA->isSpelledAsSealed() ? "sealed" : "final")
3011          << (OverloadedMethods.size() > 1);
3012      }
3013      NoteHiddenVirtualMethods(MD, OverloadedMethods);
3014      MD->setInvalidDecl();
3015      return;
3016    }
3017    // Fall through into the general case diagnostic.
3018    // FIXME: We might want to attempt typo correction here.
3019  }
3020
3021  if (!MD || !MD->isVirtual()) {
3022    if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3023      Diag(OA->getLocation(),
3024           diag::override_keyword_only_allowed_on_virtual_member_functions)
3025        << "override" << FixItHint::CreateRemoval(OA->getLocation());
3026      D->dropAttr<OverrideAttr>();
3027    }
3028    if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3029      Diag(FA->getLocation(),
3030           diag::override_keyword_only_allowed_on_virtual_member_functions)
3031        << (FA->isSpelledAsSealed() ? "sealed" : "final")
3032        << FixItHint::CreateRemoval(FA->getLocation());
3033      D->dropAttr<FinalAttr>();
3034    }
3035    return;
3036  }
3037
3038  // C++11 [class.virtual]p5:
3039  //   If a function is marked with the virt-specifier override and
3040  //   does not override a member function of a base class, the program is
3041  //   ill-formed.
3042  bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3043  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3044    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3045      << MD->getDeclName();
3046}
3047
3048void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3049  if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3050    return;
3051  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3052  if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3053    return;
3054
3055  SourceLocation Loc = MD->getLocation();
3056  SourceLocation SpellingLoc = Loc;
3057  if (getSourceManager().isMacroArgExpansion(Loc))
3058    SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3059  SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3060  if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3061      return;
3062
3063  if (MD->size_overridden_methods() > 0) {
3064    auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3065      unsigned DiagID =
3066          Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3067              ? DiagInconsistent
3068              : DiagSuggest;
3069      Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3070      const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3071      Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3072    };
3073    if (isa<CXXDestructorDecl>(MD))
3074      EmitDiag(
3075          diag::warn_inconsistent_destructor_marked_not_override_overriding,
3076          diag::warn_suggest_destructor_marked_not_override_overriding);
3077    else
3078      EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3079               diag::warn_suggest_function_marked_not_override_overriding);
3080  }
3081}
3082
3083/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3084/// function overrides a virtual member function marked 'final', according to
3085/// C++11 [class.virtual]p4.
3086bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3087                                                  const CXXMethodDecl *Old) {
3088  FinalAttr *FA = Old->getAttr<FinalAttr>();
3089  if (!FA)
3090    return false;
3091
3092  Diag(New->getLocation(), diag::err_final_function_overridden)
3093    << New->getDeclName()
3094    << FA->isSpelledAsSealed();
3095  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3096  return true;
3097}
3098
3099static bool InitializationHasSideEffects(const FieldDecl &FD) {
3100  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3101  // FIXME: Destruction of ObjC lifetime types has side-effects.
3102  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3103    return !RD->isCompleteDefinition() ||
3104           !RD->hasTrivialDefaultConstructor() ||
3105           !RD->hasTrivialDestructor();
3106  return false;
3107}
3108
3109static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3110  ParsedAttributesView::const_iterator Itr =
3111      llvm::find_if(list, [](const ParsedAttr &AL) {
3112        return AL.isDeclspecPropertyAttribute();
3113      });
3114  if (Itr != list.end())
3115    return &*Itr;
3116  return nullptr;
3117}
3118
3119// Check if there is a field shadowing.
3120void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3121                                      DeclarationName FieldName,
3122                                      const CXXRecordDecl *RD,
3123                                      bool DeclIsField) {
3124  if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3125    return;
3126
3127  // To record a shadowed field in a base
3128  std::map<CXXRecordDecl*, NamedDecl*> Bases;
3129  auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3130                           CXXBasePath &Path) {
3131    const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3132    // Record an ambiguous path directly
3133    if (Bases.find(Base) != Bases.end())
3134      return true;
3135    for (const auto Field : Base->lookup(FieldName)) {
3136      if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3137          Field->getAccess() != AS_private) {
3138        assert(Field->getAccess() != AS_none);
3139        assert(Bases.find(Base) == Bases.end());
3140        Bases[Base] = Field;
3141        return true;
3142      }
3143    }
3144    return false;
3145  };
3146
3147  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3148                     /*DetectVirtual=*/true);
3149  if (!RD->lookupInBases(FieldShadowed, Paths))
3150    return;
3151
3152  for (const auto &P : Paths) {
3153    auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3154    auto It = Bases.find(Base);
3155    // Skip duplicated bases
3156    if (It == Bases.end())
3157      continue;
3158    auto BaseField = It->second;
3159    assert(BaseField->getAccess() != AS_private);
3160    if (AS_none !=
3161        CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3162      Diag(Loc, diag::warn_shadow_field)
3163        << FieldName << RD << Base << DeclIsField;
3164      Diag(BaseField->getLocation(), diag::note_shadow_field);
3165      Bases.erase(It);
3166    }
3167  }
3168}
3169
3170/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3171/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3172/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3173/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3174/// present (but parsing it has been deferred).
3175NamedDecl *
3176Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3177                               MultiTemplateParamsArg TemplateParameterLists,
3178                               Expr *BW, const VirtSpecifiers &VS,
3179                               InClassInitStyle InitStyle) {
3180  const DeclSpec &DS = D.getDeclSpec();
3181  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3182  DeclarationName Name = NameInfo.getName();
3183  SourceLocation Loc = NameInfo.getLoc();
3184
3185  // For anonymous bitfields, the location should point to the type.
3186  if (Loc.isInvalid())
3187    Loc = D.getBeginLoc();
3188
3189  Expr *BitWidth = static_cast<Expr*>(BW);
3190
3191  assert(isa<CXXRecordDecl>(CurContext));
3192  assert(!DS.isFriendSpecified());
3193
3194  bool isFunc = D.isDeclarationOfFunction();
3195  const ParsedAttr *MSPropertyAttr =
3196      getMSPropertyAttr(D.getDeclSpec().getAttributes());
3197
3198  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3199    // The Microsoft extension __interface only permits public member functions
3200    // and prohibits constructors, destructors, operators, non-public member
3201    // functions, static methods and data members.
3202    unsigned InvalidDecl;
3203    bool ShowDeclName = true;
3204    if (!isFunc &&
3205        (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3206      InvalidDecl = 0;
3207    else if (!isFunc)
3208      InvalidDecl = 1;
3209    else if (AS != AS_public)
3210      InvalidDecl = 2;
3211    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3212      InvalidDecl = 3;
3213    else switch (Name.getNameKind()) {
3214      case DeclarationName::CXXConstructorName:
3215        InvalidDecl = 4;
3216        ShowDeclName = false;
3217        break;
3218
3219      case DeclarationName::CXXDestructorName:
3220        InvalidDecl = 5;
3221        ShowDeclName = false;
3222        break;
3223
3224      case DeclarationName::CXXOperatorName:
3225      case DeclarationName::CXXConversionFunctionName:
3226        InvalidDecl = 6;
3227        break;
3228
3229      default:
3230        InvalidDecl = 0;
3231        break;
3232    }
3233
3234    if (InvalidDecl) {
3235      if (ShowDeclName)
3236        Diag(Loc, diag::err_invalid_member_in_interface)
3237          << (InvalidDecl-1) << Name;
3238      else
3239        Diag(Loc, diag::err_invalid_member_in_interface)
3240          << (InvalidDecl-1) << "";
3241      return nullptr;
3242    }
3243  }
3244
3245  // C++ 9.2p6: A member shall not be declared to have automatic storage
3246  // duration (auto, register) or with the extern storage-class-specifier.
3247  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3248  // data members and cannot be applied to names declared const or static,
3249  // and cannot be applied to reference members.
3250  switch (DS.getStorageClassSpec()) {
3251  case DeclSpec::SCS_unspecified:
3252  case DeclSpec::SCS_typedef:
3253  case DeclSpec::SCS_static:
3254    break;
3255  case DeclSpec::SCS_mutable:
3256    if (isFunc) {
3257      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3258
3259      // FIXME: It would be nicer if the keyword was ignored only for this
3260      // declarator. Otherwise we could get follow-up errors.
3261      D.getMutableDeclSpec().ClearStorageClassSpecs();
3262    }
3263    break;
3264  default:
3265    Diag(DS.getStorageClassSpecLoc(),
3266         diag::err_storageclass_invalid_for_member);
3267    D.getMutableDeclSpec().ClearStorageClassSpecs();
3268    break;
3269  }
3270
3271  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3272                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3273                      !isFunc);
3274
3275  if (DS.hasConstexprSpecifier() && isInstField) {
3276    SemaDiagnosticBuilder B =
3277        Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3278    SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3279    if (InitStyle == ICIS_NoInit) {
3280      B << 0 << 0;
3281      if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3282        B << FixItHint::CreateRemoval(ConstexprLoc);
3283      else {
3284        B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3285        D.getMutableDeclSpec().ClearConstexprSpec();
3286        const char *PrevSpec;
3287        unsigned DiagID;
3288        bool Failed = D.getMutableDeclSpec().SetTypeQual(
3289            DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3290        (void)Failed;
3291        assert(!Failed && "Making a constexpr member const shouldn't fail");
3292      }
3293    } else {
3294      B << 1;
3295      const char *PrevSpec;
3296      unsigned DiagID;
3297      if (D.getMutableDeclSpec().SetStorageClassSpec(
3298          *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3299          Context.getPrintingPolicy())) {
3300        assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3301               "This is the only DeclSpec that should fail to be applied");
3302        B << 1;
3303      } else {
3304        B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3305        isInstField = false;
3306      }
3307    }
3308  }
3309
3310  NamedDecl *Member;
3311  if (isInstField) {
3312    CXXScopeSpec &SS = D.getCXXScopeSpec();
3313
3314    // Data members must have identifiers for names.
3315    if (!Name.isIdentifier()) {
3316      Diag(Loc, diag::err_bad_variable_name)
3317        << Name;
3318      return nullptr;
3319    }
3320
3321    IdentifierInfo *II = Name.getAsIdentifierInfo();
3322
3323    // Member field could not be with "template" keyword.
3324    // So TemplateParameterLists should be empty in this case.
3325    if (TemplateParameterLists.size()) {
3326      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3327      if (TemplateParams->size()) {
3328        // There is no such thing as a member field template.
3329        Diag(D.getIdentifierLoc(), diag::err_template_member)
3330            << II
3331            << SourceRange(TemplateParams->getTemplateLoc(),
3332                TemplateParams->getRAngleLoc());
3333      } else {
3334        // There is an extraneous 'template<>' for this member.
3335        Diag(TemplateParams->getTemplateLoc(),
3336            diag::err_template_member_noparams)
3337            << II
3338            << SourceRange(TemplateParams->getTemplateLoc(),
3339                TemplateParams->getRAngleLoc());
3340      }
3341      return nullptr;
3342    }
3343
3344    if (SS.isSet() && !SS.isInvalid()) {
3345      // The user provided a superfluous scope specifier inside a class
3346      // definition:
3347      //
3348      // class X {
3349      //   int X::member;
3350      // };
3351      if (DeclContext *DC = computeDeclContext(SS, false))
3352        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3353                                     D.getName().getKind() ==
3354                                         UnqualifiedIdKind::IK_TemplateId);
3355      else
3356        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3357          << Name << SS.getRange();
3358
3359      SS.clear();
3360    }
3361
3362    if (MSPropertyAttr) {
3363      Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3364                                BitWidth, InitStyle, AS, *MSPropertyAttr);
3365      if (!Member)
3366        return nullptr;
3367      isInstField = false;
3368    } else {
3369      Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3370                                BitWidth, InitStyle, AS);
3371      if (!Member)
3372        return nullptr;
3373    }
3374
3375    CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3376  } else {
3377    Member = HandleDeclarator(S, D, TemplateParameterLists);
3378    if (!Member)
3379      return nullptr;
3380
3381    // Non-instance-fields can't have a bitfield.
3382    if (BitWidth) {
3383      if (Member->isInvalidDecl()) {
3384        // don't emit another diagnostic.
3385      } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3386        // C++ 9.6p3: A bit-field shall not be a static member.
3387        // "static member 'A' cannot be a bit-field"
3388        Diag(Loc, diag::err_static_not_bitfield)
3389          << Name << BitWidth->getSourceRange();
3390      } else if (isa<TypedefDecl>(Member)) {
3391        // "typedef member 'x' cannot be a bit-field"
3392        Diag(Loc, diag::err_typedef_not_bitfield)
3393          << Name << BitWidth->getSourceRange();
3394      } else {
3395        // A function typedef ("typedef int f(); f a;").
3396        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3397        Diag(Loc, diag::err_not_integral_type_bitfield)
3398          << Name << cast<ValueDecl>(Member)->getType()
3399          << BitWidth->getSourceRange();
3400      }
3401
3402      BitWidth = nullptr;
3403      Member->setInvalidDecl();
3404    }
3405
3406    NamedDecl *NonTemplateMember = Member;
3407    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3408      NonTemplateMember = FunTmpl->getTemplatedDecl();
3409    else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3410      NonTemplateMember = VarTmpl->getTemplatedDecl();
3411
3412    Member->setAccess(AS);
3413
3414    // If we have declared a member function template or static data member
3415    // template, set the access of the templated declaration as well.
3416    if (NonTemplateMember != Member)
3417      NonTemplateMember->setAccess(AS);
3418
3419    // C++ [temp.deduct.guide]p3:
3420    //   A deduction guide [...] for a member class template [shall be
3421    //   declared] with the same access [as the template].
3422    if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3423      auto *TD = DG->getDeducedTemplate();
3424      // Access specifiers are only meaningful if both the template and the
3425      // deduction guide are from the same scope.
3426      if (AS != TD->getAccess() &&
3427          TD->getDeclContext()->getRedeclContext()->Equals(
3428              DG->getDeclContext()->getRedeclContext())) {
3429        Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3430        Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3431            << TD->getAccess();
3432        const AccessSpecDecl *LastAccessSpec = nullptr;
3433        for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3434          if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3435            LastAccessSpec = AccessSpec;
3436        }
3437        assert(LastAccessSpec && "differing access with no access specifier");
3438        Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3439            << AS;
3440      }
3441    }
3442  }
3443
3444  if (VS.isOverrideSpecified())
3445    Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3446                                         AttributeCommonInfo::AS_Keyword));
3447  if (VS.isFinalSpecified())
3448    Member->addAttr(FinalAttr::Create(
3449        Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3450        static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3451
3452  if (VS.getLastLocation().isValid()) {
3453    // Update the end location of a method that has a virt-specifiers.
3454    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3455      MD->setRangeEnd(VS.getLastLocation());
3456  }
3457
3458  CheckOverrideControl(Member);
3459
3460  assert((Name || isInstField) && "No identifier for non-field ?");
3461
3462  if (isInstField) {
3463    FieldDecl *FD = cast<FieldDecl>(Member);
3464    FieldCollector->Add(FD);
3465
3466    if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3467      // Remember all explicit private FieldDecls that have a name, no side
3468      // effects and are not part of a dependent type declaration.
3469      if (!FD->isImplicit() && FD->getDeclName() &&
3470          FD->getAccess() == AS_private &&
3471          !FD->hasAttr<UnusedAttr>() &&
3472          !FD->getParent()->isDependentContext() &&
3473          !InitializationHasSideEffects(*FD))
3474        UnusedPrivateFields.insert(FD);
3475    }
3476  }
3477
3478  return Member;
3479}
3480
3481namespace {
3482  class UninitializedFieldVisitor
3483      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3484    Sema &S;
3485    // List of Decls to generate a warning on.  Also remove Decls that become
3486    // initialized.
3487    llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3488    // List of base classes of the record.  Classes are removed after their
3489    // initializers.
3490    llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3491    // Vector of decls to be removed from the Decl set prior to visiting the
3492    // nodes.  These Decls may have been initialized in the prior initializer.
3493    llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3494    // If non-null, add a note to the warning pointing back to the constructor.
3495    const CXXConstructorDecl *Constructor;
3496    // Variables to hold state when processing an initializer list.  When
3497    // InitList is true, special case initialization of FieldDecls matching
3498    // InitListFieldDecl.
3499    bool InitList;
3500    FieldDecl *InitListFieldDecl;
3501    llvm::SmallVector<unsigned, 4> InitFieldIndex;
3502
3503  public:
3504    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3505    UninitializedFieldVisitor(Sema &S,
3506                              llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3507                              llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3508      : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3509        Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3510
3511    // Returns true if the use of ME is not an uninitialized use.
3512    bool IsInitListMemberExprInitialized(MemberExpr *ME,
3513                                         bool CheckReferenceOnly) {
3514      llvm::SmallVector<FieldDecl*, 4> Fields;
3515      bool ReferenceField = false;
3516      while (ME) {
3517        FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3518        if (!FD)
3519          return false;
3520        Fields.push_back(FD);
3521        if (FD->getType()->isReferenceType())
3522          ReferenceField = true;
3523        ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3524      }
3525
3526      // Binding a reference to an uninitialized field is not an
3527      // uninitialized use.
3528      if (CheckReferenceOnly && !ReferenceField)
3529        return true;
3530
3531      llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3532      // Discard the first field since it is the field decl that is being
3533      // initialized.
3534      for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3535        UsedFieldIndex.push_back((*I)->getFieldIndex());
3536      }
3537
3538      for (auto UsedIter = UsedFieldIndex.begin(),
3539                UsedEnd = UsedFieldIndex.end(),
3540                OrigIter = InitFieldIndex.begin(),
3541                OrigEnd = InitFieldIndex.end();
3542           UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3543        if (*UsedIter < *OrigIter)
3544          return true;
3545        if (*UsedIter > *OrigIter)
3546          break;
3547      }
3548
3549      return false;
3550    }
3551
3552    void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3553                          bool AddressOf) {
3554      if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3555        return;
3556
3557      // FieldME is the inner-most MemberExpr that is not an anonymous struct
3558      // or union.
3559      MemberExpr *FieldME = ME;
3560
3561      bool AllPODFields = FieldME->getType().isPODType(S.Context);
3562
3563      Expr *Base = ME;
3564      while (MemberExpr *SubME =
3565                 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3566
3567        if (isa<VarDecl>(SubME->getMemberDecl()))
3568          return;
3569
3570        if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3571          if (!FD->isAnonymousStructOrUnion())
3572            FieldME = SubME;
3573
3574        if (!FieldME->getType().isPODType(S.Context))
3575          AllPODFields = false;
3576
3577        Base = SubME->getBase();
3578      }
3579
3580      if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3581        return;
3582
3583      if (AddressOf && AllPODFields)
3584        return;
3585
3586      ValueDecl* FoundVD = FieldME->getMemberDecl();
3587
3588      if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3589        while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3590          BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3591        }
3592
3593        if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3594          QualType T = BaseCast->getType();
3595          if (T->isPointerType() &&
3596              BaseClasses.count(T->getPointeeType())) {
3597            S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3598                << T->getPointeeType() << FoundVD;
3599          }
3600        }
3601      }
3602
3603      if (!Decls.count(FoundVD))
3604        return;
3605
3606      const bool IsReference = FoundVD->getType()->isReferenceType();
3607
3608      if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3609        // Special checking for initializer lists.
3610        if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3611          return;
3612        }
3613      } else {
3614        // Prevent double warnings on use of unbounded references.
3615        if (CheckReferenceOnly && !IsReference)
3616          return;
3617      }
3618
3619      unsigned diag = IsReference
3620          ? diag::warn_reference_field_is_uninit
3621          : diag::warn_field_is_uninit;
3622      S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3623      if (Constructor)
3624        S.Diag(Constructor->getLocation(),
3625               diag::note_uninit_in_this_constructor)
3626          << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3627
3628    }
3629
3630    void HandleValue(Expr *E, bool AddressOf) {
3631      E = E->IgnoreParens();
3632
3633      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3634        HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3635                         AddressOf /*AddressOf*/);
3636        return;
3637      }
3638
3639      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3640        Visit(CO->getCond());
3641        HandleValue(CO->getTrueExpr(), AddressOf);
3642        HandleValue(CO->getFalseExpr(), AddressOf);
3643        return;
3644      }
3645
3646      if (BinaryConditionalOperator *BCO =
3647              dyn_cast<BinaryConditionalOperator>(E)) {
3648        Visit(BCO->getCond());
3649        HandleValue(BCO->getFalseExpr(), AddressOf);
3650        return;
3651      }
3652
3653      if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3654        HandleValue(OVE->getSourceExpr(), AddressOf);
3655        return;
3656      }
3657
3658      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3659        switch (BO->getOpcode()) {
3660        default:
3661          break;
3662        case(BO_PtrMemD):
3663        case(BO_PtrMemI):
3664          HandleValue(BO->getLHS(), AddressOf);
3665          Visit(BO->getRHS());
3666          return;
3667        case(BO_Comma):
3668          Visit(BO->getLHS());
3669          HandleValue(BO->getRHS(), AddressOf);
3670          return;
3671        }
3672      }
3673
3674      Visit(E);
3675    }
3676
3677    void CheckInitListExpr(InitListExpr *ILE) {
3678      InitFieldIndex.push_back(0);
3679      for (auto Child : ILE->children()) {
3680        if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3681          CheckInitListExpr(SubList);
3682        } else {
3683          Visit(Child);
3684        }
3685        ++InitFieldIndex.back();
3686      }
3687      InitFieldIndex.pop_back();
3688    }
3689
3690    void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3691                          FieldDecl *Field, const Type *BaseClass) {
3692      // Remove Decls that may have been initialized in the previous
3693      // initializer.
3694      for (ValueDecl* VD : DeclsToRemove)
3695        Decls.erase(VD);
3696      DeclsToRemove.clear();
3697
3698      Constructor = FieldConstructor;
3699      InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3700
3701      if (ILE && Field) {
3702        InitList = true;
3703        InitListFieldDecl = Field;
3704        InitFieldIndex.clear();
3705        CheckInitListExpr(ILE);
3706      } else {
3707        InitList = false;
3708        Visit(E);
3709      }
3710
3711      if (Field)
3712        Decls.erase(Field);
3713      if (BaseClass)
3714        BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3715    }
3716
3717    void VisitMemberExpr(MemberExpr *ME) {
3718      // All uses of unbounded reference fields will warn.
3719      HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3720    }
3721
3722    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3723      if (E->getCastKind() == CK_LValueToRValue) {
3724        HandleValue(E->getSubExpr(), false /*AddressOf*/);
3725        return;
3726      }
3727
3728      Inherited::VisitImplicitCastExpr(E);
3729    }
3730
3731    void VisitCXXConstructExpr(CXXConstructExpr *E) {
3732      if (E->getConstructor()->isCopyConstructor()) {
3733        Expr *ArgExpr = E->getArg(0);
3734        if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3735          if (ILE->getNumInits() == 1)
3736            ArgExpr = ILE->getInit(0);
3737        if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3738          if (ICE->getCastKind() == CK_NoOp)
3739            ArgExpr = ICE->getSubExpr();
3740        HandleValue(ArgExpr, false /*AddressOf*/);
3741        return;
3742      }
3743      Inherited::VisitCXXConstructExpr(E);
3744    }
3745
3746    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3747      Expr *Callee = E->getCallee();
3748      if (isa<MemberExpr>(Callee)) {
3749        HandleValue(Callee, false /*AddressOf*/);
3750        for (auto Arg : E->arguments())
3751          Visit(Arg);
3752        return;
3753      }
3754
3755      Inherited::VisitCXXMemberCallExpr(E);
3756    }
3757
3758    void VisitCallExpr(CallExpr *E) {
3759      // Treat std::move as a use.
3760      if (E->isCallToStdMove()) {
3761        HandleValue(E->getArg(0), /*AddressOf=*/false);
3762        return;
3763      }
3764
3765      Inherited::VisitCallExpr(E);
3766    }
3767
3768    void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3769      Expr *Callee = E->getCallee();
3770
3771      if (isa<UnresolvedLookupExpr>(Callee))
3772        return Inherited::VisitCXXOperatorCallExpr(E);
3773
3774      Visit(Callee);
3775      for (auto Arg : E->arguments())
3776        HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3777    }
3778
3779    void VisitBinaryOperator(BinaryOperator *E) {
3780      // If a field assignment is detected, remove the field from the
3781      // uninitiailized field set.
3782      if (E->getOpcode() == BO_Assign)
3783        if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3784          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3785            if (!FD->getType()->isReferenceType())
3786              DeclsToRemove.push_back(FD);
3787
3788      if (E->isCompoundAssignmentOp()) {
3789        HandleValue(E->getLHS(), false /*AddressOf*/);
3790        Visit(E->getRHS());
3791        return;
3792      }
3793
3794      Inherited::VisitBinaryOperator(E);
3795    }
3796
3797    void VisitUnaryOperator(UnaryOperator *E) {
3798      if (E->isIncrementDecrementOp()) {
3799        HandleValue(E->getSubExpr(), false /*AddressOf*/);
3800        return;
3801      }
3802      if (E->getOpcode() == UO_AddrOf) {
3803        if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3804          HandleValue(ME->getBase(), true /*AddressOf*/);
3805          return;
3806        }
3807      }
3808
3809      Inherited::VisitUnaryOperator(E);
3810    }
3811  };
3812
3813  // Diagnose value-uses of fields to initialize themselves, e.g.
3814  //   foo(foo)
3815  // where foo is not also a parameter to the constructor.
3816  // Also diagnose across field uninitialized use such as
3817  //   x(y), y(x)
3818  // TODO: implement -Wuninitialized and fold this into that framework.
3819  static void DiagnoseUninitializedFields(
3820      Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3821
3822    if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3823                                           Constructor->getLocation())) {
3824      return;
3825    }
3826
3827    if (Constructor->isInvalidDecl())
3828      return;
3829
3830    const CXXRecordDecl *RD = Constructor->getParent();
3831
3832    if (RD->isDependentContext())
3833      return;
3834
3835    // Holds fields that are uninitialized.
3836    llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3837
3838    // At the beginning, all fields are uninitialized.
3839    for (auto *I : RD->decls()) {
3840      if (auto *FD = dyn_cast<FieldDecl>(I)) {
3841        UninitializedFields.insert(FD);
3842      } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3843        UninitializedFields.insert(IFD->getAnonField());
3844      }
3845    }
3846
3847    llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3848    for (auto I : RD->bases())
3849      UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3850
3851    if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3852      return;
3853
3854    UninitializedFieldVisitor UninitializedChecker(SemaRef,
3855                                                   UninitializedFields,
3856                                                   UninitializedBaseClasses);
3857
3858    for (const auto *FieldInit : Constructor->inits()) {
3859      if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3860        break;
3861
3862      Expr *InitExpr = FieldInit->getInit();
3863      if (!InitExpr)
3864        continue;
3865
3866      if (CXXDefaultInitExpr *Default =
3867              dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3868        InitExpr = Default->getExpr();
3869        if (!InitExpr)
3870          continue;
3871        // In class initializers will point to the constructor.
3872        UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3873                                              FieldInit->getAnyMember(),
3874                                              FieldInit->getBaseClass());
3875      } else {
3876        UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3877                                              FieldInit->getAnyMember(),
3878                                              FieldInit->getBaseClass());
3879      }
3880    }
3881  }
3882} // namespace
3883
3884/// Enter a new C++ default initializer scope. After calling this, the
3885/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3886/// parsing or instantiating the initializer failed.
3887void Sema::ActOnStartCXXInClassMemberInitializer() {
3888  // Create a synthetic function scope to represent the call to the constructor
3889  // that notionally surrounds a use of this initializer.
3890  PushFunctionScope();
3891}
3892
3893void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3894  if (!D.isFunctionDeclarator())
3895    return;
3896  auto &FTI = D.getFunctionTypeInfo();
3897  if (!FTI.Params)
3898    return;
3899  for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3900                                                          FTI.NumParams)) {
3901    auto *ParamDecl = cast<NamedDecl>(Param.Param);
3902    if (ParamDecl->getDeclName())
3903      PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3904  }
3905}
3906
3907ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3908  if (ConstraintExpr.isInvalid())
3909    return ExprError();
3910  return CorrectDelayedTyposInExpr(ConstraintExpr);
3911}
3912
3913/// This is invoked after parsing an in-class initializer for a
3914/// non-static C++ class member, and after instantiating an in-class initializer
3915/// in a class template. Such actions are deferred until the class is complete.
3916void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3917                                                  SourceLocation InitLoc,
3918                                                  Expr *InitExpr) {
3919  // Pop the notional constructor scope we created earlier.
3920  PopFunctionScopeInfo(nullptr, D);
3921
3922  FieldDecl *FD = dyn_cast<FieldDecl>(D);
3923  assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3924         "must set init style when field is created");
3925
3926  if (!InitExpr) {
3927    D->setInvalidDecl();
3928    if (FD)
3929      FD->removeInClassInitializer();
3930    return;
3931  }
3932
3933  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3934    FD->setInvalidDecl();
3935    FD->removeInClassInitializer();
3936    return;
3937  }
3938
3939  ExprResult Init = InitExpr;
3940  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3941    InitializedEntity Entity =
3942        InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3943    InitializationKind Kind =
3944        FD->getInClassInitStyle() == ICIS_ListInit
3945            ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3946                                                   InitExpr->getBeginLoc(),
3947                                                   InitExpr->getEndLoc())
3948            : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3949    InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3950    Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3951    if (Init.isInvalid()) {
3952      FD->setInvalidDecl();
3953      return;
3954    }
3955  }
3956
3957  // C++11 [class.base.init]p7:
3958  //   The initialization of each base and member constitutes a
3959  //   full-expression.
3960  Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3961  if (Init.isInvalid()) {
3962    FD->setInvalidDecl();
3963    return;
3964  }
3965
3966  InitExpr = Init.get();
3967
3968  FD->setInClassInitializer(InitExpr);
3969}
3970
3971/// Find the direct and/or virtual base specifiers that
3972/// correspond to the given base type, for use in base initialization
3973/// within a constructor.
3974static bool FindBaseInitializer(Sema &SemaRef,
3975                                CXXRecordDecl *ClassDecl,
3976                                QualType BaseType,
3977                                const CXXBaseSpecifier *&DirectBaseSpec,
3978                                const CXXBaseSpecifier *&VirtualBaseSpec) {
3979  // First, check for a direct base class.
3980  DirectBaseSpec = nullptr;
3981  for (const auto &Base : ClassDecl->bases()) {
3982    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3983      // We found a direct base of this type. That's what we're
3984      // initializing.
3985      DirectBaseSpec = &Base;
3986      break;
3987    }
3988  }
3989
3990  // Check for a virtual base class.
3991  // FIXME: We might be able to short-circuit this if we know in advance that
3992  // there are no virtual bases.
3993  VirtualBaseSpec = nullptr;
3994  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3995    // We haven't found a base yet; search the class hierarchy for a
3996    // virtual base class.
3997    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3998                       /*DetectVirtual=*/false);
3999    if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4000                              SemaRef.Context.getTypeDeclType(ClassDecl),
4001                              BaseType, Paths)) {
4002      for (CXXBasePaths::paths_iterator Path = Paths.begin();
4003           Path != Paths.end(); ++Path) {
4004        if (Path->back().Base->isVirtual()) {
4005          VirtualBaseSpec = Path->back().Base;
4006          break;
4007        }
4008      }
4009    }
4010  }
4011
4012  return DirectBaseSpec || VirtualBaseSpec;
4013}
4014
4015/// Handle a C++ member initializer using braced-init-list syntax.
4016MemInitResult
4017Sema::ActOnMemInitializer(Decl *ConstructorD,
4018                          Scope *S,
4019                          CXXScopeSpec &SS,
4020                          IdentifierInfo *MemberOrBase,
4021                          ParsedType TemplateTypeTy,
4022                          const DeclSpec &DS,
4023                          SourceLocation IdLoc,
4024                          Expr *InitList,
4025                          SourceLocation EllipsisLoc) {
4026  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4027                             DS, IdLoc, InitList,
4028                             EllipsisLoc);
4029}
4030
4031/// Handle a C++ member initializer using parentheses syntax.
4032MemInitResult
4033Sema::ActOnMemInitializer(Decl *ConstructorD,
4034                          Scope *S,
4035                          CXXScopeSpec &SS,
4036                          IdentifierInfo *MemberOrBase,
4037                          ParsedType TemplateTypeTy,
4038                          const DeclSpec &DS,
4039                          SourceLocation IdLoc,
4040                          SourceLocation LParenLoc,
4041                          ArrayRef<Expr *> Args,
4042                          SourceLocation RParenLoc,
4043                          SourceLocation EllipsisLoc) {
4044  Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4045  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4046                             DS, IdLoc, List, EllipsisLoc);
4047}
4048
4049namespace {
4050
4051// Callback to only accept typo corrections that can be a valid C++ member
4052// intializer: either a non-static field member or a base class.
4053class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4054public:
4055  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4056      : ClassDecl(ClassDecl) {}
4057
4058  bool ValidateCandidate(const TypoCorrection &candidate) override {
4059    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4060      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4061        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4062      return isa<TypeDecl>(ND);
4063    }
4064    return false;
4065  }
4066
4067  std::unique_ptr<CorrectionCandidateCallback> clone() override {
4068    return std::make_unique<MemInitializerValidatorCCC>(*this);
4069  }
4070
4071private:
4072  CXXRecordDecl *ClassDecl;
4073};
4074
4075}
4076
4077ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4078                                             CXXScopeSpec &SS,
4079                                             ParsedType TemplateTypeTy,
4080                                             IdentifierInfo *MemberOrBase) {
4081  if (SS.getScopeRep() || TemplateTypeTy)
4082    return nullptr;
4083  DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4084  if (Result.empty())
4085    return nullptr;
4086  ValueDecl *Member;
4087  if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4088      (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4089    return Member;
4090  return nullptr;
4091}
4092
4093/// Handle a C++ member initializer.
4094MemInitResult
4095Sema::BuildMemInitializer(Decl *ConstructorD,
4096                          Scope *S,
4097                          CXXScopeSpec &SS,
4098                          IdentifierInfo *MemberOrBase,
4099                          ParsedType TemplateTypeTy,
4100                          const DeclSpec &DS,
4101                          SourceLocation IdLoc,
4102                          Expr *Init,
4103                          SourceLocation EllipsisLoc) {
4104  ExprResult Res = CorrectDelayedTyposInExpr(Init);
4105  if (!Res.isUsable())
4106    return true;
4107  Init = Res.get();
4108
4109  if (!ConstructorD)
4110    return true;
4111
4112  AdjustDeclIfTemplate(ConstructorD);
4113
4114  CXXConstructorDecl *Constructor
4115    = dyn_cast<CXXConstructorDecl>(ConstructorD);
4116  if (!Constructor) {
4117    // The user wrote a constructor initializer on a function that is
4118    // not a C++ constructor. Ignore the error for now, because we may
4119    // have more member initializers coming; we'll diagnose it just
4120    // once in ActOnMemInitializers.
4121    return true;
4122  }
4123
4124  CXXRecordDecl *ClassDecl = Constructor->getParent();
4125
4126  // C++ [class.base.init]p2:
4127  //   Names in a mem-initializer-id are looked up in the scope of the
4128  //   constructor's class and, if not found in that scope, are looked
4129  //   up in the scope containing the constructor's definition.
4130  //   [Note: if the constructor's class contains a member with the
4131  //   same name as a direct or virtual base class of the class, a
4132  //   mem-initializer-id naming the member or base class and composed
4133  //   of a single identifier refers to the class member. A
4134  //   mem-initializer-id for the hidden base class may be specified
4135  //   using a qualified name. ]
4136
4137  // Look for a member, first.
4138  if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4139          ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4140    if (EllipsisLoc.isValid())
4141      Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4142          << MemberOrBase
4143          << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4144
4145    return BuildMemberInitializer(Member, Init, IdLoc);
4146  }
4147  // It didn't name a member, so see if it names a class.
4148  QualType BaseType;
4149  TypeSourceInfo *TInfo = nullptr;
4150
4151  if (TemplateTypeTy) {
4152    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4153    if (BaseType.isNull())
4154      return true;
4155  } else if (DS.getTypeSpecType() == TST_decltype) {
4156    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4157  } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4158    Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4159    return true;
4160  } else {
4161    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4162    LookupParsedName(R, S, &SS);
4163
4164    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4165    if (!TyD) {
4166      if (R.isAmbiguous()) return true;
4167
4168      // We don't want access-control diagnostics here.
4169      R.suppressDiagnostics();
4170
4171      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4172        bool NotUnknownSpecialization = false;
4173        DeclContext *DC = computeDeclContext(SS, false);
4174        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4175          NotUnknownSpecialization = !Record->hasAnyDependentBases();
4176
4177        if (!NotUnknownSpecialization) {
4178          // When the scope specifier can refer to a member of an unknown
4179          // specialization, we take it as a type name.
4180          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4181                                       SS.getWithLocInContext(Context),
4182                                       *MemberOrBase, IdLoc);
4183          if (BaseType.isNull())
4184            return true;
4185
4186          TInfo = Context.CreateTypeSourceInfo(BaseType);
4187          DependentNameTypeLoc TL =
4188              TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4189          if (!TL.isNull()) {
4190            TL.setNameLoc(IdLoc);
4191            TL.setElaboratedKeywordLoc(SourceLocation());
4192            TL.setQualifierLoc(SS.getWithLocInContext(Context));
4193          }
4194
4195          R.clear();
4196          R.setLookupName(MemberOrBase);
4197        }
4198      }
4199
4200      // If no results were found, try to correct typos.
4201      TypoCorrection Corr;
4202      MemInitializerValidatorCCC CCC(ClassDecl);
4203      if (R.empty() && BaseType.isNull() &&
4204          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4205                              CCC, CTK_ErrorRecovery, ClassDecl))) {
4206        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4207          // We have found a non-static data member with a similar
4208          // name to what was typed; complain and initialize that
4209          // member.
4210          diagnoseTypo(Corr,
4211                       PDiag(diag::err_mem_init_not_member_or_class_suggest)
4212                         << MemberOrBase << true);
4213          return BuildMemberInitializer(Member, Init, IdLoc);
4214        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4215          const CXXBaseSpecifier *DirectBaseSpec;
4216          const CXXBaseSpecifier *VirtualBaseSpec;
4217          if (FindBaseInitializer(*this, ClassDecl,
4218                                  Context.getTypeDeclType(Type),
4219                                  DirectBaseSpec, VirtualBaseSpec)) {
4220            // We have found a direct or virtual base class with a
4221            // similar name to what was typed; complain and initialize
4222            // that base class.
4223            diagnoseTypo(Corr,
4224                         PDiag(diag::err_mem_init_not_member_or_class_suggest)
4225                           << MemberOrBase << false,
4226                         PDiag() /*Suppress note, we provide our own.*/);
4227
4228            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4229                                                              : VirtualBaseSpec;
4230            Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4231                << BaseSpec->getType() << BaseSpec->getSourceRange();
4232
4233            TyD = Type;
4234          }
4235        }
4236      }
4237
4238      if (!TyD && BaseType.isNull()) {
4239        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4240          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4241        return true;
4242      }
4243    }
4244
4245    if (BaseType.isNull()) {
4246      BaseType = Context.getTypeDeclType(TyD);
4247      MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4248      if (SS.isSet()) {
4249        BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4250                                             BaseType);
4251        TInfo = Context.CreateTypeSourceInfo(BaseType);
4252        ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4253        TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4254        TL.setElaboratedKeywordLoc(SourceLocation());
4255        TL.setQualifierLoc(SS.getWithLocInContext(Context));
4256      }
4257    }
4258  }
4259
4260  if (!TInfo)
4261    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4262
4263  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4264}
4265
4266MemInitResult
4267Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4268                             SourceLocation IdLoc) {
4269  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4270  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4271  assert((DirectMember || IndirectMember) &&
4272         "Member must be a FieldDecl or IndirectFieldDecl");
4273
4274  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4275    return true;
4276
4277  if (Member->isInvalidDecl())
4278    return true;
4279
4280  MultiExprArg Args;
4281  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4282    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4283  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4284    Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4285  } else {
4286    // Template instantiation doesn't reconstruct ParenListExprs for us.
4287    Args = Init;
4288  }
4289
4290  SourceRange InitRange = Init->getSourceRange();
4291
4292  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4293    // Can't check initialization for a member of dependent type or when
4294    // any of the arguments are type-dependent expressions.
4295    DiscardCleanupsInEvaluationContext();
4296  } else {
4297    bool InitList = false;
4298    if (isa<InitListExpr>(Init)) {
4299      InitList = true;
4300      Args = Init;
4301    }
4302
4303    // Initialize the member.
4304    InitializedEntity MemberEntity =
4305      DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4306                   : InitializedEntity::InitializeMember(IndirectMember,
4307                                                         nullptr);
4308    InitializationKind Kind =
4309        InitList ? InitializationKind::CreateDirectList(
4310                       IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4311                 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4312                                                    InitRange.getEnd());
4313
4314    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4315    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4316                                            nullptr);
4317    if (MemberInit.isInvalid())
4318      return true;
4319
4320    // C++11 [class.base.init]p7:
4321    //   The initialization of each base and member constitutes a
4322    //   full-expression.
4323    MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4324                                     /*DiscardedValue*/ false);
4325    if (MemberInit.isInvalid())
4326      return true;
4327
4328    Init = MemberInit.get();
4329  }
4330
4331  if (DirectMember) {
4332    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4333                                            InitRange.getBegin(), Init,
4334                                            InitRange.getEnd());
4335  } else {
4336    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4337                                            InitRange.getBegin(), Init,
4338                                            InitRange.getEnd());
4339  }
4340}
4341
4342MemInitResult
4343Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4344                                 CXXRecordDecl *ClassDecl) {
4345  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4346  if (!LangOpts.CPlusPlus11)
4347    return Diag(NameLoc, diag::err_delegating_ctor)
4348      << TInfo->getTypeLoc().getLocalSourceRange();
4349  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4350
4351  bool InitList = true;
4352  MultiExprArg Args = Init;
4353  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4354    InitList = false;
4355    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4356  }
4357
4358  SourceRange InitRange = Init->getSourceRange();
4359  // Initialize the object.
4360  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4361                                     QualType(ClassDecl->getTypeForDecl(), 0));
4362  InitializationKind Kind =
4363      InitList ? InitializationKind::CreateDirectList(
4364                     NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4365               : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4366                                                  InitRange.getEnd());
4367  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4368  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4369                                              Args, nullptr);
4370  if (DelegationInit.isInvalid())
4371    return true;
4372
4373  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4374         "Delegating constructor with no target?");
4375
4376  // C++11 [class.base.init]p7:
4377  //   The initialization of each base and member constitutes a
4378  //   full-expression.
4379  DelegationInit = ActOnFinishFullExpr(
4380      DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4381  if (DelegationInit.isInvalid())
4382    return true;
4383
4384  // If we are in a dependent context, template instantiation will
4385  // perform this type-checking again. Just save the arguments that we
4386  // received in a ParenListExpr.
4387  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4388  // of the information that we have about the base
4389  // initializer. However, deconstructing the ASTs is a dicey process,
4390  // and this approach is far more likely to get the corner cases right.
4391  if (CurContext->isDependentContext())
4392    DelegationInit = Init;
4393
4394  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4395                                          DelegationInit.getAs<Expr>(),
4396                                          InitRange.getEnd());
4397}
4398
4399MemInitResult
4400Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4401                           Expr *Init, CXXRecordDecl *ClassDecl,
4402                           SourceLocation EllipsisLoc) {
4403  SourceLocation BaseLoc
4404    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4405
4406  if (!BaseType->isDependentType() && !BaseType->isRecordType())
4407    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4408             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4409
4410  // C++ [class.base.init]p2:
4411  //   [...] Unless the mem-initializer-id names a nonstatic data
4412  //   member of the constructor's class or a direct or virtual base
4413  //   of that class, the mem-initializer is ill-formed. A
4414  //   mem-initializer-list can initialize a base class using any
4415  //   name that denotes that base class type.
4416  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4417
4418  SourceRange InitRange = Init->getSourceRange();
4419  if (EllipsisLoc.isValid()) {
4420    // This is a pack expansion.
4421    if (!BaseType->containsUnexpandedParameterPack())  {
4422      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4423        << SourceRange(BaseLoc, InitRange.getEnd());
4424
4425      EllipsisLoc = SourceLocation();
4426    }
4427  } else {
4428    // Check for any unexpanded parameter packs.
4429    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4430      return true;
4431
4432    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4433      return true;
4434  }
4435
4436  // Check for direct and virtual base classes.
4437  const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4438  const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4439  if (!Dependent) {
4440    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4441                                       BaseType))
4442      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4443
4444    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4445                        VirtualBaseSpec);
4446
4447    // C++ [base.class.init]p2:
4448    // Unless the mem-initializer-id names a nonstatic data member of the
4449    // constructor's class or a direct or virtual base of that class, the
4450    // mem-initializer is ill-formed.
4451    if (!DirectBaseSpec && !VirtualBaseSpec) {
4452      // If the class has any dependent bases, then it's possible that
4453      // one of those types will resolve to the same type as
4454      // BaseType. Therefore, just treat this as a dependent base
4455      // class initialization.  FIXME: Should we try to check the
4456      // initialization anyway? It seems odd.
4457      if (ClassDecl->hasAnyDependentBases())
4458        Dependent = true;
4459      else
4460        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4461          << BaseType << Context.getTypeDeclType(ClassDecl)
4462          << BaseTInfo->getTypeLoc().getLocalSourceRange();
4463    }
4464  }
4465
4466  if (Dependent) {
4467    DiscardCleanupsInEvaluationContext();
4468
4469    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4470                                            /*IsVirtual=*/false,
4471                                            InitRange.getBegin(), Init,
4472                                            InitRange.getEnd(), EllipsisLoc);
4473  }
4474
4475  // C++ [base.class.init]p2:
4476  //   If a mem-initializer-id is ambiguous because it designates both
4477  //   a direct non-virtual base class and an inherited virtual base
4478  //   class, the mem-initializer is ill-formed.
4479  if (DirectBaseSpec && VirtualBaseSpec)
4480    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4481      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4482
4483  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4484  if (!BaseSpec)
4485    BaseSpec = VirtualBaseSpec;
4486
4487  // Initialize the base.
4488  bool InitList = true;
4489  MultiExprArg Args = Init;
4490  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4491    InitList = false;
4492    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4493  }
4494
4495  InitializedEntity BaseEntity =
4496    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4497  InitializationKind Kind =
4498      InitList ? InitializationKind::CreateDirectList(BaseLoc)
4499               : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4500                                                  InitRange.getEnd());
4501  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4502  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4503  if (BaseInit.isInvalid())
4504    return true;
4505
4506  // C++11 [class.base.init]p7:
4507  //   The initialization of each base and member constitutes a
4508  //   full-expression.
4509  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4510                                 /*DiscardedValue*/ false);
4511  if (BaseInit.isInvalid())
4512    return true;
4513
4514  // If we are in a dependent context, template instantiation will
4515  // perform this type-checking again. Just save the arguments that we
4516  // received in a ParenListExpr.
4517  // FIXME: This isn't quite ideal, since our ASTs don't capture all
4518  // of the information that we have about the base
4519  // initializer. However, deconstructing the ASTs is a dicey process,
4520  // and this approach is far more likely to get the corner cases right.
4521  if (CurContext->isDependentContext())
4522    BaseInit = Init;
4523
4524  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4525                                          BaseSpec->isVirtual(),
4526                                          InitRange.getBegin(),
4527                                          BaseInit.getAs<Expr>(),
4528                                          InitRange.getEnd(), EllipsisLoc);
4529}
4530
4531// Create a static_cast\<T&&>(expr).
4532static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4533  if (T.isNull()) T = E->getType();
4534  QualType TargetType = SemaRef.BuildReferenceType(
4535      T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4536  SourceLocation ExprLoc = E->getBeginLoc();
4537  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4538      TargetType, ExprLoc);
4539
4540  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4541                                   SourceRange(ExprLoc, ExprLoc),
4542                                   E->getSourceRange()).get();
4543}
4544
4545/// ImplicitInitializerKind - How an implicit base or member initializer should
4546/// initialize its base or member.
4547enum ImplicitInitializerKind {
4548  IIK_Default,
4549  IIK_Copy,
4550  IIK_Move,
4551  IIK_Inherit
4552};
4553
4554static bool
4555BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4556                             ImplicitInitializerKind ImplicitInitKind,
4557                             CXXBaseSpecifier *BaseSpec,
4558                             bool IsInheritedVirtualBase,
4559                             CXXCtorInitializer *&CXXBaseInit) {
4560  InitializedEntity InitEntity
4561    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4562                                        IsInheritedVirtualBase);
4563
4564  ExprResult BaseInit;
4565
4566  switch (ImplicitInitKind) {
4567  case IIK_Inherit:
4568  case IIK_Default: {
4569    InitializationKind InitKind
4570      = InitializationKind::CreateDefault(Constructor->getLocation());
4571    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4572    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4573    break;
4574  }
4575
4576  case IIK_Move:
4577  case IIK_Copy: {
4578    bool Moving = ImplicitInitKind == IIK_Move;
4579    ParmVarDecl *Param = Constructor->getParamDecl(0);
4580    QualType ParamType = Param->getType().getNonReferenceType();
4581
4582    Expr *CopyCtorArg =
4583      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4584                          SourceLocation(), Param, false,
4585                          Constructor->getLocation(), ParamType,
4586                          VK_LValue, nullptr);
4587
4588    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4589
4590    // Cast to the base class to avoid ambiguities.
4591    QualType ArgTy =
4592      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4593                                       ParamType.getQualifiers());
4594
4595    if (Moving) {
4596      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4597    }
4598
4599    CXXCastPath BasePath;
4600    BasePath.push_back(BaseSpec);
4601    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4602                                            CK_UncheckedDerivedToBase,
4603                                            Moving ? VK_XValue : VK_LValue,
4604                                            &BasePath).get();
4605
4606    InitializationKind InitKind
4607      = InitializationKind::CreateDirect(Constructor->getLocation(),
4608                                         SourceLocation(), SourceLocation());
4609    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4610    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4611    break;
4612  }
4613  }
4614
4615  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4616  if (BaseInit.isInvalid())
4617    return true;
4618
4619  CXXBaseInit =
4620    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4621               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4622                                                        SourceLocation()),
4623                                             BaseSpec->isVirtual(),
4624                                             SourceLocation(),
4625                                             BaseInit.getAs<Expr>(),
4626                                             SourceLocation(),
4627                                             SourceLocation());
4628
4629  return false;
4630}
4631
4632static bool RefersToRValueRef(Expr *MemRef) {
4633  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4634  return Referenced->getType()->isRValueReferenceType();
4635}
4636
4637static bool
4638BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4639                               ImplicitInitializerKind ImplicitInitKind,
4640                               FieldDecl *Field, IndirectFieldDecl *Indirect,
4641                               CXXCtorInitializer *&CXXMemberInit) {
4642  if (Field->isInvalidDecl())
4643    return true;
4644
4645  SourceLocation Loc = Constructor->getLocation();
4646
4647  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4648    bool Moving = ImplicitInitKind == IIK_Move;
4649    ParmVarDecl *Param = Constructor->getParamDecl(0);
4650    QualType ParamType = Param->getType().getNonReferenceType();
4651
4652    // Suppress copying zero-width bitfields.
4653    if (Field->isZeroLengthBitField(SemaRef.Context))
4654      return false;
4655
4656    Expr *MemberExprBase =
4657      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4658                          SourceLocation(), Param, false,
4659                          Loc, ParamType, VK_LValue, nullptr);
4660
4661    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4662
4663    if (Moving) {
4664      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4665    }
4666
4667    // Build a reference to this field within the parameter.
4668    CXXScopeSpec SS;
4669    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4670                              Sema::LookupMemberName);
4671    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4672                                  : cast<ValueDecl>(Field), AS_public);
4673    MemberLookup.resolveKind();
4674    ExprResult CtorArg
4675      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4676                                         ParamType, Loc,
4677                                         /*IsArrow=*/false,
4678                                         SS,
4679                                         /*TemplateKWLoc=*/SourceLocation(),
4680                                         /*FirstQualifierInScope=*/nullptr,
4681                                         MemberLookup,
4682                                         /*TemplateArgs=*/nullptr,
4683                                         /*S*/nullptr);
4684    if (CtorArg.isInvalid())
4685      return true;
4686
4687    // C++11 [class.copy]p15:
4688    //   - if a member m has rvalue reference type T&&, it is direct-initialized
4689    //     with static_cast<T&&>(x.m);
4690    if (RefersToRValueRef(CtorArg.get())) {
4691      CtorArg = CastForMoving(SemaRef, CtorArg.get());
4692    }
4693
4694    InitializedEntity Entity =
4695        Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4696                                                       /*Implicit*/ true)
4697                 : InitializedEntity::InitializeMember(Field, nullptr,
4698                                                       /*Implicit*/ true);
4699
4700    // Direct-initialize to use the copy constructor.
4701    InitializationKind InitKind =
4702      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4703
4704    Expr *CtorArgE = CtorArg.getAs<Expr>();
4705    InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4706    ExprResult MemberInit =
4707        InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4708    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4709    if (MemberInit.isInvalid())
4710      return true;
4711
4712    if (Indirect)
4713      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4714          SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4715    else
4716      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4717          SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4718    return false;
4719  }
4720
4721  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4722         "Unhandled implicit init kind!");
4723
4724  QualType FieldBaseElementType =
4725    SemaRef.Context.getBaseElementType(Field->getType());
4726
4727  if (FieldBaseElementType->isRecordType()) {
4728    InitializedEntity InitEntity =
4729        Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4730                                                       /*Implicit*/ true)
4731                 : InitializedEntity::InitializeMember(Field, nullptr,
4732                                                       /*Implicit*/ true);
4733    InitializationKind InitKind =
4734      InitializationKind::CreateDefault(Loc);
4735
4736    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4737    ExprResult MemberInit =
4738      InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4739
4740    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4741    if (MemberInit.isInvalid())
4742      return true;
4743
4744    if (Indirect)
4745      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4746                                                               Indirect, Loc,
4747                                                               Loc,
4748                                                               MemberInit.get(),
4749                                                               Loc);
4750    else
4751      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4752                                                               Field, Loc, Loc,
4753                                                               MemberInit.get(),
4754                                                               Loc);
4755    return false;
4756  }
4757
4758  if (!Field->getParent()->isUnion()) {
4759    if (FieldBaseElementType->isReferenceType()) {
4760      SemaRef.Diag(Constructor->getLocation(),
4761                   diag::err_uninitialized_member_in_ctor)
4762      << (int)Constructor->isImplicit()
4763      << SemaRef.Context.getTagDeclType(Constructor->getParent())
4764      << 0 << Field->getDeclName();
4765      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4766      return true;
4767    }
4768
4769    if (FieldBaseElementType.isConstQualified()) {
4770      SemaRef.Diag(Constructor->getLocation(),
4771                   diag::err_uninitialized_member_in_ctor)
4772      << (int)Constructor->isImplicit()
4773      << SemaRef.Context.getTagDeclType(Constructor->getParent())
4774      << 1 << Field->getDeclName();
4775      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4776      return true;
4777    }
4778  }
4779
4780  if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4781    // ARC and Weak:
4782    //   Default-initialize Objective-C pointers to NULL.
4783    CXXMemberInit
4784      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4785                                                 Loc, Loc,
4786                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4787                                                 Loc);
4788    return false;
4789  }
4790
4791  // Nothing to initialize.
4792  CXXMemberInit = nullptr;
4793  return false;
4794}
4795
4796namespace {
4797struct BaseAndFieldInfo {
4798  Sema &S;
4799  CXXConstructorDecl *Ctor;
4800  bool AnyErrorsInInits;
4801  ImplicitInitializerKind IIK;
4802  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4803  SmallVector<CXXCtorInitializer*, 8> AllToInit;
4804  llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4805
4806  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4807    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4808    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4809    if (Ctor->getInheritedConstructor())
4810      IIK = IIK_Inherit;
4811    else if (Generated && Ctor->isCopyConstructor())
4812      IIK = IIK_Copy;
4813    else if (Generated && Ctor->isMoveConstructor())
4814      IIK = IIK_Move;
4815    else
4816      IIK = IIK_Default;
4817  }
4818
4819  bool isImplicitCopyOrMove() const {
4820    switch (IIK) {
4821    case IIK_Copy:
4822    case IIK_Move:
4823      return true;
4824
4825    case IIK_Default:
4826    case IIK_Inherit:
4827      return false;
4828    }
4829
4830    llvm_unreachable("Invalid ImplicitInitializerKind!");
4831  }
4832
4833  bool addFieldInitializer(CXXCtorInitializer *Init) {
4834    AllToInit.push_back(Init);
4835
4836    // Check whether this initializer makes the field "used".
4837    if (Init->getInit()->HasSideEffects(S.Context))
4838      S.UnusedPrivateFields.remove(Init->getAnyMember());
4839
4840    return false;
4841  }
4842
4843  bool isInactiveUnionMember(FieldDecl *Field) {
4844    RecordDecl *Record = Field->getParent();
4845    if (!Record->isUnion())
4846      return false;
4847
4848    if (FieldDecl *Active =
4849            ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4850      return Active != Field->getCanonicalDecl();
4851
4852    // In an implicit copy or move constructor, ignore any in-class initializer.
4853    if (isImplicitCopyOrMove())
4854      return true;
4855
4856    // If there's no explicit initialization, the field is active only if it
4857    // has an in-class initializer...
4858    if (Field->hasInClassInitializer())
4859      return false;
4860    // ... or it's an anonymous struct or union whose class has an in-class
4861    // initializer.
4862    if (!Field->isAnonymousStructOrUnion())
4863      return true;
4864    CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4865    return !FieldRD->hasInClassInitializer();
4866  }
4867
4868  /// Determine whether the given field is, or is within, a union member
4869  /// that is inactive (because there was an initializer given for a different
4870  /// member of the union, or because the union was not initialized at all).
4871  bool isWithinInactiveUnionMember(FieldDecl *Field,
4872                                   IndirectFieldDecl *Indirect) {
4873    if (!Indirect)
4874      return isInactiveUnionMember(Field);
4875
4876    for (auto *C : Indirect->chain()) {
4877      FieldDecl *Field = dyn_cast<FieldDecl>(C);
4878      if (Field && isInactiveUnionMember(Field))
4879        return true;
4880    }
4881    return false;
4882  }
4883};
4884}
4885
4886/// Determine whether the given type is an incomplete or zero-lenfgth
4887/// array type.
4888static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4889  if (T->isIncompleteArrayType())
4890    return true;
4891
4892  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4893    if (!ArrayT->getSize())
4894      return true;
4895
4896    T = ArrayT->getElementType();
4897  }
4898
4899  return false;
4900}
4901
4902static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4903                                    FieldDecl *Field,
4904                                    IndirectFieldDecl *Indirect = nullptr) {
4905  if (Field->isInvalidDecl())
4906    return false;
4907
4908  // Overwhelmingly common case: we have a direct initializer for this field.
4909  if (CXXCtorInitializer *Init =
4910          Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4911    return Info.addFieldInitializer(Init);
4912
4913  // C++11 [class.base.init]p8:
4914  //   if the entity is a non-static data member that has a
4915  //   brace-or-equal-initializer and either
4916  //   -- the constructor's class is a union and no other variant member of that
4917  //      union is designated by a mem-initializer-id or
4918  //   -- the constructor's class is not a union, and, if the entity is a member
4919  //      of an anonymous union, no other member of that union is designated by
4920  //      a mem-initializer-id,
4921  //   the entity is initialized as specified in [dcl.init].
4922  //
4923  // We also apply the same rules to handle anonymous structs within anonymous
4924  // unions.
4925  if (Info.isWithinInactiveUnionMember(Field, Indirect))
4926    return false;
4927
4928  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4929    ExprResult DIE =
4930        SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4931    if (DIE.isInvalid())
4932      return true;
4933
4934    auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4935    SemaRef.checkInitializerLifetime(Entity, DIE.get());
4936
4937    CXXCtorInitializer *Init;
4938    if (Indirect)
4939      Init = new (SemaRef.Context)
4940          CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4941                             SourceLocation(), DIE.get(), SourceLocation());
4942    else
4943      Init = new (SemaRef.Context)
4944          CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4945                             SourceLocation(), DIE.get(), SourceLocation());
4946    return Info.addFieldInitializer(Init);
4947  }
4948
4949  // Don't initialize incomplete or zero-length arrays.
4950  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4951    return false;
4952
4953  // Don't try to build an implicit initializer if there were semantic
4954  // errors in any of the initializers (and therefore we might be
4955  // missing some that the user actually wrote).
4956  if (Info.AnyErrorsInInits)
4957    return false;
4958
4959  CXXCtorInitializer *Init = nullptr;
4960  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4961                                     Indirect, Init))
4962    return true;
4963
4964  if (!Init)
4965    return false;
4966
4967  return Info.addFieldInitializer(Init);
4968}
4969
4970bool
4971Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4972                               CXXCtorInitializer *Initializer) {
4973  assert(Initializer->isDelegatingInitializer());
4974  Constructor->setNumCtorInitializers(1);
4975  CXXCtorInitializer **initializer =
4976    new (Context) CXXCtorInitializer*[1];
4977  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4978  Constructor->setCtorInitializers(initializer);
4979
4980  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4981    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4982    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4983  }
4984
4985  DelegatingCtorDecls.push_back(Constructor);
4986
4987  DiagnoseUninitializedFields(*this, Constructor);
4988
4989  return false;
4990}
4991
4992bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4993                               ArrayRef<CXXCtorInitializer *> Initializers) {
4994  if (Constructor->isDependentContext()) {
4995    // Just store the initializers as written, they will be checked during
4996    // instantiation.
4997    if (!Initializers.empty()) {
4998      Constructor->setNumCtorInitializers(Initializers.size());
4999      CXXCtorInitializer **baseOrMemberInitializers =
5000        new (Context) CXXCtorInitializer*[Initializers.size()];
5001      memcpy(baseOrMemberInitializers, Initializers.data(),
5002             Initializers.size() * sizeof(CXXCtorInitializer*));
5003      Constructor->setCtorInitializers(baseOrMemberInitializers);
5004    }
5005
5006    // Let template instantiation know whether we had errors.
5007    if (AnyErrors)
5008      Constructor->setInvalidDecl();
5009
5010    return false;
5011  }
5012
5013  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5014
5015  // We need to build the initializer AST according to order of construction
5016  // and not what user specified in the Initializers list.
5017  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5018  if (!ClassDecl)
5019    return true;
5020
5021  bool HadError = false;
5022
5023  for (unsigned i = 0; i < Initializers.size(); i++) {
5024    CXXCtorInitializer *Member = Initializers[i];
5025
5026    if (Member->isBaseInitializer())
5027      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5028    else {
5029      Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5030
5031      if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5032        for (auto *C : F->chain()) {
5033          FieldDecl *FD = dyn_cast<FieldDecl>(C);
5034          if (FD && FD->getParent()->isUnion())
5035            Info.ActiveUnionMember.insert(std::make_pair(
5036                FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5037        }
5038      } else if (FieldDecl *FD = Member->getMember()) {
5039        if (FD->getParent()->isUnion())
5040          Info.ActiveUnionMember.insert(std::make_pair(
5041              FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5042      }
5043    }
5044  }
5045
5046  // Keep track of the direct virtual bases.
5047  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5048  for (auto &I : ClassDecl->bases()) {
5049    if (I.isVirtual())
5050      DirectVBases.insert(&I);
5051  }
5052
5053  // Push virtual bases before others.
5054  for (auto &VBase : ClassDecl->vbases()) {
5055    if (CXXCtorInitializer *Value
5056        = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5057      // [class.base.init]p7, per DR257:
5058      //   A mem-initializer where the mem-initializer-id names a virtual base
5059      //   class is ignored during execution of a constructor of any class that
5060      //   is not the most derived class.
5061      if (ClassDecl->isAbstract()) {
5062        // FIXME: Provide a fixit to remove the base specifier. This requires
5063        // tracking the location of the associated comma for a base specifier.
5064        Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5065          << VBase.getType() << ClassDecl;
5066        DiagnoseAbstractType(ClassDecl);
5067      }
5068
5069      Info.AllToInit.push_back(Value);
5070    } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5071      // [class.base.init]p8, per DR257:
5072      //   If a given [...] base class is not named by a mem-initializer-id
5073      //   [...] and the entity is not a virtual base class of an abstract
5074      //   class, then [...] the entity is default-initialized.
5075      bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5076      CXXCtorInitializer *CXXBaseInit;
5077      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5078                                       &VBase, IsInheritedVirtualBase,
5079                                       CXXBaseInit)) {
5080        HadError = true;
5081        continue;
5082      }
5083
5084      Info.AllToInit.push_back(CXXBaseInit);
5085    }
5086  }
5087
5088  // Non-virtual bases.
5089  for (auto &Base : ClassDecl->bases()) {
5090    // Virtuals are in the virtual base list and already constructed.
5091    if (Base.isVirtual())
5092      continue;
5093
5094    if (CXXCtorInitializer *Value
5095          = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5096      Info.AllToInit.push_back(Value);
5097    } else if (!AnyErrors) {
5098      CXXCtorInitializer *CXXBaseInit;
5099      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5100                                       &Base, /*IsInheritedVirtualBase=*/false,
5101                                       CXXBaseInit)) {
5102        HadError = true;
5103        continue;
5104      }
5105
5106      Info.AllToInit.push_back(CXXBaseInit);
5107    }
5108  }
5109
5110  // Fields.
5111  for (auto *Mem : ClassDecl->decls()) {
5112    if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5113      // C++ [class.bit]p2:
5114      //   A declaration for a bit-field that omits the identifier declares an
5115      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5116      //   initialized.
5117      if (F->isUnnamedBitfield())
5118        continue;
5119
5120      // If we're not generating the implicit copy/move constructor, then we'll
5121      // handle anonymous struct/union fields based on their individual
5122      // indirect fields.
5123      if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5124        continue;
5125
5126      if (CollectFieldInitializer(*this, Info, F))
5127        HadError = true;
5128      continue;
5129    }
5130
5131    // Beyond this point, we only consider default initialization.
5132    if (Info.isImplicitCopyOrMove())
5133      continue;
5134
5135    if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5136      if (F->getType()->isIncompleteArrayType()) {
5137        assert(ClassDecl->hasFlexibleArrayMember() &&
5138               "Incomplete array type is not valid");
5139        continue;
5140      }
5141
5142      // Initialize each field of an anonymous struct individually.
5143      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5144        HadError = true;
5145
5146      continue;
5147    }
5148  }
5149
5150  unsigned NumInitializers = Info.AllToInit.size();
5151  if (NumInitializers > 0) {
5152    Constructor->setNumCtorInitializers(NumInitializers);
5153    CXXCtorInitializer **baseOrMemberInitializers =
5154      new (Context) CXXCtorInitializer*[NumInitializers];
5155    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5156           NumInitializers * sizeof(CXXCtorInitializer*));
5157    Constructor->setCtorInitializers(baseOrMemberInitializers);
5158
5159    // Constructors implicitly reference the base and member
5160    // destructors.
5161    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5162                                           Constructor->getParent());
5163  }
5164
5165  return HadError;
5166}
5167
5168static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5169  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5170    const RecordDecl *RD = RT->getDecl();
5171    if (RD->isAnonymousStructOrUnion()) {
5172      for (auto *Field : RD->fields())
5173        PopulateKeysForFields(Field, IdealInits);
5174      return;
5175    }
5176  }
5177  IdealInits.push_back(Field->getCanonicalDecl());
5178}
5179
5180static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5181  return Context.getCanonicalType(BaseType).getTypePtr();
5182}
5183
5184static const void *GetKeyForMember(ASTContext &Context,
5185                                   CXXCtorInitializer *Member) {
5186  if (!Member->isAnyMemberInitializer())
5187    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5188
5189  return Member->getAnyMember()->getCanonicalDecl();
5190}
5191
5192static void DiagnoseBaseOrMemInitializerOrder(
5193    Sema &SemaRef, const CXXConstructorDecl *Constructor,
5194    ArrayRef<CXXCtorInitializer *> Inits) {
5195  if (Constructor->getDeclContext()->isDependentContext())
5196    return;
5197
5198  // Don't check initializers order unless the warning is enabled at the
5199  // location of at least one initializer.
5200  bool ShouldCheckOrder = false;
5201  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5202    CXXCtorInitializer *Init = Inits[InitIndex];
5203    if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5204                                 Init->getSourceLocation())) {
5205      ShouldCheckOrder = true;
5206      break;
5207    }
5208  }
5209  if (!ShouldCheckOrder)
5210    return;
5211
5212  // Build the list of bases and members in the order that they'll
5213  // actually be initialized.  The explicit initializers should be in
5214  // this same order but may be missing things.
5215  SmallVector<const void*, 32> IdealInitKeys;
5216
5217  const CXXRecordDecl *ClassDecl = Constructor->getParent();
5218
5219  // 1. Virtual bases.
5220  for (const auto &VBase : ClassDecl->vbases())
5221    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5222
5223  // 2. Non-virtual bases.
5224  for (const auto &Base : ClassDecl->bases()) {
5225    if (Base.isVirtual())
5226      continue;
5227    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5228  }
5229
5230  // 3. Direct fields.
5231  for (auto *Field : ClassDecl->fields()) {
5232    if (Field->isUnnamedBitfield())
5233      continue;
5234
5235    PopulateKeysForFields(Field, IdealInitKeys);
5236  }
5237
5238  unsigned NumIdealInits = IdealInitKeys.size();
5239  unsigned IdealIndex = 0;
5240
5241  CXXCtorInitializer *PrevInit = nullptr;
5242  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5243    CXXCtorInitializer *Init = Inits[InitIndex];
5244    const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5245
5246    // Scan forward to try to find this initializer in the idealized
5247    // initializers list.
5248    for (; IdealIndex != NumIdealInits; ++IdealIndex)
5249      if (InitKey == IdealInitKeys[IdealIndex])
5250        break;
5251
5252    // If we didn't find this initializer, it must be because we
5253    // scanned past it on a previous iteration.  That can only
5254    // happen if we're out of order;  emit a warning.
5255    if (IdealIndex == NumIdealInits && PrevInit) {
5256      Sema::SemaDiagnosticBuilder D =
5257        SemaRef.Diag(PrevInit->getSourceLocation(),
5258                     diag::warn_initializer_out_of_order);
5259
5260      if (PrevInit->isAnyMemberInitializer())
5261        D << 0 << PrevInit->getAnyMember()->getDeclName();
5262      else
5263        D << 1 << PrevInit->getTypeSourceInfo()->getType();
5264
5265      if (Init->isAnyMemberInitializer())
5266        D << 0 << Init->getAnyMember()->getDeclName();
5267      else
5268        D << 1 << Init->getTypeSourceInfo()->getType();
5269
5270      // Move back to the initializer's location in the ideal list.
5271      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5272        if (InitKey == IdealInitKeys[IdealIndex])
5273          break;
5274
5275      assert(IdealIndex < NumIdealInits &&
5276             "initializer not found in initializer list");
5277    }
5278
5279    PrevInit = Init;
5280  }
5281}
5282
5283namespace {
5284bool CheckRedundantInit(Sema &S,
5285                        CXXCtorInitializer *Init,
5286                        CXXCtorInitializer *&PrevInit) {
5287  if (!PrevInit) {
5288    PrevInit = Init;
5289    return false;
5290  }
5291
5292  if (FieldDecl *Field = Init->getAnyMember())
5293    S.Diag(Init->getSourceLocation(),
5294           diag::err_multiple_mem_initialization)
5295      << Field->getDeclName()
5296      << Init->getSourceRange();
5297  else {
5298    const Type *BaseClass = Init->getBaseClass();
5299    assert(BaseClass && "neither field nor base");
5300    S.Diag(Init->getSourceLocation(),
5301           diag::err_multiple_base_initialization)
5302      << QualType(BaseClass, 0)
5303      << Init->getSourceRange();
5304  }
5305  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5306    << 0 << PrevInit->getSourceRange();
5307
5308  return true;
5309}
5310
5311typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5312typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5313
5314bool CheckRedundantUnionInit(Sema &S,
5315                             CXXCtorInitializer *Init,
5316                             RedundantUnionMap &Unions) {
5317  FieldDecl *Field = Init->getAnyMember();
5318  RecordDecl *Parent = Field->getParent();
5319  NamedDecl *Child = Field;
5320
5321  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5322    if (Parent->isUnion()) {
5323      UnionEntry &En = Unions[Parent];
5324      if (En.first && En.first != Child) {
5325        S.Diag(Init->getSourceLocation(),
5326               diag::err_multiple_mem_union_initialization)
5327          << Field->getDeclName()
5328          << Init->getSourceRange();
5329        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5330          << 0 << En.second->getSourceRange();
5331        return true;
5332      }
5333      if (!En.first) {
5334        En.first = Child;
5335        En.second = Init;
5336      }
5337      if (!Parent->isAnonymousStructOrUnion())
5338        return false;
5339    }
5340
5341    Child = Parent;
5342    Parent = cast<RecordDecl>(Parent->getDeclContext());
5343  }
5344
5345  return false;
5346}
5347}
5348
5349/// ActOnMemInitializers - Handle the member initializers for a constructor.
5350void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5351                                SourceLocation ColonLoc,
5352                                ArrayRef<CXXCtorInitializer*> MemInits,
5353                                bool AnyErrors) {
5354  if (!ConstructorDecl)
5355    return;
5356
5357  AdjustDeclIfTemplate(ConstructorDecl);
5358
5359  CXXConstructorDecl *Constructor
5360    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5361
5362  if (!Constructor) {
5363    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5364    return;
5365  }
5366
5367  // Mapping for the duplicate initializers check.
5368  // For member initializers, this is keyed with a FieldDecl*.
5369  // For base initializers, this is keyed with a Type*.
5370  llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5371
5372  // Mapping for the inconsistent anonymous-union initializers check.
5373  RedundantUnionMap MemberUnions;
5374
5375  bool HadError = false;
5376  for (unsigned i = 0; i < MemInits.size(); i++) {
5377    CXXCtorInitializer *Init = MemInits[i];
5378
5379    // Set the source order index.
5380    Init->setSourceOrder(i);
5381
5382    if (Init->isAnyMemberInitializer()) {
5383      const void *Key = GetKeyForMember(Context, Init);
5384      if (CheckRedundantInit(*this, Init, Members[Key]) ||
5385          CheckRedundantUnionInit(*this, Init, MemberUnions))
5386        HadError = true;
5387    } else if (Init->isBaseInitializer()) {
5388      const void *Key = GetKeyForMember(Context, Init);
5389      if (CheckRedundantInit(*this, Init, Members[Key]))
5390        HadError = true;
5391    } else {
5392      assert(Init->isDelegatingInitializer());
5393      // This must be the only initializer
5394      if (MemInits.size() != 1) {
5395        Diag(Init->getSourceLocation(),
5396             diag::err_delegating_initializer_alone)
5397          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5398        // We will treat this as being the only initializer.
5399      }
5400      SetDelegatingInitializer(Constructor, MemInits[i]);
5401      // Return immediately as the initializer is set.
5402      return;
5403    }
5404  }
5405
5406  if (HadError)
5407    return;
5408
5409  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5410
5411  SetCtorInitializers(Constructor, AnyErrors, MemInits);
5412
5413  DiagnoseUninitializedFields(*this, Constructor);
5414}
5415
5416void
5417Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5418                                             CXXRecordDecl *ClassDecl) {
5419  // Ignore dependent contexts. Also ignore unions, since their members never
5420  // have destructors implicitly called.
5421  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5422    return;
5423
5424  // FIXME: all the access-control diagnostics are positioned on the
5425  // field/base declaration.  That's probably good; that said, the
5426  // user might reasonably want to know why the destructor is being
5427  // emitted, and we currently don't say.
5428
5429  // Non-static data members.
5430  for (auto *Field : ClassDecl->fields()) {
5431    if (Field->isInvalidDecl())
5432      continue;
5433
5434    // Don't destroy incomplete or zero-length arrays.
5435    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5436      continue;
5437
5438    QualType FieldType = Context.getBaseElementType(Field->getType());
5439
5440    const RecordType* RT = FieldType->getAs<RecordType>();
5441    if (!RT)
5442      continue;
5443
5444    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5445    if (FieldClassDecl->isInvalidDecl())
5446      continue;
5447    if (FieldClassDecl->hasIrrelevantDestructor())
5448      continue;
5449    // The destructor for an implicit anonymous union member is never invoked.
5450    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5451      continue;
5452
5453    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5454    assert(Dtor && "No dtor found for FieldClassDecl!");
5455    CheckDestructorAccess(Field->getLocation(), Dtor,
5456                          PDiag(diag::err_access_dtor_field)
5457                            << Field->getDeclName()
5458                            << FieldType);
5459
5460    MarkFunctionReferenced(Location, Dtor);
5461    DiagnoseUseOfDecl(Dtor, Location);
5462  }
5463
5464  // We only potentially invoke the destructors of potentially constructed
5465  // subobjects.
5466  bool VisitVirtualBases = !ClassDecl->isAbstract();
5467
5468  // If the destructor exists and has already been marked used in the MS ABI,
5469  // then virtual base destructors have already been checked and marked used.
5470  // Skip checking them again to avoid duplicate diagnostics.
5471  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5472    CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5473    if (Dtor && Dtor->isUsed())
5474      VisitVirtualBases = false;
5475  }
5476
5477  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5478
5479  // Bases.
5480  for (const auto &Base : ClassDecl->bases()) {
5481    // Bases are always records in a well-formed non-dependent class.
5482    const RecordType *RT = Base.getType()->getAs<RecordType>();
5483
5484    // Remember direct virtual bases.
5485    if (Base.isVirtual()) {
5486      if (!VisitVirtualBases)
5487        continue;
5488      DirectVirtualBases.insert(RT);
5489    }
5490
5491    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5492    // If our base class is invalid, we probably can't get its dtor anyway.
5493    if (BaseClassDecl->isInvalidDecl())
5494      continue;
5495    if (BaseClassDecl->hasIrrelevantDestructor())
5496      continue;
5497
5498    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5499    assert(Dtor && "No dtor found for BaseClassDecl!");
5500
5501    // FIXME: caret should be on the start of the class name
5502    CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5503                          PDiag(diag::err_access_dtor_base)
5504                              << Base.getType() << Base.getSourceRange(),
5505                          Context.getTypeDeclType(ClassDecl));
5506
5507    MarkFunctionReferenced(Location, Dtor);
5508    DiagnoseUseOfDecl(Dtor, Location);
5509  }
5510
5511  if (VisitVirtualBases)
5512    MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5513                                         &DirectVirtualBases);
5514}
5515
5516void Sema::MarkVirtualBaseDestructorsReferenced(
5517    SourceLocation Location, CXXRecordDecl *ClassDecl,
5518    llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5519  // Virtual bases.
5520  for (const auto &VBase : ClassDecl->vbases()) {
5521    // Bases are always records in a well-formed non-dependent class.
5522    const RecordType *RT = VBase.getType()->castAs<RecordType>();
5523
5524    // Ignore already visited direct virtual bases.
5525    if (DirectVirtualBases && DirectVirtualBases->count(RT))
5526      continue;
5527
5528    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5529    // If our base class is invalid, we probably can't get its dtor anyway.
5530    if (BaseClassDecl->isInvalidDecl())
5531      continue;
5532    if (BaseClassDecl->hasIrrelevantDestructor())
5533      continue;
5534
5535    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5536    assert(Dtor && "No dtor found for BaseClassDecl!");
5537    if (CheckDestructorAccess(
5538            ClassDecl->getLocation(), Dtor,
5539            PDiag(diag::err_access_dtor_vbase)
5540                << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5541            Context.getTypeDeclType(ClassDecl)) ==
5542        AR_accessible) {
5543      CheckDerivedToBaseConversion(
5544          Context.getTypeDeclType(ClassDecl), VBase.getType(),
5545          diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5546          SourceRange(), DeclarationName(), nullptr);
5547    }
5548
5549    MarkFunctionReferenced(Location, Dtor);
5550    DiagnoseUseOfDecl(Dtor, Location);
5551  }
5552}
5553
5554void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5555  if (!CDtorDecl)
5556    return;
5557
5558  if (CXXConstructorDecl *Constructor
5559      = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5560    SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5561    DiagnoseUninitializedFields(*this, Constructor);
5562  }
5563}
5564
5565bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5566  if (!getLangOpts().CPlusPlus)
5567    return false;
5568
5569  const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5570  if (!RD)
5571    return false;
5572
5573  // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5574  // class template specialization here, but doing so breaks a lot of code.
5575
5576  // We can't answer whether something is abstract until it has a
5577  // definition. If it's currently being defined, we'll walk back
5578  // over all the declarations when we have a full definition.
5579  const CXXRecordDecl *Def = RD->getDefinition();
5580  if (!Def || Def->isBeingDefined())
5581    return false;
5582
5583  return RD->isAbstract();
5584}
5585
5586bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5587                                  TypeDiagnoser &Diagnoser) {
5588  if (!isAbstractType(Loc, T))
5589    return false;
5590
5591  T = Context.getBaseElementType(T);
5592  Diagnoser.diagnose(*this, Loc, T);
5593  DiagnoseAbstractType(T->getAsCXXRecordDecl());
5594  return true;
5595}
5596
5597void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5598  // Check if we've already emitted the list of pure virtual functions
5599  // for this class.
5600  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5601    return;
5602
5603  // If the diagnostic is suppressed, don't emit the notes. We're only
5604  // going to emit them once, so try to attach them to a diagnostic we're
5605  // actually going to show.
5606  if (Diags.isLastDiagnosticIgnored())
5607    return;
5608
5609  CXXFinalOverriderMap FinalOverriders;
5610  RD->getFinalOverriders(FinalOverriders);
5611
5612  // Keep a set of seen pure methods so we won't diagnose the same method
5613  // more than once.
5614  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5615
5616  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5617                                   MEnd = FinalOverriders.end();
5618       M != MEnd;
5619       ++M) {
5620    for (OverridingMethods::iterator SO = M->second.begin(),
5621                                  SOEnd = M->second.end();
5622         SO != SOEnd; ++SO) {
5623      // C++ [class.abstract]p4:
5624      //   A class is abstract if it contains or inherits at least one
5625      //   pure virtual function for which the final overrider is pure
5626      //   virtual.
5627
5628      //
5629      if (SO->second.size() != 1)
5630        continue;
5631
5632      if (!SO->second.front().Method->isPure())
5633        continue;
5634
5635      if (!SeenPureMethods.insert(SO->second.front().Method).second)
5636        continue;
5637
5638      Diag(SO->second.front().Method->getLocation(),
5639           diag::note_pure_virtual_function)
5640        << SO->second.front().Method->getDeclName() << RD->getDeclName();
5641    }
5642  }
5643
5644  if (!PureVirtualClassDiagSet)
5645    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5646  PureVirtualClassDiagSet->insert(RD);
5647}
5648
5649namespace {
5650struct AbstractUsageInfo {
5651  Sema &S;
5652  CXXRecordDecl *Record;
5653  CanQualType AbstractType;
5654  bool Invalid;
5655
5656  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5657    : S(S), Record(Record),
5658      AbstractType(S.Context.getCanonicalType(
5659                   S.Context.getTypeDeclType(Record))),
5660      Invalid(false) {}
5661
5662  void DiagnoseAbstractType() {
5663    if (Invalid) return;
5664    S.DiagnoseAbstractType(Record);
5665    Invalid = true;
5666  }
5667
5668  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5669};
5670
5671struct CheckAbstractUsage {
5672  AbstractUsageInfo &Info;
5673  const NamedDecl *Ctx;
5674
5675  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5676    : Info(Info), Ctx(Ctx) {}
5677
5678  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5679    switch (TL.getTypeLocClass()) {
5680#define ABSTRACT_TYPELOC(CLASS, PARENT)
5681#define TYPELOC(CLASS, PARENT) \
5682    case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5683#include "clang/AST/TypeLocNodes.def"
5684    }
5685  }
5686
5687  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5688    Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5689    for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5690      if (!TL.getParam(I))
5691        continue;
5692
5693      TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5694      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5695    }
5696  }
5697
5698  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5699    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5700  }
5701
5702  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5703    // Visit the type parameters from a permissive context.
5704    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5705      TemplateArgumentLoc TAL = TL.getArgLoc(I);
5706      if (TAL.getArgument().getKind() == TemplateArgument::Type)
5707        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5708          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5709      // TODO: other template argument types?
5710    }
5711  }
5712
5713  // Visit pointee types from a permissive context.
5714#define CheckPolymorphic(Type) \
5715  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5716    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5717  }
5718  CheckPolymorphic(PointerTypeLoc)
5719  CheckPolymorphic(ReferenceTypeLoc)
5720  CheckPolymorphic(MemberPointerTypeLoc)
5721  CheckPolymorphic(BlockPointerTypeLoc)
5722  CheckPolymorphic(AtomicTypeLoc)
5723
5724  /// Handle all the types we haven't given a more specific
5725  /// implementation for above.
5726  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5727    // Every other kind of type that we haven't called out already
5728    // that has an inner type is either (1) sugar or (2) contains that
5729    // inner type in some way as a subobject.
5730    if (TypeLoc Next = TL.getNextTypeLoc())
5731      return Visit(Next, Sel);
5732
5733    // If there's no inner type and we're in a permissive context,
5734    // don't diagnose.
5735    if (Sel == Sema::AbstractNone) return;
5736
5737    // Check whether the type matches the abstract type.
5738    QualType T = TL.getType();
5739    if (T->isArrayType()) {
5740      Sel = Sema::AbstractArrayType;
5741      T = Info.S.Context.getBaseElementType(T);
5742    }
5743    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5744    if (CT != Info.AbstractType) return;
5745
5746    // It matched; do some magic.
5747    if (Sel == Sema::AbstractArrayType) {
5748      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5749        << T << TL.getSourceRange();
5750    } else {
5751      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5752        << Sel << T << TL.getSourceRange();
5753    }
5754    Info.DiagnoseAbstractType();
5755  }
5756};
5757
5758void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5759                                  Sema::AbstractDiagSelID Sel) {
5760  CheckAbstractUsage(*this, D).Visit(TL, Sel);
5761}
5762
5763}
5764
5765/// Check for invalid uses of an abstract type in a method declaration.
5766static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5767                                    CXXMethodDecl *MD) {
5768  // No need to do the check on definitions, which require that
5769  // the return/param types be complete.
5770  if (MD->doesThisDeclarationHaveABody())
5771    return;
5772
5773  // For safety's sake, just ignore it if we don't have type source
5774  // information.  This should never happen for non-implicit methods,
5775  // but...
5776  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5777    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5778}
5779
5780/// Check for invalid uses of an abstract type within a class definition.
5781static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5782                                    CXXRecordDecl *RD) {
5783  for (auto *D : RD->decls()) {
5784    if (D->isImplicit()) continue;
5785
5786    // Methods and method templates.
5787    if (isa<CXXMethodDecl>(D)) {
5788      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5789    } else if (isa<FunctionTemplateDecl>(D)) {
5790      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5791      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5792
5793    // Fields and static variables.
5794    } else if (isa<FieldDecl>(D)) {
5795      FieldDecl *FD = cast<FieldDecl>(D);
5796      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5797        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5798    } else if (isa<VarDecl>(D)) {
5799      VarDecl *VD = cast<VarDecl>(D);
5800      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5801        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5802
5803    // Nested classes and class templates.
5804    } else if (isa<CXXRecordDecl>(D)) {
5805      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5806    } else if (isa<ClassTemplateDecl>(D)) {
5807      CheckAbstractClassUsage(Info,
5808                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5809    }
5810  }
5811}
5812
5813static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5814  Attr *ClassAttr = getDLLAttr(Class);
5815  if (!ClassAttr)
5816    return;
5817
5818  assert(ClassAttr->getKind() == attr::DLLExport);
5819
5820  TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5821
5822  if (TSK == TSK_ExplicitInstantiationDeclaration)
5823    // Don't go any further if this is just an explicit instantiation
5824    // declaration.
5825    return;
5826
5827  // Add a context note to explain how we got to any diagnostics produced below.
5828  struct MarkingClassDllexported {
5829    Sema &S;
5830    MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5831                            SourceLocation AttrLoc)
5832        : S(S) {
5833      Sema::CodeSynthesisContext Ctx;
5834      Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5835      Ctx.PointOfInstantiation = AttrLoc;
5836      Ctx.Entity = Class;
5837      S.pushCodeSynthesisContext(Ctx);
5838    }
5839    ~MarkingClassDllexported() {
5840      S.popCodeSynthesisContext();
5841    }
5842  } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5843
5844  if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5845    S.MarkVTableUsed(Class->getLocation(), Class, true);
5846
5847  for (Decl *Member : Class->decls()) {
5848    // Defined static variables that are members of an exported base
5849    // class must be marked export too.
5850    auto *VD = dyn_cast<VarDecl>(Member);
5851    if (VD && Member->getAttr<DLLExportAttr>() &&
5852        VD->getStorageClass() == SC_Static &&
5853        TSK == TSK_ImplicitInstantiation)
5854      S.MarkVariableReferenced(VD->getLocation(), VD);
5855
5856    auto *MD = dyn_cast<CXXMethodDecl>(Member);
5857    if (!MD)
5858      continue;
5859
5860    if (Member->getAttr<DLLExportAttr>()) {
5861      if (MD->isUserProvided()) {
5862        // Instantiate non-default class member functions ...
5863
5864        // .. except for certain kinds of template specializations.
5865        if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5866          continue;
5867
5868        S.MarkFunctionReferenced(Class->getLocation(), MD);
5869
5870        // The function will be passed to the consumer when its definition is
5871        // encountered.
5872      } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5873                 MD->isCopyAssignmentOperator() ||
5874                 MD->isMoveAssignmentOperator()) {
5875        // Synthesize and instantiate non-trivial implicit methods, explicitly
5876        // defaulted methods, and the copy and move assignment operators. The
5877        // latter are exported even if they are trivial, because the address of
5878        // an operator can be taken and should compare equal across libraries.
5879        S.MarkFunctionReferenced(Class->getLocation(), MD);
5880
5881        // There is no later point when we will see the definition of this
5882        // function, so pass it to the consumer now.
5883        S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5884      }
5885    }
5886  }
5887}
5888
5889static void checkForMultipleExportedDefaultConstructors(Sema &S,
5890                                                        CXXRecordDecl *Class) {
5891  // Only the MS ABI has default constructor closures, so we don't need to do
5892  // this semantic checking anywhere else.
5893  if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5894    return;
5895
5896  CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5897  for (Decl *Member : Class->decls()) {
5898    // Look for exported default constructors.
5899    auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5900    if (!CD || !CD->isDefaultConstructor())
5901      continue;
5902    auto *Attr = CD->getAttr<DLLExportAttr>();
5903    if (!Attr)
5904      continue;
5905
5906    // If the class is non-dependent, mark the default arguments as ODR-used so
5907    // that we can properly codegen the constructor closure.
5908    if (!Class->isDependentContext()) {
5909      for (ParmVarDecl *PD : CD->parameters()) {
5910        (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5911        S.DiscardCleanupsInEvaluationContext();
5912      }
5913    }
5914
5915    if (LastExportedDefaultCtor) {
5916      S.Diag(LastExportedDefaultCtor->getLocation(),
5917             diag::err_attribute_dll_ambiguous_default_ctor)
5918          << Class;
5919      S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5920          << CD->getDeclName();
5921      return;
5922    }
5923    LastExportedDefaultCtor = CD;
5924  }
5925}
5926
5927static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5928                                                       CXXRecordDecl *Class) {
5929  bool ErrorReported = false;
5930  auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5931                                                     ClassTemplateDecl *TD) {
5932    if (ErrorReported)
5933      return;
5934    S.Diag(TD->getLocation(),
5935           diag::err_cuda_device_builtin_surftex_cls_template)
5936        << /*surface*/ 0 << TD;
5937    ErrorReported = true;
5938  };
5939
5940  ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5941  if (!TD) {
5942    auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5943    if (!SD) {
5944      S.Diag(Class->getLocation(),
5945             diag::err_cuda_device_builtin_surftex_ref_decl)
5946          << /*surface*/ 0 << Class;
5947      S.Diag(Class->getLocation(),
5948             diag::note_cuda_device_builtin_surftex_should_be_template_class)
5949          << Class;
5950      return;
5951    }
5952    TD = SD->getSpecializedTemplate();
5953  }
5954
5955  TemplateParameterList *Params = TD->getTemplateParameters();
5956  unsigned N = Params->size();
5957
5958  if (N != 2) {
5959    reportIllegalClassTemplate(S, TD);
5960    S.Diag(TD->getLocation(),
5961           diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5962        << TD << 2;
5963  }
5964  if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5965    reportIllegalClassTemplate(S, TD);
5966    S.Diag(TD->getLocation(),
5967           diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5968        << TD << /*1st*/ 0 << /*type*/ 0;
5969  }
5970  if (N > 1) {
5971    auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
5972    if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5973      reportIllegalClassTemplate(S, TD);
5974      S.Diag(TD->getLocation(),
5975             diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5976          << TD << /*2nd*/ 1 << /*integer*/ 1;
5977    }
5978  }
5979}
5980
5981static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
5982                                                       CXXRecordDecl *Class) {
5983  bool ErrorReported = false;
5984  auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5985                                                     ClassTemplateDecl *TD) {
5986    if (ErrorReported)
5987      return;
5988    S.Diag(TD->getLocation(),
5989           diag::err_cuda_device_builtin_surftex_cls_template)
5990        << /*texture*/ 1 << TD;
5991    ErrorReported = true;
5992  };
5993
5994  ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5995  if (!TD) {
5996    auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5997    if (!SD) {
5998      S.Diag(Class->getLocation(),
5999             diag::err_cuda_device_builtin_surftex_ref_decl)
6000          << /*texture*/ 1 << Class;
6001      S.Diag(Class->getLocation(),
6002             diag::note_cuda_device_builtin_surftex_should_be_template_class)
6003          << Class;
6004      return;
6005    }
6006    TD = SD->getSpecializedTemplate();
6007  }
6008
6009  TemplateParameterList *Params = TD->getTemplateParameters();
6010  unsigned N = Params->size();
6011
6012  if (N != 3) {
6013    reportIllegalClassTemplate(S, TD);
6014    S.Diag(TD->getLocation(),
6015           diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6016        << TD << 3;
6017  }
6018  if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6019    reportIllegalClassTemplate(S, TD);
6020    S.Diag(TD->getLocation(),
6021           diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6022        << TD << /*1st*/ 0 << /*type*/ 0;
6023  }
6024  if (N > 1) {
6025    auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6026    if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6027      reportIllegalClassTemplate(S, TD);
6028      S.Diag(TD->getLocation(),
6029             diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6030          << TD << /*2nd*/ 1 << /*integer*/ 1;
6031    }
6032  }
6033  if (N > 2) {
6034    auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6035    if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6036      reportIllegalClassTemplate(S, TD);
6037      S.Diag(TD->getLocation(),
6038             diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6039          << TD << /*3rd*/ 2 << /*integer*/ 1;
6040    }
6041  }
6042}
6043
6044void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6045  // Mark any compiler-generated routines with the implicit code_seg attribute.
6046  for (auto *Method : Class->methods()) {
6047    if (Method->isUserProvided())
6048      continue;
6049    if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6050      Method->addAttr(A);
6051  }
6052}
6053
6054/// Check class-level dllimport/dllexport attribute.
6055void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6056  Attr *ClassAttr = getDLLAttr(Class);
6057
6058  // MSVC inherits DLL attributes to partial class template specializations.
6059  if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
6060    if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6061      if (Attr *TemplateAttr =
6062              getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6063        auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6064        A->setInherited(true);
6065        ClassAttr = A;
6066      }
6067    }
6068  }
6069
6070  if (!ClassAttr)
6071    return;
6072
6073  if (!Class->isExternallyVisible()) {
6074    Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6075        << Class << ClassAttr;
6076    return;
6077  }
6078
6079  if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6080      !ClassAttr->isInherited()) {
6081    // Diagnose dll attributes on members of class with dll attribute.
6082    for (Decl *Member : Class->decls()) {
6083      if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6084        continue;
6085      InheritableAttr *MemberAttr = getDLLAttr(Member);
6086      if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6087        continue;
6088
6089      Diag(MemberAttr->getLocation(),
6090             diag::err_attribute_dll_member_of_dll_class)
6091          << MemberAttr << ClassAttr;
6092      Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6093      Member->setInvalidDecl();
6094    }
6095  }
6096
6097  if (Class->getDescribedClassTemplate())
6098    // Don't inherit dll attribute until the template is instantiated.
6099    return;
6100
6101  // The class is either imported or exported.
6102  const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6103
6104  // Check if this was a dllimport attribute propagated from a derived class to
6105  // a base class template specialization. We don't apply these attributes to
6106  // static data members.
6107  const bool PropagatedImport =
6108      !ClassExported &&
6109      cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6110
6111  TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6112
6113  // Ignore explicit dllexport on explicit class template instantiation
6114  // declarations, except in MinGW mode.
6115  if (ClassExported && !ClassAttr->isInherited() &&
6116      TSK == TSK_ExplicitInstantiationDeclaration &&
6117      !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6118    Class->dropAttr<DLLExportAttr>();
6119    return;
6120  }
6121
6122  // Force declaration of implicit members so they can inherit the attribute.
6123  ForceDeclarationOfImplicitMembers(Class);
6124
6125  // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6126  // seem to be true in practice?
6127
6128  for (Decl *Member : Class->decls()) {
6129    VarDecl *VD = dyn_cast<VarDecl>(Member);
6130    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6131
6132    // Only methods and static fields inherit the attributes.
6133    if (!VD && !MD)
6134      continue;
6135
6136    if (MD) {
6137      // Don't process deleted methods.
6138      if (MD->isDeleted())
6139        continue;
6140
6141      if (MD->isInlined()) {
6142        // MinGW does not import or export inline methods. But do it for
6143        // template instantiations.
6144        if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6145            !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
6146            TSK != TSK_ExplicitInstantiationDeclaration &&
6147            TSK != TSK_ExplicitInstantiationDefinition)
6148          continue;
6149
6150        // MSVC versions before 2015 don't export the move assignment operators
6151        // and move constructor, so don't attempt to import/export them if
6152        // we have a definition.
6153        auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6154        if ((MD->isMoveAssignmentOperator() ||
6155             (Ctor && Ctor->isMoveConstructor())) &&
6156            !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6157          continue;
6158
6159        // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6160        // operator is exported anyway.
6161        if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6162            (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6163          continue;
6164      }
6165    }
6166
6167    // Don't apply dllimport attributes to static data members of class template
6168    // instantiations when the attribute is propagated from a derived class.
6169    if (VD && PropagatedImport)
6170      continue;
6171
6172    if (!cast<NamedDecl>(Member)->isExternallyVisible())
6173      continue;
6174
6175    if (!getDLLAttr(Member)) {
6176      InheritableAttr *NewAttr = nullptr;
6177
6178      // Do not export/import inline function when -fno-dllexport-inlines is
6179      // passed. But add attribute for later local static var check.
6180      if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6181          TSK != TSK_ExplicitInstantiationDeclaration &&
6182          TSK != TSK_ExplicitInstantiationDefinition) {
6183        if (ClassExported) {
6184          NewAttr = ::new (getASTContext())
6185              DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6186        } else {
6187          NewAttr = ::new (getASTContext())
6188              DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6189        }
6190      } else {
6191        NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6192      }
6193
6194      NewAttr->setInherited(true);
6195      Member->addAttr(NewAttr);
6196
6197      if (MD) {
6198        // Propagate DLLAttr to friend re-declarations of MD that have already
6199        // been constructed.
6200        for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6201             FD = FD->getPreviousDecl()) {
6202          if (FD->getFriendObjectKind() == Decl::FOK_None)
6203            continue;
6204          assert(!getDLLAttr(FD) &&
6205                 "friend re-decl should not already have a DLLAttr");
6206          NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6207          NewAttr->setInherited(true);
6208          FD->addAttr(NewAttr);
6209        }
6210      }
6211    }
6212  }
6213
6214  if (ClassExported)
6215    DelayedDllExportClasses.push_back(Class);
6216}
6217
6218/// Perform propagation of DLL attributes from a derived class to a
6219/// templated base class for MS compatibility.
6220void Sema::propagateDLLAttrToBaseClassTemplate(
6221    CXXRecordDecl *Class, Attr *ClassAttr,
6222    ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6223  if (getDLLAttr(
6224          BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6225    // If the base class template has a DLL attribute, don't try to change it.
6226    return;
6227  }
6228
6229  auto TSK = BaseTemplateSpec->getSpecializationKind();
6230  if (!getDLLAttr(BaseTemplateSpec) &&
6231      (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6232       TSK == TSK_ImplicitInstantiation)) {
6233    // The template hasn't been instantiated yet (or it has, but only as an
6234    // explicit instantiation declaration or implicit instantiation, which means
6235    // we haven't codegenned any members yet), so propagate the attribute.
6236    auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6237    NewAttr->setInherited(true);
6238    BaseTemplateSpec->addAttr(NewAttr);
6239
6240    // If this was an import, mark that we propagated it from a derived class to
6241    // a base class template specialization.
6242    if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6243      ImportAttr->setPropagatedToBaseTemplate();
6244
6245    // If the template is already instantiated, checkDLLAttributeRedeclaration()
6246    // needs to be run again to work see the new attribute. Otherwise this will
6247    // get run whenever the template is instantiated.
6248    if (TSK != TSK_Undeclared)
6249      checkClassLevelDLLAttribute(BaseTemplateSpec);
6250
6251    return;
6252  }
6253
6254  if (getDLLAttr(BaseTemplateSpec)) {
6255    // The template has already been specialized or instantiated with an
6256    // attribute, explicitly or through propagation. We should not try to change
6257    // it.
6258    return;
6259  }
6260
6261  // The template was previously instantiated or explicitly specialized without
6262  // a dll attribute, It's too late for us to add an attribute, so warn that
6263  // this is unsupported.
6264  Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6265      << BaseTemplateSpec->isExplicitSpecialization();
6266  Diag(ClassAttr->getLocation(), diag::note_attribute);
6267  if (BaseTemplateSpec->isExplicitSpecialization()) {
6268    Diag(BaseTemplateSpec->getLocation(),
6269           diag::note_template_class_explicit_specialization_was_here)
6270        << BaseTemplateSpec;
6271  } else {
6272    Diag(BaseTemplateSpec->getPointOfInstantiation(),
6273           diag::note_template_class_instantiation_was_here)
6274        << BaseTemplateSpec;
6275  }
6276}
6277
6278/// Determine the kind of defaulting that would be done for a given function.
6279///
6280/// If the function is both a default constructor and a copy / move constructor
6281/// (due to having a default argument for the first parameter), this picks
6282/// CXXDefaultConstructor.
6283///
6284/// FIXME: Check that case is properly handled by all callers.
6285Sema::DefaultedFunctionKind
6286Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6287  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6288    if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6289      if (Ctor->isDefaultConstructor())
6290        return Sema::CXXDefaultConstructor;
6291
6292      if (Ctor->isCopyConstructor())
6293        return Sema::CXXCopyConstructor;
6294
6295      if (Ctor->isMoveConstructor())
6296        return Sema::CXXMoveConstructor;
6297    }
6298
6299    if (MD->isCopyAssignmentOperator())
6300      return Sema::CXXCopyAssignment;
6301
6302    if (MD->isMoveAssignmentOperator())
6303      return Sema::CXXMoveAssignment;
6304
6305    if (isa<CXXDestructorDecl>(FD))
6306      return Sema::CXXDestructor;
6307  }
6308
6309  switch (FD->getDeclName().getCXXOverloadedOperator()) {
6310  case OO_EqualEqual:
6311    return DefaultedComparisonKind::Equal;
6312
6313  case OO_ExclaimEqual:
6314    return DefaultedComparisonKind::NotEqual;
6315
6316  case OO_Spaceship:
6317    // No point allowing this if <=> doesn't exist in the current language mode.
6318    if (!getLangOpts().CPlusPlus20)
6319      break;
6320    return DefaultedComparisonKind::ThreeWay;
6321
6322  case OO_Less:
6323  case OO_LessEqual:
6324  case OO_Greater:
6325  case OO_GreaterEqual:
6326    // No point allowing this if <=> doesn't exist in the current language mode.
6327    if (!getLangOpts().CPlusPlus20)
6328      break;
6329    return DefaultedComparisonKind::Relational;
6330
6331  default:
6332    break;
6333  }
6334
6335  // Not defaultable.
6336  return DefaultedFunctionKind();
6337}
6338
6339static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6340                                    SourceLocation DefaultLoc) {
6341  Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6342  if (DFK.isComparison())
6343    return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6344
6345  switch (DFK.asSpecialMember()) {
6346  case Sema::CXXDefaultConstructor:
6347    S.DefineImplicitDefaultConstructor(DefaultLoc,
6348                                       cast<CXXConstructorDecl>(FD));
6349    break;
6350  case Sema::CXXCopyConstructor:
6351    S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6352    break;
6353  case Sema::CXXCopyAssignment:
6354    S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6355    break;
6356  case Sema::CXXDestructor:
6357    S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6358    break;
6359  case Sema::CXXMoveConstructor:
6360    S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6361    break;
6362  case Sema::CXXMoveAssignment:
6363    S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6364    break;
6365  case Sema::CXXInvalid:
6366    llvm_unreachable("Invalid special member.");
6367  }
6368}
6369
6370/// Determine whether a type is permitted to be passed or returned in
6371/// registers, per C++ [class.temporary]p3.
6372static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6373                               TargetInfo::CallingConvKind CCK) {
6374  if (D->isDependentType() || D->isInvalidDecl())
6375    return false;
6376
6377  // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6378  // The PS4 platform ABI follows the behavior of Clang 3.2.
6379  if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6380    return !D->hasNonTrivialDestructorForCall() &&
6381           !D->hasNonTrivialCopyConstructorForCall();
6382
6383  if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6384    bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6385    bool DtorIsTrivialForCall = false;
6386
6387    // If a class has at least one non-deleted, trivial copy constructor, it
6388    // is passed according to the C ABI. Otherwise, it is passed indirectly.
6389    //
6390    // Note: This permits classes with non-trivial copy or move ctors to be
6391    // passed in registers, so long as they *also* have a trivial copy ctor,
6392    // which is non-conforming.
6393    if (D->needsImplicitCopyConstructor()) {
6394      if (!D->defaultedCopyConstructorIsDeleted()) {
6395        if (D->hasTrivialCopyConstructor())
6396          CopyCtorIsTrivial = true;
6397        if (D->hasTrivialCopyConstructorForCall())
6398          CopyCtorIsTrivialForCall = true;
6399      }
6400    } else {
6401      for (const CXXConstructorDecl *CD : D->ctors()) {
6402        if (CD->isCopyConstructor() && !CD->isDeleted()) {
6403          if (CD->isTrivial())
6404            CopyCtorIsTrivial = true;
6405          if (CD->isTrivialForCall())
6406            CopyCtorIsTrivialForCall = true;
6407        }
6408      }
6409    }
6410
6411    if (D->needsImplicitDestructor()) {
6412      if (!D->defaultedDestructorIsDeleted() &&
6413          D->hasTrivialDestructorForCall())
6414        DtorIsTrivialForCall = true;
6415    } else if (const auto *DD = D->getDestructor()) {
6416      if (!DD->isDeleted() && DD->isTrivialForCall())
6417        DtorIsTrivialForCall = true;
6418    }
6419
6420    // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6421    if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6422      return true;
6423
6424    // If a class has a destructor, we'd really like to pass it indirectly
6425    // because it allows us to elide copies.  Unfortunately, MSVC makes that
6426    // impossible for small types, which it will pass in a single register or
6427    // stack slot. Most objects with dtors are large-ish, so handle that early.
6428    // We can't call out all large objects as being indirect because there are
6429    // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6430    // how we pass large POD types.
6431
6432    // Note: This permits small classes with nontrivial destructors to be
6433    // passed in registers, which is non-conforming.
6434    bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6435    uint64_t TypeSize = isAArch64 ? 128 : 64;
6436
6437    if (CopyCtorIsTrivial &&
6438        S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6439      return true;
6440    return false;
6441  }
6442
6443  // Per C++ [class.temporary]p3, the relevant condition is:
6444  //   each copy constructor, move constructor, and destructor of X is
6445  //   either trivial or deleted, and X has at least one non-deleted copy
6446  //   or move constructor
6447  bool HasNonDeletedCopyOrMove = false;
6448
6449  if (D->needsImplicitCopyConstructor() &&
6450      !D->defaultedCopyConstructorIsDeleted()) {
6451    if (!D->hasTrivialCopyConstructorForCall())
6452      return false;
6453    HasNonDeletedCopyOrMove = true;
6454  }
6455
6456  if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6457      !D->defaultedMoveConstructorIsDeleted()) {
6458    if (!D->hasTrivialMoveConstructorForCall())
6459      return false;
6460    HasNonDeletedCopyOrMove = true;
6461  }
6462
6463  if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6464      !D->hasTrivialDestructorForCall())
6465    return false;
6466
6467  for (const CXXMethodDecl *MD : D->methods()) {
6468    if (MD->isDeleted())
6469      continue;
6470
6471    auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6472    if (CD && CD->isCopyOrMoveConstructor())
6473      HasNonDeletedCopyOrMove = true;
6474    else if (!isa<CXXDestructorDecl>(MD))
6475      continue;
6476
6477    if (!MD->isTrivialForCall())
6478      return false;
6479  }
6480
6481  return HasNonDeletedCopyOrMove;
6482}
6483
6484/// Report an error regarding overriding, along with any relevant
6485/// overridden methods.
6486///
6487/// \param DiagID the primary error to report.
6488/// \param MD the overriding method.
6489static bool
6490ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6491                llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6492  bool IssuedDiagnostic = false;
6493  for (const CXXMethodDecl *O : MD->overridden_methods()) {
6494    if (Report(O)) {
6495      if (!IssuedDiagnostic) {
6496        S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6497        IssuedDiagnostic = true;
6498      }
6499      S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6500    }
6501  }
6502  return IssuedDiagnostic;
6503}
6504
6505/// Perform semantic checks on a class definition that has been
6506/// completing, introducing implicitly-declared members, checking for
6507/// abstract types, etc.
6508///
6509/// \param S The scope in which the class was parsed. Null if we didn't just
6510///        parse a class definition.
6511/// \param Record The completed class.
6512void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6513  if (!Record)
6514    return;
6515
6516  if (Record->isAbstract() && !Record->isInvalidDecl()) {
6517    AbstractUsageInfo Info(*this, Record);
6518    CheckAbstractClassUsage(Info, Record);
6519  }
6520
6521  // If this is not an aggregate type and has no user-declared constructor,
6522  // complain about any non-static data members of reference or const scalar
6523  // type, since they will never get initializers.
6524  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6525      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6526      !Record->isLambda()) {
6527    bool Complained = false;
6528    for (const auto *F : Record->fields()) {
6529      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6530        continue;
6531
6532      if (F->getType()->isReferenceType() ||
6533          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6534        if (!Complained) {
6535          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6536            << Record->getTagKind() << Record;
6537          Complained = true;
6538        }
6539
6540        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6541          << F->getType()->isReferenceType()
6542          << F->getDeclName();
6543      }
6544    }
6545  }
6546
6547  if (Record->getIdentifier()) {
6548    // C++ [class.mem]p13:
6549    //   If T is the name of a class, then each of the following shall have a
6550    //   name different from T:
6551    //     - every member of every anonymous union that is a member of class T.
6552    //
6553    // C++ [class.mem]p14:
6554    //   In addition, if class T has a user-declared constructor (12.1), every
6555    //   non-static data member of class T shall have a name different from T.
6556    DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6557    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6558         ++I) {
6559      NamedDecl *D = (*I)->getUnderlyingDecl();
6560      if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6561           Record->hasUserDeclaredConstructor()) ||
6562          isa<IndirectFieldDecl>(D)) {
6563        Diag((*I)->getLocation(), diag::err_member_name_of_class)
6564          << D->getDeclName();
6565        break;
6566      }
6567    }
6568  }
6569
6570  // Warn if the class has virtual methods but non-virtual public destructor.
6571  if (Record->isPolymorphic() && !Record->isDependentType()) {
6572    CXXDestructorDecl *dtor = Record->getDestructor();
6573    if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6574        !Record->hasAttr<FinalAttr>())
6575      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6576           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6577  }
6578
6579  if (Record->isAbstract()) {
6580    if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6581      Diag(Record->getLocation(), diag::warn_abstract_final_class)
6582        << FA->isSpelledAsSealed();
6583      DiagnoseAbstractType(Record);
6584    }
6585  }
6586
6587  // Warn if the class has a final destructor but is not itself marked final.
6588  if (!Record->hasAttr<FinalAttr>()) {
6589    if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6590      if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6591        Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6592            << FA->isSpelledAsSealed()
6593            << FixItHint::CreateInsertion(
6594                   getLocForEndOfToken(Record->getLocation()),
6595                   (FA->isSpelledAsSealed() ? " sealed" : " final"));
6596        Diag(Record->getLocation(),
6597             diag::note_final_dtor_non_final_class_silence)
6598            << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6599      }
6600    }
6601  }
6602
6603  // See if trivial_abi has to be dropped.
6604  if (Record->hasAttr<TrivialABIAttr>())
6605    checkIllFormedTrivialABIStruct(*Record);
6606
6607  // Set HasTrivialSpecialMemberForCall if the record has attribute
6608  // "trivial_abi".
6609  bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6610
6611  if (HasTrivialABI)
6612    Record->setHasTrivialSpecialMemberForCall();
6613
6614  // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6615  // We check these last because they can depend on the properties of the
6616  // primary comparison functions (==, <=>).
6617  llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6618
6619  // Perform checks that can't be done until we know all the properties of a
6620  // member function (whether it's defaulted, deleted, virtual, overriding,
6621  // ...).
6622  auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6623    // A static function cannot override anything.
6624    if (MD->getStorageClass() == SC_Static) {
6625      if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6626                          [](const CXXMethodDecl *) { return true; }))
6627        return;
6628    }
6629
6630    // A deleted function cannot override a non-deleted function and vice
6631    // versa.
6632    if (ReportOverrides(*this,
6633                        MD->isDeleted() ? diag::err_deleted_override
6634                                        : diag::err_non_deleted_override,
6635                        MD, [&](const CXXMethodDecl *V) {
6636                          return MD->isDeleted() != V->isDeleted();
6637                        })) {
6638      if (MD->isDefaulted() && MD->isDeleted())
6639        // Explain why this defaulted function was deleted.
6640        DiagnoseDeletedDefaultedFunction(MD);
6641      return;
6642    }
6643
6644    // A consteval function cannot override a non-consteval function and vice
6645    // versa.
6646    if (ReportOverrides(*this,
6647                        MD->isConsteval() ? diag::err_consteval_override
6648                                          : diag::err_non_consteval_override,
6649                        MD, [&](const CXXMethodDecl *V) {
6650                          return MD->isConsteval() != V->isConsteval();
6651                        })) {
6652      if (MD->isDefaulted() && MD->isDeleted())
6653        // Explain why this defaulted function was deleted.
6654        DiagnoseDeletedDefaultedFunction(MD);
6655      return;
6656    }
6657  };
6658
6659  auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6660    if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6661      return false;
6662
6663    DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6664    if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6665        DFK.asComparison() == DefaultedComparisonKind::Relational) {
6666      DefaultedSecondaryComparisons.push_back(FD);
6667      return true;
6668    }
6669
6670    CheckExplicitlyDefaultedFunction(S, FD);
6671    return false;
6672  };
6673
6674  auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6675    // Check whether the explicitly-defaulted members are valid.
6676    bool Incomplete = CheckForDefaultedFunction(M);
6677
6678    // Skip the rest of the checks for a member of a dependent class.
6679    if (Record->isDependentType())
6680      return;
6681
6682    // For an explicitly defaulted or deleted special member, we defer
6683    // determining triviality until the class is complete. That time is now!
6684    CXXSpecialMember CSM = getSpecialMember(M);
6685    if (!M->isImplicit() && !M->isUserProvided()) {
6686      if (CSM != CXXInvalid) {
6687        M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6688        // Inform the class that we've finished declaring this member.
6689        Record->finishedDefaultedOrDeletedMember(M);
6690        M->setTrivialForCall(
6691            HasTrivialABI ||
6692            SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6693        Record->setTrivialForCallFlags(M);
6694      }
6695    }
6696
6697    // Set triviality for the purpose of calls if this is a user-provided
6698    // copy/move constructor or destructor.
6699    if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6700         CSM == CXXDestructor) && M->isUserProvided()) {
6701      M->setTrivialForCall(HasTrivialABI);
6702      Record->setTrivialForCallFlags(M);
6703    }
6704
6705    if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6706        M->hasAttr<DLLExportAttr>()) {
6707      if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6708          M->isTrivial() &&
6709          (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6710           CSM == CXXDestructor))
6711        M->dropAttr<DLLExportAttr>();
6712
6713      if (M->hasAttr<DLLExportAttr>()) {
6714        // Define after any fields with in-class initializers have been parsed.
6715        DelayedDllExportMemberFunctions.push_back(M);
6716      }
6717    }
6718
6719    // Define defaulted constexpr virtual functions that override a base class
6720    // function right away.
6721    // FIXME: We can defer doing this until the vtable is marked as used.
6722    if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6723      DefineDefaultedFunction(*this, M, M->getLocation());
6724
6725    if (!Incomplete)
6726      CheckCompletedMemberFunction(M);
6727  };
6728
6729  // Check the destructor before any other member function. We need to
6730  // determine whether it's trivial in order to determine whether the claas
6731  // type is a literal type, which is a prerequisite for determining whether
6732  // other special member functions are valid and whether they're implicitly
6733  // 'constexpr'.
6734  if (CXXDestructorDecl *Dtor = Record->getDestructor())
6735    CompleteMemberFunction(Dtor);
6736
6737  bool HasMethodWithOverrideControl = false,
6738       HasOverridingMethodWithoutOverrideControl = false;
6739  for (auto *D : Record->decls()) {
6740    if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6741      // FIXME: We could do this check for dependent types with non-dependent
6742      // bases.
6743      if (!Record->isDependentType()) {
6744        // See if a method overloads virtual methods in a base
6745        // class without overriding any.
6746        if (!M->isStatic())
6747          DiagnoseHiddenVirtualMethods(M);
6748        if (M->hasAttr<OverrideAttr>())
6749          HasMethodWithOverrideControl = true;
6750        else if (M->size_overridden_methods() > 0)
6751          HasOverridingMethodWithoutOverrideControl = true;
6752      }
6753
6754      if (!isa<CXXDestructorDecl>(M))
6755        CompleteMemberFunction(M);
6756    } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6757      CheckForDefaultedFunction(
6758          dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6759    }
6760  }
6761
6762  if (HasOverridingMethodWithoutOverrideControl) {
6763    bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6764    for (auto *M : Record->methods())
6765      DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6766  }
6767
6768  // Check the defaulted secondary comparisons after any other member functions.
6769  for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6770    CheckExplicitlyDefaultedFunction(S, FD);
6771
6772    // If this is a member function, we deferred checking it until now.
6773    if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6774      CheckCompletedMemberFunction(MD);
6775  }
6776
6777  // ms_struct is a request to use the same ABI rules as MSVC.  Check
6778  // whether this class uses any C++ features that are implemented
6779  // completely differently in MSVC, and if so, emit a diagnostic.
6780  // That diagnostic defaults to an error, but we allow projects to
6781  // map it down to a warning (or ignore it).  It's a fairly common
6782  // practice among users of the ms_struct pragma to mass-annotate
6783  // headers, sweeping up a bunch of types that the project doesn't
6784  // really rely on MSVC-compatible layout for.  We must therefore
6785  // support "ms_struct except for C++ stuff" as a secondary ABI.
6786  // Don't emit this diagnostic if the feature was enabled as a
6787  // language option (as opposed to via a pragma or attribute), as
6788  // the option -mms-bitfields otherwise essentially makes it impossible
6789  // to build C++ code, unless this diagnostic is turned off.
6790  if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6791      (Record->isPolymorphic() || Record->getNumBases())) {
6792    Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6793  }
6794
6795  checkClassLevelDLLAttribute(Record);
6796  checkClassLevelCodeSegAttribute(Record);
6797
6798  bool ClangABICompat4 =
6799      Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6800  TargetInfo::CallingConvKind CCK =
6801      Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6802  bool CanPass = canPassInRegisters(*this, Record, CCK);
6803
6804  // Do not change ArgPassingRestrictions if it has already been set to
6805  // APK_CanNeverPassInRegs.
6806  if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6807    Record->setArgPassingRestrictions(CanPass
6808                                          ? RecordDecl::APK_CanPassInRegs
6809                                          : RecordDecl::APK_CannotPassInRegs);
6810
6811  // If canPassInRegisters returns true despite the record having a non-trivial
6812  // destructor, the record is destructed in the callee. This happens only when
6813  // the record or one of its subobjects has a field annotated with trivial_abi
6814  // or a field qualified with ObjC __strong/__weak.
6815  if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6816    Record->setParamDestroyedInCallee(true);
6817  else if (Record->hasNonTrivialDestructor())
6818    Record->setParamDestroyedInCallee(CanPass);
6819
6820  if (getLangOpts().ForceEmitVTables) {
6821    // If we want to emit all the vtables, we need to mark it as used.  This
6822    // is especially required for cases like vtable assumption loads.
6823    MarkVTableUsed(Record->getInnerLocStart(), Record);
6824  }
6825
6826  if (getLangOpts().CUDA) {
6827    if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6828      checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6829    else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6830      checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6831  }
6832}
6833
6834/// Look up the special member function that would be called by a special
6835/// member function for a subobject of class type.
6836///
6837/// \param Class The class type of the subobject.
6838/// \param CSM The kind of special member function.
6839/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6840/// \param ConstRHS True if this is a copy operation with a const object
6841///        on its RHS, that is, if the argument to the outer special member
6842///        function is 'const' and this is not a field marked 'mutable'.
6843static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6844    Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6845    unsigned FieldQuals, bool ConstRHS) {
6846  unsigned LHSQuals = 0;
6847  if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6848    LHSQuals = FieldQuals;
6849
6850  unsigned RHSQuals = FieldQuals;
6851  if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6852    RHSQuals = 0;
6853  else if (ConstRHS)
6854    RHSQuals |= Qualifiers::Const;
6855
6856  return S.LookupSpecialMember(Class, CSM,
6857                               RHSQuals & Qualifiers::Const,
6858                               RHSQuals & Qualifiers::Volatile,
6859                               false,
6860                               LHSQuals & Qualifiers::Const,
6861                               LHSQuals & Qualifiers::Volatile);
6862}
6863
6864class Sema::InheritedConstructorInfo {
6865  Sema &S;
6866  SourceLocation UseLoc;
6867
6868  /// A mapping from the base classes through which the constructor was
6869  /// inherited to the using shadow declaration in that base class (or a null
6870  /// pointer if the constructor was declared in that base class).
6871  llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6872      InheritedFromBases;
6873
6874public:
6875  InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6876                           ConstructorUsingShadowDecl *Shadow)
6877      : S(S), UseLoc(UseLoc) {
6878    bool DiagnosedMultipleConstructedBases = false;
6879    CXXRecordDecl *ConstructedBase = nullptr;
6880    UsingDecl *ConstructedBaseUsing = nullptr;
6881
6882    // Find the set of such base class subobjects and check that there's a
6883    // unique constructed subobject.
6884    for (auto *D : Shadow->redecls()) {
6885      auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6886      auto *DNominatedBase = DShadow->getNominatedBaseClass();
6887      auto *DConstructedBase = DShadow->getConstructedBaseClass();
6888
6889      InheritedFromBases.insert(
6890          std::make_pair(DNominatedBase->getCanonicalDecl(),
6891                         DShadow->getNominatedBaseClassShadowDecl()));
6892      if (DShadow->constructsVirtualBase())
6893        InheritedFromBases.insert(
6894            std::make_pair(DConstructedBase->getCanonicalDecl(),
6895                           DShadow->getConstructedBaseClassShadowDecl()));
6896      else
6897        assert(DNominatedBase == DConstructedBase);
6898
6899      // [class.inhctor.init]p2:
6900      //   If the constructor was inherited from multiple base class subobjects
6901      //   of type B, the program is ill-formed.
6902      if (!ConstructedBase) {
6903        ConstructedBase = DConstructedBase;
6904        ConstructedBaseUsing = D->getUsingDecl();
6905      } else if (ConstructedBase != DConstructedBase &&
6906                 !Shadow->isInvalidDecl()) {
6907        if (!DiagnosedMultipleConstructedBases) {
6908          S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6909              << Shadow->getTargetDecl();
6910          S.Diag(ConstructedBaseUsing->getLocation(),
6911               diag::note_ambiguous_inherited_constructor_using)
6912              << ConstructedBase;
6913          DiagnosedMultipleConstructedBases = true;
6914        }
6915        S.Diag(D->getUsingDecl()->getLocation(),
6916               diag::note_ambiguous_inherited_constructor_using)
6917            << DConstructedBase;
6918      }
6919    }
6920
6921    if (DiagnosedMultipleConstructedBases)
6922      Shadow->setInvalidDecl();
6923  }
6924
6925  /// Find the constructor to use for inherited construction of a base class,
6926  /// and whether that base class constructor inherits the constructor from a
6927  /// virtual base class (in which case it won't actually invoke it).
6928  std::pair<CXXConstructorDecl *, bool>
6929  findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6930    auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6931    if (It == InheritedFromBases.end())
6932      return std::make_pair(nullptr, false);
6933
6934    // This is an intermediary class.
6935    if (It->second)
6936      return std::make_pair(
6937          S.findInheritingConstructor(UseLoc, Ctor, It->second),
6938          It->second->constructsVirtualBase());
6939
6940    // This is the base class from which the constructor was inherited.
6941    return std::make_pair(Ctor, false);
6942  }
6943};
6944
6945/// Is the special member function which would be selected to perform the
6946/// specified operation on the specified class type a constexpr constructor?
6947static bool
6948specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6949                         Sema::CXXSpecialMember CSM, unsigned Quals,
6950                         bool ConstRHS,
6951                         CXXConstructorDecl *InheritedCtor = nullptr,
6952                         Sema::InheritedConstructorInfo *Inherited = nullptr) {
6953  // If we're inheriting a constructor, see if we need to call it for this base
6954  // class.
6955  if (InheritedCtor) {
6956    assert(CSM == Sema::CXXDefaultConstructor);
6957    auto BaseCtor =
6958        Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6959    if (BaseCtor)
6960      return BaseCtor->isConstexpr();
6961  }
6962
6963  if (CSM == Sema::CXXDefaultConstructor)
6964    return ClassDecl->hasConstexprDefaultConstructor();
6965  if (CSM == Sema::CXXDestructor)
6966    return ClassDecl->hasConstexprDestructor();
6967
6968  Sema::SpecialMemberOverloadResult SMOR =
6969      lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6970  if (!SMOR.getMethod())
6971    // A constructor we wouldn't select can't be "involved in initializing"
6972    // anything.
6973    return true;
6974  return SMOR.getMethod()->isConstexpr();
6975}
6976
6977/// Determine whether the specified special member function would be constexpr
6978/// if it were implicitly defined.
6979static bool defaultedSpecialMemberIsConstexpr(
6980    Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6981    bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6982    Sema::InheritedConstructorInfo *Inherited = nullptr) {
6983  if (!S.getLangOpts().CPlusPlus11)
6984    return false;
6985
6986  // C++11 [dcl.constexpr]p4:
6987  // In the definition of a constexpr constructor [...]
6988  bool Ctor = true;
6989  switch (CSM) {
6990  case Sema::CXXDefaultConstructor:
6991    if (Inherited)
6992      break;
6993    // Since default constructor lookup is essentially trivial (and cannot
6994    // involve, for instance, template instantiation), we compute whether a
6995    // defaulted default constructor is constexpr directly within CXXRecordDecl.
6996    //
6997    // This is important for performance; we need to know whether the default
6998    // constructor is constexpr to determine whether the type is a literal type.
6999    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7000
7001  case Sema::CXXCopyConstructor:
7002  case Sema::CXXMoveConstructor:
7003    // For copy or move constructors, we need to perform overload resolution.
7004    break;
7005
7006  case Sema::CXXCopyAssignment:
7007  case Sema::CXXMoveAssignment:
7008    if (!S.getLangOpts().CPlusPlus14)
7009      return false;
7010    // In C++1y, we need to perform overload resolution.
7011    Ctor = false;
7012    break;
7013
7014  case Sema::CXXDestructor:
7015    return ClassDecl->defaultedDestructorIsConstexpr();
7016
7017  case Sema::CXXInvalid:
7018    return false;
7019  }
7020
7021  //   -- if the class is a non-empty union, or for each non-empty anonymous
7022  //      union member of a non-union class, exactly one non-static data member
7023  //      shall be initialized; [DR1359]
7024  //
7025  // If we squint, this is guaranteed, since exactly one non-static data member
7026  // will be initialized (if the constructor isn't deleted), we just don't know
7027  // which one.
7028  if (Ctor && ClassDecl->isUnion())
7029    return CSM == Sema::CXXDefaultConstructor
7030               ? ClassDecl->hasInClassInitializer() ||
7031                     !ClassDecl->hasVariantMembers()
7032               : true;
7033
7034  //   -- the class shall not have any virtual base classes;
7035  if (Ctor && ClassDecl->getNumVBases())
7036    return false;
7037
7038  // C++1y [class.copy]p26:
7039  //   -- [the class] is a literal type, and
7040  if (!Ctor && !ClassDecl->isLiteral())
7041    return false;
7042
7043  //   -- every constructor involved in initializing [...] base class
7044  //      sub-objects shall be a constexpr constructor;
7045  //   -- the assignment operator selected to copy/move each direct base
7046  //      class is a constexpr function, and
7047  for (const auto &B : ClassDecl->bases()) {
7048    const RecordType *BaseType = B.getType()->getAs<RecordType>();
7049    if (!BaseType) continue;
7050
7051    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7052    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7053                                  InheritedCtor, Inherited))
7054      return false;
7055  }
7056
7057  //   -- every constructor involved in initializing non-static data members
7058  //      [...] shall be a constexpr constructor;
7059  //   -- every non-static data member and base class sub-object shall be
7060  //      initialized
7061  //   -- for each non-static data member of X that is of class type (or array
7062  //      thereof), the assignment operator selected to copy/move that member is
7063  //      a constexpr function
7064  for (const auto *F : ClassDecl->fields()) {
7065    if (F->isInvalidDecl())
7066      continue;
7067    if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7068      continue;
7069    QualType BaseType = S.Context.getBaseElementType(F->getType());
7070    if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7071      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7072      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7073                                    BaseType.getCVRQualifiers(),
7074                                    ConstArg && !F->isMutable()))
7075        return false;
7076    } else if (CSM == Sema::CXXDefaultConstructor) {
7077      return false;
7078    }
7079  }
7080
7081  // All OK, it's constexpr!
7082  return true;
7083}
7084
7085namespace {
7086/// RAII object to register a defaulted function as having its exception
7087/// specification computed.
7088struct ComputingExceptionSpec {
7089  Sema &S;
7090
7091  ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7092      : S(S) {
7093    Sema::CodeSynthesisContext Ctx;
7094    Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7095    Ctx.PointOfInstantiation = Loc;
7096    Ctx.Entity = FD;
7097    S.pushCodeSynthesisContext(Ctx);
7098  }
7099  ~ComputingExceptionSpec() {
7100    S.popCodeSynthesisContext();
7101  }
7102};
7103}
7104
7105static Sema::ImplicitExceptionSpecification
7106ComputeDefaultedSpecialMemberExceptionSpec(
7107    Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7108    Sema::InheritedConstructorInfo *ICI);
7109
7110static Sema::ImplicitExceptionSpecification
7111ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7112                                        FunctionDecl *FD,
7113                                        Sema::DefaultedComparisonKind DCK);
7114
7115static Sema::ImplicitExceptionSpecification
7116computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7117  auto DFK = S.getDefaultedFunctionKind(FD);
7118  if (DFK.isSpecialMember())
7119    return ComputeDefaultedSpecialMemberExceptionSpec(
7120        S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7121  if (DFK.isComparison())
7122    return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7123                                                   DFK.asComparison());
7124
7125  auto *CD = cast<CXXConstructorDecl>(FD);
7126  assert(CD->getInheritedConstructor() &&
7127         "only defaulted functions and inherited constructors have implicit "
7128         "exception specs");
7129  Sema::InheritedConstructorInfo ICI(
7130      S, Loc, CD->getInheritedConstructor().getShadowDecl());
7131  return ComputeDefaultedSpecialMemberExceptionSpec(
7132      S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7133}
7134
7135static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7136                                                            CXXMethodDecl *MD) {
7137  FunctionProtoType::ExtProtoInfo EPI;
7138
7139  // Build an exception specification pointing back at this member.
7140  EPI.ExceptionSpec.Type = EST_Unevaluated;
7141  EPI.ExceptionSpec.SourceDecl = MD;
7142
7143  // Set the calling convention to the default for C++ instance methods.
7144  EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7145      S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7146                                            /*IsCXXMethod=*/true));
7147  return EPI;
7148}
7149
7150void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7151  const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7152  if (FPT->getExceptionSpecType() != EST_Unevaluated)
7153    return;
7154
7155  // Evaluate the exception specification.
7156  auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7157  auto ESI = IES.getExceptionSpec();
7158
7159  // Update the type of the special member to use it.
7160  UpdateExceptionSpec(FD, ESI);
7161}
7162
7163void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7164  assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7165
7166  DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7167  if (!DefKind) {
7168    assert(FD->getDeclContext()->isDependentContext());
7169    return;
7170  }
7171
7172  if (DefKind.isSpecialMember()
7173          ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7174                                                  DefKind.asSpecialMember())
7175          : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7176    FD->setInvalidDecl();
7177}
7178
7179bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7180                                                 CXXSpecialMember CSM) {
7181  CXXRecordDecl *RD = MD->getParent();
7182
7183  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7184         "not an explicitly-defaulted special member");
7185
7186  // Defer all checking for special members of a dependent type.
7187  if (RD->isDependentType())
7188    return false;
7189
7190  // Whether this was the first-declared instance of the constructor.
7191  // This affects whether we implicitly add an exception spec and constexpr.
7192  bool First = MD == MD->getCanonicalDecl();
7193
7194  bool HadError = false;
7195
7196  // C++11 [dcl.fct.def.default]p1:
7197  //   A function that is explicitly defaulted shall
7198  //     -- be a special member function [...] (checked elsewhere),
7199  //     -- have the same type (except for ref-qualifiers, and except that a
7200  //        copy operation can take a non-const reference) as an implicit
7201  //        declaration, and
7202  //     -- not have default arguments.
7203  // C++2a changes the second bullet to instead delete the function if it's
7204  // defaulted on its first declaration, unless it's "an assignment operator,
7205  // and its return type differs or its parameter type is not a reference".
7206  bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7207  bool ShouldDeleteForTypeMismatch = false;
7208  unsigned ExpectedParams = 1;
7209  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7210    ExpectedParams = 0;
7211  if (MD->getNumParams() != ExpectedParams) {
7212    // This checks for default arguments: a copy or move constructor with a
7213    // default argument is classified as a default constructor, and assignment
7214    // operations and destructors can't have default arguments.
7215    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7216      << CSM << MD->getSourceRange();
7217    HadError = true;
7218  } else if (MD->isVariadic()) {
7219    if (DeleteOnTypeMismatch)
7220      ShouldDeleteForTypeMismatch = true;
7221    else {
7222      Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7223        << CSM << MD->getSourceRange();
7224      HadError = true;
7225    }
7226  }
7227
7228  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7229
7230  bool CanHaveConstParam = false;
7231  if (CSM == CXXCopyConstructor)
7232    CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7233  else if (CSM == CXXCopyAssignment)
7234    CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7235
7236  QualType ReturnType = Context.VoidTy;
7237  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7238    // Check for return type matching.
7239    ReturnType = Type->getReturnType();
7240
7241    QualType DeclType = Context.getTypeDeclType(RD);
7242    DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7243    QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7244
7245    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7246      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7247        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7248      HadError = true;
7249    }
7250
7251    // A defaulted special member cannot have cv-qualifiers.
7252    if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7253      if (DeleteOnTypeMismatch)
7254        ShouldDeleteForTypeMismatch = true;
7255      else {
7256        Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7257          << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7258        HadError = true;
7259      }
7260    }
7261  }
7262
7263  // Check for parameter type matching.
7264  QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7265  bool HasConstParam = false;
7266  if (ExpectedParams && ArgType->isReferenceType()) {
7267    // Argument must be reference to possibly-const T.
7268    QualType ReferentType = ArgType->getPointeeType();
7269    HasConstParam = ReferentType.isConstQualified();
7270
7271    if (ReferentType.isVolatileQualified()) {
7272      if (DeleteOnTypeMismatch)
7273        ShouldDeleteForTypeMismatch = true;
7274      else {
7275        Diag(MD->getLocation(),
7276             diag::err_defaulted_special_member_volatile_param) << CSM;
7277        HadError = true;
7278      }
7279    }
7280
7281    if (HasConstParam && !CanHaveConstParam) {
7282      if (DeleteOnTypeMismatch)
7283        ShouldDeleteForTypeMismatch = true;
7284      else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7285        Diag(MD->getLocation(),
7286             diag::err_defaulted_special_member_copy_const_param)
7287          << (CSM == CXXCopyAssignment);
7288        // FIXME: Explain why this special member can't be const.
7289        HadError = true;
7290      } else {
7291        Diag(MD->getLocation(),
7292             diag::err_defaulted_special_member_move_const_param)
7293          << (CSM == CXXMoveAssignment);
7294        HadError = true;
7295      }
7296    }
7297  } else if (ExpectedParams) {
7298    // A copy assignment operator can take its argument by value, but a
7299    // defaulted one cannot.
7300    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7301    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7302    HadError = true;
7303  }
7304
7305  // C++11 [dcl.fct.def.default]p2:
7306  //   An explicitly-defaulted function may be declared constexpr only if it
7307  //   would have been implicitly declared as constexpr,
7308  // Do not apply this rule to members of class templates, since core issue 1358
7309  // makes such functions always instantiate to constexpr functions. For
7310  // functions which cannot be constexpr (for non-constructors in C++11 and for
7311  // destructors in C++14 and C++17), this is checked elsewhere.
7312  //
7313  // FIXME: This should not apply if the member is deleted.
7314  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7315                                                     HasConstParam);
7316  if ((getLangOpts().CPlusPlus20 ||
7317       (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7318                                  : isa<CXXConstructorDecl>(MD))) &&
7319      MD->isConstexpr() && !Constexpr &&
7320      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7321    Diag(MD->getBeginLoc(), MD->isConsteval()
7322                                ? diag::err_incorrect_defaulted_consteval
7323                                : diag::err_incorrect_defaulted_constexpr)
7324        << CSM;
7325    // FIXME: Explain why the special member can't be constexpr.
7326    HadError = true;
7327  }
7328
7329  if (First) {
7330    // C++2a [dcl.fct.def.default]p3:
7331    //   If a function is explicitly defaulted on its first declaration, it is
7332    //   implicitly considered to be constexpr if the implicit declaration
7333    //   would be.
7334    MD->setConstexprKind(
7335        Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr)
7336                  : CSK_unspecified);
7337
7338    if (!Type->hasExceptionSpec()) {
7339      // C++2a [except.spec]p3:
7340      //   If a declaration of a function does not have a noexcept-specifier
7341      //   [and] is defaulted on its first declaration, [...] the exception
7342      //   specification is as specified below
7343      FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7344      EPI.ExceptionSpec.Type = EST_Unevaluated;
7345      EPI.ExceptionSpec.SourceDecl = MD;
7346      MD->setType(Context.getFunctionType(ReturnType,
7347                                          llvm::makeArrayRef(&ArgType,
7348                                                             ExpectedParams),
7349                                          EPI));
7350    }
7351  }
7352
7353  if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7354    if (First) {
7355      SetDeclDeleted(MD, MD->getLocation());
7356      if (!inTemplateInstantiation() && !HadError) {
7357        Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7358        if (ShouldDeleteForTypeMismatch) {
7359          Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7360        } else {
7361          ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7362        }
7363      }
7364      if (ShouldDeleteForTypeMismatch && !HadError) {
7365        Diag(MD->getLocation(),
7366             diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7367      }
7368    } else {
7369      // C++11 [dcl.fct.def.default]p4:
7370      //   [For a] user-provided explicitly-defaulted function [...] if such a
7371      //   function is implicitly defined as deleted, the program is ill-formed.
7372      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7373      assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7374      ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7375      HadError = true;
7376    }
7377  }
7378
7379  return HadError;
7380}
7381
7382namespace {
7383/// Helper class for building and checking a defaulted comparison.
7384///
7385/// Defaulted functions are built in two phases:
7386///
7387///  * First, the set of operations that the function will perform are
7388///    identified, and some of them are checked. If any of the checked
7389///    operations is invalid in certain ways, the comparison function is
7390///    defined as deleted and no body is built.
7391///  * Then, if the function is not defined as deleted, the body is built.
7392///
7393/// This is accomplished by performing two visitation steps over the eventual
7394/// body of the function.
7395template<typename Derived, typename ResultList, typename Result,
7396         typename Subobject>
7397class DefaultedComparisonVisitor {
7398public:
7399  using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7400
7401  DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7402                             DefaultedComparisonKind DCK)
7403      : S(S), RD(RD), FD(FD), DCK(DCK) {
7404    if (auto *Info = FD->getDefaultedFunctionInfo()) {
7405      // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7406      // UnresolvedSet to avoid this copy.
7407      Fns.assign(Info->getUnqualifiedLookups().begin(),
7408                 Info->getUnqualifiedLookups().end());
7409    }
7410  }
7411
7412  ResultList visit() {
7413    // The type of an lvalue naming a parameter of this function.
7414    QualType ParamLvalType =
7415        FD->getParamDecl(0)->getType().getNonReferenceType();
7416
7417    ResultList Results;
7418
7419    switch (DCK) {
7420    case DefaultedComparisonKind::None:
7421      llvm_unreachable("not a defaulted comparison");
7422
7423    case DefaultedComparisonKind::Equal:
7424    case DefaultedComparisonKind::ThreeWay:
7425      getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7426      return Results;
7427
7428    case DefaultedComparisonKind::NotEqual:
7429    case DefaultedComparisonKind::Relational:
7430      Results.add(getDerived().visitExpandedSubobject(
7431          ParamLvalType, getDerived().getCompleteObject()));
7432      return Results;
7433    }
7434    llvm_unreachable("");
7435  }
7436
7437protected:
7438  Derived &getDerived() { return static_cast<Derived&>(*this); }
7439
7440  /// Visit the expanded list of subobjects of the given type, as specified in
7441  /// C++2a [class.compare.default].
7442  ///
7443  /// \return \c true if the ResultList object said we're done, \c false if not.
7444  bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7445                       Qualifiers Quals) {
7446    // C++2a [class.compare.default]p4:
7447    //   The direct base class subobjects of C
7448    for (CXXBaseSpecifier &Base : Record->bases())
7449      if (Results.add(getDerived().visitSubobject(
7450              S.Context.getQualifiedType(Base.getType(), Quals),
7451              getDerived().getBase(&Base))))
7452        return true;
7453
7454    //   followed by the non-static data members of C
7455    for (FieldDecl *Field : Record->fields()) {
7456      // Recursively expand anonymous structs.
7457      if (Field->isAnonymousStructOrUnion()) {
7458        if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7459                            Quals))
7460          return true;
7461        continue;
7462      }
7463
7464      // Figure out the type of an lvalue denoting this field.
7465      Qualifiers FieldQuals = Quals;
7466      if (Field->isMutable())
7467        FieldQuals.removeConst();
7468      QualType FieldType =
7469          S.Context.getQualifiedType(Field->getType(), FieldQuals);
7470
7471      if (Results.add(getDerived().visitSubobject(
7472              FieldType, getDerived().getField(Field))))
7473        return true;
7474    }
7475
7476    //   form a list of subobjects.
7477    return false;
7478  }
7479
7480  Result visitSubobject(QualType Type, Subobject Subobj) {
7481    //   In that list, any subobject of array type is recursively expanded
7482    const ArrayType *AT = S.Context.getAsArrayType(Type);
7483    if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7484      return getDerived().visitSubobjectArray(CAT->getElementType(),
7485                                              CAT->getSize(), Subobj);
7486    return getDerived().visitExpandedSubobject(Type, Subobj);
7487  }
7488
7489  Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7490                             Subobject Subobj) {
7491    return getDerived().visitSubobject(Type, Subobj);
7492  }
7493
7494protected:
7495  Sema &S;
7496  CXXRecordDecl *RD;
7497  FunctionDecl *FD;
7498  DefaultedComparisonKind DCK;
7499  UnresolvedSet<16> Fns;
7500};
7501
7502/// Information about a defaulted comparison, as determined by
7503/// DefaultedComparisonAnalyzer.
7504struct DefaultedComparisonInfo {
7505  bool Deleted = false;
7506  bool Constexpr = true;
7507  ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7508
7509  static DefaultedComparisonInfo deleted() {
7510    DefaultedComparisonInfo Deleted;
7511    Deleted.Deleted = true;
7512    return Deleted;
7513  }
7514
7515  bool add(const DefaultedComparisonInfo &R) {
7516    Deleted |= R.Deleted;
7517    Constexpr &= R.Constexpr;
7518    Category = commonComparisonType(Category, R.Category);
7519    return Deleted;
7520  }
7521};
7522
7523/// An element in the expanded list of subobjects of a defaulted comparison, as
7524/// specified in C++2a [class.compare.default]p4.
7525struct DefaultedComparisonSubobject {
7526  enum { CompleteObject, Member, Base } Kind;
7527  NamedDecl *Decl;
7528  SourceLocation Loc;
7529};
7530
7531/// A visitor over the notional body of a defaulted comparison that determines
7532/// whether that body would be deleted or constexpr.
7533class DefaultedComparisonAnalyzer
7534    : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7535                                        DefaultedComparisonInfo,
7536                                        DefaultedComparisonInfo,
7537                                        DefaultedComparisonSubobject> {
7538public:
7539  enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7540
7541private:
7542  DiagnosticKind Diagnose;
7543
7544public:
7545  using Base = DefaultedComparisonVisitor;
7546  using Result = DefaultedComparisonInfo;
7547  using Subobject = DefaultedComparisonSubobject;
7548
7549  friend Base;
7550
7551  DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7552                              DefaultedComparisonKind DCK,
7553                              DiagnosticKind Diagnose = NoDiagnostics)
7554      : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7555
7556  Result visit() {
7557    if ((DCK == DefaultedComparisonKind::Equal ||
7558         DCK == DefaultedComparisonKind::ThreeWay) &&
7559        RD->hasVariantMembers()) {
7560      // C++2a [class.compare.default]p2 [P2002R0]:
7561      //   A defaulted comparison operator function for class C is defined as
7562      //   deleted if [...] C has variant members.
7563      if (Diagnose == ExplainDeleted) {
7564        S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7565          << FD << RD->isUnion() << RD;
7566      }
7567      return Result::deleted();
7568    }
7569
7570    return Base::visit();
7571  }
7572
7573private:
7574  Subobject getCompleteObject() {
7575    return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7576  }
7577
7578  Subobject getBase(CXXBaseSpecifier *Base) {
7579    return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7580                     Base->getBaseTypeLoc()};
7581  }
7582
7583  Subobject getField(FieldDecl *Field) {
7584    return Subobject{Subobject::Member, Field, Field->getLocation()};
7585  }
7586
7587  Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7588    // C++2a [class.compare.default]p2 [P2002R0]:
7589    //   A defaulted <=> or == operator function for class C is defined as
7590    //   deleted if any non-static data member of C is of reference type
7591    if (Type->isReferenceType()) {
7592      if (Diagnose == ExplainDeleted) {
7593        S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7594            << FD << RD;
7595      }
7596      return Result::deleted();
7597    }
7598
7599    // [...] Let xi be an lvalue denoting the ith element [...]
7600    OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7601    Expr *Args[] = {&Xi, &Xi};
7602
7603    // All operators start by trying to apply that same operator recursively.
7604    OverloadedOperatorKind OO = FD->getOverloadedOperator();
7605    assert(OO != OO_None && "not an overloaded operator!");
7606    return visitBinaryOperator(OO, Args, Subobj);
7607  }
7608
7609  Result
7610  visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7611                      Subobject Subobj,
7612                      OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7613    // Note that there is no need to consider rewritten candidates here if
7614    // we've already found there is no viable 'operator<=>' candidate (and are
7615    // considering synthesizing a '<=>' from '==' and '<').
7616    OverloadCandidateSet CandidateSet(
7617        FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7618        OverloadCandidateSet::OperatorRewriteInfo(
7619            OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7620
7621    /// C++2a [class.compare.default]p1 [P2002R0]:
7622    ///   [...] the defaulted function itself is never a candidate for overload
7623    ///   resolution [...]
7624    CandidateSet.exclude(FD);
7625
7626    if (Args[0]->getType()->isOverloadableType())
7627      S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7628    else {
7629      // FIXME: We determine whether this is a valid expression by checking to
7630      // see if there's a viable builtin operator candidate for it. That isn't
7631      // really what the rules ask us to do, but should give the right results.
7632      S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7633    }
7634
7635    Result R;
7636
7637    OverloadCandidateSet::iterator Best;
7638    switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7639    case OR_Success: {
7640      // C++2a [class.compare.secondary]p2 [P2002R0]:
7641      //   The operator function [...] is defined as deleted if [...] the
7642      //   candidate selected by overload resolution is not a rewritten
7643      //   candidate.
7644      if ((DCK == DefaultedComparisonKind::NotEqual ||
7645           DCK == DefaultedComparisonKind::Relational) &&
7646          !Best->RewriteKind) {
7647        if (Diagnose == ExplainDeleted) {
7648          S.Diag(Best->Function->getLocation(),
7649                 diag::note_defaulted_comparison_not_rewritten_callee)
7650              << FD;
7651        }
7652        return Result::deleted();
7653      }
7654
7655      // Throughout C++2a [class.compare]: if overload resolution does not
7656      // result in a usable function, the candidate function is defined as
7657      // deleted. This requires that we selected an accessible function.
7658      //
7659      // Note that this only considers the access of the function when named
7660      // within the type of the subobject, and not the access path for any
7661      // derived-to-base conversion.
7662      CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7663      if (ArgClass && Best->FoundDecl.getDecl() &&
7664          Best->FoundDecl.getDecl()->isCXXClassMember()) {
7665        QualType ObjectType = Subobj.Kind == Subobject::Member
7666                                  ? Args[0]->getType()
7667                                  : S.Context.getRecordType(RD);
7668        if (!S.isMemberAccessibleForDeletion(
7669                ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7670                Diagnose == ExplainDeleted
7671                    ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7672                          << FD << Subobj.Kind << Subobj.Decl
7673                    : S.PDiag()))
7674          return Result::deleted();
7675      }
7676
7677      // C++2a [class.compare.default]p3 [P2002R0]:
7678      //   A defaulted comparison function is constexpr-compatible if [...]
7679      //   no overlod resolution performed [...] results in a non-constexpr
7680      //   function.
7681      if (FunctionDecl *BestFD = Best->Function) {
7682        assert(!BestFD->isDeleted() && "wrong overload resolution result");
7683        // If it's not constexpr, explain why not.
7684        if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7685          if (Subobj.Kind != Subobject::CompleteObject)
7686            S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7687              << Subobj.Kind << Subobj.Decl;
7688          S.Diag(BestFD->getLocation(),
7689                 diag::note_defaulted_comparison_not_constexpr_here);
7690          // Bail out after explaining; we don't want any more notes.
7691          return Result::deleted();
7692        }
7693        R.Constexpr &= BestFD->isConstexpr();
7694      }
7695
7696      if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7697        if (auto *BestFD = Best->Function) {
7698          // If any callee has an undeduced return type, deduce it now.
7699          // FIXME: It's not clear how a failure here should be handled. For
7700          // now, we produce an eager diagnostic, because that is forward
7701          // compatible with most (all?) other reasonable options.
7702          if (BestFD->getReturnType()->isUndeducedType() &&
7703              S.DeduceReturnType(BestFD, FD->getLocation(),
7704                                 /*Diagnose=*/false)) {
7705            // Don't produce a duplicate error when asked to explain why the
7706            // comparison is deleted: we diagnosed that when initially checking
7707            // the defaulted operator.
7708            if (Diagnose == NoDiagnostics) {
7709              S.Diag(
7710                  FD->getLocation(),
7711                  diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7712                  << Subobj.Kind << Subobj.Decl;
7713              S.Diag(
7714                  Subobj.Loc,
7715                  diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7716                  << Subobj.Kind << Subobj.Decl;
7717              S.Diag(BestFD->getLocation(),
7718                     diag::note_defaulted_comparison_cannot_deduce_callee)
7719                  << Subobj.Kind << Subobj.Decl;
7720            }
7721            return Result::deleted();
7722          }
7723          if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7724              BestFD->getCallResultType())) {
7725            R.Category = Info->Kind;
7726          } else {
7727            if (Diagnose == ExplainDeleted) {
7728              S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7729                  << Subobj.Kind << Subobj.Decl
7730                  << BestFD->getCallResultType().withoutLocalFastQualifiers();
7731              S.Diag(BestFD->getLocation(),
7732                     diag::note_defaulted_comparison_cannot_deduce_callee)
7733                  << Subobj.Kind << Subobj.Decl;
7734            }
7735            return Result::deleted();
7736          }
7737        } else {
7738          Optional<ComparisonCategoryType> Cat =
7739              getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7740          assert(Cat && "no category for builtin comparison?");
7741          R.Category = *Cat;
7742        }
7743      }
7744
7745      // Note that we might be rewriting to a different operator. That call is
7746      // not considered until we come to actually build the comparison function.
7747      break;
7748    }
7749
7750    case OR_Ambiguous:
7751      if (Diagnose == ExplainDeleted) {
7752        unsigned Kind = 0;
7753        if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7754          Kind = OO == OO_EqualEqual ? 1 : 2;
7755        CandidateSet.NoteCandidates(
7756            PartialDiagnosticAt(
7757                Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7758                                << FD << Kind << Subobj.Kind << Subobj.Decl),
7759            S, OCD_AmbiguousCandidates, Args);
7760      }
7761      R = Result::deleted();
7762      break;
7763
7764    case OR_Deleted:
7765      if (Diagnose == ExplainDeleted) {
7766        if ((DCK == DefaultedComparisonKind::NotEqual ||
7767             DCK == DefaultedComparisonKind::Relational) &&
7768            !Best->RewriteKind) {
7769          S.Diag(Best->Function->getLocation(),
7770                 diag::note_defaulted_comparison_not_rewritten_callee)
7771              << FD;
7772        } else {
7773          S.Diag(Subobj.Loc,
7774                 diag::note_defaulted_comparison_calls_deleted)
7775              << FD << Subobj.Kind << Subobj.Decl;
7776          S.NoteDeletedFunction(Best->Function);
7777        }
7778      }
7779      R = Result::deleted();
7780      break;
7781
7782    case OR_No_Viable_Function:
7783      // If there's no usable candidate, we're done unless we can rewrite a
7784      // '<=>' in terms of '==' and '<'.
7785      if (OO == OO_Spaceship &&
7786          S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7787        // For any kind of comparison category return type, we need a usable
7788        // '==' and a usable '<'.
7789        if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7790                                       &CandidateSet)))
7791          R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7792        break;
7793      }
7794
7795      if (Diagnose == ExplainDeleted) {
7796        S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7797            << FD << Subobj.Kind << Subobj.Decl;
7798
7799        // For a three-way comparison, list both the candidates for the
7800        // original operator and the candidates for the synthesized operator.
7801        if (SpaceshipCandidates) {
7802          SpaceshipCandidates->NoteCandidates(
7803              S, Args,
7804              SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7805                                                      Args, FD->getLocation()));
7806          S.Diag(Subobj.Loc,
7807                 diag::note_defaulted_comparison_no_viable_function_synthesized)
7808              << (OO == OO_EqualEqual ? 0 : 1);
7809        }
7810
7811        CandidateSet.NoteCandidates(
7812            S, Args,
7813            CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7814                                            FD->getLocation()));
7815      }
7816      R = Result::deleted();
7817      break;
7818    }
7819
7820    return R;
7821  }
7822};
7823
7824/// A list of statements.
7825struct StmtListResult {
7826  bool IsInvalid = false;
7827  llvm::SmallVector<Stmt*, 16> Stmts;
7828
7829  bool add(const StmtResult &S) {
7830    IsInvalid |= S.isInvalid();
7831    if (IsInvalid)
7832      return true;
7833    Stmts.push_back(S.get());
7834    return false;
7835  }
7836};
7837
7838/// A visitor over the notional body of a defaulted comparison that synthesizes
7839/// the actual body.
7840class DefaultedComparisonSynthesizer
7841    : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7842                                        StmtListResult, StmtResult,
7843                                        std::pair<ExprResult, ExprResult>> {
7844  SourceLocation Loc;
7845  unsigned ArrayDepth = 0;
7846
7847public:
7848  using Base = DefaultedComparisonVisitor;
7849  using ExprPair = std::pair<ExprResult, ExprResult>;
7850
7851  friend Base;
7852
7853  DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7854                                 DefaultedComparisonKind DCK,
7855                                 SourceLocation BodyLoc)
7856      : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7857
7858  /// Build a suitable function body for this defaulted comparison operator.
7859  StmtResult build() {
7860    Sema::CompoundScopeRAII CompoundScope(S);
7861
7862    StmtListResult Stmts = visit();
7863    if (Stmts.IsInvalid)
7864      return StmtError();
7865
7866    ExprResult RetVal;
7867    switch (DCK) {
7868    case DefaultedComparisonKind::None:
7869      llvm_unreachable("not a defaulted comparison");
7870
7871    case DefaultedComparisonKind::Equal: {
7872      // C++2a [class.eq]p3:
7873      //   [...] compar[e] the corresponding elements [...] until the first
7874      //   index i where xi == yi yields [...] false. If no such index exists,
7875      //   V is true. Otherwise, V is false.
7876      //
7877      // Join the comparisons with '&&'s and return the result. Use a right
7878      // fold (traversing the conditions right-to-left), because that
7879      // short-circuits more naturally.
7880      auto OldStmts = std::move(Stmts.Stmts);
7881      Stmts.Stmts.clear();
7882      ExprResult CmpSoFar;
7883      // Finish a particular comparison chain.
7884      auto FinishCmp = [&] {
7885        if (Expr *Prior = CmpSoFar.get()) {
7886          // Convert the last expression to 'return ...;'
7887          if (RetVal.isUnset() && Stmts.Stmts.empty())
7888            RetVal = CmpSoFar;
7889          // Convert any prior comparison to 'if (!(...)) return false;'
7890          else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7891            return true;
7892          CmpSoFar = ExprResult();
7893        }
7894        return false;
7895      };
7896      for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7897        Expr *E = dyn_cast<Expr>(EAsStmt);
7898        if (!E) {
7899          // Found an array comparison.
7900          if (FinishCmp() || Stmts.add(EAsStmt))
7901            return StmtError();
7902          continue;
7903        }
7904
7905        if (CmpSoFar.isUnset()) {
7906          CmpSoFar = E;
7907          continue;
7908        }
7909        CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7910        if (CmpSoFar.isInvalid())
7911          return StmtError();
7912      }
7913      if (FinishCmp())
7914        return StmtError();
7915      std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7916      //   If no such index exists, V is true.
7917      if (RetVal.isUnset())
7918        RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7919      break;
7920    }
7921
7922    case DefaultedComparisonKind::ThreeWay: {
7923      // Per C++2a [class.spaceship]p3, as a fallback add:
7924      // return static_cast<R>(std::strong_ordering::equal);
7925      QualType StrongOrdering = S.CheckComparisonCategoryType(
7926          ComparisonCategoryType::StrongOrdering, Loc,
7927          Sema::ComparisonCategoryUsage::DefaultedOperator);
7928      if (StrongOrdering.isNull())
7929        return StmtError();
7930      VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7931                             .getValueInfo(ComparisonCategoryResult::Equal)
7932                             ->VD;
7933      RetVal = getDecl(EqualVD);
7934      if (RetVal.isInvalid())
7935        return StmtError();
7936      RetVal = buildStaticCastToR(RetVal.get());
7937      break;
7938    }
7939
7940    case DefaultedComparisonKind::NotEqual:
7941    case DefaultedComparisonKind::Relational:
7942      RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7943      break;
7944    }
7945
7946    // Build the final return statement.
7947    if (RetVal.isInvalid())
7948      return StmtError();
7949    StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
7950    if (ReturnStmt.isInvalid())
7951      return StmtError();
7952    Stmts.Stmts.push_back(ReturnStmt.get());
7953
7954    return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
7955  }
7956
7957private:
7958  ExprResult getDecl(ValueDecl *VD) {
7959    return S.BuildDeclarationNameExpr(
7960        CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7961  }
7962
7963  ExprResult getParam(unsigned I) {
7964    ParmVarDecl *PD = FD->getParamDecl(I);
7965    return getDecl(PD);
7966  }
7967
7968  ExprPair getCompleteObject() {
7969    unsigned Param = 0;
7970    ExprResult LHS;
7971    if (isa<CXXMethodDecl>(FD)) {
7972      // LHS is '*this'.
7973      LHS = S.ActOnCXXThis(Loc);
7974      if (!LHS.isInvalid())
7975        LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
7976    } else {
7977      LHS = getParam(Param++);
7978    }
7979    ExprResult RHS = getParam(Param++);
7980    assert(Param == FD->getNumParams());
7981    return {LHS, RHS};
7982  }
7983
7984  ExprPair getBase(CXXBaseSpecifier *Base) {
7985    ExprPair Obj = getCompleteObject();
7986    if (Obj.first.isInvalid() || Obj.second.isInvalid())
7987      return {ExprError(), ExprError()};
7988    CXXCastPath Path = {Base};
7989    return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
7990                                CK_DerivedToBase, VK_LValue, &Path),
7991            S.ImpCastExprToType(Obj.second.get(), Base->getType(),
7992                                CK_DerivedToBase, VK_LValue, &Path)};
7993  }
7994
7995  ExprPair getField(FieldDecl *Field) {
7996    ExprPair Obj = getCompleteObject();
7997    if (Obj.first.isInvalid() || Obj.second.isInvalid())
7998      return {ExprError(), ExprError()};
7999
8000    DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8001    DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8002    return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8003                                      CXXScopeSpec(), Field, Found, NameInfo),
8004            S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8005                                      CXXScopeSpec(), Field, Found, NameInfo)};
8006  }
8007
8008  // FIXME: When expanding a subobject, register a note in the code synthesis
8009  // stack to say which subobject we're comparing.
8010
8011  StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8012    if (Cond.isInvalid())
8013      return StmtError();
8014
8015    ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8016    if (NotCond.isInvalid())
8017      return StmtError();
8018
8019    ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8020    assert(!False.isInvalid() && "should never fail");
8021    StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8022    if (ReturnFalse.isInvalid())
8023      return StmtError();
8024
8025    return S.ActOnIfStmt(Loc, false, nullptr,
8026                         S.ActOnCondition(nullptr, Loc, NotCond.get(),
8027                                          Sema::ConditionKind::Boolean),
8028                         ReturnFalse.get(), SourceLocation(), nullptr);
8029  }
8030
8031  StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8032                                 ExprPair Subobj) {
8033    QualType SizeType = S.Context.getSizeType();
8034    Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8035
8036    // Build 'size_t i$n = 0'.
8037    IdentifierInfo *IterationVarName = nullptr;
8038    {
8039      SmallString<8> Str;
8040      llvm::raw_svector_ostream OS(Str);
8041      OS << "i" << ArrayDepth;
8042      IterationVarName = &S.Context.Idents.get(OS.str());
8043    }
8044    VarDecl *IterationVar = VarDecl::Create(
8045        S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8046        S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8047    llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8048    IterationVar->setInit(
8049        IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8050    Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8051
8052    auto IterRef = [&] {
8053      ExprResult Ref = S.BuildDeclarationNameExpr(
8054          CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8055          IterationVar);
8056      assert(!Ref.isInvalid() && "can't reference our own variable?");
8057      return Ref.get();
8058    };
8059
8060    // Build 'i$n != Size'.
8061    ExprResult Cond = S.CreateBuiltinBinOp(
8062        Loc, BO_NE, IterRef(),
8063        IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8064    assert(!Cond.isInvalid() && "should never fail");
8065
8066    // Build '++i$n'.
8067    ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8068    assert(!Inc.isInvalid() && "should never fail");
8069
8070    // Build 'a[i$n]' and 'b[i$n]'.
8071    auto Index = [&](ExprResult E) {
8072      if (E.isInvalid())
8073        return ExprError();
8074      return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8075    };
8076    Subobj.first = Index(Subobj.first);
8077    Subobj.second = Index(Subobj.second);
8078
8079    // Compare the array elements.
8080    ++ArrayDepth;
8081    StmtResult Substmt = visitSubobject(Type, Subobj);
8082    --ArrayDepth;
8083
8084    if (Substmt.isInvalid())
8085      return StmtError();
8086
8087    // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8088    // For outer levels or for an 'operator<=>' we already have a suitable
8089    // statement that returns as necessary.
8090    if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8091      assert(DCK == DefaultedComparisonKind::Equal &&
8092             "should have non-expression statement");
8093      Substmt = buildIfNotCondReturnFalse(ElemCmp);
8094      if (Substmt.isInvalid())
8095        return StmtError();
8096    }
8097
8098    // Build 'for (...) ...'
8099    return S.ActOnForStmt(Loc, Loc, Init,
8100                          S.ActOnCondition(nullptr, Loc, Cond.get(),
8101                                           Sema::ConditionKind::Boolean),
8102                          S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8103                          Substmt.get());
8104  }
8105
8106  StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8107    if (Obj.first.isInvalid() || Obj.second.isInvalid())
8108      return StmtError();
8109
8110    OverloadedOperatorKind OO = FD->getOverloadedOperator();
8111    BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8112    ExprResult Op;
8113    if (Type->isOverloadableType())
8114      Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8115                                   Obj.second.get(), /*PerformADL=*/true,
8116                                   /*AllowRewrittenCandidates=*/true, FD);
8117    else
8118      Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8119    if (Op.isInvalid())
8120      return StmtError();
8121
8122    switch (DCK) {
8123    case DefaultedComparisonKind::None:
8124      llvm_unreachable("not a defaulted comparison");
8125
8126    case DefaultedComparisonKind::Equal:
8127      // Per C++2a [class.eq]p2, each comparison is individually contextually
8128      // converted to bool.
8129      Op = S.PerformContextuallyConvertToBool(Op.get());
8130      if (Op.isInvalid())
8131        return StmtError();
8132      return Op.get();
8133
8134    case DefaultedComparisonKind::ThreeWay: {
8135      // Per C++2a [class.spaceship]p3, form:
8136      //   if (R cmp = static_cast<R>(op); cmp != 0)
8137      //     return cmp;
8138      QualType R = FD->getReturnType();
8139      Op = buildStaticCastToR(Op.get());
8140      if (Op.isInvalid())
8141        return StmtError();
8142
8143      // R cmp = ...;
8144      IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8145      VarDecl *VD =
8146          VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8147                          S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8148      S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8149      Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8150
8151      // cmp != 0
8152      ExprResult VDRef = getDecl(VD);
8153      if (VDRef.isInvalid())
8154        return StmtError();
8155      llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8156      Expr *Zero =
8157          IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8158      ExprResult Comp;
8159      if (VDRef.get()->getType()->isOverloadableType())
8160        Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8161                                       true, FD);
8162      else
8163        Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8164      if (Comp.isInvalid())
8165        return StmtError();
8166      Sema::ConditionResult Cond = S.ActOnCondition(
8167          nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8168      if (Cond.isInvalid())
8169        return StmtError();
8170
8171      // return cmp;
8172      VDRef = getDecl(VD);
8173      if (VDRef.isInvalid())
8174        return StmtError();
8175      StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8176      if (ReturnStmt.isInvalid())
8177        return StmtError();
8178
8179      // if (...)
8180      return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, InitStmt, Cond,
8181                           ReturnStmt.get(), /*ElseLoc=*/SourceLocation(),
8182                           /*Else=*/nullptr);
8183    }
8184
8185    case DefaultedComparisonKind::NotEqual:
8186    case DefaultedComparisonKind::Relational:
8187      // C++2a [class.compare.secondary]p2:
8188      //   Otherwise, the operator function yields x @ y.
8189      return Op.get();
8190    }
8191    llvm_unreachable("");
8192  }
8193
8194  /// Build "static_cast<R>(E)".
8195  ExprResult buildStaticCastToR(Expr *E) {
8196    QualType R = FD->getReturnType();
8197    assert(!R->isUndeducedType() && "type should have been deduced already");
8198
8199    // Don't bother forming a no-op cast in the common case.
8200    if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8201      return E;
8202    return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8203                               S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8204                               SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8205  }
8206};
8207}
8208
8209/// Perform the unqualified lookups that might be needed to form a defaulted
8210/// comparison function for the given operator.
8211static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8212                                                  UnresolvedSetImpl &Operators,
8213                                                  OverloadedOperatorKind Op) {
8214  auto Lookup = [&](OverloadedOperatorKind OO) {
8215    Self.LookupOverloadedOperatorName(OO, S, QualType(), QualType(), Operators);
8216  };
8217
8218  // Every defaulted operator looks up itself.
8219  Lookup(Op);
8220  // ... and the rewritten form of itself, if any.
8221  if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8222    Lookup(ExtraOp);
8223
8224  // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8225  // synthesize a three-way comparison from '<' and '=='. In a dependent
8226  // context, we also need to look up '==' in case we implicitly declare a
8227  // defaulted 'operator=='.
8228  if (Op == OO_Spaceship) {
8229    Lookup(OO_ExclaimEqual);
8230    Lookup(OO_Less);
8231    Lookup(OO_EqualEqual);
8232  }
8233}
8234
8235bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8236                                              DefaultedComparisonKind DCK) {
8237  assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8238
8239  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8240  assert(RD && "defaulted comparison is not defaulted in a class");
8241
8242  // Perform any unqualified lookups we're going to need to default this
8243  // function.
8244  if (S) {
8245    UnresolvedSet<32> Operators;
8246    lookupOperatorsForDefaultedComparison(*this, S, Operators,
8247                                          FD->getOverloadedOperator());
8248    FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8249        Context, Operators.pairs()));
8250  }
8251
8252  // C++2a [class.compare.default]p1:
8253  //   A defaulted comparison operator function for some class C shall be a
8254  //   non-template function declared in the member-specification of C that is
8255  //    -- a non-static const member of C having one parameter of type
8256  //       const C&, or
8257  //    -- a friend of C having two parameters of type const C& or two
8258  //       parameters of type C.
8259  QualType ExpectedParmType1 = Context.getRecordType(RD);
8260  QualType ExpectedParmType2 =
8261      Context.getLValueReferenceType(ExpectedParmType1.withConst());
8262  if (isa<CXXMethodDecl>(FD))
8263    ExpectedParmType1 = ExpectedParmType2;
8264  for (const ParmVarDecl *Param : FD->parameters()) {
8265    if (!Param->getType()->isDependentType() &&
8266        !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8267        !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8268      // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8269      // corresponding defaulted 'operator<=>' already.
8270      if (!FD->isImplicit()) {
8271        Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8272            << (int)DCK << Param->getType() << ExpectedParmType1
8273            << !isa<CXXMethodDecl>(FD)
8274            << ExpectedParmType2 << Param->getSourceRange();
8275      }
8276      return true;
8277    }
8278  }
8279  if (FD->getNumParams() == 2 &&
8280      !Context.hasSameType(FD->getParamDecl(0)->getType(),
8281                           FD->getParamDecl(1)->getType())) {
8282    if (!FD->isImplicit()) {
8283      Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8284          << (int)DCK
8285          << FD->getParamDecl(0)->getType()
8286          << FD->getParamDecl(0)->getSourceRange()
8287          << FD->getParamDecl(1)->getType()
8288          << FD->getParamDecl(1)->getSourceRange();
8289    }
8290    return true;
8291  }
8292
8293  // ... non-static const member ...
8294  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8295    assert(!MD->isStatic() && "comparison function cannot be a static member");
8296    if (!MD->isConst()) {
8297      SourceLocation InsertLoc;
8298      if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8299        InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8300      // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8301      // corresponding defaulted 'operator<=>' already.
8302      if (!MD->isImplicit()) {
8303        Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8304          << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8305      }
8306
8307      // Add the 'const' to the type to recover.
8308      const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8309      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8310      EPI.TypeQuals.addConst();
8311      MD->setType(Context.getFunctionType(FPT->getReturnType(),
8312                                          FPT->getParamTypes(), EPI));
8313    }
8314  } else {
8315    // A non-member function declared in a class must be a friend.
8316    assert(FD->getFriendObjectKind() && "expected a friend declaration");
8317  }
8318
8319  // C++2a [class.eq]p1, [class.rel]p1:
8320  //   A [defaulted comparison other than <=>] shall have a declared return
8321  //   type bool.
8322  if (DCK != DefaultedComparisonKind::ThreeWay &&
8323      !FD->getDeclaredReturnType()->isDependentType() &&
8324      !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8325    Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8326        << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8327        << FD->getReturnTypeSourceRange();
8328    return true;
8329  }
8330  // C++2a [class.spaceship]p2 [P2002R0]:
8331  //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8332  //   R shall not contain a placeholder type.
8333  if (DCK == DefaultedComparisonKind::ThreeWay &&
8334      FD->getDeclaredReturnType()->getContainedDeducedType() &&
8335      !Context.hasSameType(FD->getDeclaredReturnType(),
8336                           Context.getAutoDeductType())) {
8337    Diag(FD->getLocation(),
8338         diag::err_defaulted_comparison_deduced_return_type_not_auto)
8339        << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8340        << FD->getReturnTypeSourceRange();
8341    return true;
8342  }
8343
8344  // For a defaulted function in a dependent class, defer all remaining checks
8345  // until instantiation.
8346  if (RD->isDependentType())
8347    return false;
8348
8349  // Determine whether the function should be defined as deleted.
8350  DefaultedComparisonInfo Info =
8351      DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8352
8353  bool First = FD == FD->getCanonicalDecl();
8354
8355  // If we want to delete the function, then do so; there's nothing else to
8356  // check in that case.
8357  if (Info.Deleted) {
8358    if (!First) {
8359      // C++11 [dcl.fct.def.default]p4:
8360      //   [For a] user-provided explicitly-defaulted function [...] if such a
8361      //   function is implicitly defined as deleted, the program is ill-formed.
8362      //
8363      // This is really just a consequence of the general rule that you can
8364      // only delete a function on its first declaration.
8365      Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8366          << FD->isImplicit() << (int)DCK;
8367      DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8368                                  DefaultedComparisonAnalyzer::ExplainDeleted)
8369          .visit();
8370      return true;
8371    }
8372
8373    SetDeclDeleted(FD, FD->getLocation());
8374    if (!inTemplateInstantiation() && !FD->isImplicit()) {
8375      Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8376          << (int)DCK;
8377      DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8378                                  DefaultedComparisonAnalyzer::ExplainDeleted)
8379          .visit();
8380    }
8381    return false;
8382  }
8383
8384  // C++2a [class.spaceship]p2:
8385  //   The return type is deduced as the common comparison type of R0, R1, ...
8386  if (DCK == DefaultedComparisonKind::ThreeWay &&
8387      FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8388    SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8389    if (RetLoc.isInvalid())
8390      RetLoc = FD->getBeginLoc();
8391    // FIXME: Should we really care whether we have the complete type and the
8392    // 'enumerator' constants here? A forward declaration seems sufficient.
8393    QualType Cat = CheckComparisonCategoryType(
8394        Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8395    if (Cat.isNull())
8396      return true;
8397    Context.adjustDeducedFunctionResultType(
8398        FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8399  }
8400
8401  // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8402  //   An explicitly-defaulted function that is not defined as deleted may be
8403  //   declared constexpr or consteval only if it is constexpr-compatible.
8404  // C++2a [class.compare.default]p3 [P2002R0]:
8405  //   A defaulted comparison function is constexpr-compatible if it satisfies
8406  //   the requirements for a constexpr function [...]
8407  // The only relevant requirements are that the parameter and return types are
8408  // literal types. The remaining conditions are checked by the analyzer.
8409  if (FD->isConstexpr()) {
8410    if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8411        CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8412        !Info.Constexpr) {
8413      Diag(FD->getBeginLoc(),
8414           diag::err_incorrect_defaulted_comparison_constexpr)
8415          << FD->isImplicit() << (int)DCK << FD->isConsteval();
8416      DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8417                                  DefaultedComparisonAnalyzer::ExplainConstexpr)
8418          .visit();
8419    }
8420  }
8421
8422  // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8423  //   If a constexpr-compatible function is explicitly defaulted on its first
8424  //   declaration, it is implicitly considered to be constexpr.
8425  // FIXME: Only applying this to the first declaration seems problematic, as
8426  // simple reorderings can affect the meaning of the program.
8427  if (First && !FD->isConstexpr() && Info.Constexpr)
8428    FD->setConstexprKind(CSK_constexpr);
8429
8430  // C++2a [except.spec]p3:
8431  //   If a declaration of a function does not have a noexcept-specifier
8432  //   [and] is defaulted on its first declaration, [...] the exception
8433  //   specification is as specified below
8434  if (FD->getExceptionSpecType() == EST_None) {
8435    auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8436    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8437    EPI.ExceptionSpec.Type = EST_Unevaluated;
8438    EPI.ExceptionSpec.SourceDecl = FD;
8439    FD->setType(Context.getFunctionType(FPT->getReturnType(),
8440                                        FPT->getParamTypes(), EPI));
8441  }
8442
8443  return false;
8444}
8445
8446void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8447                                             FunctionDecl *Spaceship) {
8448  Sema::CodeSynthesisContext Ctx;
8449  Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8450  Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8451  Ctx.Entity = Spaceship;
8452  pushCodeSynthesisContext(Ctx);
8453
8454  if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8455    EqualEqual->setImplicit();
8456
8457  popCodeSynthesisContext();
8458}
8459
8460void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8461                                     DefaultedComparisonKind DCK) {
8462  assert(FD->isDefaulted() && !FD->isDeleted() &&
8463         !FD->doesThisDeclarationHaveABody());
8464  if (FD->willHaveBody() || FD->isInvalidDecl())
8465    return;
8466
8467  SynthesizedFunctionScope Scope(*this, FD);
8468
8469  // Add a context note for diagnostics produced after this point.
8470  Scope.addContextNote(UseLoc);
8471
8472  {
8473    // Build and set up the function body.
8474    CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8475    SourceLocation BodyLoc =
8476        FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8477    StmtResult Body =
8478        DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8479    if (Body.isInvalid()) {
8480      FD->setInvalidDecl();
8481      return;
8482    }
8483    FD->setBody(Body.get());
8484    FD->markUsed(Context);
8485  }
8486
8487  // The exception specification is needed because we are defining the
8488  // function. Note that this will reuse the body we just built.
8489  ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8490
8491  if (ASTMutationListener *L = getASTMutationListener())
8492    L->CompletedImplicitDefinition(FD);
8493}
8494
8495static Sema::ImplicitExceptionSpecification
8496ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8497                                        FunctionDecl *FD,
8498                                        Sema::DefaultedComparisonKind DCK) {
8499  ComputingExceptionSpec CES(S, FD, Loc);
8500  Sema::ImplicitExceptionSpecification ExceptSpec(S);
8501
8502  if (FD->isInvalidDecl())
8503    return ExceptSpec;
8504
8505  // The common case is that we just defined the comparison function. In that
8506  // case, just look at whether the body can throw.
8507  if (FD->hasBody()) {
8508    ExceptSpec.CalledStmt(FD->getBody());
8509  } else {
8510    // Otherwise, build a body so we can check it. This should ideally only
8511    // happen when we're not actually marking the function referenced. (This is
8512    // only really important for efficiency: we don't want to build and throw
8513    // away bodies for comparison functions more than we strictly need to.)
8514
8515    // Pretend to synthesize the function body in an unevaluated context.
8516    // Note that we can't actually just go ahead and define the function here:
8517    // we are not permitted to mark its callees as referenced.
8518    Sema::SynthesizedFunctionScope Scope(S, FD);
8519    EnterExpressionEvaluationContext Context(
8520        S, Sema::ExpressionEvaluationContext::Unevaluated);
8521
8522    CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8523    SourceLocation BodyLoc =
8524        FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8525    StmtResult Body =
8526        DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8527    if (!Body.isInvalid())
8528      ExceptSpec.CalledStmt(Body.get());
8529
8530    // FIXME: Can we hold onto this body and just transform it to potentially
8531    // evaluated when we're asked to define the function rather than rebuilding
8532    // it? Either that, or we should only build the bits of the body that we
8533    // need (the expressions, not the statements).
8534  }
8535
8536  return ExceptSpec;
8537}
8538
8539void Sema::CheckDelayedMemberExceptionSpecs() {
8540  decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8541  decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8542
8543  std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8544  std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8545
8546  // Perform any deferred checking of exception specifications for virtual
8547  // destructors.
8548  for (auto &Check : Overriding)
8549    CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8550
8551  // Perform any deferred checking of exception specifications for befriended
8552  // special members.
8553  for (auto &Check : Equivalent)
8554    CheckEquivalentExceptionSpec(Check.second, Check.first);
8555}
8556
8557namespace {
8558/// CRTP base class for visiting operations performed by a special member
8559/// function (or inherited constructor).
8560template<typename Derived>
8561struct SpecialMemberVisitor {
8562  Sema &S;
8563  CXXMethodDecl *MD;
8564  Sema::CXXSpecialMember CSM;
8565  Sema::InheritedConstructorInfo *ICI;
8566
8567  // Properties of the special member, computed for convenience.
8568  bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8569
8570  SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8571                       Sema::InheritedConstructorInfo *ICI)
8572      : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8573    switch (CSM) {
8574    case Sema::CXXDefaultConstructor:
8575    case Sema::CXXCopyConstructor:
8576    case Sema::CXXMoveConstructor:
8577      IsConstructor = true;
8578      break;
8579    case Sema::CXXCopyAssignment:
8580    case Sema::CXXMoveAssignment:
8581      IsAssignment = true;
8582      break;
8583    case Sema::CXXDestructor:
8584      break;
8585    case Sema::CXXInvalid:
8586      llvm_unreachable("invalid special member kind");
8587    }
8588
8589    if (MD->getNumParams()) {
8590      if (const ReferenceType *RT =
8591              MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8592        ConstArg = RT->getPointeeType().isConstQualified();
8593    }
8594  }
8595
8596  Derived &getDerived() { return static_cast<Derived&>(*this); }
8597
8598  /// Is this a "move" special member?
8599  bool isMove() const {
8600    return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8601  }
8602
8603  /// Look up the corresponding special member in the given class.
8604  Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8605                                             unsigned Quals, bool IsMutable) {
8606    return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8607                                       ConstArg && !IsMutable);
8608  }
8609
8610  /// Look up the constructor for the specified base class to see if it's
8611  /// overridden due to this being an inherited constructor.
8612  Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8613    if (!ICI)
8614      return {};
8615    assert(CSM == Sema::CXXDefaultConstructor);
8616    auto *BaseCtor =
8617      cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8618    if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8619      return MD;
8620    return {};
8621  }
8622
8623  /// A base or member subobject.
8624  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8625
8626  /// Get the location to use for a subobject in diagnostics.
8627  static SourceLocation getSubobjectLoc(Subobject Subobj) {
8628    // FIXME: For an indirect virtual base, the direct base leading to
8629    // the indirect virtual base would be a more useful choice.
8630    if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8631      return B->getBaseTypeLoc();
8632    else
8633      return Subobj.get<FieldDecl*>()->getLocation();
8634  }
8635
8636  enum BasesToVisit {
8637    /// Visit all non-virtual (direct) bases.
8638    VisitNonVirtualBases,
8639    /// Visit all direct bases, virtual or not.
8640    VisitDirectBases,
8641    /// Visit all non-virtual bases, and all virtual bases if the class
8642    /// is not abstract.
8643    VisitPotentiallyConstructedBases,
8644    /// Visit all direct or virtual bases.
8645    VisitAllBases
8646  };
8647
8648  // Visit the bases and members of the class.
8649  bool visit(BasesToVisit Bases) {
8650    CXXRecordDecl *RD = MD->getParent();
8651
8652    if (Bases == VisitPotentiallyConstructedBases)
8653      Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8654
8655    for (auto &B : RD->bases())
8656      if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8657          getDerived().visitBase(&B))
8658        return true;
8659
8660    if (Bases == VisitAllBases)
8661      for (auto &B : RD->vbases())
8662        if (getDerived().visitBase(&B))
8663          return true;
8664
8665    for (auto *F : RD->fields())
8666      if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8667          getDerived().visitField(F))
8668        return true;
8669
8670    return false;
8671  }
8672};
8673}
8674
8675namespace {
8676struct SpecialMemberDeletionInfo
8677    : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8678  bool Diagnose;
8679
8680  SourceLocation Loc;
8681
8682  bool AllFieldsAreConst;
8683
8684  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8685                            Sema::CXXSpecialMember CSM,
8686                            Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8687      : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8688        Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8689
8690  bool inUnion() const { return MD->getParent()->isUnion(); }
8691
8692  Sema::CXXSpecialMember getEffectiveCSM() {
8693    return ICI ? Sema::CXXInvalid : CSM;
8694  }
8695
8696  bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8697
8698  bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8699  bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8700
8701  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8702  bool shouldDeleteForField(FieldDecl *FD);
8703  bool shouldDeleteForAllConstMembers();
8704
8705  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8706                                     unsigned Quals);
8707  bool shouldDeleteForSubobjectCall(Subobject Subobj,
8708                                    Sema::SpecialMemberOverloadResult SMOR,
8709                                    bool IsDtorCallInCtor);
8710
8711  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8712};
8713}
8714
8715/// Is the given special member inaccessible when used on the given
8716/// sub-object.
8717bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8718                                             CXXMethodDecl *target) {
8719  /// If we're operating on a base class, the object type is the
8720  /// type of this special member.
8721  QualType objectTy;
8722  AccessSpecifier access = target->getAccess();
8723  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8724    objectTy = S.Context.getTypeDeclType(MD->getParent());
8725    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8726
8727  // If we're operating on a field, the object type is the type of the field.
8728  } else {
8729    objectTy = S.Context.getTypeDeclType(target->getParent());
8730  }
8731
8732  return S.isMemberAccessibleForDeletion(
8733      target->getParent(), DeclAccessPair::make(target, access), objectTy);
8734}
8735
8736/// Check whether we should delete a special member due to the implicit
8737/// definition containing a call to a special member of a subobject.
8738bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8739    Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8740    bool IsDtorCallInCtor) {
8741  CXXMethodDecl *Decl = SMOR.getMethod();
8742  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8743
8744  int DiagKind = -1;
8745
8746  if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8747    DiagKind = !Decl ? 0 : 1;
8748  else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8749    DiagKind = 2;
8750  else if (!isAccessible(Subobj, Decl))
8751    DiagKind = 3;
8752  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8753           !Decl->isTrivial()) {
8754    // A member of a union must have a trivial corresponding special member.
8755    // As a weird special case, a destructor call from a union's constructor
8756    // must be accessible and non-deleted, but need not be trivial. Such a
8757    // destructor is never actually called, but is semantically checked as
8758    // if it were.
8759    DiagKind = 4;
8760  }
8761
8762  if (DiagKind == -1)
8763    return false;
8764
8765  if (Diagnose) {
8766    if (Field) {
8767      S.Diag(Field->getLocation(),
8768             diag::note_deleted_special_member_class_subobject)
8769        << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8770        << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8771    } else {
8772      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8773      S.Diag(Base->getBeginLoc(),
8774             diag::note_deleted_special_member_class_subobject)
8775          << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8776          << Base->getType() << DiagKind << IsDtorCallInCtor
8777          << /*IsObjCPtr*/false;
8778    }
8779
8780    if (DiagKind == 1)
8781      S.NoteDeletedFunction(Decl);
8782    // FIXME: Explain inaccessibility if DiagKind == 3.
8783  }
8784
8785  return true;
8786}
8787
8788/// Check whether we should delete a special member function due to having a
8789/// direct or virtual base class or non-static data member of class type M.
8790bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8791    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8792  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8793  bool IsMutable = Field && Field->isMutable();
8794
8795  // C++11 [class.ctor]p5:
8796  // -- any direct or virtual base class, or non-static data member with no
8797  //    brace-or-equal-initializer, has class type M (or array thereof) and
8798  //    either M has no default constructor or overload resolution as applied
8799  //    to M's default constructor results in an ambiguity or in a function
8800  //    that is deleted or inaccessible
8801  // C++11 [class.copy]p11, C++11 [class.copy]p23:
8802  // -- a direct or virtual base class B that cannot be copied/moved because
8803  //    overload resolution, as applied to B's corresponding special member,
8804  //    results in an ambiguity or a function that is deleted or inaccessible
8805  //    from the defaulted special member
8806  // C++11 [class.dtor]p5:
8807  // -- any direct or virtual base class [...] has a type with a destructor
8808  //    that is deleted or inaccessible
8809  if (!(CSM == Sema::CXXDefaultConstructor &&
8810        Field && Field->hasInClassInitializer()) &&
8811      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8812                                   false))
8813    return true;
8814
8815  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8816  // -- any direct or virtual base class or non-static data member has a
8817  //    type with a destructor that is deleted or inaccessible
8818  if (IsConstructor) {
8819    Sema::SpecialMemberOverloadResult SMOR =
8820        S.LookupSpecialMember(Class, Sema::CXXDestructor,
8821                              false, false, false, false, false);
8822    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8823      return true;
8824  }
8825
8826  return false;
8827}
8828
8829bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8830    FieldDecl *FD, QualType FieldType) {
8831  // The defaulted special functions are defined as deleted if this is a variant
8832  // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8833  // type under ARC.
8834  if (!FieldType.hasNonTrivialObjCLifetime())
8835    return false;
8836
8837  // Don't make the defaulted default constructor defined as deleted if the
8838  // member has an in-class initializer.
8839  if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8840    return false;
8841
8842  if (Diagnose) {
8843    auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8844    S.Diag(FD->getLocation(),
8845           diag::note_deleted_special_member_class_subobject)
8846        << getEffectiveCSM() << ParentClass << /*IsField*/true
8847        << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8848  }
8849
8850  return true;
8851}
8852
8853/// Check whether we should delete a special member function due to the class
8854/// having a particular direct or virtual base class.
8855bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8856  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8857  // If program is correct, BaseClass cannot be null, but if it is, the error
8858  // must be reported elsewhere.
8859  if (!BaseClass)
8860    return false;
8861  // If we have an inheriting constructor, check whether we're calling an
8862  // inherited constructor instead of a default constructor.
8863  Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8864  if (auto *BaseCtor = SMOR.getMethod()) {
8865    // Note that we do not check access along this path; other than that,
8866    // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8867    // FIXME: Check that the base has a usable destructor! Sink this into
8868    // shouldDeleteForClassSubobject.
8869    if (BaseCtor->isDeleted() && Diagnose) {
8870      S.Diag(Base->getBeginLoc(),
8871             diag::note_deleted_special_member_class_subobject)
8872          << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8873          << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8874          << /*IsObjCPtr*/false;
8875      S.NoteDeletedFunction(BaseCtor);
8876    }
8877    return BaseCtor->isDeleted();
8878  }
8879  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8880}
8881
8882/// Check whether we should delete a special member function due to the class
8883/// having a particular non-static data member.
8884bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8885  QualType FieldType = S.Context.getBaseElementType(FD->getType());
8886  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8887
8888  if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8889    return true;
8890
8891  if (CSM == Sema::CXXDefaultConstructor) {
8892    // For a default constructor, all references must be initialized in-class
8893    // and, if a union, it must have a non-const member.
8894    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8895      if (Diagnose)
8896        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8897          << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8898      return true;
8899    }
8900    // C++11 [class.ctor]p5: any non-variant non-static data member of
8901    // const-qualified type (or array thereof) with no
8902    // brace-or-equal-initializer does not have a user-provided default
8903    // constructor.
8904    if (!inUnion() && FieldType.isConstQualified() &&
8905        !FD->hasInClassInitializer() &&
8906        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8907      if (Diagnose)
8908        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8909          << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8910      return true;
8911    }
8912
8913    if (inUnion() && !FieldType.isConstQualified())
8914      AllFieldsAreConst = false;
8915  } else if (CSM == Sema::CXXCopyConstructor) {
8916    // For a copy constructor, data members must not be of rvalue reference
8917    // type.
8918    if (FieldType->isRValueReferenceType()) {
8919      if (Diagnose)
8920        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8921          << MD->getParent() << FD << FieldType;
8922      return true;
8923    }
8924  } else if (IsAssignment) {
8925    // For an assignment operator, data members must not be of reference type.
8926    if (FieldType->isReferenceType()) {
8927      if (Diagnose)
8928        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8929          << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8930      return true;
8931    }
8932    if (!FieldRecord && FieldType.isConstQualified()) {
8933      // C++11 [class.copy]p23:
8934      // -- a non-static data member of const non-class type (or array thereof)
8935      if (Diagnose)
8936        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8937          << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8938      return true;
8939    }
8940  }
8941
8942  if (FieldRecord) {
8943    // Some additional restrictions exist on the variant members.
8944    if (!inUnion() && FieldRecord->isUnion() &&
8945        FieldRecord->isAnonymousStructOrUnion()) {
8946      bool AllVariantFieldsAreConst = true;
8947
8948      // FIXME: Handle anonymous unions declared within anonymous unions.
8949      for (auto *UI : FieldRecord->fields()) {
8950        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
8951
8952        if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
8953          return true;
8954
8955        if (!UnionFieldType.isConstQualified())
8956          AllVariantFieldsAreConst = false;
8957
8958        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
8959        if (UnionFieldRecord &&
8960            shouldDeleteForClassSubobject(UnionFieldRecord, UI,
8961                                          UnionFieldType.getCVRQualifiers()))
8962          return true;
8963      }
8964
8965      // At least one member in each anonymous union must be non-const
8966      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
8967          !FieldRecord->field_empty()) {
8968        if (Diagnose)
8969          S.Diag(FieldRecord->getLocation(),
8970                 diag::note_deleted_default_ctor_all_const)
8971            << !!ICI << MD->getParent() << /*anonymous union*/1;
8972        return true;
8973      }
8974
8975      // Don't check the implicit member of the anonymous union type.
8976      // This is technically non-conformant, but sanity demands it.
8977      return false;
8978    }
8979
8980    if (shouldDeleteForClassSubobject(FieldRecord, FD,
8981                                      FieldType.getCVRQualifiers()))
8982      return true;
8983  }
8984
8985  return false;
8986}
8987
8988/// C++11 [class.ctor] p5:
8989///   A defaulted default constructor for a class X is defined as deleted if
8990/// X is a union and all of its variant members are of const-qualified type.
8991bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
8992  // This is a silly definition, because it gives an empty union a deleted
8993  // default constructor. Don't do that.
8994  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
8995    bool AnyFields = false;
8996    for (auto *F : MD->getParent()->fields())
8997      if ((AnyFields = !F->isUnnamedBitfield()))
8998        break;
8999    if (!AnyFields)
9000      return false;
9001    if (Diagnose)
9002      S.Diag(MD->getParent()->getLocation(),
9003             diag::note_deleted_default_ctor_all_const)
9004        << !!ICI << MD->getParent() << /*not anonymous union*/0;
9005    return true;
9006  }
9007  return false;
9008}
9009
9010/// Determine whether a defaulted special member function should be defined as
9011/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9012/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9013bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9014                                     InheritedConstructorInfo *ICI,
9015                                     bool Diagnose) {
9016  if (MD->isInvalidDecl())
9017    return false;
9018  CXXRecordDecl *RD = MD->getParent();
9019  assert(!RD->isDependentType() && "do deletion after instantiation");
9020  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9021    return false;
9022
9023  // C++11 [expr.lambda.prim]p19:
9024  //   The closure type associated with a lambda-expression has a
9025  //   deleted (8.4.3) default constructor and a deleted copy
9026  //   assignment operator.
9027  // C++2a adds back these operators if the lambda has no lambda-capture.
9028  if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9029      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9030    if (Diagnose)
9031      Diag(RD->getLocation(), diag::note_lambda_decl);
9032    return true;
9033  }
9034
9035  // For an anonymous struct or union, the copy and assignment special members
9036  // will never be used, so skip the check. For an anonymous union declared at
9037  // namespace scope, the constructor and destructor are used.
9038  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9039      RD->isAnonymousStructOrUnion())
9040    return false;
9041
9042  // C++11 [class.copy]p7, p18:
9043  //   If the class definition declares a move constructor or move assignment
9044  //   operator, an implicitly declared copy constructor or copy assignment
9045  //   operator is defined as deleted.
9046  if (MD->isImplicit() &&
9047      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9048    CXXMethodDecl *UserDeclaredMove = nullptr;
9049
9050    // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9051    // deletion of the corresponding copy operation, not both copy operations.
9052    // MSVC 2015 has adopted the standards conforming behavior.
9053    bool DeletesOnlyMatchingCopy =
9054        getLangOpts().MSVCCompat &&
9055        !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9056
9057    if (RD->hasUserDeclaredMoveConstructor() &&
9058        (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9059      if (!Diagnose) return true;
9060
9061      // Find any user-declared move constructor.
9062      for (auto *I : RD->ctors()) {
9063        if (I->isMoveConstructor()) {
9064          UserDeclaredMove = I;
9065          break;
9066        }
9067      }
9068      assert(UserDeclaredMove);
9069    } else if (RD->hasUserDeclaredMoveAssignment() &&
9070               (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9071      if (!Diagnose) return true;
9072
9073      // Find any user-declared move assignment operator.
9074      for (auto *I : RD->methods()) {
9075        if (I->isMoveAssignmentOperator()) {
9076          UserDeclaredMove = I;
9077          break;
9078        }
9079      }
9080      assert(UserDeclaredMove);
9081    }
9082
9083    if (UserDeclaredMove) {
9084      Diag(UserDeclaredMove->getLocation(),
9085           diag::note_deleted_copy_user_declared_move)
9086        << (CSM == CXXCopyAssignment) << RD
9087        << UserDeclaredMove->isMoveAssignmentOperator();
9088      return true;
9089    }
9090  }
9091
9092  // Do access control from the special member function
9093  ContextRAII MethodContext(*this, MD);
9094
9095  // C++11 [class.dtor]p5:
9096  // -- for a virtual destructor, lookup of the non-array deallocation function
9097  //    results in an ambiguity or in a function that is deleted or inaccessible
9098  if (CSM == CXXDestructor && MD->isVirtual()) {
9099    FunctionDecl *OperatorDelete = nullptr;
9100    DeclarationName Name =
9101      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9102    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9103                                 OperatorDelete, /*Diagnose*/false)) {
9104      if (Diagnose)
9105        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9106      return true;
9107    }
9108  }
9109
9110  SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9111
9112  // Per DR1611, do not consider virtual bases of constructors of abstract
9113  // classes, since we are not going to construct them.
9114  // Per DR1658, do not consider virtual bases of destructors of abstract
9115  // classes either.
9116  // Per DR2180, for assignment operators we only assign (and thus only
9117  // consider) direct bases.
9118  if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9119                                 : SMI.VisitPotentiallyConstructedBases))
9120    return true;
9121
9122  if (SMI.shouldDeleteForAllConstMembers())
9123    return true;
9124
9125  if (getLangOpts().CUDA) {
9126    // We should delete the special member in CUDA mode if target inference
9127    // failed.
9128    // For inherited constructors (non-null ICI), CSM may be passed so that MD
9129    // is treated as certain special member, which may not reflect what special
9130    // member MD really is. However inferCUDATargetForImplicitSpecialMember
9131    // expects CSM to match MD, therefore recalculate CSM.
9132    assert(ICI || CSM == getSpecialMember(MD));
9133    auto RealCSM = CSM;
9134    if (ICI)
9135      RealCSM = getSpecialMember(MD);
9136
9137    return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9138                                                   SMI.ConstArg, Diagnose);
9139  }
9140
9141  return false;
9142}
9143
9144void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9145  DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9146  assert(DFK && "not a defaultable function");
9147  assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9148
9149  if (DFK.isSpecialMember()) {
9150    ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9151                              nullptr, /*Diagnose=*/true);
9152  } else {
9153    DefaultedComparisonAnalyzer(
9154        *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9155        DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9156        .visit();
9157  }
9158}
9159
9160/// Perform lookup for a special member of the specified kind, and determine
9161/// whether it is trivial. If the triviality can be determined without the
9162/// lookup, skip it. This is intended for use when determining whether a
9163/// special member of a containing object is trivial, and thus does not ever
9164/// perform overload resolution for default constructors.
9165///
9166/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9167/// member that was most likely to be intended to be trivial, if any.
9168///
9169/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9170/// determine whether the special member is trivial.
9171static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9172                                     Sema::CXXSpecialMember CSM, unsigned Quals,
9173                                     bool ConstRHS,
9174                                     Sema::TrivialABIHandling TAH,
9175                                     CXXMethodDecl **Selected) {
9176  if (Selected)
9177    *Selected = nullptr;
9178
9179  switch (CSM) {
9180  case Sema::CXXInvalid:
9181    llvm_unreachable("not a special member");
9182
9183  case Sema::CXXDefaultConstructor:
9184    // C++11 [class.ctor]p5:
9185    //   A default constructor is trivial if:
9186    //    - all the [direct subobjects] have trivial default constructors
9187    //
9188    // Note, no overload resolution is performed in this case.
9189    if (RD->hasTrivialDefaultConstructor())
9190      return true;
9191
9192    if (Selected) {
9193      // If there's a default constructor which could have been trivial, dig it
9194      // out. Otherwise, if there's any user-provided default constructor, point
9195      // to that as an example of why there's not a trivial one.
9196      CXXConstructorDecl *DefCtor = nullptr;
9197      if (RD->needsImplicitDefaultConstructor())
9198        S.DeclareImplicitDefaultConstructor(RD);
9199      for (auto *CI : RD->ctors()) {
9200        if (!CI->isDefaultConstructor())
9201          continue;
9202        DefCtor = CI;
9203        if (!DefCtor->isUserProvided())
9204          break;
9205      }
9206
9207      *Selected = DefCtor;
9208    }
9209
9210    return false;
9211
9212  case Sema::CXXDestructor:
9213    // C++11 [class.dtor]p5:
9214    //   A destructor is trivial if:
9215    //    - all the direct [subobjects] have trivial destructors
9216    if (RD->hasTrivialDestructor() ||
9217        (TAH == Sema::TAH_ConsiderTrivialABI &&
9218         RD->hasTrivialDestructorForCall()))
9219      return true;
9220
9221    if (Selected) {
9222      if (RD->needsImplicitDestructor())
9223        S.DeclareImplicitDestructor(RD);
9224      *Selected = RD->getDestructor();
9225    }
9226
9227    return false;
9228
9229  case Sema::CXXCopyConstructor:
9230    // C++11 [class.copy]p12:
9231    //   A copy constructor is trivial if:
9232    //    - the constructor selected to copy each direct [subobject] is trivial
9233    if (RD->hasTrivialCopyConstructor() ||
9234        (TAH == Sema::TAH_ConsiderTrivialABI &&
9235         RD->hasTrivialCopyConstructorForCall())) {
9236      if (Quals == Qualifiers::Const)
9237        // We must either select the trivial copy constructor or reach an
9238        // ambiguity; no need to actually perform overload resolution.
9239        return true;
9240    } else if (!Selected) {
9241      return false;
9242    }
9243    // In C++98, we are not supposed to perform overload resolution here, but we
9244    // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9245    // cases like B as having a non-trivial copy constructor:
9246    //   struct A { template<typename T> A(T&); };
9247    //   struct B { mutable A a; };
9248    goto NeedOverloadResolution;
9249
9250  case Sema::CXXCopyAssignment:
9251    // C++11 [class.copy]p25:
9252    //   A copy assignment operator is trivial if:
9253    //    - the assignment operator selected to copy each direct [subobject] is
9254    //      trivial
9255    if (RD->hasTrivialCopyAssignment()) {
9256      if (Quals == Qualifiers::Const)
9257        return true;
9258    } else if (!Selected) {
9259      return false;
9260    }
9261    // In C++98, we are not supposed to perform overload resolution here, but we
9262    // treat that as a language defect.
9263    goto NeedOverloadResolution;
9264
9265  case Sema::CXXMoveConstructor:
9266  case Sema::CXXMoveAssignment:
9267  NeedOverloadResolution:
9268    Sema::SpecialMemberOverloadResult SMOR =
9269        lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9270
9271    // The standard doesn't describe how to behave if the lookup is ambiguous.
9272    // We treat it as not making the member non-trivial, just like the standard
9273    // mandates for the default constructor. This should rarely matter, because
9274    // the member will also be deleted.
9275    if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9276      return true;
9277
9278    if (!SMOR.getMethod()) {
9279      assert(SMOR.getKind() ==
9280             Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9281      return false;
9282    }
9283
9284    // We deliberately don't check if we found a deleted special member. We're
9285    // not supposed to!
9286    if (Selected)
9287      *Selected = SMOR.getMethod();
9288
9289    if (TAH == Sema::TAH_ConsiderTrivialABI &&
9290        (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9291      return SMOR.getMethod()->isTrivialForCall();
9292    return SMOR.getMethod()->isTrivial();
9293  }
9294
9295  llvm_unreachable("unknown special method kind");
9296}
9297
9298static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9299  for (auto *CI : RD->ctors())
9300    if (!CI->isImplicit())
9301      return CI;
9302
9303  // Look for constructor templates.
9304  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9305  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9306    if (CXXConstructorDecl *CD =
9307          dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9308      return CD;
9309  }
9310
9311  return nullptr;
9312}
9313
9314/// The kind of subobject we are checking for triviality. The values of this
9315/// enumeration are used in diagnostics.
9316enum TrivialSubobjectKind {
9317  /// The subobject is a base class.
9318  TSK_BaseClass,
9319  /// The subobject is a non-static data member.
9320  TSK_Field,
9321  /// The object is actually the complete object.
9322  TSK_CompleteObject
9323};
9324
9325/// Check whether the special member selected for a given type would be trivial.
9326static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9327                                      QualType SubType, bool ConstRHS,
9328                                      Sema::CXXSpecialMember CSM,
9329                                      TrivialSubobjectKind Kind,
9330                                      Sema::TrivialABIHandling TAH, bool Diagnose) {
9331  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9332  if (!SubRD)
9333    return true;
9334
9335  CXXMethodDecl *Selected;
9336  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9337                               ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9338    return true;
9339
9340  if (Diagnose) {
9341    if (ConstRHS)
9342      SubType.addConst();
9343
9344    if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9345      S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9346        << Kind << SubType.getUnqualifiedType();
9347      if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9348        S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9349    } else if (!Selected)
9350      S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9351        << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9352    else if (Selected->isUserProvided()) {
9353      if (Kind == TSK_CompleteObject)
9354        S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9355          << Kind << SubType.getUnqualifiedType() << CSM;
9356      else {
9357        S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9358          << Kind << SubType.getUnqualifiedType() << CSM;
9359        S.Diag(Selected->getLocation(), diag::note_declared_at);
9360      }
9361    } else {
9362      if (Kind != TSK_CompleteObject)
9363        S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9364          << Kind << SubType.getUnqualifiedType() << CSM;
9365
9366      // Explain why the defaulted or deleted special member isn't trivial.
9367      S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9368                               Diagnose);
9369    }
9370  }
9371
9372  return false;
9373}
9374
9375/// Check whether the members of a class type allow a special member to be
9376/// trivial.
9377static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9378                                     Sema::CXXSpecialMember CSM,
9379                                     bool ConstArg,
9380                                     Sema::TrivialABIHandling TAH,
9381                                     bool Diagnose) {
9382  for (const auto *FI : RD->fields()) {
9383    if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9384      continue;
9385
9386    QualType FieldType = S.Context.getBaseElementType(FI->getType());
9387
9388    // Pretend anonymous struct or union members are members of this class.
9389    if (FI->isAnonymousStructOrUnion()) {
9390      if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9391                                    CSM, ConstArg, TAH, Diagnose))
9392        return false;
9393      continue;
9394    }
9395
9396    // C++11 [class.ctor]p5:
9397    //   A default constructor is trivial if [...]
9398    //    -- no non-static data member of its class has a
9399    //       brace-or-equal-initializer
9400    if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9401      if (Diagnose)
9402        S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
9403      return false;
9404    }
9405
9406    // Objective C ARC 4.3.5:
9407    //   [...] nontrivally ownership-qualified types are [...] not trivially
9408    //   default constructible, copy constructible, move constructible, copy
9409    //   assignable, move assignable, or destructible [...]
9410    if (FieldType.hasNonTrivialObjCLifetime()) {
9411      if (Diagnose)
9412        S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9413          << RD << FieldType.getObjCLifetime();
9414      return false;
9415    }
9416
9417    bool ConstRHS = ConstArg && !FI->isMutable();
9418    if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9419                                   CSM, TSK_Field, TAH, Diagnose))
9420      return false;
9421  }
9422
9423  return true;
9424}
9425
9426/// Diagnose why the specified class does not have a trivial special member of
9427/// the given kind.
9428void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9429  QualType Ty = Context.getRecordType(RD);
9430
9431  bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9432  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9433                            TSK_CompleteObject, TAH_IgnoreTrivialABI,
9434                            /*Diagnose*/true);
9435}
9436
9437/// Determine whether a defaulted or deleted special member function is trivial,
9438/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9439/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9440bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9441                                  TrivialABIHandling TAH, bool Diagnose) {
9442  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9443
9444  CXXRecordDecl *RD = MD->getParent();
9445
9446  bool ConstArg = false;
9447
9448  // C++11 [class.copy]p12, p25: [DR1593]
9449  //   A [special member] is trivial if [...] its parameter-type-list is
9450  //   equivalent to the parameter-type-list of an implicit declaration [...]
9451  switch (CSM) {
9452  case CXXDefaultConstructor:
9453  case CXXDestructor:
9454    // Trivial default constructors and destructors cannot have parameters.
9455    break;
9456
9457  case CXXCopyConstructor:
9458  case CXXCopyAssignment: {
9459    // Trivial copy operations always have const, non-volatile parameter types.
9460    ConstArg = true;
9461    const ParmVarDecl *Param0 = MD->getParamDecl(0);
9462    const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9463    if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9464      if (Diagnose)
9465        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9466          << Param0->getSourceRange() << Param0->getType()
9467          << Context.getLValueReferenceType(
9468               Context.getRecordType(RD).withConst());
9469      return false;
9470    }
9471    break;
9472  }
9473
9474  case CXXMoveConstructor:
9475  case CXXMoveAssignment: {
9476    // Trivial move operations always have non-cv-qualified parameters.
9477    const ParmVarDecl *Param0 = MD->getParamDecl(0);
9478    const RValueReferenceType *RT =
9479      Param0->getType()->getAs<RValueReferenceType>();
9480    if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9481      if (Diagnose)
9482        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9483          << Param0->getSourceRange() << Param0->getType()
9484          << Context.getRValueReferenceType(Context.getRecordType(RD));
9485      return false;
9486    }
9487    break;
9488  }
9489
9490  case CXXInvalid:
9491    llvm_unreachable("not a special member");
9492  }
9493
9494  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9495    if (Diagnose)
9496      Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9497           diag::note_nontrivial_default_arg)
9498        << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9499    return false;
9500  }
9501  if (MD->isVariadic()) {
9502    if (Diagnose)
9503      Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9504    return false;
9505  }
9506
9507  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9508  //   A copy/move [constructor or assignment operator] is trivial if
9509  //    -- the [member] selected to copy/move each direct base class subobject
9510  //       is trivial
9511  //
9512  // C++11 [class.copy]p12, C++11 [class.copy]p25:
9513  //   A [default constructor or destructor] is trivial if
9514  //    -- all the direct base classes have trivial [default constructors or
9515  //       destructors]
9516  for (const auto &BI : RD->bases())
9517    if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9518                                   ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9519      return false;
9520
9521  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9522  //   A copy/move [constructor or assignment operator] for a class X is
9523  //   trivial if
9524  //    -- for each non-static data member of X that is of class type (or array
9525  //       thereof), the constructor selected to copy/move that member is
9526  //       trivial
9527  //
9528  // C++11 [class.copy]p12, C++11 [class.copy]p25:
9529  //   A [default constructor or destructor] is trivial if
9530  //    -- for all of the non-static data members of its class that are of class
9531  //       type (or array thereof), each such class has a trivial [default
9532  //       constructor or destructor]
9533  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9534    return false;
9535
9536  // C++11 [class.dtor]p5:
9537  //   A destructor is trivial if [...]
9538  //    -- the destructor is not virtual
9539  if (CSM == CXXDestructor && MD->isVirtual()) {
9540    if (Diagnose)
9541      Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9542    return false;
9543  }
9544
9545  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9546  //   A [special member] for class X is trivial if [...]
9547  //    -- class X has no virtual functions and no virtual base classes
9548  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9549    if (!Diagnose)
9550      return false;
9551
9552    if (RD->getNumVBases()) {
9553      // Check for virtual bases. We already know that the corresponding
9554      // member in all bases is trivial, so vbases must all be direct.
9555      CXXBaseSpecifier &BS = *RD->vbases_begin();
9556      assert(BS.isVirtual());
9557      Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9558      return false;
9559    }
9560
9561    // Must have a virtual method.
9562    for (const auto *MI : RD->methods()) {
9563      if (MI->isVirtual()) {
9564        SourceLocation MLoc = MI->getBeginLoc();
9565        Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9566        return false;
9567      }
9568    }
9569
9570    llvm_unreachable("dynamic class with no vbases and no virtual functions");
9571  }
9572
9573  // Looks like it's trivial!
9574  return true;
9575}
9576
9577namespace {
9578struct FindHiddenVirtualMethod {
9579  Sema *S;
9580  CXXMethodDecl *Method;
9581  llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9582  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9583
9584private:
9585  /// Check whether any most overridden method from MD in Methods
9586  static bool CheckMostOverridenMethods(
9587      const CXXMethodDecl *MD,
9588      const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9589    if (MD->size_overridden_methods() == 0)
9590      return Methods.count(MD->getCanonicalDecl());
9591    for (const CXXMethodDecl *O : MD->overridden_methods())
9592      if (CheckMostOverridenMethods(O, Methods))
9593        return true;
9594    return false;
9595  }
9596
9597public:
9598  /// Member lookup function that determines whether a given C++
9599  /// method overloads virtual methods in a base class without overriding any,
9600  /// to be used with CXXRecordDecl::lookupInBases().
9601  bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9602    RecordDecl *BaseRecord =
9603        Specifier->getType()->castAs<RecordType>()->getDecl();
9604
9605    DeclarationName Name = Method->getDeclName();
9606    assert(Name.getNameKind() == DeclarationName::Identifier);
9607
9608    bool foundSameNameMethod = false;
9609    SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9610    for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9611         Path.Decls = Path.Decls.slice(1)) {
9612      NamedDecl *D = Path.Decls.front();
9613      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9614        MD = MD->getCanonicalDecl();
9615        foundSameNameMethod = true;
9616        // Interested only in hidden virtual methods.
9617        if (!MD->isVirtual())
9618          continue;
9619        // If the method we are checking overrides a method from its base
9620        // don't warn about the other overloaded methods. Clang deviates from
9621        // GCC by only diagnosing overloads of inherited virtual functions that
9622        // do not override any other virtual functions in the base. GCC's
9623        // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9624        // function from a base class. These cases may be better served by a
9625        // warning (not specific to virtual functions) on call sites when the
9626        // call would select a different function from the base class, were it
9627        // visible.
9628        // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9629        if (!S->IsOverload(Method, MD, false))
9630          return true;
9631        // Collect the overload only if its hidden.
9632        if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9633          overloadedMethods.push_back(MD);
9634      }
9635    }
9636
9637    if (foundSameNameMethod)
9638      OverloadedMethods.append(overloadedMethods.begin(),
9639                               overloadedMethods.end());
9640    return foundSameNameMethod;
9641  }
9642};
9643} // end anonymous namespace
9644
9645/// Add the most overriden methods from MD to Methods
9646static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9647                        llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9648  if (MD->size_overridden_methods() == 0)
9649    Methods.insert(MD->getCanonicalDecl());
9650  else
9651    for (const CXXMethodDecl *O : MD->overridden_methods())
9652      AddMostOverridenMethods(O, Methods);
9653}
9654
9655/// Check if a method overloads virtual methods in a base class without
9656/// overriding any.
9657void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9658                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9659  if (!MD->getDeclName().isIdentifier())
9660    return;
9661
9662  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9663                     /*bool RecordPaths=*/false,
9664                     /*bool DetectVirtual=*/false);
9665  FindHiddenVirtualMethod FHVM;
9666  FHVM.Method = MD;
9667  FHVM.S = this;
9668
9669  // Keep the base methods that were overridden or introduced in the subclass
9670  // by 'using' in a set. A base method not in this set is hidden.
9671  CXXRecordDecl *DC = MD->getParent();
9672  DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9673  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9674    NamedDecl *ND = *I;
9675    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9676      ND = shad->getTargetDecl();
9677    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9678      AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9679  }
9680
9681  if (DC->lookupInBases(FHVM, Paths))
9682    OverloadedMethods = FHVM.OverloadedMethods;
9683}
9684
9685void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9686                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9687  for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9688    CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9689    PartialDiagnostic PD = PDiag(
9690         diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9691    HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9692    Diag(overloadedMD->getLocation(), PD);
9693  }
9694}
9695
9696/// Diagnose methods which overload virtual methods in a base class
9697/// without overriding any.
9698void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9699  if (MD->isInvalidDecl())
9700    return;
9701
9702  if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9703    return;
9704
9705  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9706  FindHiddenVirtualMethods(MD, OverloadedMethods);
9707  if (!OverloadedMethods.empty()) {
9708    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9709      << MD << (OverloadedMethods.size() > 1);
9710
9711    NoteHiddenVirtualMethods(MD, OverloadedMethods);
9712  }
9713}
9714
9715void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9716  auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9717    // No diagnostics if this is a template instantiation.
9718    if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9719      Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9720           diag::ext_cannot_use_trivial_abi) << &RD;
9721      Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9722           diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9723    }
9724    RD.dropAttr<TrivialABIAttr>();
9725  };
9726
9727  // Ill-formed if the copy and move constructors are deleted.
9728  auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9729    // If the type is dependent, then assume it might have
9730    // implicit copy or move ctor because we won't know yet at this point.
9731    if (RD.isDependentType())
9732      return true;
9733    if (RD.needsImplicitCopyConstructor() &&
9734        !RD.defaultedCopyConstructorIsDeleted())
9735      return true;
9736    if (RD.needsImplicitMoveConstructor() &&
9737        !RD.defaultedMoveConstructorIsDeleted())
9738      return true;
9739    for (const CXXConstructorDecl *CD : RD.ctors())
9740      if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9741        return true;
9742    return false;
9743  };
9744
9745  if (!HasNonDeletedCopyOrMoveConstructor()) {
9746    PrintDiagAndRemoveAttr(0);
9747    return;
9748  }
9749
9750  // Ill-formed if the struct has virtual functions.
9751  if (RD.isPolymorphic()) {
9752    PrintDiagAndRemoveAttr(1);
9753    return;
9754  }
9755
9756  for (const auto &B : RD.bases()) {
9757    // Ill-formed if the base class is non-trivial for the purpose of calls or a
9758    // virtual base.
9759    if (!B.getType()->isDependentType() &&
9760        !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9761      PrintDiagAndRemoveAttr(2);
9762      return;
9763    }
9764
9765    if (B.isVirtual()) {
9766      PrintDiagAndRemoveAttr(3);
9767      return;
9768    }
9769  }
9770
9771  for (const auto *FD : RD.fields()) {
9772    // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9773    // non-trivial for the purpose of calls.
9774    QualType FT = FD->getType();
9775    if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9776      PrintDiagAndRemoveAttr(4);
9777      return;
9778    }
9779
9780    if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9781      if (!RT->isDependentType() &&
9782          !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9783        PrintDiagAndRemoveAttr(5);
9784        return;
9785      }
9786  }
9787}
9788
9789void Sema::ActOnFinishCXXMemberSpecification(
9790    Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9791    SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9792  if (!TagDecl)
9793    return;
9794
9795  AdjustDeclIfTemplate(TagDecl);
9796
9797  for (const ParsedAttr &AL : AttrList) {
9798    if (AL.getKind() != ParsedAttr::AT_Visibility)
9799      continue;
9800    AL.setInvalid();
9801    Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9802  }
9803
9804  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9805              // strict aliasing violation!
9806              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9807              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9808
9809  CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9810}
9811
9812/// Find the equality comparison functions that should be implicitly declared
9813/// in a given class definition, per C++2a [class.compare.default]p3.
9814static void findImplicitlyDeclaredEqualityComparisons(
9815    ASTContext &Ctx, CXXRecordDecl *RD,
9816    llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9817  DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9818  if (!RD->lookup(EqEq).empty())
9819    // Member operator== explicitly declared: no implicit operator==s.
9820    return;
9821
9822  // Traverse friends looking for an '==' or a '<=>'.
9823  for (FriendDecl *Friend : RD->friends()) {
9824    FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9825    if (!FD) continue;
9826
9827    if (FD->getOverloadedOperator() == OO_EqualEqual) {
9828      // Friend operator== explicitly declared: no implicit operator==s.
9829      Spaceships.clear();
9830      return;
9831    }
9832
9833    if (FD->getOverloadedOperator() == OO_Spaceship &&
9834        FD->isExplicitlyDefaulted())
9835      Spaceships.push_back(FD);
9836  }
9837
9838  // Look for members named 'operator<=>'.
9839  DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9840  for (NamedDecl *ND : RD->lookup(Cmp)) {
9841    // Note that we could find a non-function here (either a function template
9842    // or a using-declaration). Neither case results in an implicit
9843    // 'operator=='.
9844    if (auto *FD = dyn_cast<FunctionDecl>(ND))
9845      if (FD->isExplicitlyDefaulted())
9846        Spaceships.push_back(FD);
9847  }
9848}
9849
9850/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9851/// special functions, such as the default constructor, copy
9852/// constructor, or destructor, to the given C++ class (C++
9853/// [special]p1).  This routine can only be executed just before the
9854/// definition of the class is complete.
9855void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9856  // Don't add implicit special members to templated classes.
9857  // FIXME: This means unqualified lookups for 'operator=' within a class
9858  // template don't work properly.
9859  if (!ClassDecl->isDependentType()) {
9860    if (ClassDecl->needsImplicitDefaultConstructor()) {
9861      ++getASTContext().NumImplicitDefaultConstructors;
9862
9863      if (ClassDecl->hasInheritedConstructor())
9864        DeclareImplicitDefaultConstructor(ClassDecl);
9865    }
9866
9867    if (ClassDecl->needsImplicitCopyConstructor()) {
9868      ++getASTContext().NumImplicitCopyConstructors;
9869
9870      // If the properties or semantics of the copy constructor couldn't be
9871      // determined while the class was being declared, force a declaration
9872      // of it now.
9873      if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9874          ClassDecl->hasInheritedConstructor())
9875        DeclareImplicitCopyConstructor(ClassDecl);
9876      // For the MS ABI we need to know whether the copy ctor is deleted. A
9877      // prerequisite for deleting the implicit copy ctor is that the class has
9878      // a move ctor or move assignment that is either user-declared or whose
9879      // semantics are inherited from a subobject. FIXME: We should provide a
9880      // more direct way for CodeGen to ask whether the constructor was deleted.
9881      else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9882               (ClassDecl->hasUserDeclaredMoveConstructor() ||
9883                ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9884                ClassDecl->hasUserDeclaredMoveAssignment() ||
9885                ClassDecl->needsOverloadResolutionForMoveAssignment()))
9886        DeclareImplicitCopyConstructor(ClassDecl);
9887    }
9888
9889    if (getLangOpts().CPlusPlus11 &&
9890        ClassDecl->needsImplicitMoveConstructor()) {
9891      ++getASTContext().NumImplicitMoveConstructors;
9892
9893      if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9894          ClassDecl->hasInheritedConstructor())
9895        DeclareImplicitMoveConstructor(ClassDecl);
9896    }
9897
9898    if (ClassDecl->needsImplicitCopyAssignment()) {
9899      ++getASTContext().NumImplicitCopyAssignmentOperators;
9900
9901      // If we have a dynamic class, then the copy assignment operator may be
9902      // virtual, so we have to declare it immediately. This ensures that, e.g.,
9903      // it shows up in the right place in the vtable and that we diagnose
9904      // problems with the implicit exception specification.
9905      if (ClassDecl->isDynamicClass() ||
9906          ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9907          ClassDecl->hasInheritedAssignment())
9908        DeclareImplicitCopyAssignment(ClassDecl);
9909    }
9910
9911    if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9912      ++getASTContext().NumImplicitMoveAssignmentOperators;
9913
9914      // Likewise for the move assignment operator.
9915      if (ClassDecl->isDynamicClass() ||
9916          ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9917          ClassDecl->hasInheritedAssignment())
9918        DeclareImplicitMoveAssignment(ClassDecl);
9919    }
9920
9921    if (ClassDecl->needsImplicitDestructor()) {
9922      ++getASTContext().NumImplicitDestructors;
9923
9924      // If we have a dynamic class, then the destructor may be virtual, so we
9925      // have to declare the destructor immediately. This ensures that, e.g., it
9926      // shows up in the right place in the vtable and that we diagnose problems
9927      // with the implicit exception specification.
9928      if (ClassDecl->isDynamicClass() ||
9929          ClassDecl->needsOverloadResolutionForDestructor())
9930        DeclareImplicitDestructor(ClassDecl);
9931    }
9932  }
9933
9934  // C++2a [class.compare.default]p3:
9935  //   If the member-specification does not explicitly declare any member or
9936  //   friend named operator==, an == operator function is declared implicitly
9937  //   for each defaulted three-way comparison operator function defined in
9938  //   the member-specification
9939  // FIXME: Consider doing this lazily.
9940  // We do this during the initial parse for a class template, not during
9941  // instantiation, so that we can handle unqualified lookups for 'operator=='
9942  // when parsing the template.
9943  if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
9944    llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
9945    findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9946                                              DefaultedSpaceships);
9947    for (auto *FD : DefaultedSpaceships)
9948      DeclareImplicitEqualityComparison(ClassDecl, FD);
9949  }
9950}
9951
9952unsigned
9953Sema::ActOnReenterTemplateScope(Decl *D,
9954                                llvm::function_ref<Scope *()> EnterScope) {
9955  if (!D)
9956    return 0;
9957  AdjustDeclIfTemplate(D);
9958
9959  // In order to get name lookup right, reenter template scopes in order from
9960  // outermost to innermost.
9961  SmallVector<TemplateParameterList *, 4> ParameterLists;
9962  DeclContext *LookupDC = dyn_cast<DeclContext>(D);
9963
9964  if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
9965    for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
9966      ParameterLists.push_back(DD->getTemplateParameterList(i));
9967
9968    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9969      if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
9970        ParameterLists.push_back(FTD->getTemplateParameters());
9971    } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
9972      LookupDC = VD->getDeclContext();
9973
9974      if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
9975        ParameterLists.push_back(VTD->getTemplateParameters());
9976      else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
9977        ParameterLists.push_back(PSD->getTemplateParameters());
9978    }
9979  } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9980    for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
9981      ParameterLists.push_back(TD->getTemplateParameterList(i));
9982
9983    if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
9984      if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
9985        ParameterLists.push_back(CTD->getTemplateParameters());
9986      else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
9987        ParameterLists.push_back(PSD->getTemplateParameters());
9988    }
9989  }
9990  // FIXME: Alias declarations and concepts.
9991
9992  unsigned Count = 0;
9993  Scope *InnermostTemplateScope = nullptr;
9994  for (TemplateParameterList *Params : ParameterLists) {
9995    // Ignore explicit specializations; they don't contribute to the template
9996    // depth.
9997    if (Params->size() == 0)
9998      continue;
9999
10000    InnermostTemplateScope = EnterScope();
10001    for (NamedDecl *Param : *Params) {
10002      if (Param->getDeclName()) {
10003        InnermostTemplateScope->AddDecl(Param);
10004        IdResolver.AddDecl(Param);
10005      }
10006    }
10007    ++Count;
10008  }
10009
10010  // Associate the new template scopes with the corresponding entities.
10011  if (InnermostTemplateScope) {
10012    assert(LookupDC && "no enclosing DeclContext for template lookup");
10013    EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10014  }
10015
10016  return Count;
10017}
10018
10019void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10020  if (!RecordD) return;
10021  AdjustDeclIfTemplate(RecordD);
10022  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10023  PushDeclContext(S, Record);
10024}
10025
10026void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10027  if (!RecordD) return;
10028  PopDeclContext();
10029}
10030
10031/// This is used to implement the constant expression evaluation part of the
10032/// attribute enable_if extension. There is nothing in standard C++ which would
10033/// require reentering parameters.
10034void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10035  if (!Param)
10036    return;
10037
10038  S->AddDecl(Param);
10039  if (Param->getDeclName())
10040    IdResolver.AddDecl(Param);
10041}
10042
10043/// ActOnStartDelayedCXXMethodDeclaration - We have completed
10044/// parsing a top-level (non-nested) C++ class, and we are now
10045/// parsing those parts of the given Method declaration that could
10046/// not be parsed earlier (C++ [class.mem]p2), such as default
10047/// arguments. This action should enter the scope of the given
10048/// Method declaration as if we had just parsed the qualified method
10049/// name. However, it should not bring the parameters into scope;
10050/// that will be performed by ActOnDelayedCXXMethodParameter.
10051void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10052}
10053
10054/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10055/// C++ method declaration. We're (re-)introducing the given
10056/// function parameter into scope for use in parsing later parts of
10057/// the method declaration. For example, we could see an
10058/// ActOnParamDefaultArgument event for this parameter.
10059void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10060  if (!ParamD)
10061    return;
10062
10063  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10064
10065  S->AddDecl(Param);
10066  if (Param->getDeclName())
10067    IdResolver.AddDecl(Param);
10068}
10069
10070/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10071/// processing the delayed method declaration for Method. The method
10072/// declaration is now considered finished. There may be a separate
10073/// ActOnStartOfFunctionDef action later (not necessarily
10074/// immediately!) for this method, if it was also defined inside the
10075/// class body.
10076void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10077  if (!MethodD)
10078    return;
10079
10080  AdjustDeclIfTemplate(MethodD);
10081
10082  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10083
10084  // Now that we have our default arguments, check the constructor
10085  // again. It could produce additional diagnostics or affect whether
10086  // the class has implicitly-declared destructors, among other
10087  // things.
10088  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10089    CheckConstructor(Constructor);
10090
10091  // Check the default arguments, which we may have added.
10092  if (!Method->isInvalidDecl())
10093    CheckCXXDefaultArguments(Method);
10094}
10095
10096// Emit the given diagnostic for each non-address-space qualifier.
10097// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10098static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10099  const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10100  if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10101    bool DiagOccured = false;
10102    FTI.MethodQualifiers->forEachQualifier(
10103        [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10104                                   SourceLocation SL) {
10105          // This diagnostic should be emitted on any qualifier except an addr
10106          // space qualifier. However, forEachQualifier currently doesn't visit
10107          // addr space qualifiers, so there's no way to write this condition
10108          // right now; we just diagnose on everything.
10109          S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10110          DiagOccured = true;
10111        });
10112    if (DiagOccured)
10113      D.setInvalidType();
10114  }
10115}
10116
10117/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10118/// the well-formedness of the constructor declarator @p D with type @p
10119/// R. If there are any errors in the declarator, this routine will
10120/// emit diagnostics and set the invalid bit to true.  In any case, the type
10121/// will be updated to reflect a well-formed type for the constructor and
10122/// returned.
10123QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10124                                          StorageClass &SC) {
10125  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10126
10127  // C++ [class.ctor]p3:
10128  //   A constructor shall not be virtual (10.3) or static (9.4). A
10129  //   constructor can be invoked for a const, volatile or const
10130  //   volatile object. A constructor shall not be declared const,
10131  //   volatile, or const volatile (9.3.2).
10132  if (isVirtual) {
10133    if (!D.isInvalidType())
10134      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10135        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10136        << SourceRange(D.getIdentifierLoc());
10137    D.setInvalidType();
10138  }
10139  if (SC == SC_Static) {
10140    if (!D.isInvalidType())
10141      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10142        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10143        << SourceRange(D.getIdentifierLoc());
10144    D.setInvalidType();
10145    SC = SC_None;
10146  }
10147
10148  if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10149    diagnoseIgnoredQualifiers(
10150        diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10151        D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10152        D.getDeclSpec().getRestrictSpecLoc(),
10153        D.getDeclSpec().getAtomicSpecLoc());
10154    D.setInvalidType();
10155  }
10156
10157  checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10158
10159  // C++0x [class.ctor]p4:
10160  //   A constructor shall not be declared with a ref-qualifier.
10161  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10162  if (FTI.hasRefQualifier()) {
10163    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10164      << FTI.RefQualifierIsLValueRef
10165      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10166    D.setInvalidType();
10167  }
10168
10169  // Rebuild the function type "R" without any type qualifiers (in
10170  // case any of the errors above fired) and with "void" as the
10171  // return type, since constructors don't have return types.
10172  const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10173  if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10174    return R;
10175
10176  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10177  EPI.TypeQuals = Qualifiers();
10178  EPI.RefQualifier = RQ_None;
10179
10180  return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10181}
10182
10183/// CheckConstructor - Checks a fully-formed constructor for
10184/// well-formedness, issuing any diagnostics required. Returns true if
10185/// the constructor declarator is invalid.
10186void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10187  CXXRecordDecl *ClassDecl
10188    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10189  if (!ClassDecl)
10190    return Constructor->setInvalidDecl();
10191
10192  // C++ [class.copy]p3:
10193  //   A declaration of a constructor for a class X is ill-formed if
10194  //   its first parameter is of type (optionally cv-qualified) X and
10195  //   either there are no other parameters or else all other
10196  //   parameters have default arguments.
10197  if (!Constructor->isInvalidDecl() &&
10198      Constructor->hasOneParamOrDefaultArgs() &&
10199      Constructor->getTemplateSpecializationKind() !=
10200          TSK_ImplicitInstantiation) {
10201    QualType ParamType = Constructor->getParamDecl(0)->getType();
10202    QualType ClassTy = Context.getTagDeclType(ClassDecl);
10203    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10204      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10205      const char *ConstRef
10206        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10207                                                        : " const &";
10208      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10209        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10210
10211      // FIXME: Rather that making the constructor invalid, we should endeavor
10212      // to fix the type.
10213      Constructor->setInvalidDecl();
10214    }
10215  }
10216}
10217
10218/// CheckDestructor - Checks a fully-formed destructor definition for
10219/// well-formedness, issuing any diagnostics required.  Returns true
10220/// on error.
10221bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10222  CXXRecordDecl *RD = Destructor->getParent();
10223
10224  if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10225    SourceLocation Loc;
10226
10227    if (!Destructor->isImplicit())
10228      Loc = Destructor->getLocation();
10229    else
10230      Loc = RD->getLocation();
10231
10232    // If we have a virtual destructor, look up the deallocation function
10233    if (FunctionDecl *OperatorDelete =
10234            FindDeallocationFunctionForDestructor(Loc, RD)) {
10235      Expr *ThisArg = nullptr;
10236
10237      // If the notional 'delete this' expression requires a non-trivial
10238      // conversion from 'this' to the type of a destroying operator delete's
10239      // first parameter, perform that conversion now.
10240      if (OperatorDelete->isDestroyingOperatorDelete()) {
10241        QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10242        if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10243          // C++ [class.dtor]p13:
10244          //   ... as if for the expression 'delete this' appearing in a
10245          //   non-virtual destructor of the destructor's class.
10246          ContextRAII SwitchContext(*this, Destructor);
10247          ExprResult This =
10248              ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10249          assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10250          This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10251          if (This.isInvalid()) {
10252            // FIXME: Register this as a context note so that it comes out
10253            // in the right order.
10254            Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10255            return true;
10256          }
10257          ThisArg = This.get();
10258        }
10259      }
10260
10261      DiagnoseUseOfDecl(OperatorDelete, Loc);
10262      MarkFunctionReferenced(Loc, OperatorDelete);
10263      Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10264    }
10265  }
10266
10267  return false;
10268}
10269
10270/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10271/// the well-formednes of the destructor declarator @p D with type @p
10272/// R. If there are any errors in the declarator, this routine will
10273/// emit diagnostics and set the declarator to invalid.  Even if this happens,
10274/// will be updated to reflect a well-formed type for the destructor and
10275/// returned.
10276QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10277                                         StorageClass& SC) {
10278  // C++ [class.dtor]p1:
10279  //   [...] A typedef-name that names a class is a class-name
10280  //   (7.1.3); however, a typedef-name that names a class shall not
10281  //   be used as the identifier in the declarator for a destructor
10282  //   declaration.
10283  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10284  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10285    Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10286      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10287  else if (const TemplateSpecializationType *TST =
10288             DeclaratorType->getAs<TemplateSpecializationType>())
10289    if (TST->isTypeAlias())
10290      Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10291        << DeclaratorType << 1;
10292
10293  // C++ [class.dtor]p2:
10294  //   A destructor is used to destroy objects of its class type. A
10295  //   destructor takes no parameters, and no return type can be
10296  //   specified for it (not even void). The address of a destructor
10297  //   shall not be taken. A destructor shall not be static. A
10298  //   destructor can be invoked for a const, volatile or const
10299  //   volatile object. A destructor shall not be declared const,
10300  //   volatile or const volatile (9.3.2).
10301  if (SC == SC_Static) {
10302    if (!D.isInvalidType())
10303      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10304        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10305        << SourceRange(D.getIdentifierLoc())
10306        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10307
10308    SC = SC_None;
10309  }
10310  if (!D.isInvalidType()) {
10311    // Destructors don't have return types, but the parser will
10312    // happily parse something like:
10313    //
10314    //   class X {
10315    //     float ~X();
10316    //   };
10317    //
10318    // The return type will be eliminated later.
10319    if (D.getDeclSpec().hasTypeSpecifier())
10320      Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10321        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10322        << SourceRange(D.getIdentifierLoc());
10323    else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10324      diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10325                                SourceLocation(),
10326                                D.getDeclSpec().getConstSpecLoc(),
10327                                D.getDeclSpec().getVolatileSpecLoc(),
10328                                D.getDeclSpec().getRestrictSpecLoc(),
10329                                D.getDeclSpec().getAtomicSpecLoc());
10330      D.setInvalidType();
10331    }
10332  }
10333
10334  checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10335
10336  // C++0x [class.dtor]p2:
10337  //   A destructor shall not be declared with a ref-qualifier.
10338  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10339  if (FTI.hasRefQualifier()) {
10340    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10341      << FTI.RefQualifierIsLValueRef
10342      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10343    D.setInvalidType();
10344  }
10345
10346  // Make sure we don't have any parameters.
10347  if (FTIHasNonVoidParameters(FTI)) {
10348    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10349
10350    // Delete the parameters.
10351    FTI.freeParams();
10352    D.setInvalidType();
10353  }
10354
10355  // Make sure the destructor isn't variadic.
10356  if (FTI.isVariadic) {
10357    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10358    D.setInvalidType();
10359  }
10360
10361  // Rebuild the function type "R" without any type qualifiers or
10362  // parameters (in case any of the errors above fired) and with
10363  // "void" as the return type, since destructors don't have return
10364  // types.
10365  if (!D.isInvalidType())
10366    return R;
10367
10368  const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10369  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10370  EPI.Variadic = false;
10371  EPI.TypeQuals = Qualifiers();
10372  EPI.RefQualifier = RQ_None;
10373  return Context.getFunctionType(Context.VoidTy, None, EPI);
10374}
10375
10376static void extendLeft(SourceRange &R, SourceRange Before) {
10377  if (Before.isInvalid())
10378    return;
10379  R.setBegin(Before.getBegin());
10380  if (R.getEnd().isInvalid())
10381    R.setEnd(Before.getEnd());
10382}
10383
10384static void extendRight(SourceRange &R, SourceRange After) {
10385  if (After.isInvalid())
10386    return;
10387  if (R.getBegin().isInvalid())
10388    R.setBegin(After.getBegin());
10389  R.setEnd(After.getEnd());
10390}
10391
10392/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10393/// well-formednes of the conversion function declarator @p D with
10394/// type @p R. If there are any errors in the declarator, this routine
10395/// will emit diagnostics and return true. Otherwise, it will return
10396/// false. Either way, the type @p R will be updated to reflect a
10397/// well-formed type for the conversion operator.
10398void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10399                                     StorageClass& SC) {
10400  // C++ [class.conv.fct]p1:
10401  //   Neither parameter types nor return type can be specified. The
10402  //   type of a conversion function (8.3.5) is "function taking no
10403  //   parameter returning conversion-type-id."
10404  if (SC == SC_Static) {
10405    if (!D.isInvalidType())
10406      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10407        << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10408        << D.getName().getSourceRange();
10409    D.setInvalidType();
10410    SC = SC_None;
10411  }
10412
10413  TypeSourceInfo *ConvTSI = nullptr;
10414  QualType ConvType =
10415      GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10416
10417  const DeclSpec &DS = D.getDeclSpec();
10418  if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10419    // Conversion functions don't have return types, but the parser will
10420    // happily parse something like:
10421    //
10422    //   class X {
10423    //     float operator bool();
10424    //   };
10425    //
10426    // The return type will be changed later anyway.
10427    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10428      << SourceRange(DS.getTypeSpecTypeLoc())
10429      << SourceRange(D.getIdentifierLoc());
10430    D.setInvalidType();
10431  } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10432    // It's also plausible that the user writes type qualifiers in the wrong
10433    // place, such as:
10434    //   struct S { const operator int(); };
10435    // FIXME: we could provide a fixit to move the qualifiers onto the
10436    // conversion type.
10437    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10438        << SourceRange(D.getIdentifierLoc()) << 0;
10439    D.setInvalidType();
10440  }
10441
10442  const auto *Proto = R->castAs<FunctionProtoType>();
10443
10444  // Make sure we don't have any parameters.
10445  if (Proto->getNumParams() > 0) {
10446    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10447
10448    // Delete the parameters.
10449    D.getFunctionTypeInfo().freeParams();
10450    D.setInvalidType();
10451  } else if (Proto->isVariadic()) {
10452    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10453    D.setInvalidType();
10454  }
10455
10456  // Diagnose "&operator bool()" and other such nonsense.  This
10457  // is actually a gcc extension which we don't support.
10458  if (Proto->getReturnType() != ConvType) {
10459    bool NeedsTypedef = false;
10460    SourceRange Before, After;
10461
10462    // Walk the chunks and extract information on them for our diagnostic.
10463    bool PastFunctionChunk = false;
10464    for (auto &Chunk : D.type_objects()) {
10465      switch (Chunk.Kind) {
10466      case DeclaratorChunk::Function:
10467        if (!PastFunctionChunk) {
10468          if (Chunk.Fun.HasTrailingReturnType) {
10469            TypeSourceInfo *TRT = nullptr;
10470            GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10471            if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10472          }
10473          PastFunctionChunk = true;
10474          break;
10475        }
10476        LLVM_FALLTHROUGH;
10477      case DeclaratorChunk::Array:
10478        NeedsTypedef = true;
10479        extendRight(After, Chunk.getSourceRange());
10480        break;
10481
10482      case DeclaratorChunk::Pointer:
10483      case DeclaratorChunk::BlockPointer:
10484      case DeclaratorChunk::Reference:
10485      case DeclaratorChunk::MemberPointer:
10486      case DeclaratorChunk::Pipe:
10487        extendLeft(Before, Chunk.getSourceRange());
10488        break;
10489
10490      case DeclaratorChunk::Paren:
10491        extendLeft(Before, Chunk.Loc);
10492        extendRight(After, Chunk.EndLoc);
10493        break;
10494      }
10495    }
10496
10497    SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10498                         After.isValid()  ? After.getBegin() :
10499                                            D.getIdentifierLoc();
10500    auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10501    DB << Before << After;
10502
10503    if (!NeedsTypedef) {
10504      DB << /*don't need a typedef*/0;
10505
10506      // If we can provide a correct fix-it hint, do so.
10507      if (After.isInvalid() && ConvTSI) {
10508        SourceLocation InsertLoc =
10509            getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10510        DB << FixItHint::CreateInsertion(InsertLoc, " ")
10511           << FixItHint::CreateInsertionFromRange(
10512                  InsertLoc, CharSourceRange::getTokenRange(Before))
10513           << FixItHint::CreateRemoval(Before);
10514      }
10515    } else if (!Proto->getReturnType()->isDependentType()) {
10516      DB << /*typedef*/1 << Proto->getReturnType();
10517    } else if (getLangOpts().CPlusPlus11) {
10518      DB << /*alias template*/2 << Proto->getReturnType();
10519    } else {
10520      DB << /*might not be fixable*/3;
10521    }
10522
10523    // Recover by incorporating the other type chunks into the result type.
10524    // Note, this does *not* change the name of the function. This is compatible
10525    // with the GCC extension:
10526    //   struct S { &operator int(); } s;
10527    //   int &r = s.operator int(); // ok in GCC
10528    //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10529    ConvType = Proto->getReturnType();
10530  }
10531
10532  // C++ [class.conv.fct]p4:
10533  //   The conversion-type-id shall not represent a function type nor
10534  //   an array type.
10535  if (ConvType->isArrayType()) {
10536    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10537    ConvType = Context.getPointerType(ConvType);
10538    D.setInvalidType();
10539  } else if (ConvType->isFunctionType()) {
10540    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10541    ConvType = Context.getPointerType(ConvType);
10542    D.setInvalidType();
10543  }
10544
10545  // Rebuild the function type "R" without any parameters (in case any
10546  // of the errors above fired) and with the conversion type as the
10547  // return type.
10548  if (D.isInvalidType())
10549    R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10550
10551  // C++0x explicit conversion operators.
10552  if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10553    Diag(DS.getExplicitSpecLoc(),
10554         getLangOpts().CPlusPlus11
10555             ? diag::warn_cxx98_compat_explicit_conversion_functions
10556             : diag::ext_explicit_conversion_functions)
10557        << SourceRange(DS.getExplicitSpecRange());
10558}
10559
10560/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10561/// the declaration of the given C++ conversion function. This routine
10562/// is responsible for recording the conversion function in the C++
10563/// class, if possible.
10564Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10565  assert(Conversion && "Expected to receive a conversion function declaration");
10566
10567  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10568
10569  // Make sure we aren't redeclaring the conversion function.
10570  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10571  // C++ [class.conv.fct]p1:
10572  //   [...] A conversion function is never used to convert a
10573  //   (possibly cv-qualified) object to the (possibly cv-qualified)
10574  //   same object type (or a reference to it), to a (possibly
10575  //   cv-qualified) base class of that type (or a reference to it),
10576  //   or to (possibly cv-qualified) void.
10577  QualType ClassType
10578    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10579  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10580    ConvType = ConvTypeRef->getPointeeType();
10581  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10582      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10583    /* Suppress diagnostics for instantiations. */;
10584  else if (Conversion->size_overridden_methods() != 0)
10585    /* Suppress diagnostics for overriding virtual function in a base class. */;
10586  else if (ConvType->isRecordType()) {
10587    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10588    if (ConvType == ClassType)
10589      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10590        << ClassType;
10591    else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10592      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10593        <<  ClassType << ConvType;
10594  } else if (ConvType->isVoidType()) {
10595    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10596      << ClassType << ConvType;
10597  }
10598
10599  if (FunctionTemplateDecl *ConversionTemplate
10600                                = Conversion->getDescribedFunctionTemplate())
10601    return ConversionTemplate;
10602
10603  return Conversion;
10604}
10605
10606namespace {
10607/// Utility class to accumulate and print a diagnostic listing the invalid
10608/// specifier(s) on a declaration.
10609struct BadSpecifierDiagnoser {
10610  BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10611      : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10612  ~BadSpecifierDiagnoser() {
10613    Diagnostic << Specifiers;
10614  }
10615
10616  template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10617    return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10618  }
10619  void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10620    return check(SpecLoc,
10621                 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10622  }
10623  void check(SourceLocation SpecLoc, const char *Spec) {
10624    if (SpecLoc.isInvalid()) return;
10625    Diagnostic << SourceRange(SpecLoc, SpecLoc);
10626    if (!Specifiers.empty()) Specifiers += " ";
10627    Specifiers += Spec;
10628  }
10629
10630  Sema &S;
10631  Sema::SemaDiagnosticBuilder Diagnostic;
10632  std::string Specifiers;
10633};
10634}
10635
10636/// Check the validity of a declarator that we parsed for a deduction-guide.
10637/// These aren't actually declarators in the grammar, so we need to check that
10638/// the user didn't specify any pieces that are not part of the deduction-guide
10639/// grammar.
10640void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10641                                         StorageClass &SC) {
10642  TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10643  TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10644  assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10645
10646  // C++ [temp.deduct.guide]p3:
10647  //   A deduction-gide shall be declared in the same scope as the
10648  //   corresponding class template.
10649  if (!CurContext->getRedeclContext()->Equals(
10650          GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10651    Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10652      << GuidedTemplateDecl;
10653    Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10654  }
10655
10656  auto &DS = D.getMutableDeclSpec();
10657  // We leave 'friend' and 'virtual' to be rejected in the normal way.
10658  if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10659      DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10660      DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10661    BadSpecifierDiagnoser Diagnoser(
10662        *this, D.getIdentifierLoc(),
10663        diag::err_deduction_guide_invalid_specifier);
10664
10665    Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10666    DS.ClearStorageClassSpecs();
10667    SC = SC_None;
10668
10669    // 'explicit' is permitted.
10670    Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10671    Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10672    Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10673    DS.ClearConstexprSpec();
10674
10675    Diagnoser.check(DS.getConstSpecLoc(), "const");
10676    Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10677    Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10678    Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10679    Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10680    DS.ClearTypeQualifiers();
10681
10682    Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10683    Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10684    Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10685    Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10686    DS.ClearTypeSpecType();
10687  }
10688
10689  if (D.isInvalidType())
10690    return;
10691
10692  // Check the declarator is simple enough.
10693  bool FoundFunction = false;
10694  for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10695    if (Chunk.Kind == DeclaratorChunk::Paren)
10696      continue;
10697    if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10698      Diag(D.getDeclSpec().getBeginLoc(),
10699           diag::err_deduction_guide_with_complex_decl)
10700          << D.getSourceRange();
10701      break;
10702    }
10703    if (!Chunk.Fun.hasTrailingReturnType()) {
10704      Diag(D.getName().getBeginLoc(),
10705           diag::err_deduction_guide_no_trailing_return_type);
10706      break;
10707    }
10708
10709    // Check that the return type is written as a specialization of
10710    // the template specified as the deduction-guide's name.
10711    ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10712    TypeSourceInfo *TSI = nullptr;
10713    QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10714    assert(TSI && "deduction guide has valid type but invalid return type?");
10715    bool AcceptableReturnType = false;
10716    bool MightInstantiateToSpecialization = false;
10717    if (auto RetTST =
10718            TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10719      TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10720      bool TemplateMatches =
10721          Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10722      if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10723        AcceptableReturnType = true;
10724      else {
10725        // This could still instantiate to the right type, unless we know it
10726        // names the wrong class template.
10727        auto *TD = SpecifiedName.getAsTemplateDecl();
10728        MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10729                                             !TemplateMatches);
10730      }
10731    } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10732      MightInstantiateToSpecialization = true;
10733    }
10734
10735    if (!AcceptableReturnType) {
10736      Diag(TSI->getTypeLoc().getBeginLoc(),
10737           diag::err_deduction_guide_bad_trailing_return_type)
10738          << GuidedTemplate << TSI->getType()
10739          << MightInstantiateToSpecialization
10740          << TSI->getTypeLoc().getSourceRange();
10741    }
10742
10743    // Keep going to check that we don't have any inner declarator pieces (we
10744    // could still have a function returning a pointer to a function).
10745    FoundFunction = true;
10746  }
10747
10748  if (D.isFunctionDefinition())
10749    Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10750}
10751
10752//===----------------------------------------------------------------------===//
10753// Namespace Handling
10754//===----------------------------------------------------------------------===//
10755
10756/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10757/// reopened.
10758static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10759                                            SourceLocation Loc,
10760                                            IdentifierInfo *II, bool *IsInline,
10761                                            NamespaceDecl *PrevNS) {
10762  assert(*IsInline != PrevNS->isInline());
10763
10764  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10765  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10766  // inline namespaces, with the intention of bringing names into namespace std.
10767  //
10768  // We support this just well enough to get that case working; this is not
10769  // sufficient to support reopening namespaces as inline in general.
10770  if (*IsInline && II && II->getName().startswith("__atomic") &&
10771      S.getSourceManager().isInSystemHeader(Loc)) {
10772    // Mark all prior declarations of the namespace as inline.
10773    for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10774         NS = NS->getPreviousDecl())
10775      NS->setInline(*IsInline);
10776    // Patch up the lookup table for the containing namespace. This isn't really
10777    // correct, but it's good enough for this particular case.
10778    for (auto *I : PrevNS->decls())
10779      if (auto *ND = dyn_cast<NamedDecl>(I))
10780        PrevNS->getParent()->makeDeclVisibleInContext(ND);
10781    return;
10782  }
10783
10784  if (PrevNS->isInline())
10785    // The user probably just forgot the 'inline', so suggest that it
10786    // be added back.
10787    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10788      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10789  else
10790    S.Diag(Loc, diag::err_inline_namespace_mismatch);
10791
10792  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10793  *IsInline = PrevNS->isInline();
10794}
10795
10796/// ActOnStartNamespaceDef - This is called at the start of a namespace
10797/// definition.
10798Decl *Sema::ActOnStartNamespaceDef(
10799    Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10800    SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10801    const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10802  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10803  // For anonymous namespace, take the location of the left brace.
10804  SourceLocation Loc = II ? IdentLoc : LBrace;
10805  bool IsInline = InlineLoc.isValid();
10806  bool IsInvalid = false;
10807  bool IsStd = false;
10808  bool AddToKnown = false;
10809  Scope *DeclRegionScope = NamespcScope->getParent();
10810
10811  NamespaceDecl *PrevNS = nullptr;
10812  if (II) {
10813    // C++ [namespace.def]p2:
10814    //   The identifier in an original-namespace-definition shall not
10815    //   have been previously defined in the declarative region in
10816    //   which the original-namespace-definition appears. The
10817    //   identifier in an original-namespace-definition is the name of
10818    //   the namespace. Subsequently in that declarative region, it is
10819    //   treated as an original-namespace-name.
10820    //
10821    // Since namespace names are unique in their scope, and we don't
10822    // look through using directives, just look for any ordinary names
10823    // as if by qualified name lookup.
10824    LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10825                   ForExternalRedeclaration);
10826    LookupQualifiedName(R, CurContext->getRedeclContext());
10827    NamedDecl *PrevDecl =
10828        R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10829    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10830
10831    if (PrevNS) {
10832      // This is an extended namespace definition.
10833      if (IsInline != PrevNS->isInline())
10834        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10835                                        &IsInline, PrevNS);
10836    } else if (PrevDecl) {
10837      // This is an invalid name redefinition.
10838      Diag(Loc, diag::err_redefinition_different_kind)
10839        << II;
10840      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10841      IsInvalid = true;
10842      // Continue on to push Namespc as current DeclContext and return it.
10843    } else if (II->isStr("std") &&
10844               CurContext->getRedeclContext()->isTranslationUnit()) {
10845      // This is the first "real" definition of the namespace "std", so update
10846      // our cache of the "std" namespace to point at this definition.
10847      PrevNS = getStdNamespace();
10848      IsStd = true;
10849      AddToKnown = !IsInline;
10850    } else {
10851      // We've seen this namespace for the first time.
10852      AddToKnown = !IsInline;
10853    }
10854  } else {
10855    // Anonymous namespaces.
10856
10857    // Determine whether the parent already has an anonymous namespace.
10858    DeclContext *Parent = CurContext->getRedeclContext();
10859    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10860      PrevNS = TU->getAnonymousNamespace();
10861    } else {
10862      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10863      PrevNS = ND->getAnonymousNamespace();
10864    }
10865
10866    if (PrevNS && IsInline != PrevNS->isInline())
10867      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10868                                      &IsInline, PrevNS);
10869  }
10870
10871  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10872                                                 StartLoc, Loc, II, PrevNS);
10873  if (IsInvalid)
10874    Namespc->setInvalidDecl();
10875
10876  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10877  AddPragmaAttributes(DeclRegionScope, Namespc);
10878
10879  // FIXME: Should we be merging attributes?
10880  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10881    PushNamespaceVisibilityAttr(Attr, Loc);
10882
10883  if (IsStd)
10884    StdNamespace = Namespc;
10885  if (AddToKnown)
10886    KnownNamespaces[Namespc] = false;
10887
10888  if (II) {
10889    PushOnScopeChains(Namespc, DeclRegionScope);
10890  } else {
10891    // Link the anonymous namespace into its parent.
10892    DeclContext *Parent = CurContext->getRedeclContext();
10893    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10894      TU->setAnonymousNamespace(Namespc);
10895    } else {
10896      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10897    }
10898
10899    CurContext->addDecl(Namespc);
10900
10901    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10902    //   behaves as if it were replaced by
10903    //     namespace unique { /* empty body */ }
10904    //     using namespace unique;
10905    //     namespace unique { namespace-body }
10906    //   where all occurrences of 'unique' in a translation unit are
10907    //   replaced by the same identifier and this identifier differs
10908    //   from all other identifiers in the entire program.
10909
10910    // We just create the namespace with an empty name and then add an
10911    // implicit using declaration, just like the standard suggests.
10912    //
10913    // CodeGen enforces the "universally unique" aspect by giving all
10914    // declarations semantically contained within an anonymous
10915    // namespace internal linkage.
10916
10917    if (!PrevNS) {
10918      UD = UsingDirectiveDecl::Create(Context, Parent,
10919                                      /* 'using' */ LBrace,
10920                                      /* 'namespace' */ SourceLocation(),
10921                                      /* qualifier */ NestedNameSpecifierLoc(),
10922                                      /* identifier */ SourceLocation(),
10923                                      Namespc,
10924                                      /* Ancestor */ Parent);
10925      UD->setImplicit();
10926      Parent->addDecl(UD);
10927    }
10928  }
10929
10930  ActOnDocumentableDecl(Namespc);
10931
10932  // Although we could have an invalid decl (i.e. the namespace name is a
10933  // redefinition), push it as current DeclContext and try to continue parsing.
10934  // FIXME: We should be able to push Namespc here, so that the each DeclContext
10935  // for the namespace has the declarations that showed up in that particular
10936  // namespace definition.
10937  PushDeclContext(NamespcScope, Namespc);
10938  return Namespc;
10939}
10940
10941/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10942/// is a namespace alias, returns the namespace it points to.
10943static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10944  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10945    return AD->getNamespace();
10946  return dyn_cast_or_null<NamespaceDecl>(D);
10947}
10948
10949/// ActOnFinishNamespaceDef - This callback is called after a namespace is
10950/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
10951void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
10952  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
10953  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
10954  Namespc->setRBraceLoc(RBrace);
10955  PopDeclContext();
10956  if (Namespc->hasAttr<VisibilityAttr>())
10957    PopPragmaVisibility(true, RBrace);
10958  // If this namespace contains an export-declaration, export it now.
10959  if (DeferredExportedNamespaces.erase(Namespc))
10960    Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
10961}
10962
10963CXXRecordDecl *Sema::getStdBadAlloc() const {
10964  return cast_or_null<CXXRecordDecl>(
10965                                  StdBadAlloc.get(Context.getExternalSource()));
10966}
10967
10968EnumDecl *Sema::getStdAlignValT() const {
10969  return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
10970}
10971
10972NamespaceDecl *Sema::getStdNamespace() const {
10973  return cast_or_null<NamespaceDecl>(
10974                                 StdNamespace.get(Context.getExternalSource()));
10975}
10976
10977NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
10978  if (!StdExperimentalNamespaceCache) {
10979    if (auto Std = getStdNamespace()) {
10980      LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
10981                          SourceLocation(), LookupNamespaceName);
10982      if (!LookupQualifiedName(Result, Std) ||
10983          !(StdExperimentalNamespaceCache =
10984                Result.getAsSingle<NamespaceDecl>()))
10985        Result.suppressDiagnostics();
10986    }
10987  }
10988  return StdExperimentalNamespaceCache;
10989}
10990
10991namespace {
10992
10993enum UnsupportedSTLSelect {
10994  USS_InvalidMember,
10995  USS_MissingMember,
10996  USS_NonTrivial,
10997  USS_Other
10998};
10999
11000struct InvalidSTLDiagnoser {
11001  Sema &S;
11002  SourceLocation Loc;
11003  QualType TyForDiags;
11004
11005  QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11006                      const VarDecl *VD = nullptr) {
11007    {
11008      auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11009               << TyForDiags << ((int)Sel);
11010      if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11011        assert(!Name.empty());
11012        D << Name;
11013      }
11014    }
11015    if (Sel == USS_InvalidMember) {
11016      S.Diag(VD->getLocation(), diag::note_var_declared_here)
11017          << VD << VD->getSourceRange();
11018    }
11019    return QualType();
11020  }
11021};
11022} // namespace
11023
11024QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11025                                           SourceLocation Loc,
11026                                           ComparisonCategoryUsage Usage) {
11027  assert(getLangOpts().CPlusPlus &&
11028         "Looking for comparison category type outside of C++.");
11029
11030  // Use an elaborated type for diagnostics which has a name containing the
11031  // prepended 'std' namespace but not any inline namespace names.
11032  auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11033    auto *NNS =
11034        NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11035    return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11036  };
11037
11038  // Check if we've already successfully checked the comparison category type
11039  // before. If so, skip checking it again.
11040  ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11041  if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11042    // The only thing we need to check is that the type has a reachable
11043    // definition in the current context.
11044    if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11045      return QualType();
11046
11047    return Info->getType();
11048  }
11049
11050  // If lookup failed
11051  if (!Info) {
11052    std::string NameForDiags = "std::";
11053    NameForDiags += ComparisonCategories::getCategoryString(Kind);
11054    Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11055        << NameForDiags << (int)Usage;
11056    return QualType();
11057  }
11058
11059  assert(Info->Kind == Kind);
11060  assert(Info->Record);
11061
11062  // Update the Record decl in case we encountered a forward declaration on our
11063  // first pass. FIXME: This is a bit of a hack.
11064  if (Info->Record->hasDefinition())
11065    Info->Record = Info->Record->getDefinition();
11066
11067  if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11068    return QualType();
11069
11070  InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11071
11072  if (!Info->Record->isTriviallyCopyable())
11073    return UnsupportedSTLError(USS_NonTrivial);
11074
11075  for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11076    CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11077    // Tolerate empty base classes.
11078    if (Base->isEmpty())
11079      continue;
11080    // Reject STL implementations which have at least one non-empty base.
11081    return UnsupportedSTLError();
11082  }
11083
11084  // Check that the STL has implemented the types using a single integer field.
11085  // This expectation allows better codegen for builtin operators. We require:
11086  //   (1) The class has exactly one field.
11087  //   (2) The field is an integral or enumeration type.
11088  auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11089  if (std::distance(FIt, FEnd) != 1 ||
11090      !FIt->getType()->isIntegralOrEnumerationType()) {
11091    return UnsupportedSTLError();
11092  }
11093
11094  // Build each of the require values and store them in Info.
11095  for (ComparisonCategoryResult CCR :
11096       ComparisonCategories::getPossibleResultsForType(Kind)) {
11097    StringRef MemName = ComparisonCategories::getResultString(CCR);
11098    ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11099
11100    if (!ValInfo)
11101      return UnsupportedSTLError(USS_MissingMember, MemName);
11102
11103    VarDecl *VD = ValInfo->VD;
11104    assert(VD && "should not be null!");
11105
11106    // Attempt to diagnose reasons why the STL definition of this type
11107    // might be foobar, including it failing to be a constant expression.
11108    // TODO Handle more ways the lookup or result can be invalid.
11109    if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
11110        !VD->checkInitIsICE())
11111      return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11112
11113    // Attempt to evaluate the var decl as a constant expression and extract
11114    // the value of its first field as a ICE. If this fails, the STL
11115    // implementation is not supported.
11116    if (!ValInfo->hasValidIntValue())
11117      return UnsupportedSTLError();
11118
11119    MarkVariableReferenced(Loc, VD);
11120  }
11121
11122  // We've successfully built the required types and expressions. Update
11123  // the cache and return the newly cached value.
11124  FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11125  return Info->getType();
11126}
11127
11128/// Retrieve the special "std" namespace, which may require us to
11129/// implicitly define the namespace.
11130NamespaceDecl *Sema::getOrCreateStdNamespace() {
11131  if (!StdNamespace) {
11132    // The "std" namespace has not yet been defined, so build one implicitly.
11133    StdNamespace = NamespaceDecl::Create(Context,
11134                                         Context.getTranslationUnitDecl(),
11135                                         /*Inline=*/false,
11136                                         SourceLocation(), SourceLocation(),
11137                                         &PP.getIdentifierTable().get("std"),
11138                                         /*PrevDecl=*/nullptr);
11139    getStdNamespace()->setImplicit(true);
11140  }
11141
11142  return getStdNamespace();
11143}
11144
11145bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11146  assert(getLangOpts().CPlusPlus &&
11147         "Looking for std::initializer_list outside of C++.");
11148
11149  // We're looking for implicit instantiations of
11150  // template <typename E> class std::initializer_list.
11151
11152  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11153    return false;
11154
11155  ClassTemplateDecl *Template = nullptr;
11156  const TemplateArgument *Arguments = nullptr;
11157
11158  if (const RecordType *RT = Ty->getAs<RecordType>()) {
11159
11160    ClassTemplateSpecializationDecl *Specialization =
11161        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11162    if (!Specialization)
11163      return false;
11164
11165    Template = Specialization->getSpecializedTemplate();
11166    Arguments = Specialization->getTemplateArgs().data();
11167  } else if (const TemplateSpecializationType *TST =
11168                 Ty->getAs<TemplateSpecializationType>()) {
11169    Template = dyn_cast_or_null<ClassTemplateDecl>(
11170        TST->getTemplateName().getAsTemplateDecl());
11171    Arguments = TST->getArgs();
11172  }
11173  if (!Template)
11174    return false;
11175
11176  if (!StdInitializerList) {
11177    // Haven't recognized std::initializer_list yet, maybe this is it.
11178    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11179    if (TemplateClass->getIdentifier() !=
11180            &PP.getIdentifierTable().get("initializer_list") ||
11181        !getStdNamespace()->InEnclosingNamespaceSetOf(
11182            TemplateClass->getDeclContext()))
11183      return false;
11184    // This is a template called std::initializer_list, but is it the right
11185    // template?
11186    TemplateParameterList *Params = Template->getTemplateParameters();
11187    if (Params->getMinRequiredArguments() != 1)
11188      return false;
11189    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11190      return false;
11191
11192    // It's the right template.
11193    StdInitializerList = Template;
11194  }
11195
11196  if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11197    return false;
11198
11199  // This is an instance of std::initializer_list. Find the argument type.
11200  if (Element)
11201    *Element = Arguments[0].getAsType();
11202  return true;
11203}
11204
11205static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11206  NamespaceDecl *Std = S.getStdNamespace();
11207  if (!Std) {
11208    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11209    return nullptr;
11210  }
11211
11212  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11213                      Loc, Sema::LookupOrdinaryName);
11214  if (!S.LookupQualifiedName(Result, Std)) {
11215    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11216    return nullptr;
11217  }
11218  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11219  if (!Template) {
11220    Result.suppressDiagnostics();
11221    // We found something weird. Complain about the first thing we found.
11222    NamedDecl *Found = *Result.begin();
11223    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11224    return nullptr;
11225  }
11226
11227  // We found some template called std::initializer_list. Now verify that it's
11228  // correct.
11229  TemplateParameterList *Params = Template->getTemplateParameters();
11230  if (Params->getMinRequiredArguments() != 1 ||
11231      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11232    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11233    return nullptr;
11234  }
11235
11236  return Template;
11237}
11238
11239QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11240  if (!StdInitializerList) {
11241    StdInitializerList = LookupStdInitializerList(*this, Loc);
11242    if (!StdInitializerList)
11243      return QualType();
11244  }
11245
11246  TemplateArgumentListInfo Args(Loc, Loc);
11247  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11248                                       Context.getTrivialTypeSourceInfo(Element,
11249                                                                        Loc)));
11250  return Context.getCanonicalType(
11251      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11252}
11253
11254bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11255  // C++ [dcl.init.list]p2:
11256  //   A constructor is an initializer-list constructor if its first parameter
11257  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11258  //   std::initializer_list<E> for some type E, and either there are no other
11259  //   parameters or else all other parameters have default arguments.
11260  if (!Ctor->hasOneParamOrDefaultArgs())
11261    return false;
11262
11263  QualType ArgType = Ctor->getParamDecl(0)->getType();
11264  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11265    ArgType = RT->getPointeeType().getUnqualifiedType();
11266
11267  return isStdInitializerList(ArgType, nullptr);
11268}
11269
11270/// Determine whether a using statement is in a context where it will be
11271/// apply in all contexts.
11272static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11273  switch (CurContext->getDeclKind()) {
11274    case Decl::TranslationUnit:
11275      return true;
11276    case Decl::LinkageSpec:
11277      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11278    default:
11279      return false;
11280  }
11281}
11282
11283namespace {
11284
11285// Callback to only accept typo corrections that are namespaces.
11286class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11287public:
11288  bool ValidateCandidate(const TypoCorrection &candidate) override {
11289    if (NamedDecl *ND = candidate.getCorrectionDecl())
11290      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11291    return false;
11292  }
11293
11294  std::unique_ptr<CorrectionCandidateCallback> clone() override {
11295    return std::make_unique<NamespaceValidatorCCC>(*this);
11296  }
11297};
11298
11299}
11300
11301static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11302                                       CXXScopeSpec &SS,
11303                                       SourceLocation IdentLoc,
11304                                       IdentifierInfo *Ident) {
11305  R.clear();
11306  NamespaceValidatorCCC CCC{};
11307  if (TypoCorrection Corrected =
11308          S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11309                        Sema::CTK_ErrorRecovery)) {
11310    if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11311      std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11312      bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11313                              Ident->getName().equals(CorrectedStr);
11314      S.diagnoseTypo(Corrected,
11315                     S.PDiag(diag::err_using_directive_member_suggest)
11316                       << Ident << DC << DroppedSpecifier << SS.getRange(),
11317                     S.PDiag(diag::note_namespace_defined_here));
11318    } else {
11319      S.diagnoseTypo(Corrected,
11320                     S.PDiag(diag::err_using_directive_suggest) << Ident,
11321                     S.PDiag(diag::note_namespace_defined_here));
11322    }
11323    R.addDecl(Corrected.getFoundDecl());
11324    return true;
11325  }
11326  return false;
11327}
11328
11329Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11330                                SourceLocation NamespcLoc, CXXScopeSpec &SS,
11331                                SourceLocation IdentLoc,
11332                                IdentifierInfo *NamespcName,
11333                                const ParsedAttributesView &AttrList) {
11334  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11335  assert(NamespcName && "Invalid NamespcName.");
11336  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11337
11338  // This can only happen along a recovery path.
11339  while (S->isTemplateParamScope())
11340    S = S->getParent();
11341  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11342
11343  UsingDirectiveDecl *UDir = nullptr;
11344  NestedNameSpecifier *Qualifier = nullptr;
11345  if (SS.isSet())
11346    Qualifier = SS.getScopeRep();
11347
11348  // Lookup namespace name.
11349  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11350  LookupParsedName(R, S, &SS);
11351  if (R.isAmbiguous())
11352    return nullptr;
11353
11354  if (R.empty()) {
11355    R.clear();
11356    // Allow "using namespace std;" or "using namespace ::std;" even if
11357    // "std" hasn't been defined yet, for GCC compatibility.
11358    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11359        NamespcName->isStr("std")) {
11360      Diag(IdentLoc, diag::ext_using_undefined_std);
11361      R.addDecl(getOrCreateStdNamespace());
11362      R.resolveKind();
11363    }
11364    // Otherwise, attempt typo correction.
11365    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11366  }
11367
11368  if (!R.empty()) {
11369    NamedDecl *Named = R.getRepresentativeDecl();
11370    NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11371    assert(NS && "expected namespace decl");
11372
11373    // The use of a nested name specifier may trigger deprecation warnings.
11374    DiagnoseUseOfDecl(Named, IdentLoc);
11375
11376    // C++ [namespace.udir]p1:
11377    //   A using-directive specifies that the names in the nominated
11378    //   namespace can be used in the scope in which the
11379    //   using-directive appears after the using-directive. During
11380    //   unqualified name lookup (3.4.1), the names appear as if they
11381    //   were declared in the nearest enclosing namespace which
11382    //   contains both the using-directive and the nominated
11383    //   namespace. [Note: in this context, "contains" means "contains
11384    //   directly or indirectly". ]
11385
11386    // Find enclosing context containing both using-directive and
11387    // nominated namespace.
11388    DeclContext *CommonAncestor = NS;
11389    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11390      CommonAncestor = CommonAncestor->getParent();
11391
11392    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11393                                      SS.getWithLocInContext(Context),
11394                                      IdentLoc, Named, CommonAncestor);
11395
11396    if (IsUsingDirectiveInToplevelContext(CurContext) &&
11397        !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11398      Diag(IdentLoc, diag::warn_using_directive_in_header);
11399    }
11400
11401    PushUsingDirective(S, UDir);
11402  } else {
11403    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11404  }
11405
11406  if (UDir)
11407    ProcessDeclAttributeList(S, UDir, AttrList);
11408
11409  return UDir;
11410}
11411
11412void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11413  // If the scope has an associated entity and the using directive is at
11414  // namespace or translation unit scope, add the UsingDirectiveDecl into
11415  // its lookup structure so qualified name lookup can find it.
11416  DeclContext *Ctx = S->getEntity();
11417  if (Ctx && !Ctx->isFunctionOrMethod())
11418    Ctx->addDecl(UDir);
11419  else
11420    // Otherwise, it is at block scope. The using-directives will affect lookup
11421    // only to the end of the scope.
11422    S->PushUsingDirective(UDir);
11423}
11424
11425Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11426                                  SourceLocation UsingLoc,
11427                                  SourceLocation TypenameLoc, CXXScopeSpec &SS,
11428                                  UnqualifiedId &Name,
11429                                  SourceLocation EllipsisLoc,
11430                                  const ParsedAttributesView &AttrList) {
11431  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11432
11433  if (SS.isEmpty()) {
11434    Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11435    return nullptr;
11436  }
11437
11438  switch (Name.getKind()) {
11439  case UnqualifiedIdKind::IK_ImplicitSelfParam:
11440  case UnqualifiedIdKind::IK_Identifier:
11441  case UnqualifiedIdKind::IK_OperatorFunctionId:
11442  case UnqualifiedIdKind::IK_LiteralOperatorId:
11443  case UnqualifiedIdKind::IK_ConversionFunctionId:
11444    break;
11445
11446  case UnqualifiedIdKind::IK_ConstructorName:
11447  case UnqualifiedIdKind::IK_ConstructorTemplateId:
11448    // C++11 inheriting constructors.
11449    Diag(Name.getBeginLoc(),
11450         getLangOpts().CPlusPlus11
11451             ? diag::warn_cxx98_compat_using_decl_constructor
11452             : diag::err_using_decl_constructor)
11453        << SS.getRange();
11454
11455    if (getLangOpts().CPlusPlus11) break;
11456
11457    return nullptr;
11458
11459  case UnqualifiedIdKind::IK_DestructorName:
11460    Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11461    return nullptr;
11462
11463  case UnqualifiedIdKind::IK_TemplateId:
11464    Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11465        << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11466    return nullptr;
11467
11468  case UnqualifiedIdKind::IK_DeductionGuideName:
11469    llvm_unreachable("cannot parse qualified deduction guide name");
11470  }
11471
11472  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11473  DeclarationName TargetName = TargetNameInfo.getName();
11474  if (!TargetName)
11475    return nullptr;
11476
11477  // Warn about access declarations.
11478  if (UsingLoc.isInvalid()) {
11479    Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11480                                 ? diag::err_access_decl
11481                                 : diag::warn_access_decl_deprecated)
11482        << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11483  }
11484
11485  if (EllipsisLoc.isInvalid()) {
11486    if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11487        DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11488      return nullptr;
11489  } else {
11490    if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11491        !TargetNameInfo.containsUnexpandedParameterPack()) {
11492      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11493        << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11494      EllipsisLoc = SourceLocation();
11495    }
11496  }
11497
11498  NamedDecl *UD =
11499      BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11500                            SS, TargetNameInfo, EllipsisLoc, AttrList,
11501                            /*IsInstantiation*/false);
11502  if (UD)
11503    PushOnScopeChains(UD, S, /*AddToContext*/ false);
11504
11505  return UD;
11506}
11507
11508/// Determine whether a using declaration considers the given
11509/// declarations as "equivalent", e.g., if they are redeclarations of
11510/// the same entity or are both typedefs of the same type.
11511static bool
11512IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11513  if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11514    return true;
11515
11516  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11517    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11518      return Context.hasSameType(TD1->getUnderlyingType(),
11519                                 TD2->getUnderlyingType());
11520
11521  return false;
11522}
11523
11524
11525/// Determines whether to create a using shadow decl for a particular
11526/// decl, given the set of decls existing prior to this using lookup.
11527bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11528                                const LookupResult &Previous,
11529                                UsingShadowDecl *&PrevShadow) {
11530  // Diagnose finding a decl which is not from a base class of the
11531  // current class.  We do this now because there are cases where this
11532  // function will silently decide not to build a shadow decl, which
11533  // will pre-empt further diagnostics.
11534  //
11535  // We don't need to do this in C++11 because we do the check once on
11536  // the qualifier.
11537  //
11538  // FIXME: diagnose the following if we care enough:
11539  //   struct A { int foo; };
11540  //   struct B : A { using A::foo; };
11541  //   template <class T> struct C : A {};
11542  //   template <class T> struct D : C<T> { using B::foo; } // <---
11543  // This is invalid (during instantiation) in C++03 because B::foo
11544  // resolves to the using decl in B, which is not a base class of D<T>.
11545  // We can't diagnose it immediately because C<T> is an unknown
11546  // specialization.  The UsingShadowDecl in D<T> then points directly
11547  // to A::foo, which will look well-formed when we instantiate.
11548  // The right solution is to not collapse the shadow-decl chain.
11549  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11550    DeclContext *OrigDC = Orig->getDeclContext();
11551
11552    // Handle enums and anonymous structs.
11553    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11554    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11555    while (OrigRec->isAnonymousStructOrUnion())
11556      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11557
11558    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11559      if (OrigDC == CurContext) {
11560        Diag(Using->getLocation(),
11561             diag::err_using_decl_nested_name_specifier_is_current_class)
11562          << Using->getQualifierLoc().getSourceRange();
11563        Diag(Orig->getLocation(), diag::note_using_decl_target);
11564        Using->setInvalidDecl();
11565        return true;
11566      }
11567
11568      Diag(Using->getQualifierLoc().getBeginLoc(),
11569           diag::err_using_decl_nested_name_specifier_is_not_base_class)
11570        << Using->getQualifier()
11571        << cast<CXXRecordDecl>(CurContext)
11572        << Using->getQualifierLoc().getSourceRange();
11573      Diag(Orig->getLocation(), diag::note_using_decl_target);
11574      Using->setInvalidDecl();
11575      return true;
11576    }
11577  }
11578
11579  if (Previous.empty()) return false;
11580
11581  NamedDecl *Target = Orig;
11582  if (isa<UsingShadowDecl>(Target))
11583    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11584
11585  // If the target happens to be one of the previous declarations, we
11586  // don't have a conflict.
11587  //
11588  // FIXME: but we might be increasing its access, in which case we
11589  // should redeclare it.
11590  NamedDecl *NonTag = nullptr, *Tag = nullptr;
11591  bool FoundEquivalentDecl = false;
11592  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11593         I != E; ++I) {
11594    NamedDecl *D = (*I)->getUnderlyingDecl();
11595    // We can have UsingDecls in our Previous results because we use the same
11596    // LookupResult for checking whether the UsingDecl itself is a valid
11597    // redeclaration.
11598    if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11599      continue;
11600
11601    if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11602      // C++ [class.mem]p19:
11603      //   If T is the name of a class, then [every named member other than
11604      //   a non-static data member] shall have a name different from T
11605      if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11606          !isa<IndirectFieldDecl>(Target) &&
11607          !isa<UnresolvedUsingValueDecl>(Target) &&
11608          DiagnoseClassNameShadow(
11609              CurContext,
11610              DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11611        return true;
11612    }
11613
11614    if (IsEquivalentForUsingDecl(Context, D, Target)) {
11615      if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11616        PrevShadow = Shadow;
11617      FoundEquivalentDecl = true;
11618    } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11619      // We don't conflict with an existing using shadow decl of an equivalent
11620      // declaration, but we're not a redeclaration of it.
11621      FoundEquivalentDecl = true;
11622    }
11623
11624    if (isVisible(D))
11625      (isa<TagDecl>(D) ? Tag : NonTag) = D;
11626  }
11627
11628  if (FoundEquivalentDecl)
11629    return false;
11630
11631  if (FunctionDecl *FD = Target->getAsFunction()) {
11632    NamedDecl *OldDecl = nullptr;
11633    switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11634                          /*IsForUsingDecl*/ true)) {
11635    case Ovl_Overload:
11636      return false;
11637
11638    case Ovl_NonFunction:
11639      Diag(Using->getLocation(), diag::err_using_decl_conflict);
11640      break;
11641
11642    // We found a decl with the exact signature.
11643    case Ovl_Match:
11644      // If we're in a record, we want to hide the target, so we
11645      // return true (without a diagnostic) to tell the caller not to
11646      // build a shadow decl.
11647      if (CurContext->isRecord())
11648        return true;
11649
11650      // If we're not in a record, this is an error.
11651      Diag(Using->getLocation(), diag::err_using_decl_conflict);
11652      break;
11653    }
11654
11655    Diag(Target->getLocation(), diag::note_using_decl_target);
11656    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11657    Using->setInvalidDecl();
11658    return true;
11659  }
11660
11661  // Target is not a function.
11662
11663  if (isa<TagDecl>(Target)) {
11664    // No conflict between a tag and a non-tag.
11665    if (!Tag) return false;
11666
11667    Diag(Using->getLocation(), diag::err_using_decl_conflict);
11668    Diag(Target->getLocation(), diag::note_using_decl_target);
11669    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11670    Using->setInvalidDecl();
11671    return true;
11672  }
11673
11674  // No conflict between a tag and a non-tag.
11675  if (!NonTag) return false;
11676
11677  Diag(Using->getLocation(), diag::err_using_decl_conflict);
11678  Diag(Target->getLocation(), diag::note_using_decl_target);
11679  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11680  Using->setInvalidDecl();
11681  return true;
11682}
11683
11684/// Determine whether a direct base class is a virtual base class.
11685static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11686  if (!Derived->getNumVBases())
11687    return false;
11688  for (auto &B : Derived->bases())
11689    if (B.getType()->getAsCXXRecordDecl() == Base)
11690      return B.isVirtual();
11691  llvm_unreachable("not a direct base class");
11692}
11693
11694/// Builds a shadow declaration corresponding to a 'using' declaration.
11695UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11696                                            UsingDecl *UD,
11697                                            NamedDecl *Orig,
11698                                            UsingShadowDecl *PrevDecl) {
11699  // If we resolved to another shadow declaration, just coalesce them.
11700  NamedDecl *Target = Orig;
11701  if (isa<UsingShadowDecl>(Target)) {
11702    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11703    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11704  }
11705
11706  NamedDecl *NonTemplateTarget = Target;
11707  if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11708    NonTemplateTarget = TargetTD->getTemplatedDecl();
11709
11710  UsingShadowDecl *Shadow;
11711  if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11712    bool IsVirtualBase =
11713        isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11714                            UD->getQualifier()->getAsRecordDecl());
11715    Shadow = ConstructorUsingShadowDecl::Create(
11716        Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11717  } else {
11718    Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11719                                     Target);
11720  }
11721  UD->addShadowDecl(Shadow);
11722
11723  Shadow->setAccess(UD->getAccess());
11724  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11725    Shadow->setInvalidDecl();
11726
11727  Shadow->setPreviousDecl(PrevDecl);
11728
11729  if (S)
11730    PushOnScopeChains(Shadow, S);
11731  else
11732    CurContext->addDecl(Shadow);
11733
11734
11735  return Shadow;
11736}
11737
11738/// Hides a using shadow declaration.  This is required by the current
11739/// using-decl implementation when a resolvable using declaration in a
11740/// class is followed by a declaration which would hide or override
11741/// one or more of the using decl's targets; for example:
11742///
11743///   struct Base { void foo(int); };
11744///   struct Derived : Base {
11745///     using Base::foo;
11746///     void foo(int);
11747///   };
11748///
11749/// The governing language is C++03 [namespace.udecl]p12:
11750///
11751///   When a using-declaration brings names from a base class into a
11752///   derived class scope, member functions in the derived class
11753///   override and/or hide member functions with the same name and
11754///   parameter types in a base class (rather than conflicting).
11755///
11756/// There are two ways to implement this:
11757///   (1) optimistically create shadow decls when they're not hidden
11758///       by existing declarations, or
11759///   (2) don't create any shadow decls (or at least don't make them
11760///       visible) until we've fully parsed/instantiated the class.
11761/// The problem with (1) is that we might have to retroactively remove
11762/// a shadow decl, which requires several O(n) operations because the
11763/// decl structures are (very reasonably) not designed for removal.
11764/// (2) avoids this but is very fiddly and phase-dependent.
11765void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11766  if (Shadow->getDeclName().getNameKind() ==
11767        DeclarationName::CXXConversionFunctionName)
11768    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11769
11770  // Remove it from the DeclContext...
11771  Shadow->getDeclContext()->removeDecl(Shadow);
11772
11773  // ...and the scope, if applicable...
11774  if (S) {
11775    S->RemoveDecl(Shadow);
11776    IdResolver.RemoveDecl(Shadow);
11777  }
11778
11779  // ...and the using decl.
11780  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11781
11782  // TODO: complain somehow if Shadow was used.  It shouldn't
11783  // be possible for this to happen, because...?
11784}
11785
11786/// Find the base specifier for a base class with the given type.
11787static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11788                                                QualType DesiredBase,
11789                                                bool &AnyDependentBases) {
11790  // Check whether the named type is a direct base class.
11791  CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11792    .getUnqualifiedType();
11793  for (auto &Base : Derived->bases()) {
11794    CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11795    if (CanonicalDesiredBase == BaseType)
11796      return &Base;
11797    if (BaseType->isDependentType())
11798      AnyDependentBases = true;
11799  }
11800  return nullptr;
11801}
11802
11803namespace {
11804class UsingValidatorCCC final : public CorrectionCandidateCallback {
11805public:
11806  UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11807                    NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11808      : HasTypenameKeyword(HasTypenameKeyword),
11809        IsInstantiation(IsInstantiation), OldNNS(NNS),
11810        RequireMemberOf(RequireMemberOf) {}
11811
11812  bool ValidateCandidate(const TypoCorrection &Candidate) override {
11813    NamedDecl *ND = Candidate.getCorrectionDecl();
11814
11815    // Keywords are not valid here.
11816    if (!ND || isa<NamespaceDecl>(ND))
11817      return false;
11818
11819    // Completely unqualified names are invalid for a 'using' declaration.
11820    if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11821      return false;
11822
11823    // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11824    // reject.
11825
11826    if (RequireMemberOf) {
11827      auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11828      if (FoundRecord && FoundRecord->isInjectedClassName()) {
11829        // No-one ever wants a using-declaration to name an injected-class-name
11830        // of a base class, unless they're declaring an inheriting constructor.
11831        ASTContext &Ctx = ND->getASTContext();
11832        if (!Ctx.getLangOpts().CPlusPlus11)
11833          return false;
11834        QualType FoundType = Ctx.getRecordType(FoundRecord);
11835
11836        // Check that the injected-class-name is named as a member of its own
11837        // type; we don't want to suggest 'using Derived::Base;', since that
11838        // means something else.
11839        NestedNameSpecifier *Specifier =
11840            Candidate.WillReplaceSpecifier()
11841                ? Candidate.getCorrectionSpecifier()
11842                : OldNNS;
11843        if (!Specifier->getAsType() ||
11844            !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11845          return false;
11846
11847        // Check that this inheriting constructor declaration actually names a
11848        // direct base class of the current class.
11849        bool AnyDependentBases = false;
11850        if (!findDirectBaseWithType(RequireMemberOf,
11851                                    Ctx.getRecordType(FoundRecord),
11852                                    AnyDependentBases) &&
11853            !AnyDependentBases)
11854          return false;
11855      } else {
11856        auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11857        if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11858          return false;
11859
11860        // FIXME: Check that the base class member is accessible?
11861      }
11862    } else {
11863      auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11864      if (FoundRecord && FoundRecord->isInjectedClassName())
11865        return false;
11866    }
11867
11868    if (isa<TypeDecl>(ND))
11869      return HasTypenameKeyword || !IsInstantiation;
11870
11871    return !HasTypenameKeyword;
11872  }
11873
11874  std::unique_ptr<CorrectionCandidateCallback> clone() override {
11875    return std::make_unique<UsingValidatorCCC>(*this);
11876  }
11877
11878private:
11879  bool HasTypenameKeyword;
11880  bool IsInstantiation;
11881  NestedNameSpecifier *OldNNS;
11882  CXXRecordDecl *RequireMemberOf;
11883};
11884} // end anonymous namespace
11885
11886/// Builds a using declaration.
11887///
11888/// \param IsInstantiation - Whether this call arises from an
11889///   instantiation of an unresolved using declaration.  We treat
11890///   the lookup differently for these declarations.
11891NamedDecl *Sema::BuildUsingDeclaration(
11892    Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11893    bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11894    DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11895    const ParsedAttributesView &AttrList, bool IsInstantiation) {
11896  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11897  SourceLocation IdentLoc = NameInfo.getLoc();
11898  assert(IdentLoc.isValid() && "Invalid TargetName location.");
11899
11900  // FIXME: We ignore attributes for now.
11901
11902  // For an inheriting constructor declaration, the name of the using
11903  // declaration is the name of a constructor in this class, not in the
11904  // base class.
11905  DeclarationNameInfo UsingName = NameInfo;
11906  if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11907    if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11908      UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11909          Context.getCanonicalType(Context.getRecordType(RD))));
11910
11911  // Do the redeclaration lookup in the current scope.
11912  LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11913                        ForVisibleRedeclaration);
11914  Previous.setHideTags(false);
11915  if (S) {
11916    LookupName(Previous, S);
11917
11918    // It is really dumb that we have to do this.
11919    LookupResult::Filter F = Previous.makeFilter();
11920    while (F.hasNext()) {
11921      NamedDecl *D = F.next();
11922      if (!isDeclInScope(D, CurContext, S))
11923        F.erase();
11924      // If we found a local extern declaration that's not ordinarily visible,
11925      // and this declaration is being added to a non-block scope, ignore it.
11926      // We're only checking for scope conflicts here, not also for violations
11927      // of the linkage rules.
11928      else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11929               !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11930        F.erase();
11931    }
11932    F.done();
11933  } else {
11934    assert(IsInstantiation && "no scope in non-instantiation");
11935    if (CurContext->isRecord())
11936      LookupQualifiedName(Previous, CurContext);
11937    else {
11938      // No redeclaration check is needed here; in non-member contexts we
11939      // diagnosed all possible conflicts with other using-declarations when
11940      // building the template:
11941      //
11942      // For a dependent non-type using declaration, the only valid case is
11943      // if we instantiate to a single enumerator. We check for conflicts
11944      // between shadow declarations we introduce, and we check in the template
11945      // definition for conflicts between a non-type using declaration and any
11946      // other declaration, which together covers all cases.
11947      //
11948      // A dependent typename using declaration will never successfully
11949      // instantiate, since it will always name a class member, so we reject
11950      // that in the template definition.
11951    }
11952  }
11953
11954  // Check for invalid redeclarations.
11955  if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
11956                                  SS, IdentLoc, Previous))
11957    return nullptr;
11958
11959  // Check for bad qualifiers.
11960  if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
11961                              IdentLoc))
11962    return nullptr;
11963
11964  DeclContext *LookupContext = computeDeclContext(SS);
11965  NamedDecl *D;
11966  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11967  if (!LookupContext || EllipsisLoc.isValid()) {
11968    if (HasTypenameKeyword) {
11969      // FIXME: not all declaration name kinds are legal here
11970      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
11971                                              UsingLoc, TypenameLoc,
11972                                              QualifierLoc,
11973                                              IdentLoc, NameInfo.getName(),
11974                                              EllipsisLoc);
11975    } else {
11976      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
11977                                           QualifierLoc, NameInfo, EllipsisLoc);
11978    }
11979    D->setAccess(AS);
11980    CurContext->addDecl(D);
11981    return D;
11982  }
11983
11984  auto Build = [&](bool Invalid) {
11985    UsingDecl *UD =
11986        UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
11987                          UsingName, HasTypenameKeyword);
11988    UD->setAccess(AS);
11989    CurContext->addDecl(UD);
11990    UD->setInvalidDecl(Invalid);
11991    return UD;
11992  };
11993  auto BuildInvalid = [&]{ return Build(true); };
11994  auto BuildValid = [&]{ return Build(false); };
11995
11996  if (RequireCompleteDeclContext(SS, LookupContext))
11997    return BuildInvalid();
11998
11999  // Look up the target name.
12000  LookupResult R(*this, NameInfo, LookupOrdinaryName);
12001
12002  // Unlike most lookups, we don't always want to hide tag
12003  // declarations: tag names are visible through the using declaration
12004  // even if hidden by ordinary names, *except* in a dependent context
12005  // where it's important for the sanity of two-phase lookup.
12006  if (!IsInstantiation)
12007    R.setHideTags(false);
12008
12009  // For the purposes of this lookup, we have a base object type
12010  // equal to that of the current context.
12011  if (CurContext->isRecord()) {
12012    R.setBaseObjectType(
12013                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12014  }
12015
12016  LookupQualifiedName(R, LookupContext);
12017
12018  // Try to correct typos if possible. If constructor name lookup finds no
12019  // results, that means the named class has no explicit constructors, and we
12020  // suppressed declaring implicit ones (probably because it's dependent or
12021  // invalid).
12022  if (R.empty() &&
12023      NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12024    // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
12025    // it will believe that glibc provides a ::gets in cases where it does not,
12026    // and will try to pull it into namespace std with a using-declaration.
12027    // Just ignore the using-declaration in that case.
12028    auto *II = NameInfo.getName().getAsIdentifierInfo();
12029    if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12030        CurContext->isStdNamespace() &&
12031        isa<TranslationUnitDecl>(LookupContext) &&
12032        getSourceManager().isInSystemHeader(UsingLoc))
12033      return nullptr;
12034    UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12035                          dyn_cast<CXXRecordDecl>(CurContext));
12036    if (TypoCorrection Corrected =
12037            CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12038                        CTK_ErrorRecovery)) {
12039      // We reject candidates where DroppedSpecifier == true, hence the
12040      // literal '0' below.
12041      diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12042                                << NameInfo.getName() << LookupContext << 0
12043                                << SS.getRange());
12044
12045      // If we picked a correction with no attached Decl we can't do anything
12046      // useful with it, bail out.
12047      NamedDecl *ND = Corrected.getCorrectionDecl();
12048      if (!ND)
12049        return BuildInvalid();
12050
12051      // If we corrected to an inheriting constructor, handle it as one.
12052      auto *RD = dyn_cast<CXXRecordDecl>(ND);
12053      if (RD && RD->isInjectedClassName()) {
12054        // The parent of the injected class name is the class itself.
12055        RD = cast<CXXRecordDecl>(RD->getParent());
12056
12057        // Fix up the information we'll use to build the using declaration.
12058        if (Corrected.WillReplaceSpecifier()) {
12059          NestedNameSpecifierLocBuilder Builder;
12060          Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12061                              QualifierLoc.getSourceRange());
12062          QualifierLoc = Builder.getWithLocInContext(Context);
12063        }
12064
12065        // In this case, the name we introduce is the name of a derived class
12066        // constructor.
12067        auto *CurClass = cast<CXXRecordDecl>(CurContext);
12068        UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12069            Context.getCanonicalType(Context.getRecordType(CurClass))));
12070        UsingName.setNamedTypeInfo(nullptr);
12071        for (auto *Ctor : LookupConstructors(RD))
12072          R.addDecl(Ctor);
12073        R.resolveKind();
12074      } else {
12075        // FIXME: Pick up all the declarations if we found an overloaded
12076        // function.
12077        UsingName.setName(ND->getDeclName());
12078        R.addDecl(ND);
12079      }
12080    } else {
12081      Diag(IdentLoc, diag::err_no_member)
12082        << NameInfo.getName() << LookupContext << SS.getRange();
12083      return BuildInvalid();
12084    }
12085  }
12086
12087  if (R.isAmbiguous())
12088    return BuildInvalid();
12089
12090  if (HasTypenameKeyword) {
12091    // If we asked for a typename and got a non-type decl, error out.
12092    if (!R.getAsSingle<TypeDecl>()) {
12093      Diag(IdentLoc, diag::err_using_typename_non_type);
12094      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12095        Diag((*I)->getUnderlyingDecl()->getLocation(),
12096             diag::note_using_decl_target);
12097      return BuildInvalid();
12098    }
12099  } else {
12100    // If we asked for a non-typename and we got a type, error out,
12101    // but only if this is an instantiation of an unresolved using
12102    // decl.  Otherwise just silently find the type name.
12103    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12104      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12105      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12106      return BuildInvalid();
12107    }
12108  }
12109
12110  // C++14 [namespace.udecl]p6:
12111  // A using-declaration shall not name a namespace.
12112  if (R.getAsSingle<NamespaceDecl>()) {
12113    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12114      << SS.getRange();
12115    return BuildInvalid();
12116  }
12117
12118  // C++14 [namespace.udecl]p7:
12119  // A using-declaration shall not name a scoped enumerator.
12120  if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12121    if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12122      Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12123        << SS.getRange();
12124      return BuildInvalid();
12125    }
12126  }
12127
12128  UsingDecl *UD = BuildValid();
12129
12130  // Some additional rules apply to inheriting constructors.
12131  if (UsingName.getName().getNameKind() ==
12132        DeclarationName::CXXConstructorName) {
12133    // Suppress access diagnostics; the access check is instead performed at the
12134    // point of use for an inheriting constructor.
12135    R.suppressDiagnostics();
12136    if (CheckInheritingConstructorUsingDecl(UD))
12137      return UD;
12138  }
12139
12140  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12141    UsingShadowDecl *PrevDecl = nullptr;
12142    if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12143      BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12144  }
12145
12146  return UD;
12147}
12148
12149NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12150                                    ArrayRef<NamedDecl *> Expansions) {
12151  assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12152         isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12153         isa<UsingPackDecl>(InstantiatedFrom));
12154
12155  auto *UPD =
12156      UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12157  UPD->setAccess(InstantiatedFrom->getAccess());
12158  CurContext->addDecl(UPD);
12159  return UPD;
12160}
12161
12162/// Additional checks for a using declaration referring to a constructor name.
12163bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12164  assert(!UD->hasTypename() && "expecting a constructor name");
12165
12166  const Type *SourceType = UD->getQualifier()->getAsType();
12167  assert(SourceType &&
12168         "Using decl naming constructor doesn't have type in scope spec.");
12169  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12170
12171  // Check whether the named type is a direct base class.
12172  bool AnyDependentBases = false;
12173  auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12174                                      AnyDependentBases);
12175  if (!Base && !AnyDependentBases) {
12176    Diag(UD->getUsingLoc(),
12177         diag::err_using_decl_constructor_not_in_direct_base)
12178      << UD->getNameInfo().getSourceRange()
12179      << QualType(SourceType, 0) << TargetClass;
12180    UD->setInvalidDecl();
12181    return true;
12182  }
12183
12184  if (Base)
12185    Base->setInheritConstructors();
12186
12187  return false;
12188}
12189
12190/// Checks that the given using declaration is not an invalid
12191/// redeclaration.  Note that this is checking only for the using decl
12192/// itself, not for any ill-formedness among the UsingShadowDecls.
12193bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12194                                       bool HasTypenameKeyword,
12195                                       const CXXScopeSpec &SS,
12196                                       SourceLocation NameLoc,
12197                                       const LookupResult &Prev) {
12198  NestedNameSpecifier *Qual = SS.getScopeRep();
12199
12200  // C++03 [namespace.udecl]p8:
12201  // C++0x [namespace.udecl]p10:
12202  //   A using-declaration is a declaration and can therefore be used
12203  //   repeatedly where (and only where) multiple declarations are
12204  //   allowed.
12205  //
12206  // That's in non-member contexts.
12207  if (!CurContext->getRedeclContext()->isRecord()) {
12208    // A dependent qualifier outside a class can only ever resolve to an
12209    // enumeration type. Therefore it conflicts with any other non-type
12210    // declaration in the same scope.
12211    // FIXME: How should we check for dependent type-type conflicts at block
12212    // scope?
12213    if (Qual->isDependent() && !HasTypenameKeyword) {
12214      for (auto *D : Prev) {
12215        if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12216          bool OldCouldBeEnumerator =
12217              isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12218          Diag(NameLoc,
12219               OldCouldBeEnumerator ? diag::err_redefinition
12220                                    : diag::err_redefinition_different_kind)
12221              << Prev.getLookupName();
12222          Diag(D->getLocation(), diag::note_previous_definition);
12223          return true;
12224        }
12225      }
12226    }
12227    return false;
12228  }
12229
12230  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12231    NamedDecl *D = *I;
12232
12233    bool DTypename;
12234    NestedNameSpecifier *DQual;
12235    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12236      DTypename = UD->hasTypename();
12237      DQual = UD->getQualifier();
12238    } else if (UnresolvedUsingValueDecl *UD
12239                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12240      DTypename = false;
12241      DQual = UD->getQualifier();
12242    } else if (UnresolvedUsingTypenameDecl *UD
12243                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12244      DTypename = true;
12245      DQual = UD->getQualifier();
12246    } else continue;
12247
12248    // using decls differ if one says 'typename' and the other doesn't.
12249    // FIXME: non-dependent using decls?
12250    if (HasTypenameKeyword != DTypename) continue;
12251
12252    // using decls differ if they name different scopes (but note that
12253    // template instantiation can cause this check to trigger when it
12254    // didn't before instantiation).
12255    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12256        Context.getCanonicalNestedNameSpecifier(DQual))
12257      continue;
12258
12259    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12260    Diag(D->getLocation(), diag::note_using_decl) << 1;
12261    return true;
12262  }
12263
12264  return false;
12265}
12266
12267
12268/// Checks that the given nested-name qualifier used in a using decl
12269/// in the current context is appropriately related to the current
12270/// scope.  If an error is found, diagnoses it and returns true.
12271bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12272                                   bool HasTypename,
12273                                   const CXXScopeSpec &SS,
12274                                   const DeclarationNameInfo &NameInfo,
12275                                   SourceLocation NameLoc) {
12276  DeclContext *NamedContext = computeDeclContext(SS);
12277
12278  if (!CurContext->isRecord()) {
12279    // C++03 [namespace.udecl]p3:
12280    // C++0x [namespace.udecl]p8:
12281    //   A using-declaration for a class member shall be a member-declaration.
12282
12283    // If we weren't able to compute a valid scope, it might validly be a
12284    // dependent class scope or a dependent enumeration unscoped scope. If
12285    // we have a 'typename' keyword, the scope must resolve to a class type.
12286    if ((HasTypename && !NamedContext) ||
12287        (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12288      auto *RD = NamedContext
12289                     ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12290                     : nullptr;
12291      if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12292        RD = nullptr;
12293
12294      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12295        << SS.getRange();
12296
12297      // If we have a complete, non-dependent source type, try to suggest a
12298      // way to get the same effect.
12299      if (!RD)
12300        return true;
12301
12302      // Find what this using-declaration was referring to.
12303      LookupResult R(*this, NameInfo, LookupOrdinaryName);
12304      R.setHideTags(false);
12305      R.suppressDiagnostics();
12306      LookupQualifiedName(R, RD);
12307
12308      if (R.getAsSingle<TypeDecl>()) {
12309        if (getLangOpts().CPlusPlus11) {
12310          // Convert 'using X::Y;' to 'using Y = X::Y;'.
12311          Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12312            << 0 // alias declaration
12313            << FixItHint::CreateInsertion(SS.getBeginLoc(),
12314                                          NameInfo.getName().getAsString() +
12315                                              " = ");
12316        } else {
12317          // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12318          SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12319          Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12320            << 1 // typedef declaration
12321            << FixItHint::CreateReplacement(UsingLoc, "typedef")
12322            << FixItHint::CreateInsertion(
12323                   InsertLoc, " " + NameInfo.getName().getAsString());
12324        }
12325      } else if (R.getAsSingle<VarDecl>()) {
12326        // Don't provide a fixit outside C++11 mode; we don't want to suggest
12327        // repeating the type of the static data member here.
12328        FixItHint FixIt;
12329        if (getLangOpts().CPlusPlus11) {
12330          // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12331          FixIt = FixItHint::CreateReplacement(
12332              UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12333        }
12334
12335        Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12336          << 2 // reference declaration
12337          << FixIt;
12338      } else if (R.getAsSingle<EnumConstantDecl>()) {
12339        // Don't provide a fixit outside C++11 mode; we don't want to suggest
12340        // repeating the type of the enumeration here, and we can't do so if
12341        // the type is anonymous.
12342        FixItHint FixIt;
12343        if (getLangOpts().CPlusPlus11) {
12344          // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12345          FixIt = FixItHint::CreateReplacement(
12346              UsingLoc,
12347              "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12348        }
12349
12350        Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12351          << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12352          << FixIt;
12353      }
12354      return true;
12355    }
12356
12357    // Otherwise, this might be valid.
12358    return false;
12359  }
12360
12361  // The current scope is a record.
12362
12363  // If the named context is dependent, we can't decide much.
12364  if (!NamedContext) {
12365    // FIXME: in C++0x, we can diagnose if we can prove that the
12366    // nested-name-specifier does not refer to a base class, which is
12367    // still possible in some cases.
12368
12369    // Otherwise we have to conservatively report that things might be
12370    // okay.
12371    return false;
12372  }
12373
12374  if (!NamedContext->isRecord()) {
12375    // Ideally this would point at the last name in the specifier,
12376    // but we don't have that level of source info.
12377    Diag(SS.getRange().getBegin(),
12378         diag::err_using_decl_nested_name_specifier_is_not_class)
12379      << SS.getScopeRep() << SS.getRange();
12380    return true;
12381  }
12382
12383  if (!NamedContext->isDependentContext() &&
12384      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12385    return true;
12386
12387  if (getLangOpts().CPlusPlus11) {
12388    // C++11 [namespace.udecl]p3:
12389    //   In a using-declaration used as a member-declaration, the
12390    //   nested-name-specifier shall name a base class of the class
12391    //   being defined.
12392
12393    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12394                                 cast<CXXRecordDecl>(NamedContext))) {
12395      if (CurContext == NamedContext) {
12396        Diag(NameLoc,
12397             diag::err_using_decl_nested_name_specifier_is_current_class)
12398          << SS.getRange();
12399        return true;
12400      }
12401
12402      if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12403        Diag(SS.getRange().getBegin(),
12404             diag::err_using_decl_nested_name_specifier_is_not_base_class)
12405          << SS.getScopeRep()
12406          << cast<CXXRecordDecl>(CurContext)
12407          << SS.getRange();
12408      }
12409      return true;
12410    }
12411
12412    return false;
12413  }
12414
12415  // C++03 [namespace.udecl]p4:
12416  //   A using-declaration used as a member-declaration shall refer
12417  //   to a member of a base class of the class being defined [etc.].
12418
12419  // Salient point: SS doesn't have to name a base class as long as
12420  // lookup only finds members from base classes.  Therefore we can
12421  // diagnose here only if we can prove that that can't happen,
12422  // i.e. if the class hierarchies provably don't intersect.
12423
12424  // TODO: it would be nice if "definitely valid" results were cached
12425  // in the UsingDecl and UsingShadowDecl so that these checks didn't
12426  // need to be repeated.
12427
12428  llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12429  auto Collect = [&Bases](const CXXRecordDecl *Base) {
12430    Bases.insert(Base);
12431    return true;
12432  };
12433
12434  // Collect all bases. Return false if we find a dependent base.
12435  if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12436    return false;
12437
12438  // Returns true if the base is dependent or is one of the accumulated base
12439  // classes.
12440  auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12441    return !Bases.count(Base);
12442  };
12443
12444  // Return false if the class has a dependent base or if it or one
12445  // of its bases is present in the base set of the current context.
12446  if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12447      !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12448    return false;
12449
12450  Diag(SS.getRange().getBegin(),
12451       diag::err_using_decl_nested_name_specifier_is_not_base_class)
12452    << SS.getScopeRep()
12453    << cast<CXXRecordDecl>(CurContext)
12454    << SS.getRange();
12455
12456  return true;
12457}
12458
12459Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12460                                  MultiTemplateParamsArg TemplateParamLists,
12461                                  SourceLocation UsingLoc, UnqualifiedId &Name,
12462                                  const ParsedAttributesView &AttrList,
12463                                  TypeResult Type, Decl *DeclFromDeclSpec) {
12464  // Skip up to the relevant declaration scope.
12465  while (S->isTemplateParamScope())
12466    S = S->getParent();
12467  assert((S->getFlags() & Scope::DeclScope) &&
12468         "got alias-declaration outside of declaration scope");
12469
12470  if (Type.isInvalid())
12471    return nullptr;
12472
12473  bool Invalid = false;
12474  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12475  TypeSourceInfo *TInfo = nullptr;
12476  GetTypeFromParser(Type.get(), &TInfo);
12477
12478  if (DiagnoseClassNameShadow(CurContext, NameInfo))
12479    return nullptr;
12480
12481  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12482                                      UPPC_DeclarationType)) {
12483    Invalid = true;
12484    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12485                                             TInfo->getTypeLoc().getBeginLoc());
12486  }
12487
12488  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12489                        TemplateParamLists.size()
12490                            ? forRedeclarationInCurContext()
12491                            : ForVisibleRedeclaration);
12492  LookupName(Previous, S);
12493
12494  // Warn about shadowing the name of a template parameter.
12495  if (Previous.isSingleResult() &&
12496      Previous.getFoundDecl()->isTemplateParameter()) {
12497    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12498    Previous.clear();
12499  }
12500
12501  assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12502         "name in alias declaration must be an identifier");
12503  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12504                                               Name.StartLocation,
12505                                               Name.Identifier, TInfo);
12506
12507  NewTD->setAccess(AS);
12508
12509  if (Invalid)
12510    NewTD->setInvalidDecl();
12511
12512  ProcessDeclAttributeList(S, NewTD, AttrList);
12513  AddPragmaAttributes(S, NewTD);
12514
12515  CheckTypedefForVariablyModifiedType(S, NewTD);
12516  Invalid |= NewTD->isInvalidDecl();
12517
12518  bool Redeclaration = false;
12519
12520  NamedDecl *NewND;
12521  if (TemplateParamLists.size()) {
12522    TypeAliasTemplateDecl *OldDecl = nullptr;
12523    TemplateParameterList *OldTemplateParams = nullptr;
12524
12525    if (TemplateParamLists.size() != 1) {
12526      Diag(UsingLoc, diag::err_alias_template_extra_headers)
12527        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12528         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12529    }
12530    TemplateParameterList *TemplateParams = TemplateParamLists[0];
12531
12532    // Check that we can declare a template here.
12533    if (CheckTemplateDeclScope(S, TemplateParams))
12534      return nullptr;
12535
12536    // Only consider previous declarations in the same scope.
12537    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12538                         /*ExplicitInstantiationOrSpecialization*/false);
12539    if (!Previous.empty()) {
12540      Redeclaration = true;
12541
12542      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12543      if (!OldDecl && !Invalid) {
12544        Diag(UsingLoc, diag::err_redefinition_different_kind)
12545          << Name.Identifier;
12546
12547        NamedDecl *OldD = Previous.getRepresentativeDecl();
12548        if (OldD->getLocation().isValid())
12549          Diag(OldD->getLocation(), diag::note_previous_definition);
12550
12551        Invalid = true;
12552      }
12553
12554      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12555        if (TemplateParameterListsAreEqual(TemplateParams,
12556                                           OldDecl->getTemplateParameters(),
12557                                           /*Complain=*/true,
12558                                           TPL_TemplateMatch))
12559          OldTemplateParams =
12560              OldDecl->getMostRecentDecl()->getTemplateParameters();
12561        else
12562          Invalid = true;
12563
12564        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12565        if (!Invalid &&
12566            !Context.hasSameType(OldTD->getUnderlyingType(),
12567                                 NewTD->getUnderlyingType())) {
12568          // FIXME: The C++0x standard does not clearly say this is ill-formed,
12569          // but we can't reasonably accept it.
12570          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12571            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12572          if (OldTD->getLocation().isValid())
12573            Diag(OldTD->getLocation(), diag::note_previous_definition);
12574          Invalid = true;
12575        }
12576      }
12577    }
12578
12579    // Merge any previous default template arguments into our parameters,
12580    // and check the parameter list.
12581    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12582                                   TPC_TypeAliasTemplate))
12583      return nullptr;
12584
12585    TypeAliasTemplateDecl *NewDecl =
12586      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12587                                    Name.Identifier, TemplateParams,
12588                                    NewTD);
12589    NewTD->setDescribedAliasTemplate(NewDecl);
12590
12591    NewDecl->setAccess(AS);
12592
12593    if (Invalid)
12594      NewDecl->setInvalidDecl();
12595    else if (OldDecl) {
12596      NewDecl->setPreviousDecl(OldDecl);
12597      CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12598    }
12599
12600    NewND = NewDecl;
12601  } else {
12602    if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12603      setTagNameForLinkagePurposes(TD, NewTD);
12604      handleTagNumbering(TD, S);
12605    }
12606    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12607    NewND = NewTD;
12608  }
12609
12610  PushOnScopeChains(NewND, S);
12611  ActOnDocumentableDecl(NewND);
12612  return NewND;
12613}
12614
12615Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12616                                   SourceLocation AliasLoc,
12617                                   IdentifierInfo *Alias, CXXScopeSpec &SS,
12618                                   SourceLocation IdentLoc,
12619                                   IdentifierInfo *Ident) {
12620
12621  // Lookup the namespace name.
12622  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12623  LookupParsedName(R, S, &SS);
12624
12625  if (R.isAmbiguous())
12626    return nullptr;
12627
12628  if (R.empty()) {
12629    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12630      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12631      return nullptr;
12632    }
12633  }
12634  assert(!R.isAmbiguous() && !R.empty());
12635  NamedDecl *ND = R.getRepresentativeDecl();
12636
12637  // Check if we have a previous declaration with the same name.
12638  LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12639                     ForVisibleRedeclaration);
12640  LookupName(PrevR, S);
12641
12642  // Check we're not shadowing a template parameter.
12643  if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12644    DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12645    PrevR.clear();
12646  }
12647
12648  // Filter out any other lookup result from an enclosing scope.
12649  FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12650                       /*AllowInlineNamespace*/false);
12651
12652  // Find the previous declaration and check that we can redeclare it.
12653  NamespaceAliasDecl *Prev = nullptr;
12654  if (PrevR.isSingleResult()) {
12655    NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12656    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12657      // We already have an alias with the same name that points to the same
12658      // namespace; check that it matches.
12659      if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12660        Prev = AD;
12661      } else if (isVisible(PrevDecl)) {
12662        Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12663          << Alias;
12664        Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12665          << AD->getNamespace();
12666        return nullptr;
12667      }
12668    } else if (isVisible(PrevDecl)) {
12669      unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12670                            ? diag::err_redefinition
12671                            : diag::err_redefinition_different_kind;
12672      Diag(AliasLoc, DiagID) << Alias;
12673      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12674      return nullptr;
12675    }
12676  }
12677
12678  // The use of a nested name specifier may trigger deprecation warnings.
12679  DiagnoseUseOfDecl(ND, IdentLoc);
12680
12681  NamespaceAliasDecl *AliasDecl =
12682    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12683                               Alias, SS.getWithLocInContext(Context),
12684                               IdentLoc, ND);
12685  if (Prev)
12686    AliasDecl->setPreviousDecl(Prev);
12687
12688  PushOnScopeChains(AliasDecl, S);
12689  return AliasDecl;
12690}
12691
12692namespace {
12693struct SpecialMemberExceptionSpecInfo
12694    : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12695  SourceLocation Loc;
12696  Sema::ImplicitExceptionSpecification ExceptSpec;
12697
12698  SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12699                                 Sema::CXXSpecialMember CSM,
12700                                 Sema::InheritedConstructorInfo *ICI,
12701                                 SourceLocation Loc)
12702      : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12703
12704  bool visitBase(CXXBaseSpecifier *Base);
12705  bool visitField(FieldDecl *FD);
12706
12707  void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12708                           unsigned Quals);
12709
12710  void visitSubobjectCall(Subobject Subobj,
12711                          Sema::SpecialMemberOverloadResult SMOR);
12712};
12713}
12714
12715bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12716  auto *RT = Base->getType()->getAs<RecordType>();
12717  if (!RT)
12718    return false;
12719
12720  auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12721  Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12722  if (auto *BaseCtor = SMOR.getMethod()) {
12723    visitSubobjectCall(Base, BaseCtor);
12724    return false;
12725  }
12726
12727  visitClassSubobject(BaseClass, Base, 0);
12728  return false;
12729}
12730
12731bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12732  if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12733    Expr *E = FD->getInClassInitializer();
12734    if (!E)
12735      // FIXME: It's a little wasteful to build and throw away a
12736      // CXXDefaultInitExpr here.
12737      // FIXME: We should have a single context note pointing at Loc, and
12738      // this location should be MD->getLocation() instead, since that's
12739      // the location where we actually use the default init expression.
12740      E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12741    if (E)
12742      ExceptSpec.CalledExpr(E);
12743  } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12744                            ->getAs<RecordType>()) {
12745    visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12746                        FD->getType().getCVRQualifiers());
12747  }
12748  return false;
12749}
12750
12751void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12752                                                         Subobject Subobj,
12753                                                         unsigned Quals) {
12754  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12755  bool IsMutable = Field && Field->isMutable();
12756  visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12757}
12758
12759void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12760    Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12761  // Note, if lookup fails, it doesn't matter what exception specification we
12762  // choose because the special member will be deleted.
12763  if (CXXMethodDecl *MD = SMOR.getMethod())
12764    ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12765}
12766
12767bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12768  llvm::APSInt Result;
12769  ExprResult Converted = CheckConvertedConstantExpression(
12770      ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12771  ExplicitSpec.setExpr(Converted.get());
12772  if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12773    ExplicitSpec.setKind(Result.getBoolValue()
12774                             ? ExplicitSpecKind::ResolvedTrue
12775                             : ExplicitSpecKind::ResolvedFalse);
12776    return true;
12777  }
12778  ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12779  return false;
12780}
12781
12782ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12783  ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12784  if (!ExplicitExpr->isTypeDependent())
12785    tryResolveExplicitSpecifier(ES);
12786  return ES;
12787}
12788
12789static Sema::ImplicitExceptionSpecification
12790ComputeDefaultedSpecialMemberExceptionSpec(
12791    Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12792    Sema::InheritedConstructorInfo *ICI) {
12793  ComputingExceptionSpec CES(S, MD, Loc);
12794
12795  CXXRecordDecl *ClassDecl = MD->getParent();
12796
12797  // C++ [except.spec]p14:
12798  //   An implicitly declared special member function (Clause 12) shall have an
12799  //   exception-specification. [...]
12800  SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12801  if (ClassDecl->isInvalidDecl())
12802    return Info.ExceptSpec;
12803
12804  // FIXME: If this diagnostic fires, we're probably missing a check for
12805  // attempting to resolve an exception specification before it's known
12806  // at a higher level.
12807  if (S.RequireCompleteType(MD->getLocation(),
12808                            S.Context.getRecordType(ClassDecl),
12809                            diag::err_exception_spec_incomplete_type))
12810    return Info.ExceptSpec;
12811
12812  // C++1z [except.spec]p7:
12813  //   [Look for exceptions thrown by] a constructor selected [...] to
12814  //   initialize a potentially constructed subobject,
12815  // C++1z [except.spec]p8:
12816  //   The exception specification for an implicitly-declared destructor, or a
12817  //   destructor without a noexcept-specifier, is potentially-throwing if and
12818  //   only if any of the destructors for any of its potentially constructed
12819  //   subojects is potentially throwing.
12820  // FIXME: We respect the first rule but ignore the "potentially constructed"
12821  // in the second rule to resolve a core issue (no number yet) that would have
12822  // us reject:
12823  //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12824  //   struct B : A {};
12825  //   struct C : B { void f(); };
12826  // ... due to giving B::~B() a non-throwing exception specification.
12827  Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12828                                : Info.VisitAllBases);
12829
12830  return Info.ExceptSpec;
12831}
12832
12833namespace {
12834/// RAII object to register a special member as being currently declared.
12835struct DeclaringSpecialMember {
12836  Sema &S;
12837  Sema::SpecialMemberDecl D;
12838  Sema::ContextRAII SavedContext;
12839  bool WasAlreadyBeingDeclared;
12840
12841  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12842      : S(S), D(RD, CSM), SavedContext(S, RD) {
12843    WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12844    if (WasAlreadyBeingDeclared)
12845      // This almost never happens, but if it does, ensure that our cache
12846      // doesn't contain a stale result.
12847      S.SpecialMemberCache.clear();
12848    else {
12849      // Register a note to be produced if we encounter an error while
12850      // declaring the special member.
12851      Sema::CodeSynthesisContext Ctx;
12852      Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12853      // FIXME: We don't have a location to use here. Using the class's
12854      // location maintains the fiction that we declare all special members
12855      // with the class, but (1) it's not clear that lying about that helps our
12856      // users understand what's going on, and (2) there may be outer contexts
12857      // on the stack (some of which are relevant) and printing them exposes
12858      // our lies.
12859      Ctx.PointOfInstantiation = RD->getLocation();
12860      Ctx.Entity = RD;
12861      Ctx.SpecialMember = CSM;
12862      S.pushCodeSynthesisContext(Ctx);
12863    }
12864  }
12865  ~DeclaringSpecialMember() {
12866    if (!WasAlreadyBeingDeclared) {
12867      S.SpecialMembersBeingDeclared.erase(D);
12868      S.popCodeSynthesisContext();
12869    }
12870  }
12871
12872  /// Are we already trying to declare this special member?
12873  bool isAlreadyBeingDeclared() const {
12874    return WasAlreadyBeingDeclared;
12875  }
12876};
12877}
12878
12879void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12880  // Look up any existing declarations, but don't trigger declaration of all
12881  // implicit special members with this name.
12882  DeclarationName Name = FD->getDeclName();
12883  LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12884                 ForExternalRedeclaration);
12885  for (auto *D : FD->getParent()->lookup(Name))
12886    if (auto *Acceptable = R.getAcceptableDecl(D))
12887      R.addDecl(Acceptable);
12888  R.resolveKind();
12889  R.suppressDiagnostics();
12890
12891  CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12892}
12893
12894void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12895                                          QualType ResultTy,
12896                                          ArrayRef<QualType> Args) {
12897  // Build an exception specification pointing back at this constructor.
12898  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12899
12900  LangAS AS = getDefaultCXXMethodAddrSpace();
12901  if (AS != LangAS::Default) {
12902    EPI.TypeQuals.addAddressSpace(AS);
12903  }
12904
12905  auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12906  SpecialMem->setType(QT);
12907}
12908
12909CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12910                                                     CXXRecordDecl *ClassDecl) {
12911  // C++ [class.ctor]p5:
12912  //   A default constructor for a class X is a constructor of class X
12913  //   that can be called without an argument. If there is no
12914  //   user-declared constructor for class X, a default constructor is
12915  //   implicitly declared. An implicitly-declared default constructor
12916  //   is an inline public member of its class.
12917  assert(ClassDecl->needsImplicitDefaultConstructor() &&
12918         "Should not build implicit default constructor!");
12919
12920  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12921  if (DSM.isAlreadyBeingDeclared())
12922    return nullptr;
12923
12924  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12925                                                     CXXDefaultConstructor,
12926                                                     false);
12927
12928  // Create the actual constructor declaration.
12929  CanQualType ClassType
12930    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12931  SourceLocation ClassLoc = ClassDecl->getLocation();
12932  DeclarationName Name
12933    = Context.DeclarationNames.getCXXConstructorName(ClassType);
12934  DeclarationNameInfo NameInfo(Name, ClassLoc);
12935  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12936      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12937      /*TInfo=*/nullptr, ExplicitSpecifier(),
12938      /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12939      Constexpr ? CSK_constexpr : CSK_unspecified);
12940  DefaultCon->setAccess(AS_public);
12941  DefaultCon->setDefaulted();
12942
12943  if (getLangOpts().CUDA) {
12944    inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12945                                            DefaultCon,
12946                                            /* ConstRHS */ false,
12947                                            /* Diagnose */ false);
12948  }
12949
12950  setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
12951
12952  // We don't need to use SpecialMemberIsTrivial here; triviality for default
12953  // constructors is easy to compute.
12954  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
12955
12956  // Note that we have declared this constructor.
12957  ++getASTContext().NumImplicitDefaultConstructorsDeclared;
12958
12959  Scope *S = getScopeForContext(ClassDecl);
12960  CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
12961
12962  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
12963    SetDeclDeleted(DefaultCon, ClassLoc);
12964
12965  if (S)
12966    PushOnScopeChains(DefaultCon, S, false);
12967  ClassDecl->addDecl(DefaultCon);
12968
12969  return DefaultCon;
12970}
12971
12972void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
12973                                            CXXConstructorDecl *Constructor) {
12974  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
12975          !Constructor->doesThisDeclarationHaveABody() &&
12976          !Constructor->isDeleted()) &&
12977    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
12978  if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
12979    return;
12980
12981  CXXRecordDecl *ClassDecl = Constructor->getParent();
12982  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
12983
12984  SynthesizedFunctionScope Scope(*this, Constructor);
12985
12986  // The exception specification is needed because we are defining the
12987  // function.
12988  ResolveExceptionSpec(CurrentLocation,
12989                       Constructor->getType()->castAs<FunctionProtoType>());
12990  MarkVTableUsed(CurrentLocation, ClassDecl);
12991
12992  // Add a context note for diagnostics produced after this point.
12993  Scope.addContextNote(CurrentLocation);
12994
12995  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
12996    Constructor->setInvalidDecl();
12997    return;
12998  }
12999
13000  SourceLocation Loc = Constructor->getEndLoc().isValid()
13001                           ? Constructor->getEndLoc()
13002                           : Constructor->getLocation();
13003  Constructor->setBody(new (Context) CompoundStmt(Loc));
13004  Constructor->markUsed(Context);
13005
13006  if (ASTMutationListener *L = getASTMutationListener()) {
13007    L->CompletedImplicitDefinition(Constructor);
13008  }
13009
13010  DiagnoseUninitializedFields(*this, Constructor);
13011}
13012
13013void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13014  // Perform any delayed checks on exception specifications.
13015  CheckDelayedMemberExceptionSpecs();
13016}
13017
13018/// Find or create the fake constructor we synthesize to model constructing an
13019/// object of a derived class via a constructor of a base class.
13020CXXConstructorDecl *
13021Sema::findInheritingConstructor(SourceLocation Loc,
13022                                CXXConstructorDecl *BaseCtor,
13023                                ConstructorUsingShadowDecl *Shadow) {
13024  CXXRecordDecl *Derived = Shadow->getParent();
13025  SourceLocation UsingLoc = Shadow->getLocation();
13026
13027  // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13028  // For now we use the name of the base class constructor as a member of the
13029  // derived class to indicate a (fake) inherited constructor name.
13030  DeclarationName Name = BaseCtor->getDeclName();
13031
13032  // Check to see if we already have a fake constructor for this inherited
13033  // constructor call.
13034  for (NamedDecl *Ctor : Derived->lookup(Name))
13035    if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13036                               ->getInheritedConstructor()
13037                               .getConstructor(),
13038                           BaseCtor))
13039      return cast<CXXConstructorDecl>(Ctor);
13040
13041  DeclarationNameInfo NameInfo(Name, UsingLoc);
13042  TypeSourceInfo *TInfo =
13043      Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13044  FunctionProtoTypeLoc ProtoLoc =
13045      TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13046
13047  // Check the inherited constructor is valid and find the list of base classes
13048  // from which it was inherited.
13049  InheritedConstructorInfo ICI(*this, Loc, Shadow);
13050
13051  bool Constexpr =
13052      BaseCtor->isConstexpr() &&
13053      defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13054                                        false, BaseCtor, &ICI);
13055
13056  CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13057      Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13058      BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13059      /*isImplicitlyDeclared=*/true,
13060      Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
13061      InheritedConstructor(Shadow, BaseCtor),
13062      BaseCtor->getTrailingRequiresClause());
13063  if (Shadow->isInvalidDecl())
13064    DerivedCtor->setInvalidDecl();
13065
13066  // Build an unevaluated exception specification for this fake constructor.
13067  const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13068  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13069  EPI.ExceptionSpec.Type = EST_Unevaluated;
13070  EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13071  DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13072                                               FPT->getParamTypes(), EPI));
13073
13074  // Build the parameter declarations.
13075  SmallVector<ParmVarDecl *, 16> ParamDecls;
13076  for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13077    TypeSourceInfo *TInfo =
13078        Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13079    ParmVarDecl *PD = ParmVarDecl::Create(
13080        Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13081        FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13082    PD->setScopeInfo(0, I);
13083    PD->setImplicit();
13084    // Ensure attributes are propagated onto parameters (this matters for
13085    // format, pass_object_size, ...).
13086    mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13087    ParamDecls.push_back(PD);
13088    ProtoLoc.setParam(I, PD);
13089  }
13090
13091  // Set up the new constructor.
13092  assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13093  DerivedCtor->setAccess(BaseCtor->getAccess());
13094  DerivedCtor->setParams(ParamDecls);
13095  Derived->addDecl(DerivedCtor);
13096
13097  if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13098    SetDeclDeleted(DerivedCtor, UsingLoc);
13099
13100  return DerivedCtor;
13101}
13102
13103void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13104  InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13105                               Ctor->getInheritedConstructor().getShadowDecl());
13106  ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13107                            /*Diagnose*/true);
13108}
13109
13110void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13111                                       CXXConstructorDecl *Constructor) {
13112  CXXRecordDecl *ClassDecl = Constructor->getParent();
13113  assert(Constructor->getInheritedConstructor() &&
13114         !Constructor->doesThisDeclarationHaveABody() &&
13115         !Constructor->isDeleted());
13116  if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13117    return;
13118
13119  // Initializations are performed "as if by a defaulted default constructor",
13120  // so enter the appropriate scope.
13121  SynthesizedFunctionScope Scope(*this, Constructor);
13122
13123  // The exception specification is needed because we are defining the
13124  // function.
13125  ResolveExceptionSpec(CurrentLocation,
13126                       Constructor->getType()->castAs<FunctionProtoType>());
13127  MarkVTableUsed(CurrentLocation, ClassDecl);
13128
13129  // Add a context note for diagnostics produced after this point.
13130  Scope.addContextNote(CurrentLocation);
13131
13132  ConstructorUsingShadowDecl *Shadow =
13133      Constructor->getInheritedConstructor().getShadowDecl();
13134  CXXConstructorDecl *InheritedCtor =
13135      Constructor->getInheritedConstructor().getConstructor();
13136
13137  // [class.inhctor.init]p1:
13138  //   initialization proceeds as if a defaulted default constructor is used to
13139  //   initialize the D object and each base class subobject from which the
13140  //   constructor was inherited
13141
13142  InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13143  CXXRecordDecl *RD = Shadow->getParent();
13144  SourceLocation InitLoc = Shadow->getLocation();
13145
13146  // Build explicit initializers for all base classes from which the
13147  // constructor was inherited.
13148  SmallVector<CXXCtorInitializer*, 8> Inits;
13149  for (bool VBase : {false, true}) {
13150    for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13151      if (B.isVirtual() != VBase)
13152        continue;
13153
13154      auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13155      if (!BaseRD)
13156        continue;
13157
13158      auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13159      if (!BaseCtor.first)
13160        continue;
13161
13162      MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13163      ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13164          InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13165
13166      auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13167      Inits.push_back(new (Context) CXXCtorInitializer(
13168          Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13169          SourceLocation()));
13170    }
13171  }
13172
13173  // We now proceed as if for a defaulted default constructor, with the relevant
13174  // initializers replaced.
13175
13176  if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13177    Constructor->setInvalidDecl();
13178    return;
13179  }
13180
13181  Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13182  Constructor->markUsed(Context);
13183
13184  if (ASTMutationListener *L = getASTMutationListener()) {
13185    L->CompletedImplicitDefinition(Constructor);
13186  }
13187
13188  DiagnoseUninitializedFields(*this, Constructor);
13189}
13190
13191CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13192  // C++ [class.dtor]p2:
13193  //   If a class has no user-declared destructor, a destructor is
13194  //   declared implicitly. An implicitly-declared destructor is an
13195  //   inline public member of its class.
13196  assert(ClassDecl->needsImplicitDestructor());
13197
13198  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13199  if (DSM.isAlreadyBeingDeclared())
13200    return nullptr;
13201
13202  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13203                                                     CXXDestructor,
13204                                                     false);
13205
13206  // Create the actual destructor declaration.
13207  CanQualType ClassType
13208    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13209  SourceLocation ClassLoc = ClassDecl->getLocation();
13210  DeclarationName Name
13211    = Context.DeclarationNames.getCXXDestructorName(ClassType);
13212  DeclarationNameInfo NameInfo(Name, ClassLoc);
13213  CXXDestructorDecl *Destructor =
13214      CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13215                                QualType(), nullptr, /*isInline=*/true,
13216                                /*isImplicitlyDeclared=*/true,
13217                                Constexpr ? CSK_constexpr : CSK_unspecified);
13218  Destructor->setAccess(AS_public);
13219  Destructor->setDefaulted();
13220
13221  if (getLangOpts().CUDA) {
13222    inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13223                                            Destructor,
13224                                            /* ConstRHS */ false,
13225                                            /* Diagnose */ false);
13226  }
13227
13228  setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13229
13230  // We don't need to use SpecialMemberIsTrivial here; triviality for
13231  // destructors is easy to compute.
13232  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13233  Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13234                                ClassDecl->hasTrivialDestructorForCall());
13235
13236  // Note that we have declared this destructor.
13237  ++getASTContext().NumImplicitDestructorsDeclared;
13238
13239  Scope *S = getScopeForContext(ClassDecl);
13240  CheckImplicitSpecialMemberDeclaration(S, Destructor);
13241
13242  // We can't check whether an implicit destructor is deleted before we complete
13243  // the definition of the class, because its validity depends on the alignment
13244  // of the class. We'll check this from ActOnFields once the class is complete.
13245  if (ClassDecl->isCompleteDefinition() &&
13246      ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13247    SetDeclDeleted(Destructor, ClassLoc);
13248
13249  // Introduce this destructor into its scope.
13250  if (S)
13251    PushOnScopeChains(Destructor, S, false);
13252  ClassDecl->addDecl(Destructor);
13253
13254  return Destructor;
13255}
13256
13257void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13258                                    CXXDestructorDecl *Destructor) {
13259  assert((Destructor->isDefaulted() &&
13260          !Destructor->doesThisDeclarationHaveABody() &&
13261          !Destructor->isDeleted()) &&
13262         "DefineImplicitDestructor - call it for implicit default dtor");
13263  if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13264    return;
13265
13266  CXXRecordDecl *ClassDecl = Destructor->getParent();
13267  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13268
13269  SynthesizedFunctionScope Scope(*this, Destructor);
13270
13271  // The exception specification is needed because we are defining the
13272  // function.
13273  ResolveExceptionSpec(CurrentLocation,
13274                       Destructor->getType()->castAs<FunctionProtoType>());
13275  MarkVTableUsed(CurrentLocation, ClassDecl);
13276
13277  // Add a context note for diagnostics produced after this point.
13278  Scope.addContextNote(CurrentLocation);
13279
13280  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13281                                         Destructor->getParent());
13282
13283  if (CheckDestructor(Destructor)) {
13284    Destructor->setInvalidDecl();
13285    return;
13286  }
13287
13288  SourceLocation Loc = Destructor->getEndLoc().isValid()
13289                           ? Destructor->getEndLoc()
13290                           : Destructor->getLocation();
13291  Destructor->setBody(new (Context) CompoundStmt(Loc));
13292  Destructor->markUsed(Context);
13293
13294  if (ASTMutationListener *L = getASTMutationListener()) {
13295    L->CompletedImplicitDefinition(Destructor);
13296  }
13297}
13298
13299void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13300                                          CXXDestructorDecl *Destructor) {
13301  if (Destructor->isInvalidDecl())
13302    return;
13303
13304  CXXRecordDecl *ClassDecl = Destructor->getParent();
13305  assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13306         "implicit complete dtors unneeded outside MS ABI");
13307  assert(ClassDecl->getNumVBases() > 0 &&
13308         "complete dtor only exists for classes with vbases");
13309
13310  SynthesizedFunctionScope Scope(*this, Destructor);
13311
13312  // Add a context note for diagnostics produced after this point.
13313  Scope.addContextNote(CurrentLocation);
13314
13315  MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13316}
13317
13318/// Perform any semantic analysis which needs to be delayed until all
13319/// pending class member declarations have been parsed.
13320void Sema::ActOnFinishCXXMemberDecls() {
13321  // If the context is an invalid C++ class, just suppress these checks.
13322  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13323    if (Record->isInvalidDecl()) {
13324      DelayedOverridingExceptionSpecChecks.clear();
13325      DelayedEquivalentExceptionSpecChecks.clear();
13326      return;
13327    }
13328    checkForMultipleExportedDefaultConstructors(*this, Record);
13329  }
13330}
13331
13332void Sema::ActOnFinishCXXNonNestedClass() {
13333  referenceDLLExportedClassMethods();
13334
13335  if (!DelayedDllExportMemberFunctions.empty()) {
13336    SmallVector<CXXMethodDecl*, 4> WorkList;
13337    std::swap(DelayedDllExportMemberFunctions, WorkList);
13338    for (CXXMethodDecl *M : WorkList) {
13339      DefineDefaultedFunction(*this, M, M->getLocation());
13340
13341      // Pass the method to the consumer to get emitted. This is not necessary
13342      // for explicit instantiation definitions, as they will get emitted
13343      // anyway.
13344      if (M->getParent()->getTemplateSpecializationKind() !=
13345          TSK_ExplicitInstantiationDefinition)
13346        ActOnFinishInlineFunctionDef(M);
13347    }
13348  }
13349}
13350
13351void Sema::referenceDLLExportedClassMethods() {
13352  if (!DelayedDllExportClasses.empty()) {
13353    // Calling ReferenceDllExportedMembers might cause the current function to
13354    // be called again, so use a local copy of DelayedDllExportClasses.
13355    SmallVector<CXXRecordDecl *, 4> WorkList;
13356    std::swap(DelayedDllExportClasses, WorkList);
13357    for (CXXRecordDecl *Class : WorkList)
13358      ReferenceDllExportedMembers(*this, Class);
13359  }
13360}
13361
13362void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13363  assert(getLangOpts().CPlusPlus11 &&
13364         "adjusting dtor exception specs was introduced in c++11");
13365
13366  if (Destructor->isDependentContext())
13367    return;
13368
13369  // C++11 [class.dtor]p3:
13370  //   A declaration of a destructor that does not have an exception-
13371  //   specification is implicitly considered to have the same exception-
13372  //   specification as an implicit declaration.
13373  const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13374  if (DtorType->hasExceptionSpec())
13375    return;
13376
13377  // Replace the destructor's type, building off the existing one. Fortunately,
13378  // the only thing of interest in the destructor type is its extended info.
13379  // The return and arguments are fixed.
13380  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13381  EPI.ExceptionSpec.Type = EST_Unevaluated;
13382  EPI.ExceptionSpec.SourceDecl = Destructor;
13383  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13384
13385  // FIXME: If the destructor has a body that could throw, and the newly created
13386  // spec doesn't allow exceptions, we should emit a warning, because this
13387  // change in behavior can break conforming C++03 programs at runtime.
13388  // However, we don't have a body or an exception specification yet, so it
13389  // needs to be done somewhere else.
13390}
13391
13392namespace {
13393/// An abstract base class for all helper classes used in building the
13394//  copy/move operators. These classes serve as factory functions and help us
13395//  avoid using the same Expr* in the AST twice.
13396class ExprBuilder {
13397  ExprBuilder(const ExprBuilder&) = delete;
13398  ExprBuilder &operator=(const ExprBuilder&) = delete;
13399
13400protected:
13401  static Expr *assertNotNull(Expr *E) {
13402    assert(E && "Expression construction must not fail.");
13403    return E;
13404  }
13405
13406public:
13407  ExprBuilder() {}
13408  virtual ~ExprBuilder() {}
13409
13410  virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13411};
13412
13413class RefBuilder: public ExprBuilder {
13414  VarDecl *Var;
13415  QualType VarType;
13416
13417public:
13418  Expr *build(Sema &S, SourceLocation Loc) const override {
13419    return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13420  }
13421
13422  RefBuilder(VarDecl *Var, QualType VarType)
13423      : Var(Var), VarType(VarType) {}
13424};
13425
13426class ThisBuilder: public ExprBuilder {
13427public:
13428  Expr *build(Sema &S, SourceLocation Loc) const override {
13429    return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13430  }
13431};
13432
13433class CastBuilder: public ExprBuilder {
13434  const ExprBuilder &Builder;
13435  QualType Type;
13436  ExprValueKind Kind;
13437  const CXXCastPath &Path;
13438
13439public:
13440  Expr *build(Sema &S, SourceLocation Loc) const override {
13441    return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13442                                             CK_UncheckedDerivedToBase, Kind,
13443                                             &Path).get());
13444  }
13445
13446  CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13447              const CXXCastPath &Path)
13448      : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13449};
13450
13451class DerefBuilder: public ExprBuilder {
13452  const ExprBuilder &Builder;
13453
13454public:
13455  Expr *build(Sema &S, SourceLocation Loc) const override {
13456    return assertNotNull(
13457        S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13458  }
13459
13460  DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13461};
13462
13463class MemberBuilder: public ExprBuilder {
13464  const ExprBuilder &Builder;
13465  QualType Type;
13466  CXXScopeSpec SS;
13467  bool IsArrow;
13468  LookupResult &MemberLookup;
13469
13470public:
13471  Expr *build(Sema &S, SourceLocation Loc) const override {
13472    return assertNotNull(S.BuildMemberReferenceExpr(
13473        Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13474        nullptr, MemberLookup, nullptr, nullptr).get());
13475  }
13476
13477  MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13478                LookupResult &MemberLookup)
13479      : Builder(Builder), Type(Type), IsArrow(IsArrow),
13480        MemberLookup(MemberLookup) {}
13481};
13482
13483class MoveCastBuilder: public ExprBuilder {
13484  const ExprBuilder &Builder;
13485
13486public:
13487  Expr *build(Sema &S, SourceLocation Loc) const override {
13488    return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13489  }
13490
13491  MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13492};
13493
13494class LvalueConvBuilder: public ExprBuilder {
13495  const ExprBuilder &Builder;
13496
13497public:
13498  Expr *build(Sema &S, SourceLocation Loc) const override {
13499    return assertNotNull(
13500        S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13501  }
13502
13503  LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13504};
13505
13506class SubscriptBuilder: public ExprBuilder {
13507  const ExprBuilder &Base;
13508  const ExprBuilder &Index;
13509
13510public:
13511  Expr *build(Sema &S, SourceLocation Loc) const override {
13512    return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13513        Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13514  }
13515
13516  SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13517      : Base(Base), Index(Index) {}
13518};
13519
13520} // end anonymous namespace
13521
13522/// When generating a defaulted copy or move assignment operator, if a field
13523/// should be copied with __builtin_memcpy rather than via explicit assignments,
13524/// do so. This optimization only applies for arrays of scalars, and for arrays
13525/// of class type where the selected copy/move-assignment operator is trivial.
13526static StmtResult
13527buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13528                           const ExprBuilder &ToB, const ExprBuilder &FromB) {
13529  // Compute the size of the memory buffer to be copied.
13530  QualType SizeType = S.Context.getSizeType();
13531  llvm::APInt Size(S.Context.getTypeSize(SizeType),
13532                   S.Context.getTypeSizeInChars(T).getQuantity());
13533
13534  // Take the address of the field references for "from" and "to". We
13535  // directly construct UnaryOperators here because semantic analysis
13536  // does not permit us to take the address of an xvalue.
13537  Expr *From = FromB.build(S, Loc);
13538  From = UnaryOperator::Create(
13539      S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13540      VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13541  Expr *To = ToB.build(S, Loc);
13542  To = UnaryOperator::Create(
13543      S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13544      VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13545
13546  const Type *E = T->getBaseElementTypeUnsafe();
13547  bool NeedsCollectableMemCpy =
13548      E->isRecordType() &&
13549      E->castAs<RecordType>()->getDecl()->hasObjectMember();
13550
13551  // Create a reference to the __builtin_objc_memmove_collectable function
13552  StringRef MemCpyName = NeedsCollectableMemCpy ?
13553    "__builtin_objc_memmove_collectable" :
13554    "__builtin_memcpy";
13555  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13556                 Sema::LookupOrdinaryName);
13557  S.LookupName(R, S.TUScope, true);
13558
13559  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13560  if (!MemCpy)
13561    // Something went horribly wrong earlier, and we will have complained
13562    // about it.
13563    return StmtError();
13564
13565  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13566                                            VK_RValue, Loc, nullptr);
13567  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13568
13569  Expr *CallArgs[] = {
13570    To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13571  };
13572  ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13573                                    Loc, CallArgs, Loc);
13574
13575  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13576  return Call.getAs<Stmt>();
13577}
13578
13579/// Builds a statement that copies/moves the given entity from \p From to
13580/// \c To.
13581///
13582/// This routine is used to copy/move the members of a class with an
13583/// implicitly-declared copy/move assignment operator. When the entities being
13584/// copied are arrays, this routine builds for loops to copy them.
13585///
13586/// \param S The Sema object used for type-checking.
13587///
13588/// \param Loc The location where the implicit copy/move is being generated.
13589///
13590/// \param T The type of the expressions being copied/moved. Both expressions
13591/// must have this type.
13592///
13593/// \param To The expression we are copying/moving to.
13594///
13595/// \param From The expression we are copying/moving from.
13596///
13597/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13598/// Otherwise, it's a non-static member subobject.
13599///
13600/// \param Copying Whether we're copying or moving.
13601///
13602/// \param Depth Internal parameter recording the depth of the recursion.
13603///
13604/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13605/// if a memcpy should be used instead.
13606static StmtResult
13607buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13608                                 const ExprBuilder &To, const ExprBuilder &From,
13609                                 bool CopyingBaseSubobject, bool Copying,
13610                                 unsigned Depth = 0) {
13611  // C++11 [class.copy]p28:
13612  //   Each subobject is assigned in the manner appropriate to its type:
13613  //
13614  //     - if the subobject is of class type, as if by a call to operator= with
13615  //       the subobject as the object expression and the corresponding
13616  //       subobject of x as a single function argument (as if by explicit
13617  //       qualification; that is, ignoring any possible virtual overriding
13618  //       functions in more derived classes);
13619  //
13620  // C++03 [class.copy]p13:
13621  //     - if the subobject is of class type, the copy assignment operator for
13622  //       the class is used (as if by explicit qualification; that is,
13623  //       ignoring any possible virtual overriding functions in more derived
13624  //       classes);
13625  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13626    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13627
13628    // Look for operator=.
13629    DeclarationName Name
13630      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13631    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13632    S.LookupQualifiedName(OpLookup, ClassDecl, false);
13633
13634    // Prior to C++11, filter out any result that isn't a copy/move-assignment
13635    // operator.
13636    if (!S.getLangOpts().CPlusPlus11) {
13637      LookupResult::Filter F = OpLookup.makeFilter();
13638      while (F.hasNext()) {
13639        NamedDecl *D = F.next();
13640        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13641          if (Method->isCopyAssignmentOperator() ||
13642              (!Copying && Method->isMoveAssignmentOperator()))
13643            continue;
13644
13645        F.erase();
13646      }
13647      F.done();
13648    }
13649
13650    // Suppress the protected check (C++ [class.protected]) for each of the
13651    // assignment operators we found. This strange dance is required when
13652    // we're assigning via a base classes's copy-assignment operator. To
13653    // ensure that we're getting the right base class subobject (without
13654    // ambiguities), we need to cast "this" to that subobject type; to
13655    // ensure that we don't go through the virtual call mechanism, we need
13656    // to qualify the operator= name with the base class (see below). However,
13657    // this means that if the base class has a protected copy assignment
13658    // operator, the protected member access check will fail. So, we
13659    // rewrite "protected" access to "public" access in this case, since we
13660    // know by construction that we're calling from a derived class.
13661    if (CopyingBaseSubobject) {
13662      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13663           L != LEnd; ++L) {
13664        if (L.getAccess() == AS_protected)
13665          L.setAccess(AS_public);
13666      }
13667    }
13668
13669    // Create the nested-name-specifier that will be used to qualify the
13670    // reference to operator=; this is required to suppress the virtual
13671    // call mechanism.
13672    CXXScopeSpec SS;
13673    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13674    SS.MakeTrivial(S.Context,
13675                   NestedNameSpecifier::Create(S.Context, nullptr, false,
13676                                               CanonicalT),
13677                   Loc);
13678
13679    // Create the reference to operator=.
13680    ExprResult OpEqualRef
13681      = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13682                                   SS, /*TemplateKWLoc=*/SourceLocation(),
13683                                   /*FirstQualifierInScope=*/nullptr,
13684                                   OpLookup,
13685                                   /*TemplateArgs=*/nullptr, /*S*/nullptr,
13686                                   /*SuppressQualifierCheck=*/true);
13687    if (OpEqualRef.isInvalid())
13688      return StmtError();
13689
13690    // Build the call to the assignment operator.
13691
13692    Expr *FromInst = From.build(S, Loc);
13693    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13694                                                  OpEqualRef.getAs<Expr>(),
13695                                                  Loc, FromInst, Loc);
13696    if (Call.isInvalid())
13697      return StmtError();
13698
13699    // If we built a call to a trivial 'operator=' while copying an array,
13700    // bail out. We'll replace the whole shebang with a memcpy.
13701    CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13702    if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13703      return StmtResult((Stmt*)nullptr);
13704
13705    // Convert to an expression-statement, and clean up any produced
13706    // temporaries.
13707    return S.ActOnExprStmt(Call);
13708  }
13709
13710  //     - if the subobject is of scalar type, the built-in assignment
13711  //       operator is used.
13712  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13713  if (!ArrayTy) {
13714    ExprResult Assignment = S.CreateBuiltinBinOp(
13715        Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13716    if (Assignment.isInvalid())
13717      return StmtError();
13718    return S.ActOnExprStmt(Assignment);
13719  }
13720
13721  //     - if the subobject is an array, each element is assigned, in the
13722  //       manner appropriate to the element type;
13723
13724  // Construct a loop over the array bounds, e.g.,
13725  //
13726  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13727  //
13728  // that will copy each of the array elements.
13729  QualType SizeType = S.Context.getSizeType();
13730
13731  // Create the iteration variable.
13732  IdentifierInfo *IterationVarName = nullptr;
13733  {
13734    SmallString<8> Str;
13735    llvm::raw_svector_ostream OS(Str);
13736    OS << "__i" << Depth;
13737    IterationVarName = &S.Context.Idents.get(OS.str());
13738  }
13739  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13740                                          IterationVarName, SizeType,
13741                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13742                                          SC_None);
13743
13744  // Initialize the iteration variable to zero.
13745  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13746  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13747
13748  // Creates a reference to the iteration variable.
13749  RefBuilder IterationVarRef(IterationVar, SizeType);
13750  LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13751
13752  // Create the DeclStmt that holds the iteration variable.
13753  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13754
13755  // Subscript the "from" and "to" expressions with the iteration variable.
13756  SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13757  MoveCastBuilder FromIndexMove(FromIndexCopy);
13758  const ExprBuilder *FromIndex;
13759  if (Copying)
13760    FromIndex = &FromIndexCopy;
13761  else
13762    FromIndex = &FromIndexMove;
13763
13764  SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13765
13766  // Build the copy/move for an individual element of the array.
13767  StmtResult Copy =
13768    buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13769                                     ToIndex, *FromIndex, CopyingBaseSubobject,
13770                                     Copying, Depth + 1);
13771  // Bail out if copying fails or if we determined that we should use memcpy.
13772  if (Copy.isInvalid() || !Copy.get())
13773    return Copy;
13774
13775  // Create the comparison against the array bound.
13776  llvm::APInt Upper
13777    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13778  Expr *Comparison = BinaryOperator::Create(
13779      S.Context, IterationVarRefRVal.build(S, Loc),
13780      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13781      S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13782
13783  // Create the pre-increment of the iteration variable. We can determine
13784  // whether the increment will overflow based on the value of the array
13785  // bound.
13786  Expr *Increment = UnaryOperator::Create(
13787      S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13788      OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13789
13790  // Construct the loop that copies all elements of this array.
13791  return S.ActOnForStmt(
13792      Loc, Loc, InitStmt,
13793      S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13794      S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13795}
13796
13797static StmtResult
13798buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13799                      const ExprBuilder &To, const ExprBuilder &From,
13800                      bool CopyingBaseSubobject, bool Copying) {
13801  // Maybe we should use a memcpy?
13802  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13803      T.isTriviallyCopyableType(S.Context))
13804    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13805
13806  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13807                                                     CopyingBaseSubobject,
13808                                                     Copying, 0));
13809
13810  // If we ended up picking a trivial assignment operator for an array of a
13811  // non-trivially-copyable class type, just emit a memcpy.
13812  if (!Result.isInvalid() && !Result.get())
13813    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13814
13815  return Result;
13816}
13817
13818CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13819  // Note: The following rules are largely analoguous to the copy
13820  // constructor rules. Note that virtual bases are not taken into account
13821  // for determining the argument type of the operator. Note also that
13822  // operators taking an object instead of a reference are allowed.
13823  assert(ClassDecl->needsImplicitCopyAssignment());
13824
13825  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13826  if (DSM.isAlreadyBeingDeclared())
13827    return nullptr;
13828
13829  QualType ArgType = Context.getTypeDeclType(ClassDecl);
13830  LangAS AS = getDefaultCXXMethodAddrSpace();
13831  if (AS != LangAS::Default)
13832    ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13833  QualType RetType = Context.getLValueReferenceType(ArgType);
13834  bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13835  if (Const)
13836    ArgType = ArgType.withConst();
13837
13838  ArgType = Context.getLValueReferenceType(ArgType);
13839
13840  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13841                                                     CXXCopyAssignment,
13842                                                     Const);
13843
13844  //   An implicitly-declared copy assignment operator is an inline public
13845  //   member of its class.
13846  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13847  SourceLocation ClassLoc = ClassDecl->getLocation();
13848  DeclarationNameInfo NameInfo(Name, ClassLoc);
13849  CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13850      Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13851      /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13852      /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
13853      SourceLocation());
13854  CopyAssignment->setAccess(AS_public);
13855  CopyAssignment->setDefaulted();
13856  CopyAssignment->setImplicit();
13857
13858  if (getLangOpts().CUDA) {
13859    inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13860                                            CopyAssignment,
13861                                            /* ConstRHS */ Const,
13862                                            /* Diagnose */ false);
13863  }
13864
13865  setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13866
13867  // Add the parameter to the operator.
13868  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13869                                               ClassLoc, ClassLoc,
13870                                               /*Id=*/nullptr, ArgType,
13871                                               /*TInfo=*/nullptr, SC_None,
13872                                               nullptr);
13873  CopyAssignment->setParams(FromParam);
13874
13875  CopyAssignment->setTrivial(
13876    ClassDecl->needsOverloadResolutionForCopyAssignment()
13877      ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13878      : ClassDecl->hasTrivialCopyAssignment());
13879
13880  // Note that we have added this copy-assignment operator.
13881  ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13882
13883  Scope *S = getScopeForContext(ClassDecl);
13884  CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13885
13886  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13887    ClassDecl->setImplicitCopyAssignmentIsDeleted();
13888    SetDeclDeleted(CopyAssignment, ClassLoc);
13889  }
13890
13891  if (S)
13892    PushOnScopeChains(CopyAssignment, S, false);
13893  ClassDecl->addDecl(CopyAssignment);
13894
13895  return CopyAssignment;
13896}
13897
13898/// Diagnose an implicit copy operation for a class which is odr-used, but
13899/// which is deprecated because the class has a user-declared copy constructor,
13900/// copy assignment operator, or destructor.
13901static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13902  assert(CopyOp->isImplicit());
13903
13904  CXXRecordDecl *RD = CopyOp->getParent();
13905  CXXMethodDecl *UserDeclaredOperation = nullptr;
13906
13907  // In Microsoft mode, assignment operations don't affect constructors and
13908  // vice versa.
13909  if (RD->hasUserDeclaredDestructor()) {
13910    UserDeclaredOperation = RD->getDestructor();
13911  } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13912             RD->hasUserDeclaredCopyConstructor() &&
13913             !S.getLangOpts().MSVCCompat) {
13914    // Find any user-declared copy constructor.
13915    for (auto *I : RD->ctors()) {
13916      if (I->isCopyConstructor()) {
13917        UserDeclaredOperation = I;
13918        break;
13919      }
13920    }
13921    assert(UserDeclaredOperation);
13922  } else if (isa<CXXConstructorDecl>(CopyOp) &&
13923             RD->hasUserDeclaredCopyAssignment() &&
13924             !S.getLangOpts().MSVCCompat) {
13925    // Find any user-declared move assignment operator.
13926    for (auto *I : RD->methods()) {
13927      if (I->isCopyAssignmentOperator()) {
13928        UserDeclaredOperation = I;
13929        break;
13930      }
13931    }
13932    assert(UserDeclaredOperation);
13933  }
13934
13935  if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13936    S.Diag(UserDeclaredOperation->getLocation(),
13937           isa<CXXDestructorDecl>(UserDeclaredOperation)
13938               ? diag::warn_deprecated_copy_dtor_operation
13939               : diag::warn_deprecated_copy_operation)
13940        << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13941  }
13942}
13943
13944void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13945                                        CXXMethodDecl *CopyAssignOperator) {
13946  assert((CopyAssignOperator->isDefaulted() &&
13947          CopyAssignOperator->isOverloadedOperator() &&
13948          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
13949          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
13950          !CopyAssignOperator->isDeleted()) &&
13951         "DefineImplicitCopyAssignment called for wrong function");
13952  if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
13953    return;
13954
13955  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
13956  if (ClassDecl->isInvalidDecl()) {
13957    CopyAssignOperator->setInvalidDecl();
13958    return;
13959  }
13960
13961  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
13962
13963  // The exception specification is needed because we are defining the
13964  // function.
13965  ResolveExceptionSpec(CurrentLocation,
13966                       CopyAssignOperator->getType()->castAs<FunctionProtoType>());
13967
13968  // Add a context note for diagnostics produced after this point.
13969  Scope.addContextNote(CurrentLocation);
13970
13971  // C++11 [class.copy]p18:
13972  //   The [definition of an implicitly declared copy assignment operator] is
13973  //   deprecated if the class has a user-declared copy constructor or a
13974  //   user-declared destructor.
13975  if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
13976    diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
13977
13978  // C++0x [class.copy]p30:
13979  //   The implicitly-defined or explicitly-defaulted copy assignment operator
13980  //   for a non-union class X performs memberwise copy assignment of its
13981  //   subobjects. The direct base classes of X are assigned first, in the
13982  //   order of their declaration in the base-specifier-list, and then the
13983  //   immediate non-static data members of X are assigned, in the order in
13984  //   which they were declared in the class definition.
13985
13986  // The statements that form the synthesized function body.
13987  SmallVector<Stmt*, 8> Statements;
13988
13989  // The parameter for the "other" object, which we are copying from.
13990  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
13991  Qualifiers OtherQuals = Other->getType().getQualifiers();
13992  QualType OtherRefType = Other->getType();
13993  if (const LValueReferenceType *OtherRef
13994                                = OtherRefType->getAs<LValueReferenceType>()) {
13995    OtherRefType = OtherRef->getPointeeType();
13996    OtherQuals = OtherRefType.getQualifiers();
13997  }
13998
13999  // Our location for everything implicitly-generated.
14000  SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14001                           ? CopyAssignOperator->getEndLoc()
14002                           : CopyAssignOperator->getLocation();
14003
14004  // Builds a DeclRefExpr for the "other" object.
14005  RefBuilder OtherRef(Other, OtherRefType);
14006
14007  // Builds the "this" pointer.
14008  ThisBuilder This;
14009
14010  // Assign base classes.
14011  bool Invalid = false;
14012  for (auto &Base : ClassDecl->bases()) {
14013    // Form the assignment:
14014    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14015    QualType BaseType = Base.getType().getUnqualifiedType();
14016    if (!BaseType->isRecordType()) {
14017      Invalid = true;
14018      continue;
14019    }
14020
14021    CXXCastPath BasePath;
14022    BasePath.push_back(&Base);
14023
14024    // Construct the "from" expression, which is an implicit cast to the
14025    // appropriately-qualified base type.
14026    CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14027                     VK_LValue, BasePath);
14028
14029    // Dereference "this".
14030    DerefBuilder DerefThis(This);
14031    CastBuilder To(DerefThis,
14032                   Context.getQualifiedType(
14033                       BaseType, CopyAssignOperator->getMethodQualifiers()),
14034                   VK_LValue, BasePath);
14035
14036    // Build the copy.
14037    StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14038                                            To, From,
14039                                            /*CopyingBaseSubobject=*/true,
14040                                            /*Copying=*/true);
14041    if (Copy.isInvalid()) {
14042      CopyAssignOperator->setInvalidDecl();
14043      return;
14044    }
14045
14046    // Success! Record the copy.
14047    Statements.push_back(Copy.getAs<Expr>());
14048  }
14049
14050  // Assign non-static members.
14051  for (auto *Field : ClassDecl->fields()) {
14052    // FIXME: We should form some kind of AST representation for the implied
14053    // memcpy in a union copy operation.
14054    if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14055      continue;
14056
14057    if (Field->isInvalidDecl()) {
14058      Invalid = true;
14059      continue;
14060    }
14061
14062    // Check for members of reference type; we can't copy those.
14063    if (Field->getType()->isReferenceType()) {
14064      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14065        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14066      Diag(Field->getLocation(), diag::note_declared_at);
14067      Invalid = true;
14068      continue;
14069    }
14070
14071    // Check for members of const-qualified, non-class type.
14072    QualType BaseType = Context.getBaseElementType(Field->getType());
14073    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14074      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14075        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14076      Diag(Field->getLocation(), diag::note_declared_at);
14077      Invalid = true;
14078      continue;
14079    }
14080
14081    // Suppress assigning zero-width bitfields.
14082    if (Field->isZeroLengthBitField(Context))
14083      continue;
14084
14085    QualType FieldType = Field->getType().getNonReferenceType();
14086    if (FieldType->isIncompleteArrayType()) {
14087      assert(ClassDecl->hasFlexibleArrayMember() &&
14088             "Incomplete array type is not valid");
14089      continue;
14090    }
14091
14092    // Build references to the field in the object we're copying from and to.
14093    CXXScopeSpec SS; // Intentionally empty
14094    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14095                              LookupMemberName);
14096    MemberLookup.addDecl(Field);
14097    MemberLookup.resolveKind();
14098
14099    MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14100
14101    MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14102
14103    // Build the copy of this field.
14104    StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14105                                            To, From,
14106                                            /*CopyingBaseSubobject=*/false,
14107                                            /*Copying=*/true);
14108    if (Copy.isInvalid()) {
14109      CopyAssignOperator->setInvalidDecl();
14110      return;
14111    }
14112
14113    // Success! Record the copy.
14114    Statements.push_back(Copy.getAs<Stmt>());
14115  }
14116
14117  if (!Invalid) {
14118    // Add a "return *this;"
14119    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14120
14121    StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14122    if (Return.isInvalid())
14123      Invalid = true;
14124    else
14125      Statements.push_back(Return.getAs<Stmt>());
14126  }
14127
14128  if (Invalid) {
14129    CopyAssignOperator->setInvalidDecl();
14130    return;
14131  }
14132
14133  StmtResult Body;
14134  {
14135    CompoundScopeRAII CompoundScope(*this);
14136    Body = ActOnCompoundStmt(Loc, Loc, Statements,
14137                             /*isStmtExpr=*/false);
14138    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14139  }
14140  CopyAssignOperator->setBody(Body.getAs<Stmt>());
14141  CopyAssignOperator->markUsed(Context);
14142
14143  if (ASTMutationListener *L = getASTMutationListener()) {
14144    L->CompletedImplicitDefinition(CopyAssignOperator);
14145  }
14146}
14147
14148CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14149  assert(ClassDecl->needsImplicitMoveAssignment());
14150
14151  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14152  if (DSM.isAlreadyBeingDeclared())
14153    return nullptr;
14154
14155  // Note: The following rules are largely analoguous to the move
14156  // constructor rules.
14157
14158  QualType ArgType = Context.getTypeDeclType(ClassDecl);
14159  LangAS AS = getDefaultCXXMethodAddrSpace();
14160  if (AS != LangAS::Default)
14161    ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14162  QualType RetType = Context.getLValueReferenceType(ArgType);
14163  ArgType = Context.getRValueReferenceType(ArgType);
14164
14165  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14166                                                     CXXMoveAssignment,
14167                                                     false);
14168
14169  //   An implicitly-declared move assignment operator is an inline public
14170  //   member of its class.
14171  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14172  SourceLocation ClassLoc = ClassDecl->getLocation();
14173  DeclarationNameInfo NameInfo(Name, ClassLoc);
14174  CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14175      Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14176      /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14177      /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
14178      SourceLocation());
14179  MoveAssignment->setAccess(AS_public);
14180  MoveAssignment->setDefaulted();
14181  MoveAssignment->setImplicit();
14182
14183  if (getLangOpts().CUDA) {
14184    inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14185                                            MoveAssignment,
14186                                            /* ConstRHS */ false,
14187                                            /* Diagnose */ false);
14188  }
14189
14190  // Build an exception specification pointing back at this member.
14191  FunctionProtoType::ExtProtoInfo EPI =
14192      getImplicitMethodEPI(*this, MoveAssignment);
14193  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14194
14195  // Add the parameter to the operator.
14196  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14197                                               ClassLoc, ClassLoc,
14198                                               /*Id=*/nullptr, ArgType,
14199                                               /*TInfo=*/nullptr, SC_None,
14200                                               nullptr);
14201  MoveAssignment->setParams(FromParam);
14202
14203  MoveAssignment->setTrivial(
14204    ClassDecl->needsOverloadResolutionForMoveAssignment()
14205      ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14206      : ClassDecl->hasTrivialMoveAssignment());
14207
14208  // Note that we have added this copy-assignment operator.
14209  ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14210
14211  Scope *S = getScopeForContext(ClassDecl);
14212  CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14213
14214  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14215    ClassDecl->setImplicitMoveAssignmentIsDeleted();
14216    SetDeclDeleted(MoveAssignment, ClassLoc);
14217  }
14218
14219  if (S)
14220    PushOnScopeChains(MoveAssignment, S, false);
14221  ClassDecl->addDecl(MoveAssignment);
14222
14223  return MoveAssignment;
14224}
14225
14226/// Check if we're implicitly defining a move assignment operator for a class
14227/// with virtual bases. Such a move assignment might move-assign the virtual
14228/// base multiple times.
14229static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14230                                               SourceLocation CurrentLocation) {
14231  assert(!Class->isDependentContext() && "should not define dependent move");
14232
14233  // Only a virtual base could get implicitly move-assigned multiple times.
14234  // Only a non-trivial move assignment can observe this. We only want to
14235  // diagnose if we implicitly define an assignment operator that assigns
14236  // two base classes, both of which move-assign the same virtual base.
14237  if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14238      Class->getNumBases() < 2)
14239    return;
14240
14241  llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14242  typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14243  VBaseMap VBases;
14244
14245  for (auto &BI : Class->bases()) {
14246    Worklist.push_back(&BI);
14247    while (!Worklist.empty()) {
14248      CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14249      CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14250
14251      // If the base has no non-trivial move assignment operators,
14252      // we don't care about moves from it.
14253      if (!Base->hasNonTrivialMoveAssignment())
14254        continue;
14255
14256      // If there's nothing virtual here, skip it.
14257      if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14258        continue;
14259
14260      // If we're not actually going to call a move assignment for this base,
14261      // or the selected move assignment is trivial, skip it.
14262      Sema::SpecialMemberOverloadResult SMOR =
14263        S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14264                              /*ConstArg*/false, /*VolatileArg*/false,
14265                              /*RValueThis*/true, /*ConstThis*/false,
14266                              /*VolatileThis*/false);
14267      if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14268          !SMOR.getMethod()->isMoveAssignmentOperator())
14269        continue;
14270
14271      if (BaseSpec->isVirtual()) {
14272        // We're going to move-assign this virtual base, and its move
14273        // assignment operator is not trivial. If this can happen for
14274        // multiple distinct direct bases of Class, diagnose it. (If it
14275        // only happens in one base, we'll diagnose it when synthesizing
14276        // that base class's move assignment operator.)
14277        CXXBaseSpecifier *&Existing =
14278            VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14279                .first->second;
14280        if (Existing && Existing != &BI) {
14281          S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14282            << Class << Base;
14283          S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14284              << (Base->getCanonicalDecl() ==
14285                  Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14286              << Base << Existing->getType() << Existing->getSourceRange();
14287          S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14288              << (Base->getCanonicalDecl() ==
14289                  BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14290              << Base << BI.getType() << BaseSpec->getSourceRange();
14291
14292          // Only diagnose each vbase once.
14293          Existing = nullptr;
14294        }
14295      } else {
14296        // Only walk over bases that have defaulted move assignment operators.
14297        // We assume that any user-provided move assignment operator handles
14298        // the multiple-moves-of-vbase case itself somehow.
14299        if (!SMOR.getMethod()->isDefaulted())
14300          continue;
14301
14302        // We're going to move the base classes of Base. Add them to the list.
14303        for (auto &BI : Base->bases())
14304          Worklist.push_back(&BI);
14305      }
14306    }
14307  }
14308}
14309
14310void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14311                                        CXXMethodDecl *MoveAssignOperator) {
14312  assert((MoveAssignOperator->isDefaulted() &&
14313          MoveAssignOperator->isOverloadedOperator() &&
14314          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14315          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14316          !MoveAssignOperator->isDeleted()) &&
14317         "DefineImplicitMoveAssignment called for wrong function");
14318  if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14319    return;
14320
14321  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14322  if (ClassDecl->isInvalidDecl()) {
14323    MoveAssignOperator->setInvalidDecl();
14324    return;
14325  }
14326
14327  // C++0x [class.copy]p28:
14328  //   The implicitly-defined or move assignment operator for a non-union class
14329  //   X performs memberwise move assignment of its subobjects. The direct base
14330  //   classes of X are assigned first, in the order of their declaration in the
14331  //   base-specifier-list, and then the immediate non-static data members of X
14332  //   are assigned, in the order in which they were declared in the class
14333  //   definition.
14334
14335  // Issue a warning if our implicit move assignment operator will move
14336  // from a virtual base more than once.
14337  checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14338
14339  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14340
14341  // The exception specification is needed because we are defining the
14342  // function.
14343  ResolveExceptionSpec(CurrentLocation,
14344                       MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14345
14346  // Add a context note for diagnostics produced after this point.
14347  Scope.addContextNote(CurrentLocation);
14348
14349  // The statements that form the synthesized function body.
14350  SmallVector<Stmt*, 8> Statements;
14351
14352  // The parameter for the "other" object, which we are move from.
14353  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14354  QualType OtherRefType =
14355      Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14356
14357  // Our location for everything implicitly-generated.
14358  SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14359                           ? MoveAssignOperator->getEndLoc()
14360                           : MoveAssignOperator->getLocation();
14361
14362  // Builds a reference to the "other" object.
14363  RefBuilder OtherRef(Other, OtherRefType);
14364  // Cast to rvalue.
14365  MoveCastBuilder MoveOther(OtherRef);
14366
14367  // Builds the "this" pointer.
14368  ThisBuilder This;
14369
14370  // Assign base classes.
14371  bool Invalid = false;
14372  for (auto &Base : ClassDecl->bases()) {
14373    // C++11 [class.copy]p28:
14374    //   It is unspecified whether subobjects representing virtual base classes
14375    //   are assigned more than once by the implicitly-defined copy assignment
14376    //   operator.
14377    // FIXME: Do not assign to a vbase that will be assigned by some other base
14378    // class. For a move-assignment, this can result in the vbase being moved
14379    // multiple times.
14380
14381    // Form the assignment:
14382    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14383    QualType BaseType = Base.getType().getUnqualifiedType();
14384    if (!BaseType->isRecordType()) {
14385      Invalid = true;
14386      continue;
14387    }
14388
14389    CXXCastPath BasePath;
14390    BasePath.push_back(&Base);
14391
14392    // Construct the "from" expression, which is an implicit cast to the
14393    // appropriately-qualified base type.
14394    CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14395
14396    // Dereference "this".
14397    DerefBuilder DerefThis(This);
14398
14399    // Implicitly cast "this" to the appropriately-qualified base type.
14400    CastBuilder To(DerefThis,
14401                   Context.getQualifiedType(
14402                       BaseType, MoveAssignOperator->getMethodQualifiers()),
14403                   VK_LValue, BasePath);
14404
14405    // Build the move.
14406    StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14407                                            To, From,
14408                                            /*CopyingBaseSubobject=*/true,
14409                                            /*Copying=*/false);
14410    if (Move.isInvalid()) {
14411      MoveAssignOperator->setInvalidDecl();
14412      return;
14413    }
14414
14415    // Success! Record the move.
14416    Statements.push_back(Move.getAs<Expr>());
14417  }
14418
14419  // Assign non-static members.
14420  for (auto *Field : ClassDecl->fields()) {
14421    // FIXME: We should form some kind of AST representation for the implied
14422    // memcpy in a union copy operation.
14423    if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14424      continue;
14425
14426    if (Field->isInvalidDecl()) {
14427      Invalid = true;
14428      continue;
14429    }
14430
14431    // Check for members of reference type; we can't move those.
14432    if (Field->getType()->isReferenceType()) {
14433      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14434        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14435      Diag(Field->getLocation(), diag::note_declared_at);
14436      Invalid = true;
14437      continue;
14438    }
14439
14440    // Check for members of const-qualified, non-class type.
14441    QualType BaseType = Context.getBaseElementType(Field->getType());
14442    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14443      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14444        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14445      Diag(Field->getLocation(), diag::note_declared_at);
14446      Invalid = true;
14447      continue;
14448    }
14449
14450    // Suppress assigning zero-width bitfields.
14451    if (Field->isZeroLengthBitField(Context))
14452      continue;
14453
14454    QualType FieldType = Field->getType().getNonReferenceType();
14455    if (FieldType->isIncompleteArrayType()) {
14456      assert(ClassDecl->hasFlexibleArrayMember() &&
14457             "Incomplete array type is not valid");
14458      continue;
14459    }
14460
14461    // Build references to the field in the object we're copying from and to.
14462    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14463                              LookupMemberName);
14464    MemberLookup.addDecl(Field);
14465    MemberLookup.resolveKind();
14466    MemberBuilder From(MoveOther, OtherRefType,
14467                       /*IsArrow=*/false, MemberLookup);
14468    MemberBuilder To(This, getCurrentThisType(),
14469                     /*IsArrow=*/true, MemberLookup);
14470
14471    assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14472        "Member reference with rvalue base must be rvalue except for reference "
14473        "members, which aren't allowed for move assignment.");
14474
14475    // Build the move of this field.
14476    StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14477                                            To, From,
14478                                            /*CopyingBaseSubobject=*/false,
14479                                            /*Copying=*/false);
14480    if (Move.isInvalid()) {
14481      MoveAssignOperator->setInvalidDecl();
14482      return;
14483    }
14484
14485    // Success! Record the copy.
14486    Statements.push_back(Move.getAs<Stmt>());
14487  }
14488
14489  if (!Invalid) {
14490    // Add a "return *this;"
14491    ExprResult ThisObj =
14492        CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14493
14494    StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14495    if (Return.isInvalid())
14496      Invalid = true;
14497    else
14498      Statements.push_back(Return.getAs<Stmt>());
14499  }
14500
14501  if (Invalid) {
14502    MoveAssignOperator->setInvalidDecl();
14503    return;
14504  }
14505
14506  StmtResult Body;
14507  {
14508    CompoundScopeRAII CompoundScope(*this);
14509    Body = ActOnCompoundStmt(Loc, Loc, Statements,
14510                             /*isStmtExpr=*/false);
14511    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14512  }
14513  MoveAssignOperator->setBody(Body.getAs<Stmt>());
14514  MoveAssignOperator->markUsed(Context);
14515
14516  if (ASTMutationListener *L = getASTMutationListener()) {
14517    L->CompletedImplicitDefinition(MoveAssignOperator);
14518  }
14519}
14520
14521CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14522                                                    CXXRecordDecl *ClassDecl) {
14523  // C++ [class.copy]p4:
14524  //   If the class definition does not explicitly declare a copy
14525  //   constructor, one is declared implicitly.
14526  assert(ClassDecl->needsImplicitCopyConstructor());
14527
14528  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14529  if (DSM.isAlreadyBeingDeclared())
14530    return nullptr;
14531
14532  QualType ClassType = Context.getTypeDeclType(ClassDecl);
14533  QualType ArgType = ClassType;
14534  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14535  if (Const)
14536    ArgType = ArgType.withConst();
14537
14538  LangAS AS = getDefaultCXXMethodAddrSpace();
14539  if (AS != LangAS::Default)
14540    ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14541
14542  ArgType = Context.getLValueReferenceType(ArgType);
14543
14544  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14545                                                     CXXCopyConstructor,
14546                                                     Const);
14547
14548  DeclarationName Name
14549    = Context.DeclarationNames.getCXXConstructorName(
14550                                           Context.getCanonicalType(ClassType));
14551  SourceLocation ClassLoc = ClassDecl->getLocation();
14552  DeclarationNameInfo NameInfo(Name, ClassLoc);
14553
14554  //   An implicitly-declared copy constructor is an inline public
14555  //   member of its class.
14556  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14557      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14558      ExplicitSpecifier(),
14559      /*isInline=*/true,
14560      /*isImplicitlyDeclared=*/true,
14561      Constexpr ? CSK_constexpr : CSK_unspecified);
14562  CopyConstructor->setAccess(AS_public);
14563  CopyConstructor->setDefaulted();
14564
14565  if (getLangOpts().CUDA) {
14566    inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14567                                            CopyConstructor,
14568                                            /* ConstRHS */ Const,
14569                                            /* Diagnose */ false);
14570  }
14571
14572  setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14573
14574  // Add the parameter to the constructor.
14575  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14576                                               ClassLoc, ClassLoc,
14577                                               /*IdentifierInfo=*/nullptr,
14578                                               ArgType, /*TInfo=*/nullptr,
14579                                               SC_None, nullptr);
14580  CopyConstructor->setParams(FromParam);
14581
14582  CopyConstructor->setTrivial(
14583      ClassDecl->needsOverloadResolutionForCopyConstructor()
14584          ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14585          : ClassDecl->hasTrivialCopyConstructor());
14586
14587  CopyConstructor->setTrivialForCall(
14588      ClassDecl->hasAttr<TrivialABIAttr>() ||
14589      (ClassDecl->needsOverloadResolutionForCopyConstructor()
14590           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14591             TAH_ConsiderTrivialABI)
14592           : ClassDecl->hasTrivialCopyConstructorForCall()));
14593
14594  // Note that we have declared this constructor.
14595  ++getASTContext().NumImplicitCopyConstructorsDeclared;
14596
14597  Scope *S = getScopeForContext(ClassDecl);
14598  CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14599
14600  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14601    ClassDecl->setImplicitCopyConstructorIsDeleted();
14602    SetDeclDeleted(CopyConstructor, ClassLoc);
14603  }
14604
14605  if (S)
14606    PushOnScopeChains(CopyConstructor, S, false);
14607  ClassDecl->addDecl(CopyConstructor);
14608
14609  return CopyConstructor;
14610}
14611
14612void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14613                                         CXXConstructorDecl *CopyConstructor) {
14614  assert((CopyConstructor->isDefaulted() &&
14615          CopyConstructor->isCopyConstructor() &&
14616          !CopyConstructor->doesThisDeclarationHaveABody() &&
14617          !CopyConstructor->isDeleted()) &&
14618         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14619  if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14620    return;
14621
14622  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14623  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14624
14625  SynthesizedFunctionScope Scope(*this, CopyConstructor);
14626
14627  // The exception specification is needed because we are defining the
14628  // function.
14629  ResolveExceptionSpec(CurrentLocation,
14630                       CopyConstructor->getType()->castAs<FunctionProtoType>());
14631  MarkVTableUsed(CurrentLocation, ClassDecl);
14632
14633  // Add a context note for diagnostics produced after this point.
14634  Scope.addContextNote(CurrentLocation);
14635
14636  // C++11 [class.copy]p7:
14637  //   The [definition of an implicitly declared copy constructor] is
14638  //   deprecated if the class has a user-declared copy assignment operator
14639  //   or a user-declared destructor.
14640  if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14641    diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14642
14643  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14644    CopyConstructor->setInvalidDecl();
14645  }  else {
14646    SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14647                             ? CopyConstructor->getEndLoc()
14648                             : CopyConstructor->getLocation();
14649    Sema::CompoundScopeRAII CompoundScope(*this);
14650    CopyConstructor->setBody(
14651        ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14652    CopyConstructor->markUsed(Context);
14653  }
14654
14655  if (ASTMutationListener *L = getASTMutationListener()) {
14656    L->CompletedImplicitDefinition(CopyConstructor);
14657  }
14658}
14659
14660CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14661                                                    CXXRecordDecl *ClassDecl) {
14662  assert(ClassDecl->needsImplicitMoveConstructor());
14663
14664  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14665  if (DSM.isAlreadyBeingDeclared())
14666    return nullptr;
14667
14668  QualType ClassType = Context.getTypeDeclType(ClassDecl);
14669
14670  QualType ArgType = ClassType;
14671  LangAS AS = getDefaultCXXMethodAddrSpace();
14672  if (AS != LangAS::Default)
14673    ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14674  ArgType = Context.getRValueReferenceType(ArgType);
14675
14676  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14677                                                     CXXMoveConstructor,
14678                                                     false);
14679
14680  DeclarationName Name
14681    = Context.DeclarationNames.getCXXConstructorName(
14682                                           Context.getCanonicalType(ClassType));
14683  SourceLocation ClassLoc = ClassDecl->getLocation();
14684  DeclarationNameInfo NameInfo(Name, ClassLoc);
14685
14686  // C++11 [class.copy]p11:
14687  //   An implicitly-declared copy/move constructor is an inline public
14688  //   member of its class.
14689  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14690      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14691      ExplicitSpecifier(),
14692      /*isInline=*/true,
14693      /*isImplicitlyDeclared=*/true,
14694      Constexpr ? CSK_constexpr : CSK_unspecified);
14695  MoveConstructor->setAccess(AS_public);
14696  MoveConstructor->setDefaulted();
14697
14698  if (getLangOpts().CUDA) {
14699    inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14700                                            MoveConstructor,
14701                                            /* ConstRHS */ false,
14702                                            /* Diagnose */ false);
14703  }
14704
14705  setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14706
14707  // Add the parameter to the constructor.
14708  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14709                                               ClassLoc, ClassLoc,
14710                                               /*IdentifierInfo=*/nullptr,
14711                                               ArgType, /*TInfo=*/nullptr,
14712                                               SC_None, nullptr);
14713  MoveConstructor->setParams(FromParam);
14714
14715  MoveConstructor->setTrivial(
14716      ClassDecl->needsOverloadResolutionForMoveConstructor()
14717          ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14718          : ClassDecl->hasTrivialMoveConstructor());
14719
14720  MoveConstructor->setTrivialForCall(
14721      ClassDecl->hasAttr<TrivialABIAttr>() ||
14722      (ClassDecl->needsOverloadResolutionForMoveConstructor()
14723           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14724                                    TAH_ConsiderTrivialABI)
14725           : ClassDecl->hasTrivialMoveConstructorForCall()));
14726
14727  // Note that we have declared this constructor.
14728  ++getASTContext().NumImplicitMoveConstructorsDeclared;
14729
14730  Scope *S = getScopeForContext(ClassDecl);
14731  CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14732
14733  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14734    ClassDecl->setImplicitMoveConstructorIsDeleted();
14735    SetDeclDeleted(MoveConstructor, ClassLoc);
14736  }
14737
14738  if (S)
14739    PushOnScopeChains(MoveConstructor, S, false);
14740  ClassDecl->addDecl(MoveConstructor);
14741
14742  return MoveConstructor;
14743}
14744
14745void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14746                                         CXXConstructorDecl *MoveConstructor) {
14747  assert((MoveConstructor->isDefaulted() &&
14748          MoveConstructor->isMoveConstructor() &&
14749          !MoveConstructor->doesThisDeclarationHaveABody() &&
14750          !MoveConstructor->isDeleted()) &&
14751         "DefineImplicitMoveConstructor - call it for implicit move ctor");
14752  if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14753    return;
14754
14755  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14756  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14757
14758  SynthesizedFunctionScope Scope(*this, MoveConstructor);
14759
14760  // The exception specification is needed because we are defining the
14761  // function.
14762  ResolveExceptionSpec(CurrentLocation,
14763                       MoveConstructor->getType()->castAs<FunctionProtoType>());
14764  MarkVTableUsed(CurrentLocation, ClassDecl);
14765
14766  // Add a context note for diagnostics produced after this point.
14767  Scope.addContextNote(CurrentLocation);
14768
14769  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14770    MoveConstructor->setInvalidDecl();
14771  } else {
14772    SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14773                             ? MoveConstructor->getEndLoc()
14774                             : MoveConstructor->getLocation();
14775    Sema::CompoundScopeRAII CompoundScope(*this);
14776    MoveConstructor->setBody(ActOnCompoundStmt(
14777        Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14778    MoveConstructor->markUsed(Context);
14779  }
14780
14781  if (ASTMutationListener *L = getASTMutationListener()) {
14782    L->CompletedImplicitDefinition(MoveConstructor);
14783  }
14784}
14785
14786bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14787  return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14788}
14789
14790void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14791                            SourceLocation CurrentLocation,
14792                            CXXConversionDecl *Conv) {
14793  SynthesizedFunctionScope Scope(*this, Conv);
14794  assert(!Conv->getReturnType()->isUndeducedType());
14795
14796  CXXRecordDecl *Lambda = Conv->getParent();
14797  FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14798  FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
14799
14800  if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14801    CallOp = InstantiateFunctionDeclaration(
14802        CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14803    if (!CallOp)
14804      return;
14805
14806    Invoker = InstantiateFunctionDeclaration(
14807        Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14808    if (!Invoker)
14809      return;
14810  }
14811
14812  if (CallOp->isInvalidDecl())
14813    return;
14814
14815  // Mark the call operator referenced (and add to pending instantiations
14816  // if necessary).
14817  // For both the conversion and static-invoker template specializations
14818  // we construct their body's in this function, so no need to add them
14819  // to the PendingInstantiations.
14820  MarkFunctionReferenced(CurrentLocation, CallOp);
14821
14822  // Fill in the __invoke function with a dummy implementation. IR generation
14823  // will fill in the actual details. Update its type in case it contained
14824  // an 'auto'.
14825  Invoker->markUsed(Context);
14826  Invoker->setReferenced();
14827  Invoker->setType(Conv->getReturnType()->getPointeeType());
14828  Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14829
14830  // Construct the body of the conversion function { return __invoke; }.
14831  Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14832                                       VK_LValue, Conv->getLocation());
14833  assert(FunctionRef && "Can't refer to __invoke function?");
14834  Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14835  Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14836                                     Conv->getLocation()));
14837  Conv->markUsed(Context);
14838  Conv->setReferenced();
14839
14840  if (ASTMutationListener *L = getASTMutationListener()) {
14841    L->CompletedImplicitDefinition(Conv);
14842    L->CompletedImplicitDefinition(Invoker);
14843  }
14844}
14845
14846
14847
14848void Sema::DefineImplicitLambdaToBlockPointerConversion(
14849       SourceLocation CurrentLocation,
14850       CXXConversionDecl *Conv)
14851{
14852  assert(!Conv->getParent()->isGenericLambda());
14853
14854  SynthesizedFunctionScope Scope(*this, Conv);
14855
14856  // Copy-initialize the lambda object as needed to capture it.
14857  Expr *This = ActOnCXXThis(CurrentLocation).get();
14858  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14859
14860  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14861                                                        Conv->getLocation(),
14862                                                        Conv, DerefThis);
14863
14864  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14865  // behavior.  Note that only the general conversion function does this
14866  // (since it's unusable otherwise); in the case where we inline the
14867  // block literal, it has block literal lifetime semantics.
14868  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14869    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
14870                                          CK_CopyAndAutoreleaseBlockObject,
14871                                          BuildBlock.get(), nullptr, VK_RValue);
14872
14873  if (BuildBlock.isInvalid()) {
14874    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14875    Conv->setInvalidDecl();
14876    return;
14877  }
14878
14879  // Create the return statement that returns the block from the conversion
14880  // function.
14881  StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14882  if (Return.isInvalid()) {
14883    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14884    Conv->setInvalidDecl();
14885    return;
14886  }
14887
14888  // Set the body of the conversion function.
14889  Stmt *ReturnS = Return.get();
14890  Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14891                                     Conv->getLocation()));
14892  Conv->markUsed(Context);
14893
14894  // We're done; notify the mutation listener, if any.
14895  if (ASTMutationListener *L = getASTMutationListener()) {
14896    L->CompletedImplicitDefinition(Conv);
14897  }
14898}
14899
14900/// Determine whether the given list arguments contains exactly one
14901/// "real" (non-default) argument.
14902static bool hasOneRealArgument(MultiExprArg Args) {
14903  switch (Args.size()) {
14904  case 0:
14905    return false;
14906
14907  default:
14908    if (!Args[1]->isDefaultArgument())
14909      return false;
14910
14911    LLVM_FALLTHROUGH;
14912  case 1:
14913    return !Args[0]->isDefaultArgument();
14914  }
14915
14916  return false;
14917}
14918
14919ExprResult
14920Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14921                            NamedDecl *FoundDecl,
14922                            CXXConstructorDecl *Constructor,
14923                            MultiExprArg ExprArgs,
14924                            bool HadMultipleCandidates,
14925                            bool IsListInitialization,
14926                            bool IsStdInitListInitialization,
14927                            bool RequiresZeroInit,
14928                            unsigned ConstructKind,
14929                            SourceRange ParenRange) {
14930  bool Elidable = false;
14931
14932  // C++0x [class.copy]p34:
14933  //   When certain criteria are met, an implementation is allowed to
14934  //   omit the copy/move construction of a class object, even if the
14935  //   copy/move constructor and/or destructor for the object have
14936  //   side effects. [...]
14937  //     - when a temporary class object that has not been bound to a
14938  //       reference (12.2) would be copied/moved to a class object
14939  //       with the same cv-unqualified type, the copy/move operation
14940  //       can be omitted by constructing the temporary object
14941  //       directly into the target of the omitted copy/move
14942  if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
14943      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
14944    Expr *SubExpr = ExprArgs[0];
14945    Elidable = SubExpr->isTemporaryObject(
14946        Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
14947  }
14948
14949  return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
14950                               FoundDecl, Constructor,
14951                               Elidable, ExprArgs, HadMultipleCandidates,
14952                               IsListInitialization,
14953                               IsStdInitListInitialization, RequiresZeroInit,
14954                               ConstructKind, ParenRange);
14955}
14956
14957ExprResult
14958Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14959                            NamedDecl *FoundDecl,
14960                            CXXConstructorDecl *Constructor,
14961                            bool Elidable,
14962                            MultiExprArg ExprArgs,
14963                            bool HadMultipleCandidates,
14964                            bool IsListInitialization,
14965                            bool IsStdInitListInitialization,
14966                            bool RequiresZeroInit,
14967                            unsigned ConstructKind,
14968                            SourceRange ParenRange) {
14969  if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
14970    Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
14971    if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
14972      return ExprError();
14973  }
14974
14975  return BuildCXXConstructExpr(
14976      ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
14977      HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
14978      RequiresZeroInit, ConstructKind, ParenRange);
14979}
14980
14981/// BuildCXXConstructExpr - Creates a complete call to a constructor,
14982/// including handling of its default argument expressions.
14983ExprResult
14984Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14985                            CXXConstructorDecl *Constructor,
14986                            bool Elidable,
14987                            MultiExprArg ExprArgs,
14988                            bool HadMultipleCandidates,
14989                            bool IsListInitialization,
14990                            bool IsStdInitListInitialization,
14991                            bool RequiresZeroInit,
14992                            unsigned ConstructKind,
14993                            SourceRange ParenRange) {
14994  assert(declaresSameEntity(
14995             Constructor->getParent(),
14996             DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
14997         "given constructor for wrong type");
14998  MarkFunctionReferenced(ConstructLoc, Constructor);
14999  if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15000    return ExprError();
15001  if (getLangOpts().SYCLIsDevice &&
15002      !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15003    return ExprError();
15004
15005  return CheckForImmediateInvocation(
15006      CXXConstructExpr::Create(
15007          Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15008          HadMultipleCandidates, IsListInitialization,
15009          IsStdInitListInitialization, RequiresZeroInit,
15010          static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15011          ParenRange),
15012      Constructor);
15013}
15014
15015ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15016  assert(Field->hasInClassInitializer());
15017
15018  // If we already have the in-class initializer nothing needs to be done.
15019  if (Field->getInClassInitializer())
15020    return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15021
15022  // If we might have already tried and failed to instantiate, don't try again.
15023  if (Field->isInvalidDecl())
15024    return ExprError();
15025
15026  // Maybe we haven't instantiated the in-class initializer. Go check the
15027  // pattern FieldDecl to see if it has one.
15028  CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15029
15030  if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15031    CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15032    DeclContext::lookup_result Lookup =
15033        ClassPattern->lookup(Field->getDeclName());
15034
15035    // Lookup can return at most two results: the pattern for the field, or the
15036    // injected class name of the parent record. No other member can have the
15037    // same name as the field.
15038    // In modules mode, lookup can return multiple results (coming from
15039    // different modules).
15040    assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
15041           "more than two lookup results for field name");
15042    FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
15043    if (!Pattern) {
15044      assert(isa<CXXRecordDecl>(Lookup[0]) &&
15045             "cannot have other non-field member with same name");
15046      for (auto L : Lookup)
15047        if (isa<FieldDecl>(L)) {
15048          Pattern = cast<FieldDecl>(L);
15049          break;
15050        }
15051      assert(Pattern && "We must have set the Pattern!");
15052    }
15053
15054    if (!Pattern->hasInClassInitializer() ||
15055        InstantiateInClassInitializer(Loc, Field, Pattern,
15056                                      getTemplateInstantiationArgs(Field))) {
15057      // Don't diagnose this again.
15058      Field->setInvalidDecl();
15059      return ExprError();
15060    }
15061    return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15062  }
15063
15064  // DR1351:
15065  //   If the brace-or-equal-initializer of a non-static data member
15066  //   invokes a defaulted default constructor of its class or of an
15067  //   enclosing class in a potentially evaluated subexpression, the
15068  //   program is ill-formed.
15069  //
15070  // This resolution is unworkable: the exception specification of the
15071  // default constructor can be needed in an unevaluated context, in
15072  // particular, in the operand of a noexcept-expression, and we can be
15073  // unable to compute an exception specification for an enclosed class.
15074  //
15075  // Any attempt to resolve the exception specification of a defaulted default
15076  // constructor before the initializer is lexically complete will ultimately
15077  // come here at which point we can diagnose it.
15078  RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15079  Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
15080      << OutermostClass << Field;
15081  Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
15082  // Recover by marking the field invalid, unless we're in a SFINAE context.
15083  if (!isSFINAEContext())
15084    Field->setInvalidDecl();
15085  return ExprError();
15086}
15087
15088void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15089  if (VD->isInvalidDecl()) return;
15090  // If initializing the variable failed, don't also diagnose problems with
15091  // the desctructor, they're likely related.
15092  if (VD->getInit() && VD->getInit()->containsErrors())
15093    return;
15094
15095  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15096  if (ClassDecl->isInvalidDecl()) return;
15097  if (ClassDecl->hasIrrelevantDestructor()) return;
15098  if (ClassDecl->isDependentContext()) return;
15099
15100  if (VD->isNoDestroy(getASTContext()))
15101    return;
15102
15103  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15104
15105  // If this is an array, we'll require the destructor during initialization, so
15106  // we can skip over this. We still want to emit exit-time destructor warnings
15107  // though.
15108  if (!VD->getType()->isArrayType()) {
15109    MarkFunctionReferenced(VD->getLocation(), Destructor);
15110    CheckDestructorAccess(VD->getLocation(), Destructor,
15111                          PDiag(diag::err_access_dtor_var)
15112                              << VD->getDeclName() << VD->getType());
15113    DiagnoseUseOfDecl(Destructor, VD->getLocation());
15114  }
15115
15116  if (Destructor->isTrivial()) return;
15117
15118  // If the destructor is constexpr, check whether the variable has constant
15119  // destruction now.
15120  if (Destructor->isConstexpr()) {
15121    bool HasConstantInit = false;
15122    if (VD->getInit() && !VD->getInit()->isValueDependent())
15123      HasConstantInit = VD->evaluateValue();
15124    SmallVector<PartialDiagnosticAt, 8> Notes;
15125    if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15126        HasConstantInit) {
15127      Diag(VD->getLocation(),
15128           diag::err_constexpr_var_requires_const_destruction) << VD;
15129      for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15130        Diag(Notes[I].first, Notes[I].second);
15131    }
15132  }
15133
15134  if (!VD->hasGlobalStorage()) return;
15135
15136  // Emit warning for non-trivial dtor in global scope (a real global,
15137  // class-static, function-static).
15138  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15139
15140  // TODO: this should be re-enabled for static locals by !CXAAtExit
15141  if (!VD->isStaticLocal())
15142    Diag(VD->getLocation(), diag::warn_global_destructor);
15143}
15144
15145/// Given a constructor and the set of arguments provided for the
15146/// constructor, convert the arguments and add any required default arguments
15147/// to form a proper call to this constructor.
15148///
15149/// \returns true if an error occurred, false otherwise.
15150bool
15151Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15152                              MultiExprArg ArgsPtr,
15153                              SourceLocation Loc,
15154                              SmallVectorImpl<Expr*> &ConvertedArgs,
15155                              bool AllowExplicit,
15156                              bool IsListInitialization) {
15157  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15158  unsigned NumArgs = ArgsPtr.size();
15159  Expr **Args = ArgsPtr.data();
15160
15161  const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15162  unsigned NumParams = Proto->getNumParams();
15163
15164  // If too few arguments are available, we'll fill in the rest with defaults.
15165  if (NumArgs < NumParams)
15166    ConvertedArgs.reserve(NumParams);
15167  else
15168    ConvertedArgs.reserve(NumArgs);
15169
15170  VariadicCallType CallType =
15171    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15172  SmallVector<Expr *, 8> AllArgs;
15173  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15174                                        Proto, 0,
15175                                        llvm::makeArrayRef(Args, NumArgs),
15176                                        AllArgs,
15177                                        CallType, AllowExplicit,
15178                                        IsListInitialization);
15179  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15180
15181  DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15182
15183  CheckConstructorCall(Constructor,
15184                       llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15185                       Proto, Loc);
15186
15187  return Invalid;
15188}
15189
15190static inline bool
15191CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15192                                       const FunctionDecl *FnDecl) {
15193  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15194  if (isa<NamespaceDecl>(DC)) {
15195    return SemaRef.Diag(FnDecl->getLocation(),
15196                        diag::err_operator_new_delete_declared_in_namespace)
15197      << FnDecl->getDeclName();
15198  }
15199
15200  if (isa<TranslationUnitDecl>(DC) &&
15201      FnDecl->getStorageClass() == SC_Static) {
15202    return SemaRef.Diag(FnDecl->getLocation(),
15203                        diag::err_operator_new_delete_declared_static)
15204      << FnDecl->getDeclName();
15205  }
15206
15207  return false;
15208}
15209
15210static QualType
15211RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15212  QualType QTy = PtrTy->getPointeeType();
15213  QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15214  return SemaRef.Context.getPointerType(QTy);
15215}
15216
15217static inline bool
15218CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15219                            CanQualType ExpectedResultType,
15220                            CanQualType ExpectedFirstParamType,
15221                            unsigned DependentParamTypeDiag,
15222                            unsigned InvalidParamTypeDiag) {
15223  QualType ResultType =
15224      FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15225
15226  // The operator is valid on any address space for OpenCL.
15227  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15228    if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15229      ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15230    }
15231  }
15232
15233  // Check that the result type is what we expect.
15234  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15235    // Reject even if the type is dependent; an operator delete function is
15236    // required to have a non-dependent result type.
15237    return SemaRef.Diag(
15238               FnDecl->getLocation(),
15239               ResultType->isDependentType()
15240                   ? diag::err_operator_new_delete_dependent_result_type
15241                   : diag::err_operator_new_delete_invalid_result_type)
15242           << FnDecl->getDeclName() << ExpectedResultType;
15243  }
15244
15245  // A function template must have at least 2 parameters.
15246  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15247    return SemaRef.Diag(FnDecl->getLocation(),
15248                      diag::err_operator_new_delete_template_too_few_parameters)
15249        << FnDecl->getDeclName();
15250
15251  // The function decl must have at least 1 parameter.
15252  if (FnDecl->getNumParams() == 0)
15253    return SemaRef.Diag(FnDecl->getLocation(),
15254                        diag::err_operator_new_delete_too_few_parameters)
15255      << FnDecl->getDeclName();
15256
15257  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15258  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15259    // The operator is valid on any address space for OpenCL.
15260    if (auto *PtrTy =
15261            FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15262      FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15263    }
15264  }
15265
15266  // Check that the first parameter type is what we expect.
15267  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15268      ExpectedFirstParamType) {
15269    // The first parameter type is not allowed to be dependent. As a tentative
15270    // DR resolution, we allow a dependent parameter type if it is the right
15271    // type anyway, to allow destroying operator delete in class templates.
15272    return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15273                                                   ? DependentParamTypeDiag
15274                                                   : InvalidParamTypeDiag)
15275           << FnDecl->getDeclName() << ExpectedFirstParamType;
15276  }
15277
15278  return false;
15279}
15280
15281static bool
15282CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15283  // C++ [basic.stc.dynamic.allocation]p1:
15284  //   A program is ill-formed if an allocation function is declared in a
15285  //   namespace scope other than global scope or declared static in global
15286  //   scope.
15287  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15288    return true;
15289
15290  CanQualType SizeTy =
15291    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15292
15293  // C++ [basic.stc.dynamic.allocation]p1:
15294  //  The return type shall be void*. The first parameter shall have type
15295  //  std::size_t.
15296  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15297                                  SizeTy,
15298                                  diag::err_operator_new_dependent_param_type,
15299                                  diag::err_operator_new_param_type))
15300    return true;
15301
15302  // C++ [basic.stc.dynamic.allocation]p1:
15303  //  The first parameter shall not have an associated default argument.
15304  if (FnDecl->getParamDecl(0)->hasDefaultArg())
15305    return SemaRef.Diag(FnDecl->getLocation(),
15306                        diag::err_operator_new_default_arg)
15307      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15308
15309  return false;
15310}
15311
15312static bool
15313CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15314  // C++ [basic.stc.dynamic.deallocation]p1:
15315  //   A program is ill-formed if deallocation functions are declared in a
15316  //   namespace scope other than global scope or declared static in global
15317  //   scope.
15318  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15319    return true;
15320
15321  auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15322
15323  // C++ P0722:
15324  //   Within a class C, the first parameter of a destroying operator delete
15325  //   shall be of type C *. The first parameter of any other deallocation
15326  //   function shall be of type void *.
15327  CanQualType ExpectedFirstParamType =
15328      MD && MD->isDestroyingOperatorDelete()
15329          ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15330                SemaRef.Context.getRecordType(MD->getParent())))
15331          : SemaRef.Context.VoidPtrTy;
15332
15333  // C++ [basic.stc.dynamic.deallocation]p2:
15334  //   Each deallocation function shall return void
15335  if (CheckOperatorNewDeleteTypes(
15336          SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15337          diag::err_operator_delete_dependent_param_type,
15338          diag::err_operator_delete_param_type))
15339    return true;
15340
15341  // C++ P0722:
15342  //   A destroying operator delete shall be a usual deallocation function.
15343  if (MD && !MD->getParent()->isDependentContext() &&
15344      MD->isDestroyingOperatorDelete() &&
15345      !SemaRef.isUsualDeallocationFunction(MD)) {
15346    SemaRef.Diag(MD->getLocation(),
15347                 diag::err_destroying_operator_delete_not_usual);
15348    return true;
15349  }
15350
15351  return false;
15352}
15353
15354/// CheckOverloadedOperatorDeclaration - Check whether the declaration
15355/// of this overloaded operator is well-formed. If so, returns false;
15356/// otherwise, emits appropriate diagnostics and returns true.
15357bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15358  assert(FnDecl && FnDecl->isOverloadedOperator() &&
15359         "Expected an overloaded operator declaration");
15360
15361  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15362
15363  // C++ [over.oper]p5:
15364  //   The allocation and deallocation functions, operator new,
15365  //   operator new[], operator delete and operator delete[], are
15366  //   described completely in 3.7.3. The attributes and restrictions
15367  //   found in the rest of this subclause do not apply to them unless
15368  //   explicitly stated in 3.7.3.
15369  if (Op == OO_Delete || Op == OO_Array_Delete)
15370    return CheckOperatorDeleteDeclaration(*this, FnDecl);
15371
15372  if (Op == OO_New || Op == OO_Array_New)
15373    return CheckOperatorNewDeclaration(*this, FnDecl);
15374
15375  // C++ [over.oper]p6:
15376  //   An operator function shall either be a non-static member
15377  //   function or be a non-member function and have at least one
15378  //   parameter whose type is a class, a reference to a class, an
15379  //   enumeration, or a reference to an enumeration.
15380  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15381    if (MethodDecl->isStatic())
15382      return Diag(FnDecl->getLocation(),
15383                  diag::err_operator_overload_static) << FnDecl->getDeclName();
15384  } else {
15385    bool ClassOrEnumParam = false;
15386    for (auto Param : FnDecl->parameters()) {
15387      QualType ParamType = Param->getType().getNonReferenceType();
15388      if (ParamType->isDependentType() || ParamType->isRecordType() ||
15389          ParamType->isEnumeralType()) {
15390        ClassOrEnumParam = true;
15391        break;
15392      }
15393    }
15394
15395    if (!ClassOrEnumParam)
15396      return Diag(FnDecl->getLocation(),
15397                  diag::err_operator_overload_needs_class_or_enum)
15398        << FnDecl->getDeclName();
15399  }
15400
15401  // C++ [over.oper]p8:
15402  //   An operator function cannot have default arguments (8.3.6),
15403  //   except where explicitly stated below.
15404  //
15405  // Only the function-call operator allows default arguments
15406  // (C++ [over.call]p1).
15407  if (Op != OO_Call) {
15408    for (auto Param : FnDecl->parameters()) {
15409      if (Param->hasDefaultArg())
15410        return Diag(Param->getLocation(),
15411                    diag::err_operator_overload_default_arg)
15412          << FnDecl->getDeclName() << Param->getDefaultArgRange();
15413    }
15414  }
15415
15416  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15417    { false, false, false }
15418#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15419    , { Unary, Binary, MemberOnly }
15420#include "clang/Basic/OperatorKinds.def"
15421  };
15422
15423  bool CanBeUnaryOperator = OperatorUses[Op][0];
15424  bool CanBeBinaryOperator = OperatorUses[Op][1];
15425  bool MustBeMemberOperator = OperatorUses[Op][2];
15426
15427  // C++ [over.oper]p8:
15428  //   [...] Operator functions cannot have more or fewer parameters
15429  //   than the number required for the corresponding operator, as
15430  //   described in the rest of this subclause.
15431  unsigned NumParams = FnDecl->getNumParams()
15432                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15433  if (Op != OO_Call &&
15434      ((NumParams == 1 && !CanBeUnaryOperator) ||
15435       (NumParams == 2 && !CanBeBinaryOperator) ||
15436       (NumParams < 1) || (NumParams > 2))) {
15437    // We have the wrong number of parameters.
15438    unsigned ErrorKind;
15439    if (CanBeUnaryOperator && CanBeBinaryOperator) {
15440      ErrorKind = 2;  // 2 -> unary or binary.
15441    } else if (CanBeUnaryOperator) {
15442      ErrorKind = 0;  // 0 -> unary
15443    } else {
15444      assert(CanBeBinaryOperator &&
15445             "All non-call overloaded operators are unary or binary!");
15446      ErrorKind = 1;  // 1 -> binary
15447    }
15448
15449    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15450      << FnDecl->getDeclName() << NumParams << ErrorKind;
15451  }
15452
15453  // Overloaded operators other than operator() cannot be variadic.
15454  if (Op != OO_Call &&
15455      FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15456    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15457      << FnDecl->getDeclName();
15458  }
15459
15460  // Some operators must be non-static member functions.
15461  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15462    return Diag(FnDecl->getLocation(),
15463                diag::err_operator_overload_must_be_member)
15464      << FnDecl->getDeclName();
15465  }
15466
15467  // C++ [over.inc]p1:
15468  //   The user-defined function called operator++ implements the
15469  //   prefix and postfix ++ operator. If this function is a member
15470  //   function with no parameters, or a non-member function with one
15471  //   parameter of class or enumeration type, it defines the prefix
15472  //   increment operator ++ for objects of that type. If the function
15473  //   is a member function with one parameter (which shall be of type
15474  //   int) or a non-member function with two parameters (the second
15475  //   of which shall be of type int), it defines the postfix
15476  //   increment operator ++ for objects of that type.
15477  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15478    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15479    QualType ParamType = LastParam->getType();
15480
15481    if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15482        !ParamType->isDependentType())
15483      return Diag(LastParam->getLocation(),
15484                  diag::err_operator_overload_post_incdec_must_be_int)
15485        << LastParam->getType() << (Op == OO_MinusMinus);
15486  }
15487
15488  return false;
15489}
15490
15491static bool
15492checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15493                                          FunctionTemplateDecl *TpDecl) {
15494  TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15495
15496  // Must have one or two template parameters.
15497  if (TemplateParams->size() == 1) {
15498    NonTypeTemplateParmDecl *PmDecl =
15499        dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15500
15501    // The template parameter must be a char parameter pack.
15502    if (PmDecl && PmDecl->isTemplateParameterPack() &&
15503        SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15504      return false;
15505
15506  } else if (TemplateParams->size() == 2) {
15507    TemplateTypeParmDecl *PmType =
15508        dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15509    NonTypeTemplateParmDecl *PmArgs =
15510        dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15511
15512    // The second template parameter must be a parameter pack with the
15513    // first template parameter as its type.
15514    if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15515        PmArgs->isTemplateParameterPack()) {
15516      const TemplateTypeParmType *TArgs =
15517          PmArgs->getType()->getAs<TemplateTypeParmType>();
15518      if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15519          TArgs->getIndex() == PmType->getIndex()) {
15520        if (!SemaRef.inTemplateInstantiation())
15521          SemaRef.Diag(TpDecl->getLocation(),
15522                       diag::ext_string_literal_operator_template);
15523        return false;
15524      }
15525    }
15526  }
15527
15528  SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15529               diag::err_literal_operator_template)
15530      << TpDecl->getTemplateParameters()->getSourceRange();
15531  return true;
15532}
15533
15534/// CheckLiteralOperatorDeclaration - Check whether the declaration
15535/// of this literal operator function is well-formed. If so, returns
15536/// false; otherwise, emits appropriate diagnostics and returns true.
15537bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15538  if (isa<CXXMethodDecl>(FnDecl)) {
15539    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15540      << FnDecl->getDeclName();
15541    return true;
15542  }
15543
15544  if (FnDecl->isExternC()) {
15545    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15546    if (const LinkageSpecDecl *LSD =
15547            FnDecl->getDeclContext()->getExternCContext())
15548      Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15549    return true;
15550  }
15551
15552  // This might be the definition of a literal operator template.
15553  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15554
15555  // This might be a specialization of a literal operator template.
15556  if (!TpDecl)
15557    TpDecl = FnDecl->getPrimaryTemplate();
15558
15559  // template <char...> type operator "" name() and
15560  // template <class T, T...> type operator "" name() are the only valid
15561  // template signatures, and the only valid signatures with no parameters.
15562  if (TpDecl) {
15563    if (FnDecl->param_size() != 0) {
15564      Diag(FnDecl->getLocation(),
15565           diag::err_literal_operator_template_with_params);
15566      return true;
15567    }
15568
15569    if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15570      return true;
15571
15572  } else if (FnDecl->param_size() == 1) {
15573    const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15574
15575    QualType ParamType = Param->getType().getUnqualifiedType();
15576
15577    // Only unsigned long long int, long double, any character type, and const
15578    // char * are allowed as the only parameters.
15579    if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15580        ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15581        Context.hasSameType(ParamType, Context.CharTy) ||
15582        Context.hasSameType(ParamType, Context.WideCharTy) ||
15583        Context.hasSameType(ParamType, Context.Char8Ty) ||
15584        Context.hasSameType(ParamType, Context.Char16Ty) ||
15585        Context.hasSameType(ParamType, Context.Char32Ty)) {
15586    } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15587      QualType InnerType = Ptr->getPointeeType();
15588
15589      // Pointer parameter must be a const char *.
15590      if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15591                                Context.CharTy) &&
15592            InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15593        Diag(Param->getSourceRange().getBegin(),
15594             diag::err_literal_operator_param)
15595            << ParamType << "'const char *'" << Param->getSourceRange();
15596        return true;
15597      }
15598
15599    } else if (ParamType->isRealFloatingType()) {
15600      Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15601          << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15602      return true;
15603
15604    } else if (ParamType->isIntegerType()) {
15605      Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15606          << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15607      return true;
15608
15609    } else {
15610      Diag(Param->getSourceRange().getBegin(),
15611           diag::err_literal_operator_invalid_param)
15612          << ParamType << Param->getSourceRange();
15613      return true;
15614    }
15615
15616  } else if (FnDecl->param_size() == 2) {
15617    FunctionDecl::param_iterator Param = FnDecl->param_begin();
15618
15619    // First, verify that the first parameter is correct.
15620
15621    QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15622
15623    // Two parameter function must have a pointer to const as a
15624    // first parameter; let's strip those qualifiers.
15625    const PointerType *PT = FirstParamType->getAs<PointerType>();
15626
15627    if (!PT) {
15628      Diag((*Param)->getSourceRange().getBegin(),
15629           diag::err_literal_operator_param)
15630          << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15631      return true;
15632    }
15633
15634    QualType PointeeType = PT->getPointeeType();
15635    // First parameter must be const
15636    if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15637      Diag((*Param)->getSourceRange().getBegin(),
15638           diag::err_literal_operator_param)
15639          << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15640      return true;
15641    }
15642
15643    QualType InnerType = PointeeType.getUnqualifiedType();
15644    // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15645    // const char32_t* are allowed as the first parameter to a two-parameter
15646    // function
15647    if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15648          Context.hasSameType(InnerType, Context.WideCharTy) ||
15649          Context.hasSameType(InnerType, Context.Char8Ty) ||
15650          Context.hasSameType(InnerType, Context.Char16Ty) ||
15651          Context.hasSameType(InnerType, Context.Char32Ty))) {
15652      Diag((*Param)->getSourceRange().getBegin(),
15653           diag::err_literal_operator_param)
15654          << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15655      return true;
15656    }
15657
15658    // Move on to the second and final parameter.
15659    ++Param;
15660
15661    // The second parameter must be a std::size_t.
15662    QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15663    if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15664      Diag((*Param)->getSourceRange().getBegin(),
15665           diag::err_literal_operator_param)
15666          << SecondParamType << Context.getSizeType()
15667          << (*Param)->getSourceRange();
15668      return true;
15669    }
15670  } else {
15671    Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15672    return true;
15673  }
15674
15675  // Parameters are good.
15676
15677  // A parameter-declaration-clause containing a default argument is not
15678  // equivalent to any of the permitted forms.
15679  for (auto Param : FnDecl->parameters()) {
15680    if (Param->hasDefaultArg()) {
15681      Diag(Param->getDefaultArgRange().getBegin(),
15682           diag::err_literal_operator_default_argument)
15683        << Param->getDefaultArgRange();
15684      break;
15685    }
15686  }
15687
15688  StringRef LiteralName
15689    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15690  if (LiteralName[0] != '_' &&
15691      !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15692    // C++11 [usrlit.suffix]p1:
15693    //   Literal suffix identifiers that do not start with an underscore
15694    //   are reserved for future standardization.
15695    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15696      << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15697  }
15698
15699  return false;
15700}
15701
15702/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15703/// linkage specification, including the language and (if present)
15704/// the '{'. ExternLoc is the location of the 'extern', Lang is the
15705/// language string literal. LBraceLoc, if valid, provides the location of
15706/// the '{' brace. Otherwise, this linkage specification does not
15707/// have any braces.
15708Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15709                                           Expr *LangStr,
15710                                           SourceLocation LBraceLoc) {
15711  StringLiteral *Lit = cast<StringLiteral>(LangStr);
15712  if (!Lit->isAscii()) {
15713    Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15714      << LangStr->getSourceRange();
15715    return nullptr;
15716  }
15717
15718  StringRef Lang = Lit->getString();
15719  LinkageSpecDecl::LanguageIDs Language;
15720  if (Lang == "C")
15721    Language = LinkageSpecDecl::lang_c;
15722  else if (Lang == "C++")
15723    Language = LinkageSpecDecl::lang_cxx;
15724  else {
15725    Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15726      << LangStr->getSourceRange();
15727    return nullptr;
15728  }
15729
15730  // FIXME: Add all the various semantics of linkage specifications
15731
15732  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15733                                               LangStr->getExprLoc(), Language,
15734                                               LBraceLoc.isValid());
15735  CurContext->addDecl(D);
15736  PushDeclContext(S, D);
15737  return D;
15738}
15739
15740/// ActOnFinishLinkageSpecification - Complete the definition of
15741/// the C++ linkage specification LinkageSpec. If RBraceLoc is
15742/// valid, it's the position of the closing '}' brace in a linkage
15743/// specification that uses braces.
15744Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15745                                            Decl *LinkageSpec,
15746                                            SourceLocation RBraceLoc) {
15747  if (RBraceLoc.isValid()) {
15748    LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15749    LSDecl->setRBraceLoc(RBraceLoc);
15750  }
15751  PopDeclContext();
15752  return LinkageSpec;
15753}
15754
15755Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15756                                  const ParsedAttributesView &AttrList,
15757                                  SourceLocation SemiLoc) {
15758  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15759  // Attribute declarations appertain to empty declaration so we handle
15760  // them here.
15761  ProcessDeclAttributeList(S, ED, AttrList);
15762
15763  CurContext->addDecl(ED);
15764  return ED;
15765}
15766
15767/// Perform semantic analysis for the variable declaration that
15768/// occurs within a C++ catch clause, returning the newly-created
15769/// variable.
15770VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15771                                         TypeSourceInfo *TInfo,
15772                                         SourceLocation StartLoc,
15773                                         SourceLocation Loc,
15774                                         IdentifierInfo *Name) {
15775  bool Invalid = false;
15776  QualType ExDeclType = TInfo->getType();
15777
15778  // Arrays and functions decay.
15779  if (ExDeclType->isArrayType())
15780    ExDeclType = Context.getArrayDecayedType(ExDeclType);
15781  else if (ExDeclType->isFunctionType())
15782    ExDeclType = Context.getPointerType(ExDeclType);
15783
15784  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15785  // The exception-declaration shall not denote a pointer or reference to an
15786  // incomplete type, other than [cv] void*.
15787  // N2844 forbids rvalue references.
15788  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15789    Diag(Loc, diag::err_catch_rvalue_ref);
15790    Invalid = true;
15791  }
15792
15793  if (ExDeclType->isVariablyModifiedType()) {
15794    Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15795    Invalid = true;
15796  }
15797
15798  QualType BaseType = ExDeclType;
15799  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15800  unsigned DK = diag::err_catch_incomplete;
15801  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15802    BaseType = Ptr->getPointeeType();
15803    Mode = 1;
15804    DK = diag::err_catch_incomplete_ptr;
15805  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15806    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15807    BaseType = Ref->getPointeeType();
15808    Mode = 2;
15809    DK = diag::err_catch_incomplete_ref;
15810  }
15811  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15812      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15813    Invalid = true;
15814
15815  if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15816    Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15817    Invalid = true;
15818  }
15819
15820  if (!Invalid && !ExDeclType->isDependentType() &&
15821      RequireNonAbstractType(Loc, ExDeclType,
15822                             diag::err_abstract_type_in_decl,
15823                             AbstractVariableType))
15824    Invalid = true;
15825
15826  // Only the non-fragile NeXT runtime currently supports C++ catches
15827  // of ObjC types, and no runtime supports catching ObjC types by value.
15828  if (!Invalid && getLangOpts().ObjC) {
15829    QualType T = ExDeclType;
15830    if (const ReferenceType *RT = T->getAs<ReferenceType>())
15831      T = RT->getPointeeType();
15832
15833    if (T->isObjCObjectType()) {
15834      Diag(Loc, diag::err_objc_object_catch);
15835      Invalid = true;
15836    } else if (T->isObjCObjectPointerType()) {
15837      // FIXME: should this be a test for macosx-fragile specifically?
15838      if (getLangOpts().ObjCRuntime.isFragile())
15839        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15840    }
15841  }
15842
15843  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15844                                    ExDeclType, TInfo, SC_None);
15845  ExDecl->setExceptionVariable(true);
15846
15847  // In ARC, infer 'retaining' for variables of retainable type.
15848  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15849    Invalid = true;
15850
15851  if (!Invalid && !ExDeclType->isDependentType()) {
15852    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15853      // Insulate this from anything else we might currently be parsing.
15854      EnterExpressionEvaluationContext scope(
15855          *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15856
15857      // C++ [except.handle]p16:
15858      //   The object declared in an exception-declaration or, if the
15859      //   exception-declaration does not specify a name, a temporary (12.2) is
15860      //   copy-initialized (8.5) from the exception object. [...]
15861      //   The object is destroyed when the handler exits, after the destruction
15862      //   of any automatic objects initialized within the handler.
15863      //
15864      // We just pretend to initialize the object with itself, then make sure
15865      // it can be destroyed later.
15866      QualType initType = Context.getExceptionObjectType(ExDeclType);
15867
15868      InitializedEntity entity =
15869        InitializedEntity::InitializeVariable(ExDecl);
15870      InitializationKind initKind =
15871        InitializationKind::CreateCopy(Loc, SourceLocation());
15872
15873      Expr *opaqueValue =
15874        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15875      InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15876      ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15877      if (result.isInvalid())
15878        Invalid = true;
15879      else {
15880        // If the constructor used was non-trivial, set this as the
15881        // "initializer".
15882        CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15883        if (!construct->getConstructor()->isTrivial()) {
15884          Expr *init = MaybeCreateExprWithCleanups(construct);
15885          ExDecl->setInit(init);
15886        }
15887
15888        // And make sure it's destructable.
15889        FinalizeVarWithDestructor(ExDecl, recordType);
15890      }
15891    }
15892  }
15893
15894  if (Invalid)
15895    ExDecl->setInvalidDecl();
15896
15897  return ExDecl;
15898}
15899
15900/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15901/// handler.
15902Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15903  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15904  bool Invalid = D.isInvalidType();
15905
15906  // Check for unexpanded parameter packs.
15907  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15908                                      UPPC_ExceptionType)) {
15909    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15910                                             D.getIdentifierLoc());
15911    Invalid = true;
15912  }
15913
15914  IdentifierInfo *II = D.getIdentifier();
15915  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15916                                             LookupOrdinaryName,
15917                                             ForVisibleRedeclaration)) {
15918    // The scope should be freshly made just for us. There is just no way
15919    // it contains any previous declaration, except for function parameters in
15920    // a function-try-block's catch statement.
15921    assert(!S->isDeclScope(PrevDecl));
15922    if (isDeclInScope(PrevDecl, CurContext, S)) {
15923      Diag(D.getIdentifierLoc(), diag::err_redefinition)
15924        << D.getIdentifier();
15925      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15926      Invalid = true;
15927    } else if (PrevDecl->isTemplateParameter())
15928      // Maybe we will complain about the shadowed template parameter.
15929      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15930  }
15931
15932  if (D.getCXXScopeSpec().isSet() && !Invalid) {
15933    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15934      << D.getCXXScopeSpec().getRange();
15935    Invalid = true;
15936  }
15937
15938  VarDecl *ExDecl = BuildExceptionDeclaration(
15939      S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
15940  if (Invalid)
15941    ExDecl->setInvalidDecl();
15942
15943  // Add the exception declaration into this scope.
15944  if (II)
15945    PushOnScopeChains(ExDecl, S);
15946  else
15947    CurContext->addDecl(ExDecl);
15948
15949  ProcessDeclAttributes(S, ExDecl, D);
15950  return ExDecl;
15951}
15952
15953Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15954                                         Expr *AssertExpr,
15955                                         Expr *AssertMessageExpr,
15956                                         SourceLocation RParenLoc) {
15957  StringLiteral *AssertMessage =
15958      AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
15959
15960  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
15961    return nullptr;
15962
15963  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
15964                                      AssertMessage, RParenLoc, false);
15965}
15966
15967Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15968                                         Expr *AssertExpr,
15969                                         StringLiteral *AssertMessage,
15970                                         SourceLocation RParenLoc,
15971                                         bool Failed) {
15972  assert(AssertExpr != nullptr && "Expected non-null condition");
15973  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
15974      !Failed) {
15975    // In a static_assert-declaration, the constant-expression shall be a
15976    // constant expression that can be contextually converted to bool.
15977    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
15978    if (Converted.isInvalid())
15979      Failed = true;
15980
15981    ExprResult FullAssertExpr =
15982        ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
15983                            /*DiscardedValue*/ false,
15984                            /*IsConstexpr*/ true);
15985    if (FullAssertExpr.isInvalid())
15986      Failed = true;
15987    else
15988      AssertExpr = FullAssertExpr.get();
15989
15990    llvm::APSInt Cond;
15991    if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
15992          diag::err_static_assert_expression_is_not_constant,
15993          /*AllowFold=*/false).isInvalid())
15994      Failed = true;
15995
15996    if (!Failed && !Cond) {
15997      SmallString<256> MsgBuffer;
15998      llvm::raw_svector_ostream Msg(MsgBuffer);
15999      if (AssertMessage)
16000        AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16001
16002      Expr *InnerCond = nullptr;
16003      std::string InnerCondDescription;
16004      std::tie(InnerCond, InnerCondDescription) =
16005        findFailedBooleanCondition(Converted.get());
16006      if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16007        // Drill down into concept specialization expressions to see why they
16008        // weren't satisfied.
16009        Diag(StaticAssertLoc, diag::err_static_assert_failed)
16010          << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16011        ConstraintSatisfaction Satisfaction;
16012        if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16013          DiagnoseUnsatisfiedConstraint(Satisfaction);
16014      } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16015                           && !isa<IntegerLiteral>(InnerCond)) {
16016        Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16017          << InnerCondDescription << !AssertMessage
16018          << Msg.str() << InnerCond->getSourceRange();
16019      } else {
16020        Diag(StaticAssertLoc, diag::err_static_assert_failed)
16021          << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16022      }
16023      Failed = true;
16024    }
16025  } else {
16026    ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16027                                                    /*DiscardedValue*/false,
16028                                                    /*IsConstexpr*/true);
16029    if (FullAssertExpr.isInvalid())
16030      Failed = true;
16031    else
16032      AssertExpr = FullAssertExpr.get();
16033  }
16034
16035  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16036                                        AssertExpr, AssertMessage, RParenLoc,
16037                                        Failed);
16038
16039  CurContext->addDecl(Decl);
16040  return Decl;
16041}
16042
16043/// Perform semantic analysis of the given friend type declaration.
16044///
16045/// \returns A friend declaration that.
16046FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16047                                      SourceLocation FriendLoc,
16048                                      TypeSourceInfo *TSInfo) {
16049  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16050
16051  QualType T = TSInfo->getType();
16052  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16053
16054  // C++03 [class.friend]p2:
16055  //   An elaborated-type-specifier shall be used in a friend declaration
16056  //   for a class.*
16057  //
16058  //   * The class-key of the elaborated-type-specifier is required.
16059  if (!CodeSynthesisContexts.empty()) {
16060    // Do not complain about the form of friend template types during any kind
16061    // of code synthesis. For template instantiation, we will have complained
16062    // when the template was defined.
16063  } else {
16064    if (!T->isElaboratedTypeSpecifier()) {
16065      // If we evaluated the type to a record type, suggest putting
16066      // a tag in front.
16067      if (const RecordType *RT = T->getAs<RecordType>()) {
16068        RecordDecl *RD = RT->getDecl();
16069
16070        SmallString<16> InsertionText(" ");
16071        InsertionText += RD->getKindName();
16072
16073        Diag(TypeRange.getBegin(),
16074             getLangOpts().CPlusPlus11 ?
16075               diag::warn_cxx98_compat_unelaborated_friend_type :
16076               diag::ext_unelaborated_friend_type)
16077          << (unsigned) RD->getTagKind()
16078          << T
16079          << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16080                                        InsertionText);
16081      } else {
16082        Diag(FriendLoc,
16083             getLangOpts().CPlusPlus11 ?
16084               diag::warn_cxx98_compat_nonclass_type_friend :
16085               diag::ext_nonclass_type_friend)
16086          << T
16087          << TypeRange;
16088      }
16089    } else if (T->getAs<EnumType>()) {
16090      Diag(FriendLoc,
16091           getLangOpts().CPlusPlus11 ?
16092             diag::warn_cxx98_compat_enum_friend :
16093             diag::ext_enum_friend)
16094        << T
16095        << TypeRange;
16096    }
16097
16098    // C++11 [class.friend]p3:
16099    //   A friend declaration that does not declare a function shall have one
16100    //   of the following forms:
16101    //     friend elaborated-type-specifier ;
16102    //     friend simple-type-specifier ;
16103    //     friend typename-specifier ;
16104    if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16105      Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16106  }
16107
16108  //   If the type specifier in a friend declaration designates a (possibly
16109  //   cv-qualified) class type, that class is declared as a friend; otherwise,
16110  //   the friend declaration is ignored.
16111  return FriendDecl::Create(Context, CurContext,
16112                            TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16113                            FriendLoc);
16114}
16115
16116/// Handle a friend tag declaration where the scope specifier was
16117/// templated.
16118Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16119                                    unsigned TagSpec, SourceLocation TagLoc,
16120                                    CXXScopeSpec &SS, IdentifierInfo *Name,
16121                                    SourceLocation NameLoc,
16122                                    const ParsedAttributesView &Attr,
16123                                    MultiTemplateParamsArg TempParamLists) {
16124  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16125
16126  bool IsMemberSpecialization = false;
16127  bool Invalid = false;
16128
16129  if (TemplateParameterList *TemplateParams =
16130          MatchTemplateParametersToScopeSpecifier(
16131              TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16132              IsMemberSpecialization, Invalid)) {
16133    if (TemplateParams->size() > 0) {
16134      // This is a declaration of a class template.
16135      if (Invalid)
16136        return nullptr;
16137
16138      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16139                                NameLoc, Attr, TemplateParams, AS_public,
16140                                /*ModulePrivateLoc=*/SourceLocation(),
16141                                FriendLoc, TempParamLists.size() - 1,
16142                                TempParamLists.data()).get();
16143    } else {
16144      // The "template<>" header is extraneous.
16145      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16146        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16147      IsMemberSpecialization = true;
16148    }
16149  }
16150
16151  if (Invalid) return nullptr;
16152
16153  bool isAllExplicitSpecializations = true;
16154  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16155    if (TempParamLists[I]->size()) {
16156      isAllExplicitSpecializations = false;
16157      break;
16158    }
16159  }
16160
16161  // FIXME: don't ignore attributes.
16162
16163  // If it's explicit specializations all the way down, just forget
16164  // about the template header and build an appropriate non-templated
16165  // friend.  TODO: for source fidelity, remember the headers.
16166  if (isAllExplicitSpecializations) {
16167    if (SS.isEmpty()) {
16168      bool Owned = false;
16169      bool IsDependent = false;
16170      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16171                      Attr, AS_public,
16172                      /*ModulePrivateLoc=*/SourceLocation(),
16173                      MultiTemplateParamsArg(), Owned, IsDependent,
16174                      /*ScopedEnumKWLoc=*/SourceLocation(),
16175                      /*ScopedEnumUsesClassTag=*/false,
16176                      /*UnderlyingType=*/TypeResult(),
16177                      /*IsTypeSpecifier=*/false,
16178                      /*IsTemplateParamOrArg=*/false);
16179    }
16180
16181    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16182    ElaboratedTypeKeyword Keyword
16183      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16184    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16185                                   *Name, NameLoc);
16186    if (T.isNull())
16187      return nullptr;
16188
16189    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16190    if (isa<DependentNameType>(T)) {
16191      DependentNameTypeLoc TL =
16192          TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16193      TL.setElaboratedKeywordLoc(TagLoc);
16194      TL.setQualifierLoc(QualifierLoc);
16195      TL.setNameLoc(NameLoc);
16196    } else {
16197      ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16198      TL.setElaboratedKeywordLoc(TagLoc);
16199      TL.setQualifierLoc(QualifierLoc);
16200      TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16201    }
16202
16203    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16204                                            TSI, FriendLoc, TempParamLists);
16205    Friend->setAccess(AS_public);
16206    CurContext->addDecl(Friend);
16207    return Friend;
16208  }
16209
16210  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16211
16212
16213
16214  // Handle the case of a templated-scope friend class.  e.g.
16215  //   template <class T> class A<T>::B;
16216  // FIXME: we don't support these right now.
16217  Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16218    << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16219  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16220  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16221  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16222  DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16223  TL.setElaboratedKeywordLoc(TagLoc);
16224  TL.setQualifierLoc(SS.getWithLocInContext(Context));
16225  TL.setNameLoc(NameLoc);
16226
16227  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16228                                          TSI, FriendLoc, TempParamLists);
16229  Friend->setAccess(AS_public);
16230  Friend->setUnsupportedFriend(true);
16231  CurContext->addDecl(Friend);
16232  return Friend;
16233}
16234
16235/// Handle a friend type declaration.  This works in tandem with
16236/// ActOnTag.
16237///
16238/// Notes on friend class templates:
16239///
16240/// We generally treat friend class declarations as if they were
16241/// declaring a class.  So, for example, the elaborated type specifier
16242/// in a friend declaration is required to obey the restrictions of a
16243/// class-head (i.e. no typedefs in the scope chain), template
16244/// parameters are required to match up with simple template-ids, &c.
16245/// However, unlike when declaring a template specialization, it's
16246/// okay to refer to a template specialization without an empty
16247/// template parameter declaration, e.g.
16248///   friend class A<T>::B<unsigned>;
16249/// We permit this as a special case; if there are any template
16250/// parameters present at all, require proper matching, i.e.
16251///   template <> template \<class T> friend class A<int>::B;
16252Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16253                                MultiTemplateParamsArg TempParams) {
16254  SourceLocation Loc = DS.getBeginLoc();
16255
16256  assert(DS.isFriendSpecified());
16257  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16258
16259  // C++ [class.friend]p3:
16260  // A friend declaration that does not declare a function shall have one of
16261  // the following forms:
16262  //     friend elaborated-type-specifier ;
16263  //     friend simple-type-specifier ;
16264  //     friend typename-specifier ;
16265  //
16266  // Any declaration with a type qualifier does not have that form. (It's
16267  // legal to specify a qualified type as a friend, you just can't write the
16268  // keywords.)
16269  if (DS.getTypeQualifiers()) {
16270    if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16271      Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16272    if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16273      Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16274    if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16275      Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16276    if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16277      Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16278    if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16279      Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16280  }
16281
16282  // Try to convert the decl specifier to a type.  This works for
16283  // friend templates because ActOnTag never produces a ClassTemplateDecl
16284  // for a TUK_Friend.
16285  Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
16286  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16287  QualType T = TSI->getType();
16288  if (TheDeclarator.isInvalidType())
16289    return nullptr;
16290
16291  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16292    return nullptr;
16293
16294  // This is definitely an error in C++98.  It's probably meant to
16295  // be forbidden in C++0x, too, but the specification is just
16296  // poorly written.
16297  //
16298  // The problem is with declarations like the following:
16299  //   template <T> friend A<T>::foo;
16300  // where deciding whether a class C is a friend or not now hinges
16301  // on whether there exists an instantiation of A that causes
16302  // 'foo' to equal C.  There are restrictions on class-heads
16303  // (which we declare (by fiat) elaborated friend declarations to
16304  // be) that makes this tractable.
16305  //
16306  // FIXME: handle "template <> friend class A<T>;", which
16307  // is possibly well-formed?  Who even knows?
16308  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16309    Diag(Loc, diag::err_tagless_friend_type_template)
16310      << DS.getSourceRange();
16311    return nullptr;
16312  }
16313
16314  // C++98 [class.friend]p1: A friend of a class is a function
16315  //   or class that is not a member of the class . . .
16316  // This is fixed in DR77, which just barely didn't make the C++03
16317  // deadline.  It's also a very silly restriction that seriously
16318  // affects inner classes and which nobody else seems to implement;
16319  // thus we never diagnose it, not even in -pedantic.
16320  //
16321  // But note that we could warn about it: it's always useless to
16322  // friend one of your own members (it's not, however, worthless to
16323  // friend a member of an arbitrary specialization of your template).
16324
16325  Decl *D;
16326  if (!TempParams.empty())
16327    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16328                                   TempParams,
16329                                   TSI,
16330                                   DS.getFriendSpecLoc());
16331  else
16332    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16333
16334  if (!D)
16335    return nullptr;
16336
16337  D->setAccess(AS_public);
16338  CurContext->addDecl(D);
16339
16340  return D;
16341}
16342
16343NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16344                                        MultiTemplateParamsArg TemplateParams) {
16345  const DeclSpec &DS = D.getDeclSpec();
16346
16347  assert(DS.isFriendSpecified());
16348  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16349
16350  SourceLocation Loc = D.getIdentifierLoc();
16351  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16352
16353  // C++ [class.friend]p1
16354  //   A friend of a class is a function or class....
16355  // Note that this sees through typedefs, which is intended.
16356  // It *doesn't* see through dependent types, which is correct
16357  // according to [temp.arg.type]p3:
16358  //   If a declaration acquires a function type through a
16359  //   type dependent on a template-parameter and this causes
16360  //   a declaration that does not use the syntactic form of a
16361  //   function declarator to have a function type, the program
16362  //   is ill-formed.
16363  if (!TInfo->getType()->isFunctionType()) {
16364    Diag(Loc, diag::err_unexpected_friend);
16365
16366    // It might be worthwhile to try to recover by creating an
16367    // appropriate declaration.
16368    return nullptr;
16369  }
16370
16371  // C++ [namespace.memdef]p3
16372  //  - If a friend declaration in a non-local class first declares a
16373  //    class or function, the friend class or function is a member
16374  //    of the innermost enclosing namespace.
16375  //  - The name of the friend is not found by simple name lookup
16376  //    until a matching declaration is provided in that namespace
16377  //    scope (either before or after the class declaration granting
16378  //    friendship).
16379  //  - If a friend function is called, its name may be found by the
16380  //    name lookup that considers functions from namespaces and
16381  //    classes associated with the types of the function arguments.
16382  //  - When looking for a prior declaration of a class or a function
16383  //    declared as a friend, scopes outside the innermost enclosing
16384  //    namespace scope are not considered.
16385
16386  CXXScopeSpec &SS = D.getCXXScopeSpec();
16387  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16388  assert(NameInfo.getName());
16389
16390  // Check for unexpanded parameter packs.
16391  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16392      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16393      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16394    return nullptr;
16395
16396  // The context we found the declaration in, or in which we should
16397  // create the declaration.
16398  DeclContext *DC;
16399  Scope *DCScope = S;
16400  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16401                        ForExternalRedeclaration);
16402
16403  // There are five cases here.
16404  //   - There's no scope specifier and we're in a local class. Only look
16405  //     for functions declared in the immediately-enclosing block scope.
16406  // We recover from invalid scope qualifiers as if they just weren't there.
16407  FunctionDecl *FunctionContainingLocalClass = nullptr;
16408  if ((SS.isInvalid() || !SS.isSet()) &&
16409      (FunctionContainingLocalClass =
16410           cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16411    // C++11 [class.friend]p11:
16412    //   If a friend declaration appears in a local class and the name
16413    //   specified is an unqualified name, a prior declaration is
16414    //   looked up without considering scopes that are outside the
16415    //   innermost enclosing non-class scope. For a friend function
16416    //   declaration, if there is no prior declaration, the program is
16417    //   ill-formed.
16418
16419    // Find the innermost enclosing non-class scope. This is the block
16420    // scope containing the local class definition (or for a nested class,
16421    // the outer local class).
16422    DCScope = S->getFnParent();
16423
16424    // Look up the function name in the scope.
16425    Previous.clear(LookupLocalFriendName);
16426    LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16427
16428    if (!Previous.empty()) {
16429      // All possible previous declarations must have the same context:
16430      // either they were declared at block scope or they are members of
16431      // one of the enclosing local classes.
16432      DC = Previous.getRepresentativeDecl()->getDeclContext();
16433    } else {
16434      // This is ill-formed, but provide the context that we would have
16435      // declared the function in, if we were permitted to, for error recovery.
16436      DC = FunctionContainingLocalClass;
16437    }
16438    adjustContextForLocalExternDecl(DC);
16439
16440    // C++ [class.friend]p6:
16441    //   A function can be defined in a friend declaration of a class if and
16442    //   only if the class is a non-local class (9.8), the function name is
16443    //   unqualified, and the function has namespace scope.
16444    if (D.isFunctionDefinition()) {
16445      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16446    }
16447
16448  //   - There's no scope specifier, in which case we just go to the
16449  //     appropriate scope and look for a function or function template
16450  //     there as appropriate.
16451  } else if (SS.isInvalid() || !SS.isSet()) {
16452    // C++11 [namespace.memdef]p3:
16453    //   If the name in a friend declaration is neither qualified nor
16454    //   a template-id and the declaration is a function or an
16455    //   elaborated-type-specifier, the lookup to determine whether
16456    //   the entity has been previously declared shall not consider
16457    //   any scopes outside the innermost enclosing namespace.
16458    bool isTemplateId =
16459        D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16460
16461    // Find the appropriate context according to the above.
16462    DC = CurContext;
16463
16464    // Skip class contexts.  If someone can cite chapter and verse
16465    // for this behavior, that would be nice --- it's what GCC and
16466    // EDG do, and it seems like a reasonable intent, but the spec
16467    // really only says that checks for unqualified existing
16468    // declarations should stop at the nearest enclosing namespace,
16469    // not that they should only consider the nearest enclosing
16470    // namespace.
16471    while (DC->isRecord())
16472      DC = DC->getParent();
16473
16474    DeclContext *LookupDC = DC;
16475    while (LookupDC->isTransparentContext())
16476      LookupDC = LookupDC->getParent();
16477
16478    while (true) {
16479      LookupQualifiedName(Previous, LookupDC);
16480
16481      if (!Previous.empty()) {
16482        DC = LookupDC;
16483        break;
16484      }
16485
16486      if (isTemplateId) {
16487        if (isa<TranslationUnitDecl>(LookupDC)) break;
16488      } else {
16489        if (LookupDC->isFileContext()) break;
16490      }
16491      LookupDC = LookupDC->getParent();
16492    }
16493
16494    DCScope = getScopeForDeclContext(S, DC);
16495
16496  //   - There's a non-dependent scope specifier, in which case we
16497  //     compute it and do a previous lookup there for a function
16498  //     or function template.
16499  } else if (!SS.getScopeRep()->isDependent()) {
16500    DC = computeDeclContext(SS);
16501    if (!DC) return nullptr;
16502
16503    if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16504
16505    LookupQualifiedName(Previous, DC);
16506
16507    // C++ [class.friend]p1: A friend of a class is a function or
16508    //   class that is not a member of the class . . .
16509    if (DC->Equals(CurContext))
16510      Diag(DS.getFriendSpecLoc(),
16511           getLangOpts().CPlusPlus11 ?
16512             diag::warn_cxx98_compat_friend_is_member :
16513             diag::err_friend_is_member);
16514
16515    if (D.isFunctionDefinition()) {
16516      // C++ [class.friend]p6:
16517      //   A function can be defined in a friend declaration of a class if and
16518      //   only if the class is a non-local class (9.8), the function name is
16519      //   unqualified, and the function has namespace scope.
16520      //
16521      // FIXME: We should only do this if the scope specifier names the
16522      // innermost enclosing namespace; otherwise the fixit changes the
16523      // meaning of the code.
16524      SemaDiagnosticBuilder DB
16525        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16526
16527      DB << SS.getScopeRep();
16528      if (DC->isFileContext())
16529        DB << FixItHint::CreateRemoval(SS.getRange());
16530      SS.clear();
16531    }
16532
16533  //   - There's a scope specifier that does not match any template
16534  //     parameter lists, in which case we use some arbitrary context,
16535  //     create a method or method template, and wait for instantiation.
16536  //   - There's a scope specifier that does match some template
16537  //     parameter lists, which we don't handle right now.
16538  } else {
16539    if (D.isFunctionDefinition()) {
16540      // C++ [class.friend]p6:
16541      //   A function can be defined in a friend declaration of a class if and
16542      //   only if the class is a non-local class (9.8), the function name is
16543      //   unqualified, and the function has namespace scope.
16544      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16545        << SS.getScopeRep();
16546    }
16547
16548    DC = CurContext;
16549    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16550  }
16551
16552  if (!DC->isRecord()) {
16553    int DiagArg = -1;
16554    switch (D.getName().getKind()) {
16555    case UnqualifiedIdKind::IK_ConstructorTemplateId:
16556    case UnqualifiedIdKind::IK_ConstructorName:
16557      DiagArg = 0;
16558      break;
16559    case UnqualifiedIdKind::IK_DestructorName:
16560      DiagArg = 1;
16561      break;
16562    case UnqualifiedIdKind::IK_ConversionFunctionId:
16563      DiagArg = 2;
16564      break;
16565    case UnqualifiedIdKind::IK_DeductionGuideName:
16566      DiagArg = 3;
16567      break;
16568    case UnqualifiedIdKind::IK_Identifier:
16569    case UnqualifiedIdKind::IK_ImplicitSelfParam:
16570    case UnqualifiedIdKind::IK_LiteralOperatorId:
16571    case UnqualifiedIdKind::IK_OperatorFunctionId:
16572    case UnqualifiedIdKind::IK_TemplateId:
16573      break;
16574    }
16575    // This implies that it has to be an operator or function.
16576    if (DiagArg >= 0) {
16577      Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16578      return nullptr;
16579    }
16580  }
16581
16582  // FIXME: This is an egregious hack to cope with cases where the scope stack
16583  // does not contain the declaration context, i.e., in an out-of-line
16584  // definition of a class.
16585  Scope FakeDCScope(S, Scope::DeclScope, Diags);
16586  if (!DCScope) {
16587    FakeDCScope.setEntity(DC);
16588    DCScope = &FakeDCScope;
16589  }
16590
16591  bool AddToScope = true;
16592  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16593                                          TemplateParams, AddToScope);
16594  if (!ND) return nullptr;
16595
16596  assert(ND->getLexicalDeclContext() == CurContext);
16597
16598  // If we performed typo correction, we might have added a scope specifier
16599  // and changed the decl context.
16600  DC = ND->getDeclContext();
16601
16602  // Add the function declaration to the appropriate lookup tables,
16603  // adjusting the redeclarations list as necessary.  We don't
16604  // want to do this yet if the friending class is dependent.
16605  //
16606  // Also update the scope-based lookup if the target context's
16607  // lookup context is in lexical scope.
16608  if (!CurContext->isDependentContext()) {
16609    DC = DC->getRedeclContext();
16610    DC->makeDeclVisibleInContext(ND);
16611    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16612      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16613  }
16614
16615  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16616                                       D.getIdentifierLoc(), ND,
16617                                       DS.getFriendSpecLoc());
16618  FrD->setAccess(AS_public);
16619  CurContext->addDecl(FrD);
16620
16621  if (ND->isInvalidDecl()) {
16622    FrD->setInvalidDecl();
16623  } else {
16624    if (DC->isRecord()) CheckFriendAccess(ND);
16625
16626    FunctionDecl *FD;
16627    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16628      FD = FTD->getTemplatedDecl();
16629    else
16630      FD = cast<FunctionDecl>(ND);
16631
16632    // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16633    // default argument expression, that declaration shall be a definition
16634    // and shall be the only declaration of the function or function
16635    // template in the translation unit.
16636    if (functionDeclHasDefaultArgument(FD)) {
16637      // We can't look at FD->getPreviousDecl() because it may not have been set
16638      // if we're in a dependent context. If the function is known to be a
16639      // redeclaration, we will have narrowed Previous down to the right decl.
16640      if (D.isRedeclaration()) {
16641        Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16642        Diag(Previous.getRepresentativeDecl()->getLocation(),
16643             diag::note_previous_declaration);
16644      } else if (!D.isFunctionDefinition())
16645        Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16646    }
16647
16648    // Mark templated-scope function declarations as unsupported.
16649    if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16650      Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16651        << SS.getScopeRep() << SS.getRange()
16652        << cast<CXXRecordDecl>(CurContext);
16653      FrD->setUnsupportedFriend(true);
16654    }
16655  }
16656
16657  return ND;
16658}
16659
16660void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16661  AdjustDeclIfTemplate(Dcl);
16662
16663  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16664  if (!Fn) {
16665    Diag(DelLoc, diag::err_deleted_non_function);
16666    return;
16667  }
16668
16669  // Deleted function does not have a body.
16670  Fn->setWillHaveBody(false);
16671
16672  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16673    // Don't consider the implicit declaration we generate for explicit
16674    // specializations. FIXME: Do not generate these implicit declarations.
16675    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16676         Prev->getPreviousDecl()) &&
16677        !Prev->isDefined()) {
16678      Diag(DelLoc, diag::err_deleted_decl_not_first);
16679      Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16680           Prev->isImplicit() ? diag::note_previous_implicit_declaration
16681                              : diag::note_previous_declaration);
16682      // We can't recover from this; the declaration might have already
16683      // been used.
16684      Fn->setInvalidDecl();
16685      return;
16686    }
16687
16688    // To maintain the invariant that functions are only deleted on their first
16689    // declaration, mark the implicitly-instantiated declaration of the
16690    // explicitly-specialized function as deleted instead of marking the
16691    // instantiated redeclaration.
16692    Fn = Fn->getCanonicalDecl();
16693  }
16694
16695  // dllimport/dllexport cannot be deleted.
16696  if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16697    Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16698    Fn->setInvalidDecl();
16699  }
16700
16701  // C++11 [basic.start.main]p3:
16702  //   A program that defines main as deleted [...] is ill-formed.
16703  if (Fn->isMain())
16704    Diag(DelLoc, diag::err_deleted_main);
16705
16706  // C++11 [dcl.fct.def.delete]p4:
16707  //  A deleted function is implicitly inline.
16708  Fn->setImplicitlyInline();
16709  Fn->setDeletedAsWritten();
16710}
16711
16712void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16713  if (!Dcl || Dcl->isInvalidDecl())
16714    return;
16715
16716  auto *FD = dyn_cast<FunctionDecl>(Dcl);
16717  if (!FD) {
16718    if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16719      if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16720        Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16721        return;
16722      }
16723    }
16724
16725    Diag(DefaultLoc, diag::err_default_special_members)
16726        << getLangOpts().CPlusPlus20;
16727    return;
16728  }
16729
16730  // Reject if this can't possibly be a defaultable function.
16731  DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16732  if (!DefKind &&
16733      // A dependent function that doesn't locally look defaultable can
16734      // still instantiate to a defaultable function if it's a constructor
16735      // or assignment operator.
16736      (!FD->isDependentContext() ||
16737       (!isa<CXXConstructorDecl>(FD) &&
16738        FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16739    Diag(DefaultLoc, diag::err_default_special_members)
16740        << getLangOpts().CPlusPlus20;
16741    return;
16742  }
16743
16744  if (DefKind.isComparison() &&
16745      !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16746    Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16747        << (int)DefKind.asComparison();
16748    return;
16749  }
16750
16751  // Issue compatibility warning. We already warned if the operator is
16752  // 'operator<=>' when parsing the '<=>' token.
16753  if (DefKind.isComparison() &&
16754      DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16755    Diag(DefaultLoc, getLangOpts().CPlusPlus20
16756                         ? diag::warn_cxx17_compat_defaulted_comparison
16757                         : diag::ext_defaulted_comparison);
16758  }
16759
16760  FD->setDefaulted();
16761  FD->setExplicitlyDefaulted();
16762
16763  // Defer checking functions that are defaulted in a dependent context.
16764  if (FD->isDependentContext())
16765    return;
16766
16767  // Unset that we will have a body for this function. We might not,
16768  // if it turns out to be trivial, and we don't need this marking now
16769  // that we've marked it as defaulted.
16770  FD->setWillHaveBody(false);
16771
16772  // If this definition appears within the record, do the checking when
16773  // the record is complete. This is always the case for a defaulted
16774  // comparison.
16775  if (DefKind.isComparison())
16776    return;
16777  auto *MD = cast<CXXMethodDecl>(FD);
16778
16779  const FunctionDecl *Primary = FD;
16780  if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16781    // Ask the template instantiation pattern that actually had the
16782    // '= default' on it.
16783    Primary = Pattern;
16784
16785  // If the method was defaulted on its first declaration, we will have
16786  // already performed the checking in CheckCompletedCXXClass. Such a
16787  // declaration doesn't trigger an implicit definition.
16788  if (Primary->getCanonicalDecl()->isDefaulted())
16789    return;
16790
16791  // FIXME: Once we support defining comparisons out of class, check for a
16792  // defaulted comparison here.
16793  if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16794    MD->setInvalidDecl();
16795  else
16796    DefineDefaultedFunction(*this, MD, DefaultLoc);
16797}
16798
16799static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16800  for (Stmt *SubStmt : S->children()) {
16801    if (!SubStmt)
16802      continue;
16803    if (isa<ReturnStmt>(SubStmt))
16804      Self.Diag(SubStmt->getBeginLoc(),
16805                diag::err_return_in_constructor_handler);
16806    if (!isa<Expr>(SubStmt))
16807      SearchForReturnInStmt(Self, SubStmt);
16808  }
16809}
16810
16811void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16812  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16813    CXXCatchStmt *Handler = TryBlock->getHandler(I);
16814    SearchForReturnInStmt(*this, Handler);
16815  }
16816}
16817
16818bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16819                                             const CXXMethodDecl *Old) {
16820  const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16821  const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16822
16823  if (OldFT->hasExtParameterInfos()) {
16824    for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16825      // A parameter of the overriding method should be annotated with noescape
16826      // if the corresponding parameter of the overridden method is annotated.
16827      if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16828          !NewFT->getExtParameterInfo(I).isNoEscape()) {
16829        Diag(New->getParamDecl(I)->getLocation(),
16830             diag::warn_overriding_method_missing_noescape);
16831        Diag(Old->getParamDecl(I)->getLocation(),
16832             diag::note_overridden_marked_noescape);
16833      }
16834  }
16835
16836  // Virtual overrides must have the same code_seg.
16837  const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16838  const auto *NewCSA = New->getAttr<CodeSegAttr>();
16839  if ((NewCSA || OldCSA) &&
16840      (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16841    Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16842    Diag(Old->getLocation(), diag::note_previous_declaration);
16843    return true;
16844  }
16845
16846  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16847
16848  // If the calling conventions match, everything is fine
16849  if (NewCC == OldCC)
16850    return false;
16851
16852  // If the calling conventions mismatch because the new function is static,
16853  // suppress the calling convention mismatch error; the error about static
16854  // function override (err_static_overrides_virtual from
16855  // Sema::CheckFunctionDeclaration) is more clear.
16856  if (New->getStorageClass() == SC_Static)
16857    return false;
16858
16859  Diag(New->getLocation(),
16860       diag::err_conflicting_overriding_cc_attributes)
16861    << New->getDeclName() << New->getType() << Old->getType();
16862  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16863  return true;
16864}
16865
16866bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16867                                             const CXXMethodDecl *Old) {
16868  QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16869  QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16870
16871  if (Context.hasSameType(NewTy, OldTy) ||
16872      NewTy->isDependentType() || OldTy->isDependentType())
16873    return false;
16874
16875  // Check if the return types are covariant
16876  QualType NewClassTy, OldClassTy;
16877
16878  /// Both types must be pointers or references to classes.
16879  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16880    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16881      NewClassTy = NewPT->getPointeeType();
16882      OldClassTy = OldPT->getPointeeType();
16883    }
16884  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16885    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16886      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16887        NewClassTy = NewRT->getPointeeType();
16888        OldClassTy = OldRT->getPointeeType();
16889      }
16890    }
16891  }
16892
16893  // The return types aren't either both pointers or references to a class type.
16894  if (NewClassTy.isNull()) {
16895    Diag(New->getLocation(),
16896         diag::err_different_return_type_for_overriding_virtual_function)
16897        << New->getDeclName() << NewTy << OldTy
16898        << New->getReturnTypeSourceRange();
16899    Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16900        << Old->getReturnTypeSourceRange();
16901
16902    return true;
16903  }
16904
16905  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16906    // C++14 [class.virtual]p8:
16907    //   If the class type in the covariant return type of D::f differs from
16908    //   that of B::f, the class type in the return type of D::f shall be
16909    //   complete at the point of declaration of D::f or shall be the class
16910    //   type D.
16911    if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16912      if (!RT->isBeingDefined() &&
16913          RequireCompleteType(New->getLocation(), NewClassTy,
16914                              diag::err_covariant_return_incomplete,
16915                              New->getDeclName()))
16916        return true;
16917    }
16918
16919    // Check if the new class derives from the old class.
16920    if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16921      Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16922          << New->getDeclName() << NewTy << OldTy
16923          << New->getReturnTypeSourceRange();
16924      Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16925          << Old->getReturnTypeSourceRange();
16926      return true;
16927    }
16928
16929    // Check if we the conversion from derived to base is valid.
16930    if (CheckDerivedToBaseConversion(
16931            NewClassTy, OldClassTy,
16932            diag::err_covariant_return_inaccessible_base,
16933            diag::err_covariant_return_ambiguous_derived_to_base_conv,
16934            New->getLocation(), New->getReturnTypeSourceRange(),
16935            New->getDeclName(), nullptr)) {
16936      // FIXME: this note won't trigger for delayed access control
16937      // diagnostics, and it's impossible to get an undelayed error
16938      // here from access control during the original parse because
16939      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
16940      Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16941          << Old->getReturnTypeSourceRange();
16942      return true;
16943    }
16944  }
16945
16946  // The qualifiers of the return types must be the same.
16947  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
16948    Diag(New->getLocation(),
16949         diag::err_covariant_return_type_different_qualifications)
16950        << New->getDeclName() << NewTy << OldTy
16951        << New->getReturnTypeSourceRange();
16952    Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16953        << Old->getReturnTypeSourceRange();
16954    return true;
16955  }
16956
16957
16958  // The new class type must have the same or less qualifiers as the old type.
16959  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
16960    Diag(New->getLocation(),
16961         diag::err_covariant_return_type_class_type_more_qualified)
16962        << New->getDeclName() << NewTy << OldTy
16963        << New->getReturnTypeSourceRange();
16964    Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16965        << Old->getReturnTypeSourceRange();
16966    return true;
16967  }
16968
16969  return false;
16970}
16971
16972/// Mark the given method pure.
16973///
16974/// \param Method the method to be marked pure.
16975///
16976/// \param InitRange the source range that covers the "0" initializer.
16977bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
16978  SourceLocation EndLoc = InitRange.getEnd();
16979  if (EndLoc.isValid())
16980    Method->setRangeEnd(EndLoc);
16981
16982  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
16983    Method->setPure();
16984    return false;
16985  }
16986
16987  if (!Method->isInvalidDecl())
16988    Diag(Method->getLocation(), diag::err_non_virtual_pure)
16989      << Method->getDeclName() << InitRange;
16990  return true;
16991}
16992
16993void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
16994  if (D->getFriendObjectKind())
16995    Diag(D->getLocation(), diag::err_pure_friend);
16996  else if (auto *M = dyn_cast<CXXMethodDecl>(D))
16997    CheckPureMethod(M, ZeroLoc);
16998  else
16999    Diag(D->getLocation(), diag::err_illegal_initializer);
17000}
17001
17002/// Determine whether the given declaration is a global variable or
17003/// static data member.
17004static bool isNonlocalVariable(const Decl *D) {
17005  if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17006    return Var->hasGlobalStorage();
17007
17008  return false;
17009}
17010
17011/// Invoked when we are about to parse an initializer for the declaration
17012/// 'Dcl'.
17013///
17014/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17015/// static data member of class X, names should be looked up in the scope of
17016/// class X. If the declaration had a scope specifier, a scope will have
17017/// been created and passed in for this purpose. Otherwise, S will be null.
17018void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17019  // If there is no declaration, there was an error parsing it.
17020  if (!D || D->isInvalidDecl())
17021    return;
17022
17023  // We will always have a nested name specifier here, but this declaration
17024  // might not be out of line if the specifier names the current namespace:
17025  //   extern int n;
17026  //   int ::n = 0;
17027  if (S && D->isOutOfLine())
17028    EnterDeclaratorContext(S, D->getDeclContext());
17029
17030  // If we are parsing the initializer for a static data member, push a
17031  // new expression evaluation context that is associated with this static
17032  // data member.
17033  if (isNonlocalVariable(D))
17034    PushExpressionEvaluationContext(
17035        ExpressionEvaluationContext::PotentiallyEvaluated, D);
17036}
17037
17038/// Invoked after we are finished parsing an initializer for the declaration D.
17039void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17040  // If there is no declaration, there was an error parsing it.
17041  if (!D || D->isInvalidDecl())
17042    return;
17043
17044  if (isNonlocalVariable(D))
17045    PopExpressionEvaluationContext();
17046
17047  if (S && D->isOutOfLine())
17048    ExitDeclaratorContext(S);
17049}
17050
17051/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17052/// C++ if/switch/while/for statement.
17053/// e.g: "if (int x = f()) {...}"
17054DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17055  // C++ 6.4p2:
17056  // The declarator shall not specify a function or an array.
17057  // The type-specifier-seq shall not contain typedef and shall not declare a
17058  // new class or enumeration.
17059  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17060         "Parser allowed 'typedef' as storage class of condition decl.");
17061
17062  Decl *Dcl = ActOnDeclarator(S, D);
17063  if (!Dcl)
17064    return true;
17065
17066  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17067    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17068      << D.getSourceRange();
17069    return true;
17070  }
17071
17072  return Dcl;
17073}
17074
17075void Sema::LoadExternalVTableUses() {
17076  if (!ExternalSource)
17077    return;
17078
17079  SmallVector<ExternalVTableUse, 4> VTables;
17080  ExternalSource->ReadUsedVTables(VTables);
17081  SmallVector<VTableUse, 4> NewUses;
17082  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17083    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17084      = VTablesUsed.find(VTables[I].Record);
17085    // Even if a definition wasn't required before, it may be required now.
17086    if (Pos != VTablesUsed.end()) {
17087      if (!Pos->second && VTables[I].DefinitionRequired)
17088        Pos->second = true;
17089      continue;
17090    }
17091
17092    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17093    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17094  }
17095
17096  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17097}
17098
17099void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17100                          bool DefinitionRequired) {
17101  // Ignore any vtable uses in unevaluated operands or for classes that do
17102  // not have a vtable.
17103  if (!Class->isDynamicClass() || Class->isDependentContext() ||
17104      CurContext->isDependentContext() || isUnevaluatedContext())
17105    return;
17106  // Do not mark as used if compiling for the device outside of the target
17107  // region.
17108  if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17109      !isInOpenMPDeclareTargetContext() &&
17110      !isInOpenMPTargetExecutionDirective()) {
17111    if (!DefinitionRequired)
17112      MarkVirtualMembersReferenced(Loc, Class);
17113    return;
17114  }
17115
17116  // Try to insert this class into the map.
17117  LoadExternalVTableUses();
17118  Class = Class->getCanonicalDecl();
17119  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17120    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17121  if (!Pos.second) {
17122    // If we already had an entry, check to see if we are promoting this vtable
17123    // to require a definition. If so, we need to reappend to the VTableUses
17124    // list, since we may have already processed the first entry.
17125    if (DefinitionRequired && !Pos.first->second) {
17126      Pos.first->second = true;
17127    } else {
17128      // Otherwise, we can early exit.
17129      return;
17130    }
17131  } else {
17132    // The Microsoft ABI requires that we perform the destructor body
17133    // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17134    // the deleting destructor is emitted with the vtable, not with the
17135    // destructor definition as in the Itanium ABI.
17136    if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17137      CXXDestructorDecl *DD = Class->getDestructor();
17138      if (DD && DD->isVirtual() && !DD->isDeleted()) {
17139        if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17140          // If this is an out-of-line declaration, marking it referenced will
17141          // not do anything. Manually call CheckDestructor to look up operator
17142          // delete().
17143          ContextRAII SavedContext(*this, DD);
17144          CheckDestructor(DD);
17145        } else {
17146          MarkFunctionReferenced(Loc, Class->getDestructor());
17147        }
17148      }
17149    }
17150  }
17151
17152  // Local classes need to have their virtual members marked
17153  // immediately. For all other classes, we mark their virtual members
17154  // at the end of the translation unit.
17155  if (Class->isLocalClass())
17156    MarkVirtualMembersReferenced(Loc, Class);
17157  else
17158    VTableUses.push_back(std::make_pair(Class, Loc));
17159}
17160
17161bool Sema::DefineUsedVTables() {
17162  LoadExternalVTableUses();
17163  if (VTableUses.empty())
17164    return false;
17165
17166  // Note: The VTableUses vector could grow as a result of marking
17167  // the members of a class as "used", so we check the size each
17168  // time through the loop and prefer indices (which are stable) to
17169  // iterators (which are not).
17170  bool DefinedAnything = false;
17171  for (unsigned I = 0; I != VTableUses.size(); ++I) {
17172    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17173    if (!Class)
17174      continue;
17175    TemplateSpecializationKind ClassTSK =
17176        Class->getTemplateSpecializationKind();
17177
17178    SourceLocation Loc = VTableUses[I].second;
17179
17180    bool DefineVTable = true;
17181
17182    // If this class has a key function, but that key function is
17183    // defined in another translation unit, we don't need to emit the
17184    // vtable even though we're using it.
17185    const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17186    if (KeyFunction && !KeyFunction->hasBody()) {
17187      // The key function is in another translation unit.
17188      DefineVTable = false;
17189      TemplateSpecializationKind TSK =
17190          KeyFunction->getTemplateSpecializationKind();
17191      assert(TSK != TSK_ExplicitInstantiationDefinition &&
17192             TSK != TSK_ImplicitInstantiation &&
17193             "Instantiations don't have key functions");
17194      (void)TSK;
17195    } else if (!KeyFunction) {
17196      // If we have a class with no key function that is the subject
17197      // of an explicit instantiation declaration, suppress the
17198      // vtable; it will live with the explicit instantiation
17199      // definition.
17200      bool IsExplicitInstantiationDeclaration =
17201          ClassTSK == TSK_ExplicitInstantiationDeclaration;
17202      for (auto R : Class->redecls()) {
17203        TemplateSpecializationKind TSK
17204          = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17205        if (TSK == TSK_ExplicitInstantiationDeclaration)
17206          IsExplicitInstantiationDeclaration = true;
17207        else if (TSK == TSK_ExplicitInstantiationDefinition) {
17208          IsExplicitInstantiationDeclaration = false;
17209          break;
17210        }
17211      }
17212
17213      if (IsExplicitInstantiationDeclaration)
17214        DefineVTable = false;
17215    }
17216
17217    // The exception specifications for all virtual members may be needed even
17218    // if we are not providing an authoritative form of the vtable in this TU.
17219    // We may choose to emit it available_externally anyway.
17220    if (!DefineVTable) {
17221      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17222      continue;
17223    }
17224
17225    // Mark all of the virtual members of this class as referenced, so
17226    // that we can build a vtable. Then, tell the AST consumer that a
17227    // vtable for this class is required.
17228    DefinedAnything = true;
17229    MarkVirtualMembersReferenced(Loc, Class);
17230    CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17231    if (VTablesUsed[Canonical])
17232      Consumer.HandleVTable(Class);
17233
17234    // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17235    // no key function or the key function is inlined. Don't warn in C++ ABIs
17236    // that lack key functions, since the user won't be able to make one.
17237    if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17238        Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17239      const FunctionDecl *KeyFunctionDef = nullptr;
17240      if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17241                           KeyFunctionDef->isInlined())) {
17242        Diag(Class->getLocation(),
17243             ClassTSK == TSK_ExplicitInstantiationDefinition
17244                 ? diag::warn_weak_template_vtable
17245                 : diag::warn_weak_vtable)
17246            << Class;
17247      }
17248    }
17249  }
17250  VTableUses.clear();
17251
17252  return DefinedAnything;
17253}
17254
17255void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17256                                                 const CXXRecordDecl *RD) {
17257  for (const auto *I : RD->methods())
17258    if (I->isVirtual() && !I->isPure())
17259      ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17260}
17261
17262void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17263                                        const CXXRecordDecl *RD,
17264                                        bool ConstexprOnly) {
17265  // Mark all functions which will appear in RD's vtable as used.
17266  CXXFinalOverriderMap FinalOverriders;
17267  RD->getFinalOverriders(FinalOverriders);
17268  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17269                                            E = FinalOverriders.end();
17270       I != E; ++I) {
17271    for (OverridingMethods::const_iterator OI = I->second.begin(),
17272                                           OE = I->second.end();
17273         OI != OE; ++OI) {
17274      assert(OI->second.size() > 0 && "no final overrider");
17275      CXXMethodDecl *Overrider = OI->second.front().Method;
17276
17277      // C++ [basic.def.odr]p2:
17278      //   [...] A virtual member function is used if it is not pure. [...]
17279      if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17280        MarkFunctionReferenced(Loc, Overrider);
17281    }
17282  }
17283
17284  // Only classes that have virtual bases need a VTT.
17285  if (RD->getNumVBases() == 0)
17286    return;
17287
17288  for (const auto &I : RD->bases()) {
17289    const auto *Base =
17290        cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17291    if (Base->getNumVBases() == 0)
17292      continue;
17293    MarkVirtualMembersReferenced(Loc, Base);
17294  }
17295}
17296
17297/// SetIvarInitializers - This routine builds initialization ASTs for the
17298/// Objective-C implementation whose ivars need be initialized.
17299void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17300  if (!getLangOpts().CPlusPlus)
17301    return;
17302  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17303    SmallVector<ObjCIvarDecl*, 8> ivars;
17304    CollectIvarsToConstructOrDestruct(OID, ivars);
17305    if (ivars.empty())
17306      return;
17307    SmallVector<CXXCtorInitializer*, 32> AllToInit;
17308    for (unsigned i = 0; i < ivars.size(); i++) {
17309      FieldDecl *Field = ivars[i];
17310      if (Field->isInvalidDecl())
17311        continue;
17312
17313      CXXCtorInitializer *Member;
17314      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17315      InitializationKind InitKind =
17316        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17317
17318      InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17319      ExprResult MemberInit =
17320        InitSeq.Perform(*this, InitEntity, InitKind, None);
17321      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17322      // Note, MemberInit could actually come back empty if no initialization
17323      // is required (e.g., because it would call a trivial default constructor)
17324      if (!MemberInit.get() || MemberInit.isInvalid())
17325        continue;
17326
17327      Member =
17328        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17329                                         SourceLocation(),
17330                                         MemberInit.getAs<Expr>(),
17331                                         SourceLocation());
17332      AllToInit.push_back(Member);
17333
17334      // Be sure that the destructor is accessible and is marked as referenced.
17335      if (const RecordType *RecordTy =
17336              Context.getBaseElementType(Field->getType())
17337                  ->getAs<RecordType>()) {
17338        CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17339        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17340          MarkFunctionReferenced(Field->getLocation(), Destructor);
17341          CheckDestructorAccess(Field->getLocation(), Destructor,
17342                            PDiag(diag::err_access_dtor_ivar)
17343                              << Context.getBaseElementType(Field->getType()));
17344        }
17345      }
17346    }
17347    ObjCImplementation->setIvarInitializers(Context,
17348                                            AllToInit.data(), AllToInit.size());
17349  }
17350}
17351
17352static
17353void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17354                           llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17355                           llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17356                           llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17357                           Sema &S) {
17358  if (Ctor->isInvalidDecl())
17359    return;
17360
17361  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17362
17363  // Target may not be determinable yet, for instance if this is a dependent
17364  // call in an uninstantiated template.
17365  if (Target) {
17366    const FunctionDecl *FNTarget = nullptr;
17367    (void)Target->hasBody(FNTarget);
17368    Target = const_cast<CXXConstructorDecl*>(
17369      cast_or_null<CXXConstructorDecl>(FNTarget));
17370  }
17371
17372  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17373                     // Avoid dereferencing a null pointer here.
17374                     *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17375
17376  if (!Current.insert(Canonical).second)
17377    return;
17378
17379  // We know that beyond here, we aren't chaining into a cycle.
17380  if (!Target || !Target->isDelegatingConstructor() ||
17381      Target->isInvalidDecl() || Valid.count(TCanonical)) {
17382    Valid.insert(Current.begin(), Current.end());
17383    Current.clear();
17384  // We've hit a cycle.
17385  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17386             Current.count(TCanonical)) {
17387    // If we haven't diagnosed this cycle yet, do so now.
17388    if (!Invalid.count(TCanonical)) {
17389      S.Diag((*Ctor->init_begin())->getSourceLocation(),
17390             diag::warn_delegating_ctor_cycle)
17391        << Ctor;
17392
17393      // Don't add a note for a function delegating directly to itself.
17394      if (TCanonical != Canonical)
17395        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17396
17397      CXXConstructorDecl *C = Target;
17398      while (C->getCanonicalDecl() != Canonical) {
17399        const FunctionDecl *FNTarget = nullptr;
17400        (void)C->getTargetConstructor()->hasBody(FNTarget);
17401        assert(FNTarget && "Ctor cycle through bodiless function");
17402
17403        C = const_cast<CXXConstructorDecl*>(
17404          cast<CXXConstructorDecl>(FNTarget));
17405        S.Diag(C->getLocation(), diag::note_which_delegates_to);
17406      }
17407    }
17408
17409    Invalid.insert(Current.begin(), Current.end());
17410    Current.clear();
17411  } else {
17412    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17413  }
17414}
17415
17416
17417void Sema::CheckDelegatingCtorCycles() {
17418  llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17419
17420  for (DelegatingCtorDeclsType::iterator
17421         I = DelegatingCtorDecls.begin(ExternalSource),
17422         E = DelegatingCtorDecls.end();
17423       I != E; ++I)
17424    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17425
17426  for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17427    (*CI)->setInvalidDecl();
17428}
17429
17430namespace {
17431  /// AST visitor that finds references to the 'this' expression.
17432  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17433    Sema &S;
17434
17435  public:
17436    explicit FindCXXThisExpr(Sema &S) : S(S) { }
17437
17438    bool VisitCXXThisExpr(CXXThisExpr *E) {
17439      S.Diag(E->getLocation(), diag::err_this_static_member_func)
17440        << E->isImplicit();
17441      return false;
17442    }
17443  };
17444}
17445
17446bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17447  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17448  if (!TSInfo)
17449    return false;
17450
17451  TypeLoc TL = TSInfo->getTypeLoc();
17452  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17453  if (!ProtoTL)
17454    return false;
17455
17456  // C++11 [expr.prim.general]p3:
17457  //   [The expression this] shall not appear before the optional
17458  //   cv-qualifier-seq and it shall not appear within the declaration of a
17459  //   static member function (although its type and value category are defined
17460  //   within a static member function as they are within a non-static member
17461  //   function). [ Note: this is because declaration matching does not occur
17462  //  until the complete declarator is known. - end note ]
17463  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17464  FindCXXThisExpr Finder(*this);
17465
17466  // If the return type came after the cv-qualifier-seq, check it now.
17467  if (Proto->hasTrailingReturn() &&
17468      !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17469    return true;
17470
17471  // Check the exception specification.
17472  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17473    return true;
17474
17475  // Check the trailing requires clause
17476  if (Expr *E = Method->getTrailingRequiresClause())
17477    if (!Finder.TraverseStmt(E))
17478      return true;
17479
17480  return checkThisInStaticMemberFunctionAttributes(Method);
17481}
17482
17483bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17484  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17485  if (!TSInfo)
17486    return false;
17487
17488  TypeLoc TL = TSInfo->getTypeLoc();
17489  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17490  if (!ProtoTL)
17491    return false;
17492
17493  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17494  FindCXXThisExpr Finder(*this);
17495
17496  switch (Proto->getExceptionSpecType()) {
17497  case EST_Unparsed:
17498  case EST_Uninstantiated:
17499  case EST_Unevaluated:
17500  case EST_BasicNoexcept:
17501  case EST_NoThrow:
17502  case EST_DynamicNone:
17503  case EST_MSAny:
17504  case EST_None:
17505    break;
17506
17507  case EST_DependentNoexcept:
17508  case EST_NoexceptFalse:
17509  case EST_NoexceptTrue:
17510    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17511      return true;
17512    LLVM_FALLTHROUGH;
17513
17514  case EST_Dynamic:
17515    for (const auto &E : Proto->exceptions()) {
17516      if (!Finder.TraverseType(E))
17517        return true;
17518    }
17519    break;
17520  }
17521
17522  return false;
17523}
17524
17525bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17526  FindCXXThisExpr Finder(*this);
17527
17528  // Check attributes.
17529  for (const auto *A : Method->attrs()) {
17530    // FIXME: This should be emitted by tblgen.
17531    Expr *Arg = nullptr;
17532    ArrayRef<Expr *> Args;
17533    if (const auto *G = dyn_cast<GuardedByAttr>(A))
17534      Arg = G->getArg();
17535    else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17536      Arg = G->getArg();
17537    else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17538      Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17539    else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17540      Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17541    else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17542      Arg = ETLF->getSuccessValue();
17543      Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17544    } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17545      Arg = STLF->getSuccessValue();
17546      Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17547    } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17548      Arg = LR->getArg();
17549    else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17550      Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17551    else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17552      Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17553    else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17554      Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17555    else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17556      Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17557    else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17558      Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17559
17560    if (Arg && !Finder.TraverseStmt(Arg))
17561      return true;
17562
17563    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17564      if (!Finder.TraverseStmt(Args[I]))
17565        return true;
17566    }
17567  }
17568
17569  return false;
17570}
17571
17572void Sema::checkExceptionSpecification(
17573    bool IsTopLevel, ExceptionSpecificationType EST,
17574    ArrayRef<ParsedType> DynamicExceptions,
17575    ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17576    SmallVectorImpl<QualType> &Exceptions,
17577    FunctionProtoType::ExceptionSpecInfo &ESI) {
17578  Exceptions.clear();
17579  ESI.Type = EST;
17580  if (EST == EST_Dynamic) {
17581    Exceptions.reserve(DynamicExceptions.size());
17582    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17583      // FIXME: Preserve type source info.
17584      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17585
17586      if (IsTopLevel) {
17587        SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17588        collectUnexpandedParameterPacks(ET, Unexpanded);
17589        if (!Unexpanded.empty()) {
17590          DiagnoseUnexpandedParameterPacks(
17591              DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17592              Unexpanded);
17593          continue;
17594        }
17595      }
17596
17597      // Check that the type is valid for an exception spec, and
17598      // drop it if not.
17599      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17600        Exceptions.push_back(ET);
17601    }
17602    ESI.Exceptions = Exceptions;
17603    return;
17604  }
17605
17606  if (isComputedNoexcept(EST)) {
17607    assert((NoexceptExpr->isTypeDependent() ||
17608            NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17609            Context.BoolTy) &&
17610           "Parser should have made sure that the expression is boolean");
17611    if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17612      ESI.Type = EST_BasicNoexcept;
17613      return;
17614    }
17615
17616    ESI.NoexceptExpr = NoexceptExpr;
17617    return;
17618  }
17619}
17620
17621void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17622             ExceptionSpecificationType EST,
17623             SourceRange SpecificationRange,
17624             ArrayRef<ParsedType> DynamicExceptions,
17625             ArrayRef<SourceRange> DynamicExceptionRanges,
17626             Expr *NoexceptExpr) {
17627  if (!MethodD)
17628    return;
17629
17630  // Dig out the method we're referring to.
17631  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17632    MethodD = FunTmpl->getTemplatedDecl();
17633
17634  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17635  if (!Method)
17636    return;
17637
17638  // Check the exception specification.
17639  llvm::SmallVector<QualType, 4> Exceptions;
17640  FunctionProtoType::ExceptionSpecInfo ESI;
17641  checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17642                              DynamicExceptionRanges, NoexceptExpr, Exceptions,
17643                              ESI);
17644
17645  // Update the exception specification on the function type.
17646  Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17647
17648  if (Method->isStatic())
17649    checkThisInStaticMemberFunctionExceptionSpec(Method);
17650
17651  if (Method->isVirtual()) {
17652    // Check overrides, which we previously had to delay.
17653    for (const CXXMethodDecl *O : Method->overridden_methods())
17654      CheckOverridingFunctionExceptionSpec(Method, O);
17655  }
17656}
17657
17658/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17659///
17660MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17661                                       SourceLocation DeclStart, Declarator &D,
17662                                       Expr *BitWidth,
17663                                       InClassInitStyle InitStyle,
17664                                       AccessSpecifier AS,
17665                                       const ParsedAttr &MSPropertyAttr) {
17666  IdentifierInfo *II = D.getIdentifier();
17667  if (!II) {
17668    Diag(DeclStart, diag::err_anonymous_property);
17669    return nullptr;
17670  }
17671  SourceLocation Loc = D.getIdentifierLoc();
17672
17673  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17674  QualType T = TInfo->getType();
17675  if (getLangOpts().CPlusPlus) {
17676    CheckExtraCXXDefaultArguments(D);
17677
17678    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17679                                        UPPC_DataMemberType)) {
17680      D.setInvalidType();
17681      T = Context.IntTy;
17682      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17683    }
17684  }
17685
17686  DiagnoseFunctionSpecifiers(D.getDeclSpec());
17687
17688  if (D.getDeclSpec().isInlineSpecified())
17689    Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17690        << getLangOpts().CPlusPlus17;
17691  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17692    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17693         diag::err_invalid_thread)
17694      << DeclSpec::getSpecifierName(TSCS);
17695
17696  // Check to see if this name was declared as a member previously
17697  NamedDecl *PrevDecl = nullptr;
17698  LookupResult Previous(*this, II, Loc, LookupMemberName,
17699                        ForVisibleRedeclaration);
17700  LookupName(Previous, S);
17701  switch (Previous.getResultKind()) {
17702  case LookupResult::Found:
17703  case LookupResult::FoundUnresolvedValue:
17704    PrevDecl = Previous.getAsSingle<NamedDecl>();
17705    break;
17706
17707  case LookupResult::FoundOverloaded:
17708    PrevDecl = Previous.getRepresentativeDecl();
17709    break;
17710
17711  case LookupResult::NotFound:
17712  case LookupResult::NotFoundInCurrentInstantiation:
17713  case LookupResult::Ambiguous:
17714    break;
17715  }
17716
17717  if (PrevDecl && PrevDecl->isTemplateParameter()) {
17718    // Maybe we will complain about the shadowed template parameter.
17719    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17720    // Just pretend that we didn't see the previous declaration.
17721    PrevDecl = nullptr;
17722  }
17723
17724  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17725    PrevDecl = nullptr;
17726
17727  SourceLocation TSSL = D.getBeginLoc();
17728  MSPropertyDecl *NewPD =
17729      MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17730                             MSPropertyAttr.getPropertyDataGetter(),
17731                             MSPropertyAttr.getPropertyDataSetter());
17732  ProcessDeclAttributes(TUScope, NewPD, D);
17733  NewPD->setAccess(AS);
17734
17735  if (NewPD->isInvalidDecl())
17736    Record->setInvalidDecl();
17737
17738  if (D.getDeclSpec().isModulePrivateSpecified())
17739    NewPD->setModulePrivate();
17740
17741  if (NewPD->isInvalidDecl() && PrevDecl) {
17742    // Don't introduce NewFD into scope; there's already something
17743    // with the same name in the same scope.
17744  } else if (II) {
17745    PushOnScopeChains(NewPD, S);
17746  } else
17747    Record->addDecl(NewPD);
17748
17749  return NewPD;
17750}
17751
17752void Sema::ActOnStartFunctionDeclarationDeclarator(
17753    Declarator &Declarator, unsigned TemplateParameterDepth) {
17754  auto &Info = InventedParameterInfos.emplace_back();
17755  TemplateParameterList *ExplicitParams = nullptr;
17756  ArrayRef<TemplateParameterList *> ExplicitLists =
17757      Declarator.getTemplateParameterLists();
17758  if (!ExplicitLists.empty()) {
17759    bool IsMemberSpecialization, IsInvalid;
17760    ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17761        Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17762        Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17763        ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17764        /*SuppressDiagnostic=*/true);
17765  }
17766  if (ExplicitParams) {
17767    Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17768    for (NamedDecl *Param : *ExplicitParams)
17769      Info.TemplateParams.push_back(Param);
17770    Info.NumExplicitTemplateParams = ExplicitParams->size();
17771  } else {
17772    Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17773    Info.NumExplicitTemplateParams = 0;
17774  }
17775}
17776
17777void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17778  auto &FSI = InventedParameterInfos.back();
17779  if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17780    if (FSI.NumExplicitTemplateParams != 0) {
17781      TemplateParameterList *ExplicitParams =
17782          Declarator.getTemplateParameterLists().back();
17783      Declarator.setInventedTemplateParameterList(
17784          TemplateParameterList::Create(
17785              Context, ExplicitParams->getTemplateLoc(),
17786              ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17787              ExplicitParams->getRAngleLoc(),
17788              ExplicitParams->getRequiresClause()));
17789    } else {
17790      Declarator.setInventedTemplateParameterList(
17791          TemplateParameterList::Create(
17792              Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17793              SourceLocation(), /*RequiresClause=*/nullptr));
17794    }
17795  }
17796  InventedParameterInfos.pop_back();
17797}
17798