1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.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/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/LiteralSupport.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include <map>
44 #include <set>
45 
46 using namespace clang;
47 
48 //===----------------------------------------------------------------------===//
49 // CheckDefaultArgumentVisitor
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54   /// the default argument of a parameter to determine whether it
55   /// contains any ill-formed subexpressions. For example, this will
56   /// diagnose the use of local variables or parameters within the
57   /// default argument expression.
58   class CheckDefaultArgumentVisitor
59     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60     Expr *DefaultArg;
61     Sema *S;
62 
63   public:
64     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65       : DefaultArg(defarg), S(s) {}
66 
67     bool VisitExpr(Expr *Node);
68     bool VisitDeclRefExpr(DeclRefExpr *DRE);
69     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70     bool VisitLambdaExpr(LambdaExpr *Lambda);
71     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72   };
73 
74   /// VisitExpr - Visit all of the children of this expression.
75   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76     bool IsInvalid = false;
77     for (Stmt *SubStmt : Node->children())
78       IsInvalid |= Visit(SubStmt);
79     return IsInvalid;
80   }
81 
82   /// VisitDeclRefExpr - Visit a reference to a declaration, to
83   /// determine whether this declaration can be used in the default
84   /// argument expression.
85   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86     NamedDecl *Decl = DRE->getDecl();
87     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88       // C++ [dcl.fct.default]p9
89       //   Default arguments are evaluated each time the function is
90       //   called. The order of evaluation of function arguments is
91       //   unspecified. Consequently, parameters of a function shall not
92       //   be used in default argument expressions, even if they are not
93       //   evaluated. Parameters of a function declared before a default
94       //   argument expression are in scope and can hide namespace and
95       //   class member names.
96       return S->Diag(DRE->getLocStart(),
97                      diag::err_param_default_argument_references_param)
98          << Param->getDeclName() << DefaultArg->getSourceRange();
99     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100       // C++ [dcl.fct.default]p7
101       //   Local variables shall not be used in default argument
102       //   expressions.
103       if (VDecl->isLocalVarDecl())
104         return S->Diag(DRE->getLocStart(),
105                        diag::err_param_default_argument_references_local)
106           << VDecl->getDeclName() << DefaultArg->getSourceRange();
107     }
108 
109     return false;
110   }
111 
112   /// VisitCXXThisExpr - Visit a C++ "this" expression.
113   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114     // C++ [dcl.fct.default]p8:
115     //   The keyword this shall not be used in a default argument of a
116     //   member function.
117     return S->Diag(ThisE->getLocStart(),
118                    diag::err_param_default_argument_references_this)
119                << ThisE->getSourceRange();
120   }
121 
122   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123     bool Invalid = false;
124     for (PseudoObjectExpr::semantics_iterator
125            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126       Expr *E = *i;
127 
128       // Look through bindings.
129       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130         E = OVE->getSourceExpr();
131         assert(E && "pseudo-object binding without source expression?");
132       }
133 
134       Invalid |= Visit(E);
135     }
136     return Invalid;
137   }
138 
139   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140     // C++11 [expr.lambda.prim]p13:
141     //   A lambda-expression appearing in a default argument shall not
142     //   implicitly or explicitly capture any entity.
143     if (Lambda->capture_begin() == Lambda->capture_end())
144       return false;
145 
146     return S->Diag(Lambda->getLocStart(),
147                    diag::err_lambda_capture_default_arg);
148   }
149 }
150 
151 void
152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153                                                  const CXXMethodDecl *Method) {
154   // If we have an MSAny spec already, don't bother.
155   if (!Method || ComputedEST == EST_MSAny)
156     return;
157 
158   const FunctionProtoType *Proto
159     = Method->getType()->getAs<FunctionProtoType>();
160   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161   if (!Proto)
162     return;
163 
164   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165 
166   // If we have a throw-all spec at this point, ignore the function.
167   if (ComputedEST == EST_None)
168     return;
169 
170   switch(EST) {
171   // If this function can throw any exceptions, make a note of that.
172   case EST_MSAny:
173   case EST_None:
174     ClearExceptions();
175     ComputedEST = EST;
176     return;
177   // FIXME: If the call to this decl is using any of its default arguments, we
178   // need to search them for potentially-throwing calls.
179   // If this function has a basic noexcept, it doesn't affect the outcome.
180   case EST_BasicNoexcept:
181     return;
182   // If we're still at noexcept(true) and there's a nothrow() callee,
183   // change to that specification.
184   case EST_DynamicNone:
185     if (ComputedEST == EST_BasicNoexcept)
186       ComputedEST = EST_DynamicNone;
187     return;
188   // Check out noexcept specs.
189   case EST_ComputedNoexcept:
190   {
191     FunctionProtoType::NoexceptResult NR =
192         Proto->getNoexceptSpec(Self->Context);
193     assert(NR != FunctionProtoType::NR_NoNoexcept &&
194            "Must have noexcept result for EST_ComputedNoexcept.");
195     assert(NR != FunctionProtoType::NR_Dependent &&
196            "Should not generate implicit declarations for dependent cases, "
197            "and don't know how to handle them anyway.");
198     // noexcept(false) -> no spec on the new function
199     if (NR == FunctionProtoType::NR_Throw) {
200       ClearExceptions();
201       ComputedEST = EST_None;
202     }
203     // noexcept(true) won't change anything either.
204     return;
205   }
206   default:
207     break;
208   }
209   assert(EST == EST_Dynamic && "EST case not considered earlier.");
210   assert(ComputedEST != EST_None &&
211          "Shouldn't collect exceptions when throw-all is guaranteed.");
212   ComputedEST = EST_Dynamic;
213   // Record the exceptions in this function's exception specification.
214   for (const auto &E : Proto->exceptions())
215     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216       Exceptions.push_back(E);
217 }
218 
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220   if (!E || ComputedEST == EST_MSAny)
221     return;
222 
223   // FIXME:
224   //
225   // C++0x [except.spec]p14:
226   //   [An] implicit exception-specification specifies the type-id T if and
227   // only if T is allowed by the exception-specification of a function directly
228   // invoked by f's implicit definition; f shall allow all exceptions if any
229   // function it directly invokes allows all exceptions, and f shall allow no
230   // exceptions if every function it directly invokes allows no exceptions.
231   //
232   // Note in particular that if an implicit exception-specification is generated
233   // for a function containing a throw-expression, that specification can still
234   // be noexcept(true).
235   //
236   // Note also that 'directly invoked' is not defined in the standard, and there
237   // is no indication that we should only consider potentially-evaluated calls.
238   //
239   // Ultimately we should implement the intent of the standard: the exception
240   // specification should be the set of exceptions which can be thrown by the
241   // implicit definition. For now, we assume that any non-nothrow expression can
242   // throw any exception.
243 
244   if (Self->canThrow(E))
245     ComputedEST = EST_None;
246 }
247 
248 bool
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250                               SourceLocation EqualLoc) {
251   if (RequireCompleteType(Param->getLocation(), Param->getType(),
252                           diag::err_typecheck_decl_incomplete_type)) {
253     Param->setInvalidDecl();
254     return true;
255   }
256 
257   // C++ [dcl.fct.default]p5
258   //   A default argument expression is implicitly converted (clause
259   //   4) to the parameter type. The default argument expression has
260   //   the same semantic constraints as the initializer expression in
261   //   a declaration of a variable of the parameter type, using the
262   //   copy-initialization semantics (8.5).
263   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264                                                                     Param);
265   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266                                                            EqualLoc);
267   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269   if (Result.isInvalid())
270     return true;
271   Arg = Result.getAs<Expr>();
272 
273   CheckCompletedExpr(Arg, EqualLoc);
274   Arg = MaybeCreateExprWithCleanups(Arg);
275 
276   // Okay: add the default argument to the parameter
277   Param->setDefaultArg(Arg);
278 
279   // We have already instantiated this parameter; provide each of the
280   // instantiations with the uninstantiated default argument.
281   UnparsedDefaultArgInstantiationsMap::iterator InstPos
282     = UnparsedDefaultArgInstantiations.find(Param);
283   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287     // We're done tracking this parameter's instantiations.
288     UnparsedDefaultArgInstantiations.erase(InstPos);
289   }
290 
291   return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299                                 Expr *DefaultArg) {
300   if (!param || !DefaultArg)
301     return;
302 
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   UnparsedDefaultArgLocs.erase(Param);
305 
306   // Default arguments are only permitted in C++
307   if (!getLangOpts().CPlusPlus) {
308     Diag(EqualLoc, diag::err_param_default_argument)
309       << DefaultArg->getSourceRange();
310     Param->setInvalidDecl();
311     return;
312   }
313 
314   // Check for unexpanded parameter packs.
315   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316     Param->setInvalidDecl();
317     return;
318   }
319 
320   // C++11 [dcl.fct.default]p3
321   //   A default argument expression [...] shall not be specified for a
322   //   parameter pack.
323   if (Param->isParameterPack()) {
324     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325         << DefaultArg->getSourceRange();
326     return;
327   }
328 
329   // Check that the default argument is well-formed
330   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331   if (DefaultArgChecker.Visit(DefaultArg)) {
332     Param->setInvalidDecl();
333     return;
334   }
335 
336   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337 }
338 
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344                                              SourceLocation EqualLoc,
345                                              SourceLocation ArgLoc) {
346   if (!param)
347     return;
348 
349   ParmVarDecl *Param = cast<ParmVarDecl>(param);
350   Param->setUnparsedDefaultArg();
351   UnparsedDefaultArgLocs[Param] = ArgLoc;
352 }
353 
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
356 void Sema::ActOnParamDefaultArgumentError(Decl *param,
357                                           SourceLocation EqualLoc) {
358   if (!param)
359     return;
360 
361   ParmVarDecl *Param = cast<ParmVarDecl>(param);
362   Param->setInvalidDecl();
363   UnparsedDefaultArgLocs.erase(Param);
364   Param->setDefaultArg(new(Context)
365                        OpaqueValueExpr(EqualLoc,
366                                        Param->getType().getNonReferenceType(),
367                                        VK_RValue));
368 }
369 
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376   // C++ [dcl.fct.default]p3
377   //   A default argument expression shall be specified only in the
378   //   parameter-declaration-clause of a function declaration or in a
379   //   template-parameter (14.1). It shall not be specified for a
380   //   parameter pack. If it is specified in a
381   //   parameter-declaration-clause, it shall not occur within a
382   //   declarator or abstract-declarator of a parameter-declaration.
383   bool MightBeFunction = D.isFunctionDeclarationContext();
384   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385     DeclaratorChunk &chunk = D.getTypeObject(i);
386     if (chunk.Kind == DeclaratorChunk::Function) {
387       if (MightBeFunction) {
388         // This is a function declaration. It can have default arguments, but
389         // keep looking in case its return type is a function type with default
390         // arguments.
391         MightBeFunction = false;
392         continue;
393       }
394       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395            ++argIdx) {
396         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397         if (Param->hasUnparsedDefaultArg()) {
398           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
399           SourceRange SR;
400           if (Toks->size() > 1)
401             SR = SourceRange((*Toks)[1].getLocation(),
402                              Toks->back().getLocation());
403           else
404             SR = UnparsedDefaultArgLocs[Param];
405           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
406             << SR;
407           delete Toks;
408           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
409         } else if (Param->getDefaultArg()) {
410           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
411             << Param->getDefaultArg()->getSourceRange();
412           Param->setDefaultArg(nullptr);
413         }
414       }
415     } else if (chunk.Kind != DeclaratorChunk::Paren) {
416       MightBeFunction = false;
417     }
418   }
419 }
420 
421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
422   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
423     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
424     if (!PVD->hasDefaultArg())
425       return false;
426     if (!PVD->hasInheritedDefaultArg())
427       return true;
428   }
429   return false;
430 }
431 
432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
433 /// function, once we already know that they have the same
434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
435 /// error, false otherwise.
436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
437                                 Scope *S) {
438   bool Invalid = false;
439 
440   // The declaration context corresponding to the scope is the semantic
441   // parent, unless this is a local function declaration, in which case
442   // it is that surrounding function.
443   DeclContext *ScopeDC = New->isLocalExternDecl()
444                              ? New->getLexicalDeclContext()
445                              : New->getDeclContext();
446 
447   // Find the previous declaration for the purpose of default arguments.
448   FunctionDecl *PrevForDefaultArgs = Old;
449   for (/**/; PrevForDefaultArgs;
450        // Don't bother looking back past the latest decl if this is a local
451        // extern declaration; nothing else could work.
452        PrevForDefaultArgs = New->isLocalExternDecl()
453                                 ? nullptr
454                                 : PrevForDefaultArgs->getPreviousDecl()) {
455     // Ignore hidden declarations.
456     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
457       continue;
458 
459     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
460         !New->isCXXClassMember()) {
461       // Ignore default arguments of old decl if they are not in
462       // the same scope and this is not an out-of-line definition of
463       // a member function.
464       continue;
465     }
466 
467     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
468       // If only one of these is a local function declaration, then they are
469       // declared in different scopes, even though isDeclInScope may think
470       // they're in the same scope. (If both are local, the scope check is
471       // sufficent, and if neither is local, then they are in the same scope.)
472       continue;
473     }
474 
475     // We found the right previous declaration.
476     break;
477   }
478 
479   // C++ [dcl.fct.default]p4:
480   //   For non-template functions, default arguments can be added in
481   //   later declarations of a function in the same
482   //   scope. Declarations in different scopes have completely
483   //   distinct sets of default arguments. That is, declarations in
484   //   inner scopes do not acquire default arguments from
485   //   declarations in outer scopes, and vice versa. In a given
486   //   function declaration, all parameters subsequent to a
487   //   parameter with a default argument shall have default
488   //   arguments supplied in this or previous declarations. A
489   //   default argument shall not be redefined by a later
490   //   declaration (not even to the same value).
491   //
492   // C++ [dcl.fct.default]p6:
493   //   Except for member functions of class templates, the default arguments
494   //   in a member function definition that appears outside of the class
495   //   definition are added to the set of default arguments provided by the
496   //   member function declaration in the class definition.
497   for (unsigned p = 0, NumParams = PrevForDefaultArgs
498                                        ? PrevForDefaultArgs->getNumParams()
499                                        : 0;
500        p < NumParams; ++p) {
501     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
502     ParmVarDecl *NewParam = New->getParamDecl(p);
503 
504     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
505     bool NewParamHasDfl = NewParam->hasDefaultArg();
506 
507     if (OldParamHasDfl && NewParamHasDfl) {
508       unsigned DiagDefaultParamID =
509         diag::err_param_default_argument_redefinition;
510 
511       // MSVC accepts that default parameters be redefined for member functions
512       // of template class. The new default parameter's value is ignored.
513       Invalid = true;
514       if (getLangOpts().MicrosoftExt) {
515         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
516         if (MD && MD->getParent()->getDescribedClassTemplate()) {
517           // Merge the old default argument into the new parameter.
518           NewParam->setHasInheritedDefaultArg();
519           if (OldParam->hasUninstantiatedDefaultArg())
520             NewParam->setUninstantiatedDefaultArg(
521                                       OldParam->getUninstantiatedDefaultArg());
522           else
523             NewParam->setDefaultArg(OldParam->getInit());
524           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
525           Invalid = false;
526         }
527       }
528 
529       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
530       // hint here. Alternatively, we could walk the type-source information
531       // for NewParam to find the last source location in the type... but it
532       // isn't worth the effort right now. This is the kind of test case that
533       // is hard to get right:
534       //   int f(int);
535       //   void g(int (*fp)(int) = f);
536       //   void g(int (*fp)(int) = &f);
537       Diag(NewParam->getLocation(), DiagDefaultParamID)
538         << NewParam->getDefaultArgRange();
539 
540       // Look for the function declaration where the default argument was
541       // actually written, which may be a declaration prior to Old.
542       for (auto Older = PrevForDefaultArgs;
543            OldParam->hasInheritedDefaultArg(); /**/) {
544         Older = Older->getPreviousDecl();
545         OldParam = Older->getParamDecl(p);
546       }
547 
548       Diag(OldParam->getLocation(), diag::note_previous_definition)
549         << OldParam->getDefaultArgRange();
550     } else if (OldParamHasDfl) {
551       // Merge the old default argument into the new parameter.
552       // It's important to use getInit() here;  getDefaultArg()
553       // strips off any top-level ExprWithCleanups.
554       NewParam->setHasInheritedDefaultArg();
555       if (OldParam->hasUnparsedDefaultArg())
556         NewParam->setUnparsedDefaultArg();
557       else if (OldParam->hasUninstantiatedDefaultArg())
558         NewParam->setUninstantiatedDefaultArg(
559                                       OldParam->getUninstantiatedDefaultArg());
560       else
561         NewParam->setDefaultArg(OldParam->getInit());
562     } else if (NewParamHasDfl) {
563       if (New->getDescribedFunctionTemplate()) {
564         // Paragraph 4, quoted above, only applies to non-template functions.
565         Diag(NewParam->getLocation(),
566              diag::err_param_default_argument_template_redecl)
567           << NewParam->getDefaultArgRange();
568         Diag(PrevForDefaultArgs->getLocation(),
569              diag::note_template_prev_declaration)
570             << false;
571       } else if (New->getTemplateSpecializationKind()
572                    != TSK_ImplicitInstantiation &&
573                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
574         // C++ [temp.expr.spec]p21:
575         //   Default function arguments shall not be specified in a declaration
576         //   or a definition for one of the following explicit specializations:
577         //     - the explicit specialization of a function template;
578         //     - the explicit specialization of a member function template;
579         //     - the explicit specialization of a member function of a class
580         //       template where the class template specialization to which the
581         //       member function specialization belongs is implicitly
582         //       instantiated.
583         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
584           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
585           << New->getDeclName()
586           << NewParam->getDefaultArgRange();
587       } else if (New->getDeclContext()->isDependentContext()) {
588         // C++ [dcl.fct.default]p6 (DR217):
589         //   Default arguments for a member function of a class template shall
590         //   be specified on the initial declaration of the member function
591         //   within the class template.
592         //
593         // Reading the tea leaves a bit in DR217 and its reference to DR205
594         // leads me to the conclusion that one cannot add default function
595         // arguments for an out-of-line definition of a member function of a
596         // dependent type.
597         int WhichKind = 2;
598         if (CXXRecordDecl *Record
599               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
600           if (Record->getDescribedClassTemplate())
601             WhichKind = 0;
602           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
603             WhichKind = 1;
604           else
605             WhichKind = 2;
606         }
607 
608         Diag(NewParam->getLocation(),
609              diag::err_param_default_argument_member_template_redecl)
610           << WhichKind
611           << NewParam->getDefaultArgRange();
612       }
613     }
614   }
615 
616   // DR1344: If a default argument is added outside a class definition and that
617   // default argument makes the function a special member function, the program
618   // is ill-formed. This can only happen for constructors.
619   if (isa<CXXConstructorDecl>(New) &&
620       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
621     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
622                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
623     if (NewSM != OldSM) {
624       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
625       assert(NewParam->hasDefaultArg());
626       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
627         << NewParam->getDefaultArgRange() << NewSM;
628       Diag(Old->getLocation(), diag::note_previous_declaration);
629     }
630   }
631 
632   const FunctionDecl *Def;
633   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
634   // template has a constexpr specifier then all its declarations shall
635   // contain the constexpr specifier.
636   if (New->isConstexpr() != Old->isConstexpr()) {
637     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
638       << New << New->isConstexpr();
639     Diag(Old->getLocation(), diag::note_previous_declaration);
640     Invalid = true;
641   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
642              Old->isDefined(Def)) {
643     // C++11 [dcl.fcn.spec]p4:
644     //   If the definition of a function appears in a translation unit before its
645     //   first declaration as inline, the program is ill-formed.
646     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
647     Diag(Def->getLocation(), diag::note_previous_definition);
648     Invalid = true;
649   }
650 
651   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
652   // argument expression, that declaration shall be a definition and shall be
653   // the only declaration of the function or function template in the
654   // translation unit.
655   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
656       functionDeclHasDefaultArgument(Old)) {
657     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
658     Diag(Old->getLocation(), diag::note_previous_declaration);
659     Invalid = true;
660   }
661 
662   return Invalid;
663 }
664 
665 NamedDecl *
666 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
667                                    MultiTemplateParamsArg TemplateParamLists) {
668   assert(D.isDecompositionDeclarator());
669   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
670 
671   // The syntax only allows a decomposition declarator as a simple-declaration
672   // or a for-range-declaration, but we parse it in more cases than that.
673   if (!D.mayHaveDecompositionDeclarator()) {
674     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
675       << Decomp.getSourceRange();
676     return nullptr;
677   }
678 
679   if (!TemplateParamLists.empty()) {
680     // FIXME: There's no rule against this, but there are also no rules that
681     // would actually make it usable, so we reject it for now.
682     Diag(TemplateParamLists.front()->getTemplateLoc(),
683          diag::err_decomp_decl_template);
684     return nullptr;
685   }
686 
687   Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
688                                    ? diag::warn_cxx14_compat_decomp_decl
689                                    : diag::ext_decomp_decl)
690       << Decomp.getSourceRange();
691 
692   // The semantic context is always just the current context.
693   DeclContext *const DC = CurContext;
694 
695   // C++1z [dcl.dcl]/8:
696   //   The decl-specifier-seq shall contain only the type-specifier auto
697   //   and cv-qualifiers.
698   auto &DS = D.getDeclSpec();
699   {
700     SmallVector<StringRef, 8> BadSpecifiers;
701     SmallVector<SourceLocation, 8> BadSpecifierLocs;
702     if (auto SCS = DS.getStorageClassSpec()) {
703       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
704       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
705     }
706     if (auto TSCS = DS.getThreadStorageClassSpec()) {
707       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
708       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
709     }
710     if (DS.isConstexprSpecified()) {
711       BadSpecifiers.push_back("constexpr");
712       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
713     }
714     if (DS.isInlineSpecified()) {
715       BadSpecifiers.push_back("inline");
716       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
717     }
718     if (!BadSpecifiers.empty()) {
719       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
720       Err << (int)BadSpecifiers.size()
721           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
722       // Don't add FixItHints to remove the specifiers; we do still respect
723       // them when building the underlying variable.
724       for (auto Loc : BadSpecifierLocs)
725         Err << SourceRange(Loc, Loc);
726     }
727     // We can't recover from it being declared as a typedef.
728     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
729       return nullptr;
730   }
731 
732   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
733   QualType R = TInfo->getType();
734 
735   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
736                                       UPPC_DeclarationType))
737     D.setInvalidType();
738 
739   // The syntax only allows a single ref-qualifier prior to the decomposition
740   // declarator. No other declarator chunks are permitted. Also check the type
741   // specifier here.
742   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
743       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
744       (D.getNumTypeObjects() == 1 &&
745        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
746     Diag(Decomp.getLSquareLoc(),
747          (D.hasGroupingParens() ||
748           (D.getNumTypeObjects() &&
749            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
750              ? diag::err_decomp_decl_parens
751              : diag::err_decomp_decl_type)
752         << R;
753 
754     // In most cases, there's no actual problem with an explicitly-specified
755     // type, but a function type won't work here, and ActOnVariableDeclarator
756     // shouldn't be called for such a type.
757     if (R->isFunctionType())
758       D.setInvalidType();
759   }
760 
761   // Build the BindingDecls.
762   SmallVector<BindingDecl*, 8> Bindings;
763 
764   // Build the BindingDecls.
765   for (auto &B : D.getDecompositionDeclarator().bindings()) {
766     // Check for name conflicts.
767     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
768     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
769                           ForRedeclaration);
770     LookupName(Previous, S,
771                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
772 
773     // It's not permitted to shadow a template parameter name.
774     if (Previous.isSingleResult() &&
775         Previous.getFoundDecl()->isTemplateParameter()) {
776       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
777                                       Previous.getFoundDecl());
778       Previous.clear();
779     }
780 
781     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
782                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
783     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
784                          /*AllowInlineNamespace*/false);
785     if (!Previous.empty()) {
786       auto *Old = Previous.getRepresentativeDecl();
787       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
788       Diag(Old->getLocation(), diag::note_previous_definition);
789     }
790 
791     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
792     PushOnScopeChains(BD, S, true);
793     Bindings.push_back(BD);
794     ParsingInitForAutoVars.insert(BD);
795   }
796 
797   // There are no prior lookup results for the variable itself, because it
798   // is unnamed.
799   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
800                                Decomp.getLSquareLoc());
801   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
802 
803   // Build the variable that holds the non-decomposed object.
804   bool AddToScope = true;
805   NamedDecl *New =
806       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
807                               MultiTemplateParamsArg(), AddToScope, Bindings);
808   CurContext->addHiddenDecl(New);
809 
810   if (isInOpenMPDeclareTargetContext())
811     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
812 
813   return New;
814 }
815 
816 static bool checkSimpleDecomposition(
817     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
818     QualType DecompType, llvm::APSInt NumElems, QualType ElemType,
819     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
820   if ((int64_t)Bindings.size() != NumElems) {
821     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
822         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
823         << (NumElems < Bindings.size());
824     return true;
825   }
826 
827   unsigned I = 0;
828   for (auto *B : Bindings) {
829     SourceLocation Loc = B->getLocation();
830     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
831     if (E.isInvalid())
832       return true;
833     E = GetInit(Loc, E.get(), I++);
834     if (E.isInvalid())
835       return true;
836     B->setBinding(ElemType, E.get());
837   }
838 
839   return false;
840 }
841 
842 static bool checkArrayLikeDecomposition(Sema &S,
843                                         ArrayRef<BindingDecl *> Bindings,
844                                         ValueDecl *Src, QualType DecompType,
845                                         llvm::APSInt NumElems,
846                                         QualType ElemType) {
847   return checkSimpleDecomposition(
848       S, Bindings, Src, DecompType, NumElems, ElemType,
849       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
850         ExprResult E = S.ActOnIntegerConstant(Loc, I);
851         if (E.isInvalid())
852           return ExprError();
853         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
854       });
855 }
856 
857 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
858                                     ValueDecl *Src, QualType DecompType,
859                                     const ConstantArrayType *CAT) {
860   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
861                                      llvm::APSInt(CAT->getSize()),
862                                      CAT->getElementType());
863 }
864 
865 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
866                                      ValueDecl *Src, QualType DecompType,
867                                      const VectorType *VT) {
868   return checkArrayLikeDecomposition(
869       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
870       S.Context.getQualifiedType(VT->getElementType(),
871                                  DecompType.getQualifiers()));
872 }
873 
874 static bool checkComplexDecomposition(Sema &S,
875                                       ArrayRef<BindingDecl *> Bindings,
876                                       ValueDecl *Src, QualType DecompType,
877                                       const ComplexType *CT) {
878   return checkSimpleDecomposition(
879       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
880       S.Context.getQualifiedType(CT->getElementType(),
881                                  DecompType.getQualifiers()),
882       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
883         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
884       });
885 }
886 
887 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
888                                      TemplateArgumentListInfo &Args) {
889   SmallString<128> SS;
890   llvm::raw_svector_ostream OS(SS);
891   bool First = true;
892   for (auto &Arg : Args.arguments()) {
893     if (!First)
894       OS << ", ";
895     Arg.getArgument().print(PrintingPolicy, OS);
896     First = false;
897   }
898   return OS.str();
899 }
900 
901 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
902                                      SourceLocation Loc, StringRef Trait,
903                                      TemplateArgumentListInfo &Args,
904                                      unsigned DiagID) {
905   auto DiagnoseMissing = [&] {
906     if (DiagID)
907       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
908                                                Args);
909     return true;
910   };
911 
912   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
913   NamespaceDecl *Std = S.getStdNamespace();
914   if (!Std)
915     return DiagnoseMissing();
916 
917   // Look up the trait itself, within namespace std. We can diagnose various
918   // problems with this lookup even if we've been asked to not diagnose a
919   // missing specialization, because this can only fail if the user has been
920   // declaring their own names in namespace std or we don't support the
921   // standard library implementation in use.
922   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
923                       Loc, Sema::LookupOrdinaryName);
924   if (!S.LookupQualifiedName(Result, Std))
925     return DiagnoseMissing();
926   if (Result.isAmbiguous())
927     return true;
928 
929   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
930   if (!TraitTD) {
931     Result.suppressDiagnostics();
932     NamedDecl *Found = *Result.begin();
933     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
934     S.Diag(Found->getLocation(), diag::note_declared_at);
935     return true;
936   }
937 
938   // Build the template-id.
939   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
940   if (TraitTy.isNull())
941     return true;
942   if (!S.isCompleteType(Loc, TraitTy)) {
943     if (DiagID)
944       S.RequireCompleteType(
945           Loc, TraitTy, DiagID,
946           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
947     return true;
948   }
949 
950   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
951   assert(RD && "specialization of class template is not a class?");
952 
953   // Look up the member of the trait type.
954   S.LookupQualifiedName(TraitMemberLookup, RD);
955   return TraitMemberLookup.isAmbiguous();
956 }
957 
958 static TemplateArgumentLoc
959 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
960                                    uint64_t I) {
961   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
962   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
963 }
964 
965 static TemplateArgumentLoc
966 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
967   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
968 }
969 
970 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
971 
972 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
973                                llvm::APSInt &Size) {
974   EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
975 
976   DeclarationName Value = S.PP.getIdentifierInfo("value");
977   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
978 
979   // Form template argument list for tuple_size<T>.
980   TemplateArgumentListInfo Args(Loc, Loc);
981   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
982 
983   // If there's no tuple_size specialization, it's not tuple-like.
984   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
985     return IsTupleLike::NotTupleLike;
986 
987   // FIXME: According to the standard, we're not supposed to diagnose if any
988   // of the steps below fail (or if lookup for ::value is ambiguous or otherwise
989   // results in an error), but this is subject to a pending CWG issue / NB
990   // comment, which says we do diagnose if tuple_size<T> is complete but
991   // tuple_size<T>::value is not an ICE.
992 
993   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
994     LookupResult &R;
995     TemplateArgumentListInfo &Args;
996     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
997         : R(R), Args(Args) {}
998     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
999       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1000           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1001     }
1002   } Diagnoser(R, Args);
1003 
1004   if (R.empty()) {
1005     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1006     return IsTupleLike::Error;
1007   }
1008 
1009   ExprResult E =
1010       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1011   if (E.isInvalid())
1012     return IsTupleLike::Error;
1013 
1014   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1015   if (E.isInvalid())
1016     return IsTupleLike::Error;
1017 
1018   return IsTupleLike::TupleLike;
1019 }
1020 
1021 /// \return std::tuple_element<I, T>::type.
1022 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1023                                         unsigned I, QualType T) {
1024   // Form template argument list for tuple_element<I, T>.
1025   TemplateArgumentListInfo Args(Loc, Loc);
1026   Args.addArgument(
1027       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1028   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1029 
1030   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1031   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1032   if (lookupStdTypeTraitMember(
1033           S, R, Loc, "tuple_element", Args,
1034           diag::err_decomp_decl_std_tuple_element_not_specialized))
1035     return QualType();
1036 
1037   auto *TD = R.getAsSingle<TypeDecl>();
1038   if (!TD) {
1039     R.suppressDiagnostics();
1040     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1041       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1042     if (!R.empty())
1043       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1044     return QualType();
1045   }
1046 
1047   return S.Context.getTypeDeclType(TD);
1048 }
1049 
1050 namespace {
1051 struct BindingDiagnosticTrap {
1052   Sema &S;
1053   DiagnosticErrorTrap Trap;
1054   BindingDecl *BD;
1055 
1056   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1057       : S(S), Trap(S.Diags), BD(BD) {}
1058   ~BindingDiagnosticTrap() {
1059     if (Trap.hasErrorOccurred())
1060       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1061   }
1062 };
1063 }
1064 
1065 static bool checkTupleLikeDecomposition(Sema &S,
1066                                         ArrayRef<BindingDecl *> Bindings,
1067                                         VarDecl *Src, QualType DecompType,
1068                                         llvm::APSInt TupleSize) {
1069   if ((int64_t)Bindings.size() != TupleSize) {
1070     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1071         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1072         << (TupleSize < Bindings.size());
1073     return true;
1074   }
1075 
1076   if (Bindings.empty())
1077     return false;
1078 
1079   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1080 
1081   // [dcl.decomp]p3:
1082   //   The unqualified-id get is looked up in the scope of E by class member
1083   //   access lookup
1084   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1085   bool UseMemberGet = false;
1086   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1087     if (auto *RD = DecompType->getAsCXXRecordDecl())
1088       S.LookupQualifiedName(MemberGet, RD);
1089     if (MemberGet.isAmbiguous())
1090       return true;
1091     UseMemberGet = !MemberGet.empty();
1092     S.FilterAcceptableTemplateNames(MemberGet);
1093   }
1094 
1095   unsigned I = 0;
1096   for (auto *B : Bindings) {
1097     BindingDiagnosticTrap Trap(S, B);
1098     SourceLocation Loc = B->getLocation();
1099 
1100     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1101     if (E.isInvalid())
1102       return true;
1103 
1104     //   e is an lvalue if the type of the entity is an lvalue reference and
1105     //   an xvalue otherwise
1106     if (!Src->getType()->isLValueReferenceType())
1107       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1108                                    E.get(), nullptr, VK_XValue);
1109 
1110     TemplateArgumentListInfo Args(Loc, Loc);
1111     Args.addArgument(
1112         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1113 
1114     if (UseMemberGet) {
1115       //   if [lookup of member get] finds at least one declaration, the
1116       //   initializer is e.get<i-1>().
1117       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1118                                      CXXScopeSpec(), SourceLocation(), nullptr,
1119                                      MemberGet, &Args, nullptr);
1120       if (E.isInvalid())
1121         return true;
1122 
1123       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1124     } else {
1125       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1126       //   in the associated namespaces.
1127       Expr *Get = UnresolvedLookupExpr::Create(
1128           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1129           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1130           UnresolvedSetIterator(), UnresolvedSetIterator());
1131 
1132       Expr *Arg = E.get();
1133       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1134     }
1135     if (E.isInvalid())
1136       return true;
1137     Expr *Init = E.get();
1138 
1139     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1140     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1141     if (T.isNull())
1142       return true;
1143 
1144     //   each vi is a variable of type "reference to T" initialized with the
1145     //   initializer, where the reference is an lvalue reference if the
1146     //   initializer is an lvalue and an rvalue reference otherwise
1147     QualType RefType =
1148         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1149     if (RefType.isNull())
1150       return true;
1151     auto *RefVD = VarDecl::Create(
1152         S.Context, Src->getDeclContext(), Loc, Loc,
1153         B->getDeclName().getAsIdentifierInfo(), RefType,
1154         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1155     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1156     RefVD->setTSCSpec(Src->getTSCSpec());
1157     RefVD->setImplicit();
1158     if (Src->isInlineSpecified())
1159       RefVD->setInlineSpecified();
1160     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1161 
1162     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1163     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1164     InitializationSequence Seq(S, Entity, Kind, Init);
1165     E = Seq.Perform(S, Entity, Kind, Init);
1166     if (E.isInvalid())
1167       return true;
1168     E = S.ActOnFinishFullExpr(E.get(), Loc);
1169     if (E.isInvalid())
1170       return true;
1171     RefVD->setInit(E.get());
1172     RefVD->checkInitIsICE();
1173 
1174     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1175                                    DeclarationNameInfo(B->getDeclName(), Loc),
1176                                    RefVD);
1177     if (E.isInvalid())
1178       return true;
1179 
1180     B->setBinding(T, E.get());
1181     I++;
1182   }
1183 
1184   return false;
1185 }
1186 
1187 /// Find the base class to decompose in a built-in decomposition of a class type.
1188 /// This base class search is, unfortunately, not quite like any other that we
1189 /// perform anywhere else in C++.
1190 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1191                                                       SourceLocation Loc,
1192                                                       const CXXRecordDecl *RD,
1193                                                       CXXCastPath &BasePath) {
1194   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1195                           CXXBasePath &Path) {
1196     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1197   };
1198 
1199   const CXXRecordDecl *ClassWithFields = nullptr;
1200   if (RD->hasDirectFields())
1201     // [dcl.decomp]p4:
1202     //   Otherwise, all of E's non-static data members shall be public direct
1203     //   members of E ...
1204     ClassWithFields = RD;
1205   else {
1206     //   ... or of ...
1207     CXXBasePaths Paths;
1208     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1209     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1210       // If no classes have fields, just decompose RD itself. (This will work
1211       // if and only if zero bindings were provided.)
1212       return RD;
1213     }
1214 
1215     CXXBasePath *BestPath = nullptr;
1216     for (auto &P : Paths) {
1217       if (!BestPath)
1218         BestPath = &P;
1219       else if (!S.Context.hasSameType(P.back().Base->getType(),
1220                                       BestPath->back().Base->getType())) {
1221         //   ... the same ...
1222         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1223           << false << RD << BestPath->back().Base->getType()
1224           << P.back().Base->getType();
1225         return nullptr;
1226       } else if (P.Access < BestPath->Access) {
1227         BestPath = &P;
1228       }
1229     }
1230 
1231     //   ... unambiguous ...
1232     QualType BaseType = BestPath->back().Base->getType();
1233     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1234       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1235         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1236       return nullptr;
1237     }
1238 
1239     //   ... public base class of E.
1240     if (BestPath->Access != AS_public) {
1241       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1242         << RD << BaseType;
1243       for (auto &BS : *BestPath) {
1244         if (BS.Base->getAccessSpecifier() != AS_public) {
1245           S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1246             << (BS.Base->getAccessSpecifier() == AS_protected)
1247             << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1248           break;
1249         }
1250       }
1251       return nullptr;
1252     }
1253 
1254     ClassWithFields = BaseType->getAsCXXRecordDecl();
1255     S.BuildBasePathArray(Paths, BasePath);
1256   }
1257 
1258   // The above search did not check whether the selected class itself has base
1259   // classes with fields, so check that now.
1260   CXXBasePaths Paths;
1261   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1262     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1263       << (ClassWithFields == RD) << RD << ClassWithFields
1264       << Paths.front().back().Base->getType();
1265     return nullptr;
1266   }
1267 
1268   return ClassWithFields;
1269 }
1270 
1271 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1272                                      ValueDecl *Src, QualType DecompType,
1273                                      const CXXRecordDecl *RD) {
1274   CXXCastPath BasePath;
1275   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1276   if (!RD)
1277     return true;
1278   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1279                                                  DecompType.getQualifiers());
1280 
1281   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1282     unsigned NumFields = std::distance(RD->field_begin(), RD->field_end());
1283     assert(Bindings.size() != NumFields);
1284     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1285         << DecompType << (unsigned)Bindings.size() << NumFields
1286         << (NumFields < Bindings.size());
1287     return true;
1288   };
1289 
1290   //   all of E's non-static data members shall be public [...] members,
1291   //   E shall not have an anonymous union member, ...
1292   unsigned I = 0;
1293   for (auto *FD : RD->fields()) {
1294     if (FD->isUnnamedBitfield())
1295       continue;
1296 
1297     if (FD->isAnonymousStructOrUnion()) {
1298       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1299         << DecompType << FD->getType()->isUnionType();
1300       S.Diag(FD->getLocation(), diag::note_declared_at);
1301       return true;
1302     }
1303 
1304     // We have a real field to bind.
1305     if (I >= Bindings.size())
1306       return DiagnoseBadNumberOfBindings();
1307     auto *B = Bindings[I++];
1308 
1309     SourceLocation Loc = B->getLocation();
1310     if (FD->getAccess() != AS_public) {
1311       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1312 
1313       // Determine whether the access specifier was explicit.
1314       bool Implicit = true;
1315       for (const auto *D : RD->decls()) {
1316         if (declaresSameEntity(D, FD))
1317           break;
1318         if (isa<AccessSpecDecl>(D)) {
1319           Implicit = false;
1320           break;
1321         }
1322       }
1323 
1324       S.Diag(FD->getLocation(), diag::note_access_natural)
1325         << (FD->getAccess() == AS_protected) << Implicit;
1326       return true;
1327     }
1328 
1329     // Initialize the binding to Src.FD.
1330     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1331     if (E.isInvalid())
1332       return true;
1333     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1334                             VK_LValue, &BasePath);
1335     if (E.isInvalid())
1336       return true;
1337     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1338                                   CXXScopeSpec(), FD,
1339                                   DeclAccessPair::make(FD, FD->getAccess()),
1340                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1341     if (E.isInvalid())
1342       return true;
1343 
1344     // If the type of the member is T, the referenced type is cv T, where cv is
1345     // the cv-qualification of the decomposition expression.
1346     //
1347     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1348     // 'const' to the type of the field.
1349     Qualifiers Q = DecompType.getQualifiers();
1350     if (FD->isMutable())
1351       Q.removeConst();
1352     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1353   }
1354 
1355   if (I != Bindings.size())
1356     return DiagnoseBadNumberOfBindings();
1357 
1358   return false;
1359 }
1360 
1361 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1362   QualType DecompType = DD->getType();
1363 
1364   // If the type of the decomposition is dependent, then so is the type of
1365   // each binding.
1366   if (DecompType->isDependentType()) {
1367     for (auto *B : DD->bindings())
1368       B->setType(Context.DependentTy);
1369     return;
1370   }
1371 
1372   DecompType = DecompType.getNonReferenceType();
1373   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1374 
1375   // C++1z [dcl.decomp]/2:
1376   //   If E is an array type [...]
1377   // As an extension, we also support decomposition of built-in complex and
1378   // vector types.
1379   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1380     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1381       DD->setInvalidDecl();
1382     return;
1383   }
1384   if (auto *VT = DecompType->getAs<VectorType>()) {
1385     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1386       DD->setInvalidDecl();
1387     return;
1388   }
1389   if (auto *CT = DecompType->getAs<ComplexType>()) {
1390     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1391       DD->setInvalidDecl();
1392     return;
1393   }
1394 
1395   // C++1z [dcl.decomp]/3:
1396   //   if the expression std::tuple_size<E>::value is a well-formed integral
1397   //   constant expression, [...]
1398   llvm::APSInt TupleSize(32);
1399   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1400   case IsTupleLike::Error:
1401     DD->setInvalidDecl();
1402     return;
1403 
1404   case IsTupleLike::TupleLike:
1405     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1406       DD->setInvalidDecl();
1407     return;
1408 
1409   case IsTupleLike::NotTupleLike:
1410     break;
1411   }
1412 
1413   // C++1z [dcl.dcl]/8:
1414   //   [E shall be of array or non-union class type]
1415   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1416   if (!RD || RD->isUnion()) {
1417     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1418         << DD << !RD << DecompType;
1419     DD->setInvalidDecl();
1420     return;
1421   }
1422 
1423   // C++1z [dcl.decomp]/4:
1424   //   all of E's non-static data members shall be [...] direct members of
1425   //   E or of the same unambiguous public base class of E, ...
1426   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1427     DD->setInvalidDecl();
1428 }
1429 
1430 /// \brief Merge the exception specifications of two variable declarations.
1431 ///
1432 /// This is called when there's a redeclaration of a VarDecl. The function
1433 /// checks if the redeclaration might have an exception specification and
1434 /// validates compatibility and merges the specs if necessary.
1435 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1436   // Shortcut if exceptions are disabled.
1437   if (!getLangOpts().CXXExceptions)
1438     return;
1439 
1440   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1441          "Should only be called if types are otherwise the same.");
1442 
1443   QualType NewType = New->getType();
1444   QualType OldType = Old->getType();
1445 
1446   // We're only interested in pointers and references to functions, as well
1447   // as pointers to member functions.
1448   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1449     NewType = R->getPointeeType();
1450     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1451   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1452     NewType = P->getPointeeType();
1453     OldType = OldType->getAs<PointerType>()->getPointeeType();
1454   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1455     NewType = M->getPointeeType();
1456     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1457   }
1458 
1459   if (!NewType->isFunctionProtoType())
1460     return;
1461 
1462   // There's lots of special cases for functions. For function pointers, system
1463   // libraries are hopefully not as broken so that we don't need these
1464   // workarounds.
1465   if (CheckEquivalentExceptionSpec(
1466         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1467         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1468     New->setInvalidDecl();
1469   }
1470 }
1471 
1472 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1473 /// function declaration are well-formed according to C++
1474 /// [dcl.fct.default].
1475 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1476   unsigned NumParams = FD->getNumParams();
1477   unsigned p;
1478 
1479   // Find first parameter with a default argument
1480   for (p = 0; p < NumParams; ++p) {
1481     ParmVarDecl *Param = FD->getParamDecl(p);
1482     if (Param->hasDefaultArg())
1483       break;
1484   }
1485 
1486   // C++11 [dcl.fct.default]p4:
1487   //   In a given function declaration, each parameter subsequent to a parameter
1488   //   with a default argument shall have a default argument supplied in this or
1489   //   a previous declaration or shall be a function parameter pack. A default
1490   //   argument shall not be redefined by a later declaration (not even to the
1491   //   same value).
1492   unsigned LastMissingDefaultArg = 0;
1493   for (; p < NumParams; ++p) {
1494     ParmVarDecl *Param = FD->getParamDecl(p);
1495     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1496       if (Param->isInvalidDecl())
1497         /* We already complained about this parameter. */;
1498       else if (Param->getIdentifier())
1499         Diag(Param->getLocation(),
1500              diag::err_param_default_argument_missing_name)
1501           << Param->getIdentifier();
1502       else
1503         Diag(Param->getLocation(),
1504              diag::err_param_default_argument_missing);
1505 
1506       LastMissingDefaultArg = p;
1507     }
1508   }
1509 
1510   if (LastMissingDefaultArg > 0) {
1511     // Some default arguments were missing. Clear out all of the
1512     // default arguments up to (and including) the last missing
1513     // default argument, so that we leave the function parameters
1514     // in a semantically valid state.
1515     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1516       ParmVarDecl *Param = FD->getParamDecl(p);
1517       if (Param->hasDefaultArg()) {
1518         Param->setDefaultArg(nullptr);
1519       }
1520     }
1521   }
1522 }
1523 
1524 // CheckConstexprParameterTypes - Check whether a function's parameter types
1525 // are all literal types. If so, return true. If not, produce a suitable
1526 // diagnostic and return false.
1527 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1528                                          const FunctionDecl *FD) {
1529   unsigned ArgIndex = 0;
1530   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1531   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1532                                               e = FT->param_type_end();
1533        i != e; ++i, ++ArgIndex) {
1534     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1535     SourceLocation ParamLoc = PD->getLocation();
1536     if (!(*i)->isDependentType() &&
1537         SemaRef.RequireLiteralType(ParamLoc, *i,
1538                                    diag::err_constexpr_non_literal_param,
1539                                    ArgIndex+1, PD->getSourceRange(),
1540                                    isa<CXXConstructorDecl>(FD)))
1541       return false;
1542   }
1543   return true;
1544 }
1545 
1546 /// \brief Get diagnostic %select index for tag kind for
1547 /// record diagnostic message.
1548 /// WARNING: Indexes apply to particular diagnostics only!
1549 ///
1550 /// \returns diagnostic %select index.
1551 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1552   switch (Tag) {
1553   case TTK_Struct: return 0;
1554   case TTK_Interface: return 1;
1555   case TTK_Class:  return 2;
1556   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1557   }
1558 }
1559 
1560 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1561 // the requirements of a constexpr function definition or a constexpr
1562 // constructor definition. If so, return true. If not, produce appropriate
1563 // diagnostics and return false.
1564 //
1565 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1566 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1567   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1568   if (MD && MD->isInstance()) {
1569     // C++11 [dcl.constexpr]p4:
1570     //  The definition of a constexpr constructor shall satisfy the following
1571     //  constraints:
1572     //  - the class shall not have any virtual base classes;
1573     const CXXRecordDecl *RD = MD->getParent();
1574     if (RD->getNumVBases()) {
1575       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1576         << isa<CXXConstructorDecl>(NewFD)
1577         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1578       for (const auto &I : RD->vbases())
1579         Diag(I.getLocStart(),
1580              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1581       return false;
1582     }
1583   }
1584 
1585   if (!isa<CXXConstructorDecl>(NewFD)) {
1586     // C++11 [dcl.constexpr]p3:
1587     //  The definition of a constexpr function shall satisfy the following
1588     //  constraints:
1589     // - it shall not be virtual;
1590     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1591     if (Method && Method->isVirtual()) {
1592       Method = Method->getCanonicalDecl();
1593       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1594 
1595       // If it's not obvious why this function is virtual, find an overridden
1596       // function which uses the 'virtual' keyword.
1597       const CXXMethodDecl *WrittenVirtual = Method;
1598       while (!WrittenVirtual->isVirtualAsWritten())
1599         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1600       if (WrittenVirtual != Method)
1601         Diag(WrittenVirtual->getLocation(),
1602              diag::note_overridden_virtual_function);
1603       return false;
1604     }
1605 
1606     // - its return type shall be a literal type;
1607     QualType RT = NewFD->getReturnType();
1608     if (!RT->isDependentType() &&
1609         RequireLiteralType(NewFD->getLocation(), RT,
1610                            diag::err_constexpr_non_literal_return))
1611       return false;
1612   }
1613 
1614   // - each of its parameter types shall be a literal type;
1615   if (!CheckConstexprParameterTypes(*this, NewFD))
1616     return false;
1617 
1618   return true;
1619 }
1620 
1621 /// Check the given declaration statement is legal within a constexpr function
1622 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1623 ///
1624 /// \return true if the body is OK (maybe only as an extension), false if we
1625 ///         have diagnosed a problem.
1626 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1627                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1628   // C++11 [dcl.constexpr]p3 and p4:
1629   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1630   //  contain only
1631   for (const auto *DclIt : DS->decls()) {
1632     switch (DclIt->getKind()) {
1633     case Decl::StaticAssert:
1634     case Decl::Using:
1635     case Decl::UsingShadow:
1636     case Decl::UsingDirective:
1637     case Decl::UnresolvedUsingTypename:
1638     case Decl::UnresolvedUsingValue:
1639       //   - static_assert-declarations
1640       //   - using-declarations,
1641       //   - using-directives,
1642       continue;
1643 
1644     case Decl::Typedef:
1645     case Decl::TypeAlias: {
1646       //   - typedef declarations and alias-declarations that do not define
1647       //     classes or enumerations,
1648       const auto *TN = cast<TypedefNameDecl>(DclIt);
1649       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1650         // Don't allow variably-modified types in constexpr functions.
1651         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1652         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1653           << TL.getSourceRange() << TL.getType()
1654           << isa<CXXConstructorDecl>(Dcl);
1655         return false;
1656       }
1657       continue;
1658     }
1659 
1660     case Decl::Enum:
1661     case Decl::CXXRecord:
1662       // C++1y allows types to be defined, not just declared.
1663       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1664         SemaRef.Diag(DS->getLocStart(),
1665                      SemaRef.getLangOpts().CPlusPlus14
1666                        ? diag::warn_cxx11_compat_constexpr_type_definition
1667                        : diag::ext_constexpr_type_definition)
1668           << isa<CXXConstructorDecl>(Dcl);
1669       continue;
1670 
1671     case Decl::EnumConstant:
1672     case Decl::IndirectField:
1673     case Decl::ParmVar:
1674       // These can only appear with other declarations which are banned in
1675       // C++11 and permitted in C++1y, so ignore them.
1676       continue;
1677 
1678     case Decl::Var:
1679     case Decl::Decomposition: {
1680       // C++1y [dcl.constexpr]p3 allows anything except:
1681       //   a definition of a variable of non-literal type or of static or
1682       //   thread storage duration or for which no initialization is performed.
1683       const auto *VD = cast<VarDecl>(DclIt);
1684       if (VD->isThisDeclarationADefinition()) {
1685         if (VD->isStaticLocal()) {
1686           SemaRef.Diag(VD->getLocation(),
1687                        diag::err_constexpr_local_var_static)
1688             << isa<CXXConstructorDecl>(Dcl)
1689             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1690           return false;
1691         }
1692         if (!VD->getType()->isDependentType() &&
1693             SemaRef.RequireLiteralType(
1694               VD->getLocation(), VD->getType(),
1695               diag::err_constexpr_local_var_non_literal_type,
1696               isa<CXXConstructorDecl>(Dcl)))
1697           return false;
1698         if (!VD->getType()->isDependentType() &&
1699             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1700           SemaRef.Diag(VD->getLocation(),
1701                        diag::err_constexpr_local_var_no_init)
1702             << isa<CXXConstructorDecl>(Dcl);
1703           return false;
1704         }
1705       }
1706       SemaRef.Diag(VD->getLocation(),
1707                    SemaRef.getLangOpts().CPlusPlus14
1708                     ? diag::warn_cxx11_compat_constexpr_local_var
1709                     : diag::ext_constexpr_local_var)
1710         << isa<CXXConstructorDecl>(Dcl);
1711       continue;
1712     }
1713 
1714     case Decl::NamespaceAlias:
1715     case Decl::Function:
1716       // These are disallowed in C++11 and permitted in C++1y. Allow them
1717       // everywhere as an extension.
1718       if (!Cxx1yLoc.isValid())
1719         Cxx1yLoc = DS->getLocStart();
1720       continue;
1721 
1722     default:
1723       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1724         << isa<CXXConstructorDecl>(Dcl);
1725       return false;
1726     }
1727   }
1728 
1729   return true;
1730 }
1731 
1732 /// Check that the given field is initialized within a constexpr constructor.
1733 ///
1734 /// \param Dcl The constexpr constructor being checked.
1735 /// \param Field The field being checked. This may be a member of an anonymous
1736 ///        struct or union nested within the class being checked.
1737 /// \param Inits All declarations, including anonymous struct/union members and
1738 ///        indirect members, for which any initialization was provided.
1739 /// \param Diagnosed Set to true if an error is produced.
1740 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1741                                           const FunctionDecl *Dcl,
1742                                           FieldDecl *Field,
1743                                           llvm::SmallSet<Decl*, 16> &Inits,
1744                                           bool &Diagnosed) {
1745   if (Field->isInvalidDecl())
1746     return;
1747 
1748   if (Field->isUnnamedBitfield())
1749     return;
1750 
1751   // Anonymous unions with no variant members and empty anonymous structs do not
1752   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1753   // indirect fields don't need initializing.
1754   if (Field->isAnonymousStructOrUnion() &&
1755       (Field->getType()->isUnionType()
1756            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1757            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1758     return;
1759 
1760   if (!Inits.count(Field)) {
1761     if (!Diagnosed) {
1762       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1763       Diagnosed = true;
1764     }
1765     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1766   } else if (Field->isAnonymousStructOrUnion()) {
1767     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1768     for (auto *I : RD->fields())
1769       // If an anonymous union contains an anonymous struct of which any member
1770       // is initialized, all members must be initialized.
1771       if (!RD->isUnion() || Inits.count(I))
1772         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1773   }
1774 }
1775 
1776 /// Check the provided statement is allowed in a constexpr function
1777 /// definition.
1778 static bool
1779 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1780                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1781                            SourceLocation &Cxx1yLoc) {
1782   // - its function-body shall be [...] a compound-statement that contains only
1783   switch (S->getStmtClass()) {
1784   case Stmt::NullStmtClass:
1785     //   - null statements,
1786     return true;
1787 
1788   case Stmt::DeclStmtClass:
1789     //   - static_assert-declarations
1790     //   - using-declarations,
1791     //   - using-directives,
1792     //   - typedef declarations and alias-declarations that do not define
1793     //     classes or enumerations,
1794     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1795       return false;
1796     return true;
1797 
1798   case Stmt::ReturnStmtClass:
1799     //   - and exactly one return statement;
1800     if (isa<CXXConstructorDecl>(Dcl)) {
1801       // C++1y allows return statements in constexpr constructors.
1802       if (!Cxx1yLoc.isValid())
1803         Cxx1yLoc = S->getLocStart();
1804       return true;
1805     }
1806 
1807     ReturnStmts.push_back(S->getLocStart());
1808     return true;
1809 
1810   case Stmt::CompoundStmtClass: {
1811     // C++1y allows compound-statements.
1812     if (!Cxx1yLoc.isValid())
1813       Cxx1yLoc = S->getLocStart();
1814 
1815     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1816     for (auto *BodyIt : CompStmt->body()) {
1817       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1818                                       Cxx1yLoc))
1819         return false;
1820     }
1821     return true;
1822   }
1823 
1824   case Stmt::AttributedStmtClass:
1825     if (!Cxx1yLoc.isValid())
1826       Cxx1yLoc = S->getLocStart();
1827     return true;
1828 
1829   case Stmt::IfStmtClass: {
1830     // C++1y allows if-statements.
1831     if (!Cxx1yLoc.isValid())
1832       Cxx1yLoc = S->getLocStart();
1833 
1834     IfStmt *If = cast<IfStmt>(S);
1835     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1836                                     Cxx1yLoc))
1837       return false;
1838     if (If->getElse() &&
1839         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1840                                     Cxx1yLoc))
1841       return false;
1842     return true;
1843   }
1844 
1845   case Stmt::WhileStmtClass:
1846   case Stmt::DoStmtClass:
1847   case Stmt::ForStmtClass:
1848   case Stmt::CXXForRangeStmtClass:
1849   case Stmt::ContinueStmtClass:
1850     // C++1y allows all of these. We don't allow them as extensions in C++11,
1851     // because they don't make sense without variable mutation.
1852     if (!SemaRef.getLangOpts().CPlusPlus14)
1853       break;
1854     if (!Cxx1yLoc.isValid())
1855       Cxx1yLoc = S->getLocStart();
1856     for (Stmt *SubStmt : S->children())
1857       if (SubStmt &&
1858           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1859                                       Cxx1yLoc))
1860         return false;
1861     return true;
1862 
1863   case Stmt::SwitchStmtClass:
1864   case Stmt::CaseStmtClass:
1865   case Stmt::DefaultStmtClass:
1866   case Stmt::BreakStmtClass:
1867     // C++1y allows switch-statements, and since they don't need variable
1868     // mutation, we can reasonably allow them in C++11 as an extension.
1869     if (!Cxx1yLoc.isValid())
1870       Cxx1yLoc = S->getLocStart();
1871     for (Stmt *SubStmt : S->children())
1872       if (SubStmt &&
1873           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1874                                       Cxx1yLoc))
1875         return false;
1876     return true;
1877 
1878   default:
1879     if (!isa<Expr>(S))
1880       break;
1881 
1882     // C++1y allows expression-statements.
1883     if (!Cxx1yLoc.isValid())
1884       Cxx1yLoc = S->getLocStart();
1885     return true;
1886   }
1887 
1888   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1889     << isa<CXXConstructorDecl>(Dcl);
1890   return false;
1891 }
1892 
1893 /// Check the body for the given constexpr function declaration only contains
1894 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1895 ///
1896 /// \return true if the body is OK, false if we have diagnosed a problem.
1897 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1898   if (isa<CXXTryStmt>(Body)) {
1899     // C++11 [dcl.constexpr]p3:
1900     //  The definition of a constexpr function shall satisfy the following
1901     //  constraints: [...]
1902     // - its function-body shall be = delete, = default, or a
1903     //   compound-statement
1904     //
1905     // C++11 [dcl.constexpr]p4:
1906     //  In the definition of a constexpr constructor, [...]
1907     // - its function-body shall not be a function-try-block;
1908     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1909       << isa<CXXConstructorDecl>(Dcl);
1910     return false;
1911   }
1912 
1913   SmallVector<SourceLocation, 4> ReturnStmts;
1914 
1915   // - its function-body shall be [...] a compound-statement that contains only
1916   //   [... list of cases ...]
1917   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1918   SourceLocation Cxx1yLoc;
1919   for (auto *BodyIt : CompBody->body()) {
1920     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1921       return false;
1922   }
1923 
1924   if (Cxx1yLoc.isValid())
1925     Diag(Cxx1yLoc,
1926          getLangOpts().CPlusPlus14
1927            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1928            : diag::ext_constexpr_body_invalid_stmt)
1929       << isa<CXXConstructorDecl>(Dcl);
1930 
1931   if (const CXXConstructorDecl *Constructor
1932         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1933     const CXXRecordDecl *RD = Constructor->getParent();
1934     // DR1359:
1935     // - every non-variant non-static data member and base class sub-object
1936     //   shall be initialized;
1937     // DR1460:
1938     // - if the class is a union having variant members, exactly one of them
1939     //   shall be initialized;
1940     if (RD->isUnion()) {
1941       if (Constructor->getNumCtorInitializers() == 0 &&
1942           RD->hasVariantMembers()) {
1943         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1944         return false;
1945       }
1946     } else if (!Constructor->isDependentContext() &&
1947                !Constructor->isDelegatingConstructor()) {
1948       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1949 
1950       // Skip detailed checking if we have enough initializers, and we would
1951       // allow at most one initializer per member.
1952       bool AnyAnonStructUnionMembers = false;
1953       unsigned Fields = 0;
1954       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1955            E = RD->field_end(); I != E; ++I, ++Fields) {
1956         if (I->isAnonymousStructOrUnion()) {
1957           AnyAnonStructUnionMembers = true;
1958           break;
1959         }
1960       }
1961       // DR1460:
1962       // - if the class is a union-like class, but is not a union, for each of
1963       //   its anonymous union members having variant members, exactly one of
1964       //   them shall be initialized;
1965       if (AnyAnonStructUnionMembers ||
1966           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1967         // Check initialization of non-static data members. Base classes are
1968         // always initialized so do not need to be checked. Dependent bases
1969         // might not have initializers in the member initializer list.
1970         llvm::SmallSet<Decl*, 16> Inits;
1971         for (const auto *I: Constructor->inits()) {
1972           if (FieldDecl *FD = I->getMember())
1973             Inits.insert(FD);
1974           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1975             Inits.insert(ID->chain_begin(), ID->chain_end());
1976         }
1977 
1978         bool Diagnosed = false;
1979         for (auto *I : RD->fields())
1980           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1981         if (Diagnosed)
1982           return false;
1983       }
1984     }
1985   } else {
1986     if (ReturnStmts.empty()) {
1987       // C++1y doesn't require constexpr functions to contain a 'return'
1988       // statement. We still do, unless the return type might be void, because
1989       // otherwise if there's no return statement, the function cannot
1990       // be used in a core constant expression.
1991       bool OK = getLangOpts().CPlusPlus14 &&
1992                 (Dcl->getReturnType()->isVoidType() ||
1993                  Dcl->getReturnType()->isDependentType());
1994       Diag(Dcl->getLocation(),
1995            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1996               : diag::err_constexpr_body_no_return);
1997       if (!OK)
1998         return false;
1999     } else if (ReturnStmts.size() > 1) {
2000       Diag(ReturnStmts.back(),
2001            getLangOpts().CPlusPlus14
2002              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2003              : diag::ext_constexpr_body_multiple_return);
2004       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2005         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2006     }
2007   }
2008 
2009   // C++11 [dcl.constexpr]p5:
2010   //   if no function argument values exist such that the function invocation
2011   //   substitution would produce a constant expression, the program is
2012   //   ill-formed; no diagnostic required.
2013   // C++11 [dcl.constexpr]p3:
2014   //   - every constructor call and implicit conversion used in initializing the
2015   //     return value shall be one of those allowed in a constant expression.
2016   // C++11 [dcl.constexpr]p4:
2017   //   - every constructor involved in initializing non-static data members and
2018   //     base class sub-objects shall be a constexpr constructor.
2019   SmallVector<PartialDiagnosticAt, 8> Diags;
2020   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2021     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2022       << isa<CXXConstructorDecl>(Dcl);
2023     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2024       Diag(Diags[I].first, Diags[I].second);
2025     // Don't return false here: we allow this for compatibility in
2026     // system headers.
2027   }
2028 
2029   return true;
2030 }
2031 
2032 /// isCurrentClassName - Determine whether the identifier II is the
2033 /// name of the class type currently being defined. In the case of
2034 /// nested classes, this will only return true if II is the name of
2035 /// the innermost class.
2036 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2037                               const CXXScopeSpec *SS) {
2038   assert(getLangOpts().CPlusPlus && "No class names in C!");
2039 
2040   CXXRecordDecl *CurDecl;
2041   if (SS && SS->isSet() && !SS->isInvalid()) {
2042     DeclContext *DC = computeDeclContext(*SS, true);
2043     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2044   } else
2045     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2046 
2047   if (CurDecl && CurDecl->getIdentifier())
2048     return &II == CurDecl->getIdentifier();
2049   return false;
2050 }
2051 
2052 /// \brief Determine whether the identifier II is a typo for the name of
2053 /// the class type currently being defined. If so, update it to the identifier
2054 /// that should have been used.
2055 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2056   assert(getLangOpts().CPlusPlus && "No class names in C!");
2057 
2058   if (!getLangOpts().SpellChecking)
2059     return false;
2060 
2061   CXXRecordDecl *CurDecl;
2062   if (SS && SS->isSet() && !SS->isInvalid()) {
2063     DeclContext *DC = computeDeclContext(*SS, true);
2064     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2065   } else
2066     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2067 
2068   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2069       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2070           < II->getLength()) {
2071     II = CurDecl->getIdentifier();
2072     return true;
2073   }
2074 
2075   return false;
2076 }
2077 
2078 /// \brief Determine whether the given class is a base class of the given
2079 /// class, including looking at dependent bases.
2080 static bool findCircularInheritance(const CXXRecordDecl *Class,
2081                                     const CXXRecordDecl *Current) {
2082   SmallVector<const CXXRecordDecl*, 8> Queue;
2083 
2084   Class = Class->getCanonicalDecl();
2085   while (true) {
2086     for (const auto &I : Current->bases()) {
2087       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2088       if (!Base)
2089         continue;
2090 
2091       Base = Base->getDefinition();
2092       if (!Base)
2093         continue;
2094 
2095       if (Base->getCanonicalDecl() == Class)
2096         return true;
2097 
2098       Queue.push_back(Base);
2099     }
2100 
2101     if (Queue.empty())
2102       return false;
2103 
2104     Current = Queue.pop_back_val();
2105   }
2106 
2107   return false;
2108 }
2109 
2110 /// \brief Check the validity of a C++ base class specifier.
2111 ///
2112 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2113 /// and returns NULL otherwise.
2114 CXXBaseSpecifier *
2115 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2116                          SourceRange SpecifierRange,
2117                          bool Virtual, AccessSpecifier Access,
2118                          TypeSourceInfo *TInfo,
2119                          SourceLocation EllipsisLoc) {
2120   QualType BaseType = TInfo->getType();
2121 
2122   // C++ [class.union]p1:
2123   //   A union shall not have base classes.
2124   if (Class->isUnion()) {
2125     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2126       << SpecifierRange;
2127     return nullptr;
2128   }
2129 
2130   if (EllipsisLoc.isValid() &&
2131       !TInfo->getType()->containsUnexpandedParameterPack()) {
2132     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2133       << TInfo->getTypeLoc().getSourceRange();
2134     EllipsisLoc = SourceLocation();
2135   }
2136 
2137   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2138 
2139   if (BaseType->isDependentType()) {
2140     // Make sure that we don't have circular inheritance among our dependent
2141     // bases. For non-dependent bases, the check for completeness below handles
2142     // this.
2143     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2144       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2145           ((BaseDecl = BaseDecl->getDefinition()) &&
2146            findCircularInheritance(Class, BaseDecl))) {
2147         Diag(BaseLoc, diag::err_circular_inheritance)
2148           << BaseType << Context.getTypeDeclType(Class);
2149 
2150         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2151           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2152             << BaseType;
2153 
2154         return nullptr;
2155       }
2156     }
2157 
2158     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2159                                           Class->getTagKind() == TTK_Class,
2160                                           Access, TInfo, EllipsisLoc);
2161   }
2162 
2163   // Base specifiers must be record types.
2164   if (!BaseType->isRecordType()) {
2165     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2166     return nullptr;
2167   }
2168 
2169   // C++ [class.union]p1:
2170   //   A union shall not be used as a base class.
2171   if (BaseType->isUnionType()) {
2172     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2173     return nullptr;
2174   }
2175 
2176   // For the MS ABI, propagate DLL attributes to base class templates.
2177   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2178     if (Attr *ClassAttr = getDLLAttr(Class)) {
2179       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2180               BaseType->getAsCXXRecordDecl())) {
2181         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2182                                             BaseLoc);
2183       }
2184     }
2185   }
2186 
2187   // C++ [class.derived]p2:
2188   //   The class-name in a base-specifier shall not be an incompletely
2189   //   defined class.
2190   if (RequireCompleteType(BaseLoc, BaseType,
2191                           diag::err_incomplete_base_class, SpecifierRange)) {
2192     Class->setInvalidDecl();
2193     return nullptr;
2194   }
2195 
2196   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2197   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2198   assert(BaseDecl && "Record type has no declaration");
2199   BaseDecl = BaseDecl->getDefinition();
2200   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2201   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2202   assert(CXXBaseDecl && "Base type is not a C++ type");
2203 
2204   // A class which contains a flexible array member is not suitable for use as a
2205   // base class:
2206   //   - If the layout determines that a base comes before another base,
2207   //     the flexible array member would index into the subsequent base.
2208   //   - If the layout determines that base comes before the derived class,
2209   //     the flexible array member would index into the derived class.
2210   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2211     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2212       << CXXBaseDecl->getDeclName();
2213     return nullptr;
2214   }
2215 
2216   // C++ [class]p3:
2217   //   If a class is marked final and it appears as a base-type-specifier in
2218   //   base-clause, the program is ill-formed.
2219   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2220     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2221       << CXXBaseDecl->getDeclName()
2222       << FA->isSpelledAsSealed();
2223     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2224         << CXXBaseDecl->getDeclName() << FA->getRange();
2225     return nullptr;
2226   }
2227 
2228   if (BaseDecl->isInvalidDecl())
2229     Class->setInvalidDecl();
2230 
2231   // Create the base specifier.
2232   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2233                                         Class->getTagKind() == TTK_Class,
2234                                         Access, TInfo, EllipsisLoc);
2235 }
2236 
2237 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2238 /// one entry in the base class list of a class specifier, for
2239 /// example:
2240 ///    class foo : public bar, virtual private baz {
2241 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2242 BaseResult
2243 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2244                          ParsedAttributes &Attributes,
2245                          bool Virtual, AccessSpecifier Access,
2246                          ParsedType basetype, SourceLocation BaseLoc,
2247                          SourceLocation EllipsisLoc) {
2248   if (!classdecl)
2249     return true;
2250 
2251   AdjustDeclIfTemplate(classdecl);
2252   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2253   if (!Class)
2254     return true;
2255 
2256   // We haven't yet attached the base specifiers.
2257   Class->setIsParsingBaseSpecifiers();
2258 
2259   // We do not support any C++11 attributes on base-specifiers yet.
2260   // Diagnose any attributes we see.
2261   if (!Attributes.empty()) {
2262     for (AttributeList *Attr = Attributes.getList(); Attr;
2263          Attr = Attr->getNext()) {
2264       if (Attr->isInvalid() ||
2265           Attr->getKind() == AttributeList::IgnoredAttribute)
2266         continue;
2267       Diag(Attr->getLoc(),
2268            Attr->getKind() == AttributeList::UnknownAttribute
2269              ? diag::warn_unknown_attribute_ignored
2270              : diag::err_base_specifier_attribute)
2271         << Attr->getName();
2272     }
2273   }
2274 
2275   TypeSourceInfo *TInfo = nullptr;
2276   GetTypeFromParser(basetype, &TInfo);
2277 
2278   if (EllipsisLoc.isInvalid() &&
2279       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2280                                       UPPC_BaseType))
2281     return true;
2282 
2283   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2284                                                       Virtual, Access, TInfo,
2285                                                       EllipsisLoc))
2286     return BaseSpec;
2287   else
2288     Class->setInvalidDecl();
2289 
2290   return true;
2291 }
2292 
2293 /// Use small set to collect indirect bases.  As this is only used
2294 /// locally, there's no need to abstract the small size parameter.
2295 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2296 
2297 /// \brief Recursively add the bases of Type.  Don't add Type itself.
2298 static void
2299 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2300                   const QualType &Type)
2301 {
2302   // Even though the incoming type is a base, it might not be
2303   // a class -- it could be a template parm, for instance.
2304   if (auto Rec = Type->getAs<RecordType>()) {
2305     auto Decl = Rec->getAsCXXRecordDecl();
2306 
2307     // Iterate over its bases.
2308     for (const auto &BaseSpec : Decl->bases()) {
2309       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2310         .getUnqualifiedType();
2311       if (Set.insert(Base).second)
2312         // If we've not already seen it, recurse.
2313         NoteIndirectBases(Context, Set, Base);
2314     }
2315   }
2316 }
2317 
2318 /// \brief Performs the actual work of attaching the given base class
2319 /// specifiers to a C++ class.
2320 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2321                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2322  if (Bases.empty())
2323     return false;
2324 
2325   // Used to keep track of which base types we have already seen, so
2326   // that we can properly diagnose redundant direct base types. Note
2327   // that the key is always the unqualified canonical type of the base
2328   // class.
2329   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2330 
2331   // Used to track indirect bases so we can see if a direct base is
2332   // ambiguous.
2333   IndirectBaseSet IndirectBaseTypes;
2334 
2335   // Copy non-redundant base specifiers into permanent storage.
2336   unsigned NumGoodBases = 0;
2337   bool Invalid = false;
2338   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2339     QualType NewBaseType
2340       = Context.getCanonicalType(Bases[idx]->getType());
2341     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2342 
2343     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2344     if (KnownBase) {
2345       // C++ [class.mi]p3:
2346       //   A class shall not be specified as a direct base class of a
2347       //   derived class more than once.
2348       Diag(Bases[idx]->getLocStart(),
2349            diag::err_duplicate_base_class)
2350         << KnownBase->getType()
2351         << Bases[idx]->getSourceRange();
2352 
2353       // Delete the duplicate base class specifier; we're going to
2354       // overwrite its pointer later.
2355       Context.Deallocate(Bases[idx]);
2356 
2357       Invalid = true;
2358     } else {
2359       // Okay, add this new base class.
2360       KnownBase = Bases[idx];
2361       Bases[NumGoodBases++] = Bases[idx];
2362 
2363       // Note this base's direct & indirect bases, if there could be ambiguity.
2364       if (Bases.size() > 1)
2365         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2366 
2367       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2368         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2369         if (Class->isInterface() &&
2370               (!RD->isInterface() ||
2371                KnownBase->getAccessSpecifier() != AS_public)) {
2372           // The Microsoft extension __interface does not permit bases that
2373           // are not themselves public interfaces.
2374           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2375             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2376             << RD->getSourceRange();
2377           Invalid = true;
2378         }
2379         if (RD->hasAttr<WeakAttr>())
2380           Class->addAttr(WeakAttr::CreateImplicit(Context));
2381       }
2382     }
2383   }
2384 
2385   // Attach the remaining base class specifiers to the derived class.
2386   Class->setBases(Bases.data(), NumGoodBases);
2387 
2388   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2389     // Check whether this direct base is inaccessible due to ambiguity.
2390     QualType BaseType = Bases[idx]->getType();
2391     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2392       .getUnqualifiedType();
2393 
2394     if (IndirectBaseTypes.count(CanonicalBase)) {
2395       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2396                          /*DetectVirtual=*/true);
2397       bool found
2398         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2399       assert(found);
2400       (void)found;
2401 
2402       if (Paths.isAmbiguous(CanonicalBase))
2403         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2404           << BaseType << getAmbiguousPathsDisplayString(Paths)
2405           << Bases[idx]->getSourceRange();
2406       else
2407         assert(Bases[idx]->isVirtual());
2408     }
2409 
2410     // Delete the base class specifier, since its data has been copied
2411     // into the CXXRecordDecl.
2412     Context.Deallocate(Bases[idx]);
2413   }
2414 
2415   return Invalid;
2416 }
2417 
2418 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2419 /// class, after checking whether there are any duplicate base
2420 /// classes.
2421 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2422                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2423   if (!ClassDecl || Bases.empty())
2424     return;
2425 
2426   AdjustDeclIfTemplate(ClassDecl);
2427   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2428 }
2429 
2430 /// \brief Determine whether the type \p Derived is a C++ class that is
2431 /// derived from the type \p Base.
2432 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2433   if (!getLangOpts().CPlusPlus)
2434     return false;
2435 
2436   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2437   if (!DerivedRD)
2438     return false;
2439 
2440   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2441   if (!BaseRD)
2442     return false;
2443 
2444   // If either the base or the derived type is invalid, don't try to
2445   // check whether one is derived from the other.
2446   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2447     return false;
2448 
2449   // FIXME: In a modules build, do we need the entire path to be visible for us
2450   // to be able to use the inheritance relationship?
2451   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2452     return false;
2453 
2454   return DerivedRD->isDerivedFrom(BaseRD);
2455 }
2456 
2457 /// \brief Determine whether the type \p Derived is a C++ class that is
2458 /// derived from the type \p Base.
2459 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2460                          CXXBasePaths &Paths) {
2461   if (!getLangOpts().CPlusPlus)
2462     return false;
2463 
2464   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2465   if (!DerivedRD)
2466     return false;
2467 
2468   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2469   if (!BaseRD)
2470     return false;
2471 
2472   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2473     return false;
2474 
2475   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2476 }
2477 
2478 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2479                               CXXCastPath &BasePathArray) {
2480   assert(BasePathArray.empty() && "Base path array must be empty!");
2481   assert(Paths.isRecordingPaths() && "Must record paths!");
2482 
2483   const CXXBasePath &Path = Paths.front();
2484 
2485   // We first go backward and check if we have a virtual base.
2486   // FIXME: It would be better if CXXBasePath had the base specifier for
2487   // the nearest virtual base.
2488   unsigned Start = 0;
2489   for (unsigned I = Path.size(); I != 0; --I) {
2490     if (Path[I - 1].Base->isVirtual()) {
2491       Start = I - 1;
2492       break;
2493     }
2494   }
2495 
2496   // Now add all bases.
2497   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2498     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2499 }
2500 
2501 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2502 /// conversion (where Derived and Base are class types) is
2503 /// well-formed, meaning that the conversion is unambiguous (and
2504 /// that all of the base classes are accessible). Returns true
2505 /// and emits a diagnostic if the code is ill-formed, returns false
2506 /// otherwise. Loc is the location where this routine should point to
2507 /// if there is an error, and Range is the source range to highlight
2508 /// if there is an error.
2509 ///
2510 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2511 /// diagnostic for the respective type of error will be suppressed, but the
2512 /// check for ill-formed code will still be performed.
2513 bool
2514 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2515                                    unsigned InaccessibleBaseID,
2516                                    unsigned AmbigiousBaseConvID,
2517                                    SourceLocation Loc, SourceRange Range,
2518                                    DeclarationName Name,
2519                                    CXXCastPath *BasePath,
2520                                    bool IgnoreAccess) {
2521   // First, determine whether the path from Derived to Base is
2522   // ambiguous. This is slightly more expensive than checking whether
2523   // the Derived to Base conversion exists, because here we need to
2524   // explore multiple paths to determine if there is an ambiguity.
2525   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2526                      /*DetectVirtual=*/false);
2527   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2528   assert(DerivationOkay &&
2529          "Can only be used with a derived-to-base conversion");
2530   (void)DerivationOkay;
2531 
2532   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
2533     if (!IgnoreAccess) {
2534       // Check that the base class can be accessed.
2535       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2536                                    InaccessibleBaseID)) {
2537         case AR_inaccessible:
2538           return true;
2539         case AR_accessible:
2540         case AR_dependent:
2541         case AR_delayed:
2542           break;
2543       }
2544     }
2545 
2546     // Build a base path if necessary.
2547     if (BasePath)
2548       BuildBasePathArray(Paths, *BasePath);
2549     return false;
2550   }
2551 
2552   if (AmbigiousBaseConvID) {
2553     // We know that the derived-to-base conversion is ambiguous, and
2554     // we're going to produce a diagnostic. Perform the derived-to-base
2555     // search just one more time to compute all of the possible paths so
2556     // that we can print them out. This is more expensive than any of
2557     // the previous derived-to-base checks we've done, but at this point
2558     // performance isn't as much of an issue.
2559     Paths.clear();
2560     Paths.setRecordingPaths(true);
2561     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2562     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2563     (void)StillOkay;
2564 
2565     // Build up a textual representation of the ambiguous paths, e.g.,
2566     // D -> B -> A, that will be used to illustrate the ambiguous
2567     // conversions in the diagnostic. We only print one of the paths
2568     // to each base class subobject.
2569     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2570 
2571     Diag(Loc, AmbigiousBaseConvID)
2572     << Derived << Base << PathDisplayStr << Range << Name;
2573   }
2574   return true;
2575 }
2576 
2577 bool
2578 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2579                                    SourceLocation Loc, SourceRange Range,
2580                                    CXXCastPath *BasePath,
2581                                    bool IgnoreAccess) {
2582   return CheckDerivedToBaseConversion(
2583       Derived, Base, diag::err_upcast_to_inaccessible_base,
2584       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2585       BasePath, IgnoreAccess);
2586 }
2587 
2588 
2589 /// @brief Builds a string representing ambiguous paths from a
2590 /// specific derived class to different subobjects of the same base
2591 /// class.
2592 ///
2593 /// This function builds a string that can be used in error messages
2594 /// to show the different paths that one can take through the
2595 /// inheritance hierarchy to go from the derived class to different
2596 /// subobjects of a base class. The result looks something like this:
2597 /// @code
2598 /// struct D -> struct B -> struct A
2599 /// struct D -> struct C -> struct A
2600 /// @endcode
2601 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2602   std::string PathDisplayStr;
2603   std::set<unsigned> DisplayedPaths;
2604   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2605        Path != Paths.end(); ++Path) {
2606     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2607       // We haven't displayed a path to this particular base
2608       // class subobject yet.
2609       PathDisplayStr += "\n    ";
2610       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2611       for (CXXBasePath::const_iterator Element = Path->begin();
2612            Element != Path->end(); ++Element)
2613         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2614     }
2615   }
2616 
2617   return PathDisplayStr;
2618 }
2619 
2620 //===----------------------------------------------------------------------===//
2621 // C++ class member Handling
2622 //===----------------------------------------------------------------------===//
2623 
2624 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2625 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2626                                 SourceLocation ASLoc,
2627                                 SourceLocation ColonLoc,
2628                                 AttributeList *Attrs) {
2629   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2630   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2631                                                   ASLoc, ColonLoc);
2632   CurContext->addHiddenDecl(ASDecl);
2633   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2634 }
2635 
2636 /// CheckOverrideControl - Check C++11 override control semantics.
2637 void Sema::CheckOverrideControl(NamedDecl *D) {
2638   if (D->isInvalidDecl())
2639     return;
2640 
2641   // We only care about "override" and "final" declarations.
2642   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2643     return;
2644 
2645   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2646 
2647   // We can't check dependent instance methods.
2648   if (MD && MD->isInstance() &&
2649       (MD->getParent()->hasAnyDependentBases() ||
2650        MD->getType()->isDependentType()))
2651     return;
2652 
2653   if (MD && !MD->isVirtual()) {
2654     // If we have a non-virtual method, check if if hides a virtual method.
2655     // (In that case, it's most likely the method has the wrong type.)
2656     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2657     FindHiddenVirtualMethods(MD, OverloadedMethods);
2658 
2659     if (!OverloadedMethods.empty()) {
2660       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2661         Diag(OA->getLocation(),
2662              diag::override_keyword_hides_virtual_member_function)
2663           << "override" << (OverloadedMethods.size() > 1);
2664       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2665         Diag(FA->getLocation(),
2666              diag::override_keyword_hides_virtual_member_function)
2667           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2668           << (OverloadedMethods.size() > 1);
2669       }
2670       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2671       MD->setInvalidDecl();
2672       return;
2673     }
2674     // Fall through into the general case diagnostic.
2675     // FIXME: We might want to attempt typo correction here.
2676   }
2677 
2678   if (!MD || !MD->isVirtual()) {
2679     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2680       Diag(OA->getLocation(),
2681            diag::override_keyword_only_allowed_on_virtual_member_functions)
2682         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2683       D->dropAttr<OverrideAttr>();
2684     }
2685     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2686       Diag(FA->getLocation(),
2687            diag::override_keyword_only_allowed_on_virtual_member_functions)
2688         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2689         << FixItHint::CreateRemoval(FA->getLocation());
2690       D->dropAttr<FinalAttr>();
2691     }
2692     return;
2693   }
2694 
2695   // C++11 [class.virtual]p5:
2696   //   If a function is marked with the virt-specifier override and
2697   //   does not override a member function of a base class, the program is
2698   //   ill-formed.
2699   bool HasOverriddenMethods =
2700     MD->begin_overridden_methods() != MD->end_overridden_methods();
2701   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2702     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2703       << MD->getDeclName();
2704 }
2705 
2706 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2707   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2708     return;
2709   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2710   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2711       isa<CXXDestructorDecl>(MD))
2712     return;
2713 
2714   SourceLocation Loc = MD->getLocation();
2715   SourceLocation SpellingLoc = Loc;
2716   if (getSourceManager().isMacroArgExpansion(Loc))
2717     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2718   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2719   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2720       return;
2721 
2722   if (MD->size_overridden_methods() > 0) {
2723     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2724       << MD->getDeclName();
2725     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2726     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2727   }
2728 }
2729 
2730 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2731 /// function overrides a virtual member function marked 'final', according to
2732 /// C++11 [class.virtual]p4.
2733 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2734                                                   const CXXMethodDecl *Old) {
2735   FinalAttr *FA = Old->getAttr<FinalAttr>();
2736   if (!FA)
2737     return false;
2738 
2739   Diag(New->getLocation(), diag::err_final_function_overridden)
2740     << New->getDeclName()
2741     << FA->isSpelledAsSealed();
2742   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2743   return true;
2744 }
2745 
2746 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2747   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2748   // FIXME: Destruction of ObjC lifetime types has side-effects.
2749   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2750     return !RD->isCompleteDefinition() ||
2751            !RD->hasTrivialDefaultConstructor() ||
2752            !RD->hasTrivialDestructor();
2753   return false;
2754 }
2755 
2756 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2757   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2758     if (it->isDeclspecPropertyAttribute())
2759       return it;
2760   return nullptr;
2761 }
2762 
2763 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2764 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2765 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2766 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2767 /// present (but parsing it has been deferred).
2768 NamedDecl *
2769 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2770                                MultiTemplateParamsArg TemplateParameterLists,
2771                                Expr *BW, const VirtSpecifiers &VS,
2772                                InClassInitStyle InitStyle) {
2773   const DeclSpec &DS = D.getDeclSpec();
2774   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2775   DeclarationName Name = NameInfo.getName();
2776   SourceLocation Loc = NameInfo.getLoc();
2777 
2778   // For anonymous bitfields, the location should point to the type.
2779   if (Loc.isInvalid())
2780     Loc = D.getLocStart();
2781 
2782   Expr *BitWidth = static_cast<Expr*>(BW);
2783 
2784   assert(isa<CXXRecordDecl>(CurContext));
2785   assert(!DS.isFriendSpecified());
2786 
2787   bool isFunc = D.isDeclarationOfFunction();
2788 
2789   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2790     // The Microsoft extension __interface only permits public member functions
2791     // and prohibits constructors, destructors, operators, non-public member
2792     // functions, static methods and data members.
2793     unsigned InvalidDecl;
2794     bool ShowDeclName = true;
2795     if (!isFunc)
2796       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2797     else if (AS != AS_public)
2798       InvalidDecl = 2;
2799     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2800       InvalidDecl = 3;
2801     else switch (Name.getNameKind()) {
2802       case DeclarationName::CXXConstructorName:
2803         InvalidDecl = 4;
2804         ShowDeclName = false;
2805         break;
2806 
2807       case DeclarationName::CXXDestructorName:
2808         InvalidDecl = 5;
2809         ShowDeclName = false;
2810         break;
2811 
2812       case DeclarationName::CXXOperatorName:
2813       case DeclarationName::CXXConversionFunctionName:
2814         InvalidDecl = 6;
2815         break;
2816 
2817       default:
2818         InvalidDecl = 0;
2819         break;
2820     }
2821 
2822     if (InvalidDecl) {
2823       if (ShowDeclName)
2824         Diag(Loc, diag::err_invalid_member_in_interface)
2825           << (InvalidDecl-1) << Name;
2826       else
2827         Diag(Loc, diag::err_invalid_member_in_interface)
2828           << (InvalidDecl-1) << "";
2829       return nullptr;
2830     }
2831   }
2832 
2833   // C++ 9.2p6: A member shall not be declared to have automatic storage
2834   // duration (auto, register) or with the extern storage-class-specifier.
2835   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2836   // data members and cannot be applied to names declared const or static,
2837   // and cannot be applied to reference members.
2838   switch (DS.getStorageClassSpec()) {
2839   case DeclSpec::SCS_unspecified:
2840   case DeclSpec::SCS_typedef:
2841   case DeclSpec::SCS_static:
2842     break;
2843   case DeclSpec::SCS_mutable:
2844     if (isFunc) {
2845       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2846 
2847       // FIXME: It would be nicer if the keyword was ignored only for this
2848       // declarator. Otherwise we could get follow-up errors.
2849       D.getMutableDeclSpec().ClearStorageClassSpecs();
2850     }
2851     break;
2852   default:
2853     Diag(DS.getStorageClassSpecLoc(),
2854          diag::err_storageclass_invalid_for_member);
2855     D.getMutableDeclSpec().ClearStorageClassSpecs();
2856     break;
2857   }
2858 
2859   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2860                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2861                       !isFunc);
2862 
2863   if (DS.isConstexprSpecified() && isInstField) {
2864     SemaDiagnosticBuilder B =
2865         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2866     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2867     if (InitStyle == ICIS_NoInit) {
2868       B << 0 << 0;
2869       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2870         B << FixItHint::CreateRemoval(ConstexprLoc);
2871       else {
2872         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2873         D.getMutableDeclSpec().ClearConstexprSpec();
2874         const char *PrevSpec;
2875         unsigned DiagID;
2876         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2877             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2878         (void)Failed;
2879         assert(!Failed && "Making a constexpr member const shouldn't fail");
2880       }
2881     } else {
2882       B << 1;
2883       const char *PrevSpec;
2884       unsigned DiagID;
2885       if (D.getMutableDeclSpec().SetStorageClassSpec(
2886           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2887           Context.getPrintingPolicy())) {
2888         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2889                "This is the only DeclSpec that should fail to be applied");
2890         B << 1;
2891       } else {
2892         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2893         isInstField = false;
2894       }
2895     }
2896   }
2897 
2898   NamedDecl *Member;
2899   if (isInstField) {
2900     CXXScopeSpec &SS = D.getCXXScopeSpec();
2901 
2902     // Data members must have identifiers for names.
2903     if (!Name.isIdentifier()) {
2904       Diag(Loc, diag::err_bad_variable_name)
2905         << Name;
2906       return nullptr;
2907     }
2908 
2909     IdentifierInfo *II = Name.getAsIdentifierInfo();
2910 
2911     // Member field could not be with "template" keyword.
2912     // So TemplateParameterLists should be empty in this case.
2913     if (TemplateParameterLists.size()) {
2914       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2915       if (TemplateParams->size()) {
2916         // There is no such thing as a member field template.
2917         Diag(D.getIdentifierLoc(), diag::err_template_member)
2918             << II
2919             << SourceRange(TemplateParams->getTemplateLoc(),
2920                 TemplateParams->getRAngleLoc());
2921       } else {
2922         // There is an extraneous 'template<>' for this member.
2923         Diag(TemplateParams->getTemplateLoc(),
2924             diag::err_template_member_noparams)
2925             << II
2926             << SourceRange(TemplateParams->getTemplateLoc(),
2927                 TemplateParams->getRAngleLoc());
2928       }
2929       return nullptr;
2930     }
2931 
2932     if (SS.isSet() && !SS.isInvalid()) {
2933       // The user provided a superfluous scope specifier inside a class
2934       // definition:
2935       //
2936       // class X {
2937       //   int X::member;
2938       // };
2939       if (DeclContext *DC = computeDeclContext(SS, false))
2940         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2941       else
2942         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2943           << Name << SS.getRange();
2944 
2945       SS.clear();
2946     }
2947 
2948     AttributeList *MSPropertyAttr =
2949       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2950     if (MSPropertyAttr) {
2951       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2952                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2953       if (!Member)
2954         return nullptr;
2955       isInstField = false;
2956     } else {
2957       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2958                                 BitWidth, InitStyle, AS);
2959       if (!Member)
2960         return nullptr;
2961     }
2962   } else {
2963     Member = HandleDeclarator(S, D, TemplateParameterLists);
2964     if (!Member)
2965       return nullptr;
2966 
2967     // Non-instance-fields can't have a bitfield.
2968     if (BitWidth) {
2969       if (Member->isInvalidDecl()) {
2970         // don't emit another diagnostic.
2971       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2972         // C++ 9.6p3: A bit-field shall not be a static member.
2973         // "static member 'A' cannot be a bit-field"
2974         Diag(Loc, diag::err_static_not_bitfield)
2975           << Name << BitWidth->getSourceRange();
2976       } else if (isa<TypedefDecl>(Member)) {
2977         // "typedef member 'x' cannot be a bit-field"
2978         Diag(Loc, diag::err_typedef_not_bitfield)
2979           << Name << BitWidth->getSourceRange();
2980       } else {
2981         // A function typedef ("typedef int f(); f a;").
2982         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2983         Diag(Loc, diag::err_not_integral_type_bitfield)
2984           << Name << cast<ValueDecl>(Member)->getType()
2985           << BitWidth->getSourceRange();
2986       }
2987 
2988       BitWidth = nullptr;
2989       Member->setInvalidDecl();
2990     }
2991 
2992     Member->setAccess(AS);
2993 
2994     // If we have declared a member function template or static data member
2995     // template, set the access of the templated declaration as well.
2996     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2997       FunTmpl->getTemplatedDecl()->setAccess(AS);
2998     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2999       VarTmpl->getTemplatedDecl()->setAccess(AS);
3000   }
3001 
3002   if (VS.isOverrideSpecified())
3003     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3004   if (VS.isFinalSpecified())
3005     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3006                                             VS.isFinalSpelledSealed()));
3007 
3008   if (VS.getLastLocation().isValid()) {
3009     // Update the end location of a method that has a virt-specifiers.
3010     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3011       MD->setRangeEnd(VS.getLastLocation());
3012   }
3013 
3014   CheckOverrideControl(Member);
3015 
3016   assert((Name || isInstField) && "No identifier for non-field ?");
3017 
3018   if (isInstField) {
3019     FieldDecl *FD = cast<FieldDecl>(Member);
3020     FieldCollector->Add(FD);
3021 
3022     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3023       // Remember all explicit private FieldDecls that have a name, no side
3024       // effects and are not part of a dependent type declaration.
3025       if (!FD->isImplicit() && FD->getDeclName() &&
3026           FD->getAccess() == AS_private &&
3027           !FD->hasAttr<UnusedAttr>() &&
3028           !FD->getParent()->isDependentContext() &&
3029           !InitializationHasSideEffects(*FD))
3030         UnusedPrivateFields.insert(FD);
3031     }
3032   }
3033 
3034   return Member;
3035 }
3036 
3037 namespace {
3038   class UninitializedFieldVisitor
3039       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3040     Sema &S;
3041     // List of Decls to generate a warning on.  Also remove Decls that become
3042     // initialized.
3043     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3044     // List of base classes of the record.  Classes are removed after their
3045     // initializers.
3046     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3047     // Vector of decls to be removed from the Decl set prior to visiting the
3048     // nodes.  These Decls may have been initialized in the prior initializer.
3049     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3050     // If non-null, add a note to the warning pointing back to the constructor.
3051     const CXXConstructorDecl *Constructor;
3052     // Variables to hold state when processing an initializer list.  When
3053     // InitList is true, special case initialization of FieldDecls matching
3054     // InitListFieldDecl.
3055     bool InitList;
3056     FieldDecl *InitListFieldDecl;
3057     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3058 
3059   public:
3060     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3061     UninitializedFieldVisitor(Sema &S,
3062                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3063                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3064       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3065         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3066 
3067     // Returns true if the use of ME is not an uninitialized use.
3068     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3069                                          bool CheckReferenceOnly) {
3070       llvm::SmallVector<FieldDecl*, 4> Fields;
3071       bool ReferenceField = false;
3072       while (ME) {
3073         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3074         if (!FD)
3075           return false;
3076         Fields.push_back(FD);
3077         if (FD->getType()->isReferenceType())
3078           ReferenceField = true;
3079         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3080       }
3081 
3082       // Binding a reference to an unintialized field is not an
3083       // uninitialized use.
3084       if (CheckReferenceOnly && !ReferenceField)
3085         return true;
3086 
3087       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3088       // Discard the first field since it is the field decl that is being
3089       // initialized.
3090       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3091         UsedFieldIndex.push_back((*I)->getFieldIndex());
3092       }
3093 
3094       for (auto UsedIter = UsedFieldIndex.begin(),
3095                 UsedEnd = UsedFieldIndex.end(),
3096                 OrigIter = InitFieldIndex.begin(),
3097                 OrigEnd = InitFieldIndex.end();
3098            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3099         if (*UsedIter < *OrigIter)
3100           return true;
3101         if (*UsedIter > *OrigIter)
3102           break;
3103       }
3104 
3105       return false;
3106     }
3107 
3108     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3109                           bool AddressOf) {
3110       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3111         return;
3112 
3113       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3114       // or union.
3115       MemberExpr *FieldME = ME;
3116 
3117       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3118 
3119       Expr *Base = ME;
3120       while (MemberExpr *SubME =
3121                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3122 
3123         if (isa<VarDecl>(SubME->getMemberDecl()))
3124           return;
3125 
3126         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3127           if (!FD->isAnonymousStructOrUnion())
3128             FieldME = SubME;
3129 
3130         if (!FieldME->getType().isPODType(S.Context))
3131           AllPODFields = false;
3132 
3133         Base = SubME->getBase();
3134       }
3135 
3136       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3137         return;
3138 
3139       if (AddressOf && AllPODFields)
3140         return;
3141 
3142       ValueDecl* FoundVD = FieldME->getMemberDecl();
3143 
3144       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3145         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3146           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3147         }
3148 
3149         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3150           QualType T = BaseCast->getType();
3151           if (T->isPointerType() &&
3152               BaseClasses.count(T->getPointeeType())) {
3153             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3154                 << T->getPointeeType() << FoundVD;
3155           }
3156         }
3157       }
3158 
3159       if (!Decls.count(FoundVD))
3160         return;
3161 
3162       const bool IsReference = FoundVD->getType()->isReferenceType();
3163 
3164       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3165         // Special checking for initializer lists.
3166         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3167           return;
3168         }
3169       } else {
3170         // Prevent double warnings on use of unbounded references.
3171         if (CheckReferenceOnly && !IsReference)
3172           return;
3173       }
3174 
3175       unsigned diag = IsReference
3176           ? diag::warn_reference_field_is_uninit
3177           : diag::warn_field_is_uninit;
3178       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3179       if (Constructor)
3180         S.Diag(Constructor->getLocation(),
3181                diag::note_uninit_in_this_constructor)
3182           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3183 
3184     }
3185 
3186     void HandleValue(Expr *E, bool AddressOf) {
3187       E = E->IgnoreParens();
3188 
3189       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3190         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3191                          AddressOf /*AddressOf*/);
3192         return;
3193       }
3194 
3195       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3196         Visit(CO->getCond());
3197         HandleValue(CO->getTrueExpr(), AddressOf);
3198         HandleValue(CO->getFalseExpr(), AddressOf);
3199         return;
3200       }
3201 
3202       if (BinaryConditionalOperator *BCO =
3203               dyn_cast<BinaryConditionalOperator>(E)) {
3204         Visit(BCO->getCond());
3205         HandleValue(BCO->getFalseExpr(), AddressOf);
3206         return;
3207       }
3208 
3209       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3210         HandleValue(OVE->getSourceExpr(), AddressOf);
3211         return;
3212       }
3213 
3214       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3215         switch (BO->getOpcode()) {
3216         default:
3217           break;
3218         case(BO_PtrMemD):
3219         case(BO_PtrMemI):
3220           HandleValue(BO->getLHS(), AddressOf);
3221           Visit(BO->getRHS());
3222           return;
3223         case(BO_Comma):
3224           Visit(BO->getLHS());
3225           HandleValue(BO->getRHS(), AddressOf);
3226           return;
3227         }
3228       }
3229 
3230       Visit(E);
3231     }
3232 
3233     void CheckInitListExpr(InitListExpr *ILE) {
3234       InitFieldIndex.push_back(0);
3235       for (auto Child : ILE->children()) {
3236         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3237           CheckInitListExpr(SubList);
3238         } else {
3239           Visit(Child);
3240         }
3241         ++InitFieldIndex.back();
3242       }
3243       InitFieldIndex.pop_back();
3244     }
3245 
3246     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3247                           FieldDecl *Field, const Type *BaseClass) {
3248       // Remove Decls that may have been initialized in the previous
3249       // initializer.
3250       for (ValueDecl* VD : DeclsToRemove)
3251         Decls.erase(VD);
3252       DeclsToRemove.clear();
3253 
3254       Constructor = FieldConstructor;
3255       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3256 
3257       if (ILE && Field) {
3258         InitList = true;
3259         InitListFieldDecl = Field;
3260         InitFieldIndex.clear();
3261         CheckInitListExpr(ILE);
3262       } else {
3263         InitList = false;
3264         Visit(E);
3265       }
3266 
3267       if (Field)
3268         Decls.erase(Field);
3269       if (BaseClass)
3270         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3271     }
3272 
3273     void VisitMemberExpr(MemberExpr *ME) {
3274       // All uses of unbounded reference fields will warn.
3275       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3276     }
3277 
3278     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3279       if (E->getCastKind() == CK_LValueToRValue) {
3280         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3281         return;
3282       }
3283 
3284       Inherited::VisitImplicitCastExpr(E);
3285     }
3286 
3287     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3288       if (E->getConstructor()->isCopyConstructor()) {
3289         Expr *ArgExpr = E->getArg(0);
3290         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3291           if (ILE->getNumInits() == 1)
3292             ArgExpr = ILE->getInit(0);
3293         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3294           if (ICE->getCastKind() == CK_NoOp)
3295             ArgExpr = ICE->getSubExpr();
3296         HandleValue(ArgExpr, false /*AddressOf*/);
3297         return;
3298       }
3299       Inherited::VisitCXXConstructExpr(E);
3300     }
3301 
3302     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3303       Expr *Callee = E->getCallee();
3304       if (isa<MemberExpr>(Callee)) {
3305         HandleValue(Callee, false /*AddressOf*/);
3306         for (auto Arg : E->arguments())
3307           Visit(Arg);
3308         return;
3309       }
3310 
3311       Inherited::VisitCXXMemberCallExpr(E);
3312     }
3313 
3314     void VisitCallExpr(CallExpr *E) {
3315       // Treat std::move as a use.
3316       if (E->getNumArgs() == 1) {
3317         if (FunctionDecl *FD = E->getDirectCallee()) {
3318           if (FD->isInStdNamespace() && FD->getIdentifier() &&
3319               FD->getIdentifier()->isStr("move")) {
3320             HandleValue(E->getArg(0), false /*AddressOf*/);
3321             return;
3322           }
3323         }
3324       }
3325 
3326       Inherited::VisitCallExpr(E);
3327     }
3328 
3329     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3330       Expr *Callee = E->getCallee();
3331 
3332       if (isa<UnresolvedLookupExpr>(Callee))
3333         return Inherited::VisitCXXOperatorCallExpr(E);
3334 
3335       Visit(Callee);
3336       for (auto Arg : E->arguments())
3337         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3338     }
3339 
3340     void VisitBinaryOperator(BinaryOperator *E) {
3341       // If a field assignment is detected, remove the field from the
3342       // uninitiailized field set.
3343       if (E->getOpcode() == BO_Assign)
3344         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3345           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3346             if (!FD->getType()->isReferenceType())
3347               DeclsToRemove.push_back(FD);
3348 
3349       if (E->isCompoundAssignmentOp()) {
3350         HandleValue(E->getLHS(), false /*AddressOf*/);
3351         Visit(E->getRHS());
3352         return;
3353       }
3354 
3355       Inherited::VisitBinaryOperator(E);
3356     }
3357 
3358     void VisitUnaryOperator(UnaryOperator *E) {
3359       if (E->isIncrementDecrementOp()) {
3360         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3361         return;
3362       }
3363       if (E->getOpcode() == UO_AddrOf) {
3364         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3365           HandleValue(ME->getBase(), true /*AddressOf*/);
3366           return;
3367         }
3368       }
3369 
3370       Inherited::VisitUnaryOperator(E);
3371     }
3372   };
3373 
3374   // Diagnose value-uses of fields to initialize themselves, e.g.
3375   //   foo(foo)
3376   // where foo is not also a parameter to the constructor.
3377   // Also diagnose across field uninitialized use such as
3378   //   x(y), y(x)
3379   // TODO: implement -Wuninitialized and fold this into that framework.
3380   static void DiagnoseUninitializedFields(
3381       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3382 
3383     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3384                                            Constructor->getLocation())) {
3385       return;
3386     }
3387 
3388     if (Constructor->isInvalidDecl())
3389       return;
3390 
3391     const CXXRecordDecl *RD = Constructor->getParent();
3392 
3393     if (RD->getDescribedClassTemplate())
3394       return;
3395 
3396     // Holds fields that are uninitialized.
3397     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3398 
3399     // At the beginning, all fields are uninitialized.
3400     for (auto *I : RD->decls()) {
3401       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3402         UninitializedFields.insert(FD);
3403       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3404         UninitializedFields.insert(IFD->getAnonField());
3405       }
3406     }
3407 
3408     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3409     for (auto I : RD->bases())
3410       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3411 
3412     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3413       return;
3414 
3415     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3416                                                    UninitializedFields,
3417                                                    UninitializedBaseClasses);
3418 
3419     for (const auto *FieldInit : Constructor->inits()) {
3420       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3421         break;
3422 
3423       Expr *InitExpr = FieldInit->getInit();
3424       if (!InitExpr)
3425         continue;
3426 
3427       if (CXXDefaultInitExpr *Default =
3428               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3429         InitExpr = Default->getExpr();
3430         if (!InitExpr)
3431           continue;
3432         // In class initializers will point to the constructor.
3433         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3434                                               FieldInit->getAnyMember(),
3435                                               FieldInit->getBaseClass());
3436       } else {
3437         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3438                                               FieldInit->getAnyMember(),
3439                                               FieldInit->getBaseClass());
3440       }
3441     }
3442   }
3443 } // namespace
3444 
3445 /// \brief Enter a new C++ default initializer scope. After calling this, the
3446 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3447 /// parsing or instantiating the initializer failed.
3448 void Sema::ActOnStartCXXInClassMemberInitializer() {
3449   // Create a synthetic function scope to represent the call to the constructor
3450   // that notionally surrounds a use of this initializer.
3451   PushFunctionScope();
3452 }
3453 
3454 /// \brief This is invoked after parsing an in-class initializer for a
3455 /// non-static C++ class member, and after instantiating an in-class initializer
3456 /// in a class template. Such actions are deferred until the class is complete.
3457 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3458                                                   SourceLocation InitLoc,
3459                                                   Expr *InitExpr) {
3460   // Pop the notional constructor scope we created earlier.
3461   PopFunctionScopeInfo(nullptr, D);
3462 
3463   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3464   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3465          "must set init style when field is created");
3466 
3467   if (!InitExpr) {
3468     D->setInvalidDecl();
3469     if (FD)
3470       FD->removeInClassInitializer();
3471     return;
3472   }
3473 
3474   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3475     FD->setInvalidDecl();
3476     FD->removeInClassInitializer();
3477     return;
3478   }
3479 
3480   ExprResult Init = InitExpr;
3481   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3482     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3483     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
3484         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
3485         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3486     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3487     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3488     if (Init.isInvalid()) {
3489       FD->setInvalidDecl();
3490       return;
3491     }
3492   }
3493 
3494   // C++11 [class.base.init]p7:
3495   //   The initialization of each base and member constitutes a
3496   //   full-expression.
3497   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3498   if (Init.isInvalid()) {
3499     FD->setInvalidDecl();
3500     return;
3501   }
3502 
3503   InitExpr = Init.get();
3504 
3505   FD->setInClassInitializer(InitExpr);
3506 }
3507 
3508 /// \brief Find the direct and/or virtual base specifiers that
3509 /// correspond to the given base type, for use in base initialization
3510 /// within a constructor.
3511 static bool FindBaseInitializer(Sema &SemaRef,
3512                                 CXXRecordDecl *ClassDecl,
3513                                 QualType BaseType,
3514                                 const CXXBaseSpecifier *&DirectBaseSpec,
3515                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3516   // First, check for a direct base class.
3517   DirectBaseSpec = nullptr;
3518   for (const auto &Base : ClassDecl->bases()) {
3519     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3520       // We found a direct base of this type. That's what we're
3521       // initializing.
3522       DirectBaseSpec = &Base;
3523       break;
3524     }
3525   }
3526 
3527   // Check for a virtual base class.
3528   // FIXME: We might be able to short-circuit this if we know in advance that
3529   // there are no virtual bases.
3530   VirtualBaseSpec = nullptr;
3531   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3532     // We haven't found a base yet; search the class hierarchy for a
3533     // virtual base class.
3534     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3535                        /*DetectVirtual=*/false);
3536     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3537                               SemaRef.Context.getTypeDeclType(ClassDecl),
3538                               BaseType, Paths)) {
3539       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3540            Path != Paths.end(); ++Path) {
3541         if (Path->back().Base->isVirtual()) {
3542           VirtualBaseSpec = Path->back().Base;
3543           break;
3544         }
3545       }
3546     }
3547   }
3548 
3549   return DirectBaseSpec || VirtualBaseSpec;
3550 }
3551 
3552 /// \brief Handle a C++ member initializer using braced-init-list syntax.
3553 MemInitResult
3554 Sema::ActOnMemInitializer(Decl *ConstructorD,
3555                           Scope *S,
3556                           CXXScopeSpec &SS,
3557                           IdentifierInfo *MemberOrBase,
3558                           ParsedType TemplateTypeTy,
3559                           const DeclSpec &DS,
3560                           SourceLocation IdLoc,
3561                           Expr *InitList,
3562                           SourceLocation EllipsisLoc) {
3563   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3564                              DS, IdLoc, InitList,
3565                              EllipsisLoc);
3566 }
3567 
3568 /// \brief Handle a C++ member initializer using parentheses syntax.
3569 MemInitResult
3570 Sema::ActOnMemInitializer(Decl *ConstructorD,
3571                           Scope *S,
3572                           CXXScopeSpec &SS,
3573                           IdentifierInfo *MemberOrBase,
3574                           ParsedType TemplateTypeTy,
3575                           const DeclSpec &DS,
3576                           SourceLocation IdLoc,
3577                           SourceLocation LParenLoc,
3578                           ArrayRef<Expr *> Args,
3579                           SourceLocation RParenLoc,
3580                           SourceLocation EllipsisLoc) {
3581   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3582                                            Args, RParenLoc);
3583   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3584                              DS, IdLoc, List, EllipsisLoc);
3585 }
3586 
3587 namespace {
3588 
3589 // Callback to only accept typo corrections that can be a valid C++ member
3590 // intializer: either a non-static field member or a base class.
3591 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3592 public:
3593   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3594       : ClassDecl(ClassDecl) {}
3595 
3596   bool ValidateCandidate(const TypoCorrection &candidate) override {
3597     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3598       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3599         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3600       return isa<TypeDecl>(ND);
3601     }
3602     return false;
3603   }
3604 
3605 private:
3606   CXXRecordDecl *ClassDecl;
3607 };
3608 
3609 }
3610 
3611 /// \brief Handle a C++ member initializer.
3612 MemInitResult
3613 Sema::BuildMemInitializer(Decl *ConstructorD,
3614                           Scope *S,
3615                           CXXScopeSpec &SS,
3616                           IdentifierInfo *MemberOrBase,
3617                           ParsedType TemplateTypeTy,
3618                           const DeclSpec &DS,
3619                           SourceLocation IdLoc,
3620                           Expr *Init,
3621                           SourceLocation EllipsisLoc) {
3622   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3623   if (!Res.isUsable())
3624     return true;
3625   Init = Res.get();
3626 
3627   if (!ConstructorD)
3628     return true;
3629 
3630   AdjustDeclIfTemplate(ConstructorD);
3631 
3632   CXXConstructorDecl *Constructor
3633     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3634   if (!Constructor) {
3635     // The user wrote a constructor initializer on a function that is
3636     // not a C++ constructor. Ignore the error for now, because we may
3637     // have more member initializers coming; we'll diagnose it just
3638     // once in ActOnMemInitializers.
3639     return true;
3640   }
3641 
3642   CXXRecordDecl *ClassDecl = Constructor->getParent();
3643 
3644   // C++ [class.base.init]p2:
3645   //   Names in a mem-initializer-id are looked up in the scope of the
3646   //   constructor's class and, if not found in that scope, are looked
3647   //   up in the scope containing the constructor's definition.
3648   //   [Note: if the constructor's class contains a member with the
3649   //   same name as a direct or virtual base class of the class, a
3650   //   mem-initializer-id naming the member or base class and composed
3651   //   of a single identifier refers to the class member. A
3652   //   mem-initializer-id for the hidden base class may be specified
3653   //   using a qualified name. ]
3654   if (!SS.getScopeRep() && !TemplateTypeTy) {
3655     // Look for a member, first.
3656     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3657     if (!Result.empty()) {
3658       ValueDecl *Member;
3659       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3660           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3661         if (EllipsisLoc.isValid())
3662           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3663             << MemberOrBase
3664             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3665 
3666         return BuildMemberInitializer(Member, Init, IdLoc);
3667       }
3668     }
3669   }
3670   // It didn't name a member, so see if it names a class.
3671   QualType BaseType;
3672   TypeSourceInfo *TInfo = nullptr;
3673 
3674   if (TemplateTypeTy) {
3675     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3676   } else if (DS.getTypeSpecType() == TST_decltype) {
3677     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3678   } else {
3679     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3680     LookupParsedName(R, S, &SS);
3681 
3682     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3683     if (!TyD) {
3684       if (R.isAmbiguous()) return true;
3685 
3686       // We don't want access-control diagnostics here.
3687       R.suppressDiagnostics();
3688 
3689       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3690         bool NotUnknownSpecialization = false;
3691         DeclContext *DC = computeDeclContext(SS, false);
3692         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3693           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3694 
3695         if (!NotUnknownSpecialization) {
3696           // When the scope specifier can refer to a member of an unknown
3697           // specialization, we take it as a type name.
3698           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3699                                        SS.getWithLocInContext(Context),
3700                                        *MemberOrBase, IdLoc);
3701           if (BaseType.isNull())
3702             return true;
3703 
3704           R.clear();
3705           R.setLookupName(MemberOrBase);
3706         }
3707       }
3708 
3709       // If no results were found, try to correct typos.
3710       TypoCorrection Corr;
3711       if (R.empty() && BaseType.isNull() &&
3712           (Corr = CorrectTypo(
3713                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3714                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3715                CTK_ErrorRecovery, ClassDecl))) {
3716         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3717           // We have found a non-static data member with a similar
3718           // name to what was typed; complain and initialize that
3719           // member.
3720           diagnoseTypo(Corr,
3721                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3722                          << MemberOrBase << true);
3723           return BuildMemberInitializer(Member, Init, IdLoc);
3724         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3725           const CXXBaseSpecifier *DirectBaseSpec;
3726           const CXXBaseSpecifier *VirtualBaseSpec;
3727           if (FindBaseInitializer(*this, ClassDecl,
3728                                   Context.getTypeDeclType(Type),
3729                                   DirectBaseSpec, VirtualBaseSpec)) {
3730             // We have found a direct or virtual base class with a
3731             // similar name to what was typed; complain and initialize
3732             // that base class.
3733             diagnoseTypo(Corr,
3734                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3735                            << MemberOrBase << false,
3736                          PDiag() /*Suppress note, we provide our own.*/);
3737 
3738             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3739                                                               : VirtualBaseSpec;
3740             Diag(BaseSpec->getLocStart(),
3741                  diag::note_base_class_specified_here)
3742               << BaseSpec->getType()
3743               << BaseSpec->getSourceRange();
3744 
3745             TyD = Type;
3746           }
3747         }
3748       }
3749 
3750       if (!TyD && BaseType.isNull()) {
3751         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3752           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3753         return true;
3754       }
3755     }
3756 
3757     if (BaseType.isNull()) {
3758       BaseType = Context.getTypeDeclType(TyD);
3759       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3760       if (SS.isSet()) {
3761         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3762                                              BaseType);
3763         TInfo = Context.CreateTypeSourceInfo(BaseType);
3764         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3765         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3766         TL.setElaboratedKeywordLoc(SourceLocation());
3767         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3768       }
3769     }
3770   }
3771 
3772   if (!TInfo)
3773     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3774 
3775   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3776 }
3777 
3778 /// Checks a member initializer expression for cases where reference (or
3779 /// pointer) members are bound to by-value parameters (or their addresses).
3780 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3781                                                Expr *Init,
3782                                                SourceLocation IdLoc) {
3783   QualType MemberTy = Member->getType();
3784 
3785   // We only handle pointers and references currently.
3786   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3787   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3788     return;
3789 
3790   const bool IsPointer = MemberTy->isPointerType();
3791   if (IsPointer) {
3792     if (const UnaryOperator *Op
3793           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3794       // The only case we're worried about with pointers requires taking the
3795       // address.
3796       if (Op->getOpcode() != UO_AddrOf)
3797         return;
3798 
3799       Init = Op->getSubExpr();
3800     } else {
3801       // We only handle address-of expression initializers for pointers.
3802       return;
3803     }
3804   }
3805 
3806   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3807     // We only warn when referring to a non-reference parameter declaration.
3808     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3809     if (!Parameter || Parameter->getType()->isReferenceType())
3810       return;
3811 
3812     S.Diag(Init->getExprLoc(),
3813            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3814                      : diag::warn_bind_ref_member_to_parameter)
3815       << Member << Parameter << Init->getSourceRange();
3816   } else {
3817     // Other initializers are fine.
3818     return;
3819   }
3820 
3821   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3822     << (unsigned)IsPointer;
3823 }
3824 
3825 MemInitResult
3826 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3827                              SourceLocation IdLoc) {
3828   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3829   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3830   assert((DirectMember || IndirectMember) &&
3831          "Member must be a FieldDecl or IndirectFieldDecl");
3832 
3833   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3834     return true;
3835 
3836   if (Member->isInvalidDecl())
3837     return true;
3838 
3839   MultiExprArg Args;
3840   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3841     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3842   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3843     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3844   } else {
3845     // Template instantiation doesn't reconstruct ParenListExprs for us.
3846     Args = Init;
3847   }
3848 
3849   SourceRange InitRange = Init->getSourceRange();
3850 
3851   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3852     // Can't check initialization for a member of dependent type or when
3853     // any of the arguments are type-dependent expressions.
3854     DiscardCleanupsInEvaluationContext();
3855   } else {
3856     bool InitList = false;
3857     if (isa<InitListExpr>(Init)) {
3858       InitList = true;
3859       Args = Init;
3860     }
3861 
3862     // Initialize the member.
3863     InitializedEntity MemberEntity =
3864       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3865                    : InitializedEntity::InitializeMember(IndirectMember,
3866                                                          nullptr);
3867     InitializationKind Kind =
3868       InitList ? InitializationKind::CreateDirectList(IdLoc)
3869                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3870                                                   InitRange.getEnd());
3871 
3872     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3873     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3874                                             nullptr);
3875     if (MemberInit.isInvalid())
3876       return true;
3877 
3878     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3879 
3880     // C++11 [class.base.init]p7:
3881     //   The initialization of each base and member constitutes a
3882     //   full-expression.
3883     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3884     if (MemberInit.isInvalid())
3885       return true;
3886 
3887     Init = MemberInit.get();
3888   }
3889 
3890   if (DirectMember) {
3891     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3892                                             InitRange.getBegin(), Init,
3893                                             InitRange.getEnd());
3894   } else {
3895     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3896                                             InitRange.getBegin(), Init,
3897                                             InitRange.getEnd());
3898   }
3899 }
3900 
3901 MemInitResult
3902 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3903                                  CXXRecordDecl *ClassDecl) {
3904   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3905   if (!LangOpts.CPlusPlus11)
3906     return Diag(NameLoc, diag::err_delegating_ctor)
3907       << TInfo->getTypeLoc().getLocalSourceRange();
3908   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3909 
3910   bool InitList = true;
3911   MultiExprArg Args = Init;
3912   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3913     InitList = false;
3914     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3915   }
3916 
3917   SourceRange InitRange = Init->getSourceRange();
3918   // Initialize the object.
3919   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3920                                      QualType(ClassDecl->getTypeForDecl(), 0));
3921   InitializationKind Kind =
3922     InitList ? InitializationKind::CreateDirectList(NameLoc)
3923              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3924                                                 InitRange.getEnd());
3925   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3926   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3927                                               Args, nullptr);
3928   if (DelegationInit.isInvalid())
3929     return true;
3930 
3931   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3932          "Delegating constructor with no target?");
3933 
3934   // C++11 [class.base.init]p7:
3935   //   The initialization of each base and member constitutes a
3936   //   full-expression.
3937   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3938                                        InitRange.getBegin());
3939   if (DelegationInit.isInvalid())
3940     return true;
3941 
3942   // If we are in a dependent context, template instantiation will
3943   // perform this type-checking again. Just save the arguments that we
3944   // received in a ParenListExpr.
3945   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3946   // of the information that we have about the base
3947   // initializer. However, deconstructing the ASTs is a dicey process,
3948   // and this approach is far more likely to get the corner cases right.
3949   if (CurContext->isDependentContext())
3950     DelegationInit = Init;
3951 
3952   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3953                                           DelegationInit.getAs<Expr>(),
3954                                           InitRange.getEnd());
3955 }
3956 
3957 MemInitResult
3958 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3959                            Expr *Init, CXXRecordDecl *ClassDecl,
3960                            SourceLocation EllipsisLoc) {
3961   SourceLocation BaseLoc
3962     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3963 
3964   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3965     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3966              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3967 
3968   // C++ [class.base.init]p2:
3969   //   [...] Unless the mem-initializer-id names a nonstatic data
3970   //   member of the constructor's class or a direct or virtual base
3971   //   of that class, the mem-initializer is ill-formed. A
3972   //   mem-initializer-list can initialize a base class using any
3973   //   name that denotes that base class type.
3974   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3975 
3976   SourceRange InitRange = Init->getSourceRange();
3977   if (EllipsisLoc.isValid()) {
3978     // This is a pack expansion.
3979     if (!BaseType->containsUnexpandedParameterPack())  {
3980       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3981         << SourceRange(BaseLoc, InitRange.getEnd());
3982 
3983       EllipsisLoc = SourceLocation();
3984     }
3985   } else {
3986     // Check for any unexpanded parameter packs.
3987     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3988       return true;
3989 
3990     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3991       return true;
3992   }
3993 
3994   // Check for direct and virtual base classes.
3995   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3996   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3997   if (!Dependent) {
3998     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3999                                        BaseType))
4000       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4001 
4002     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4003                         VirtualBaseSpec);
4004 
4005     // C++ [base.class.init]p2:
4006     // Unless the mem-initializer-id names a nonstatic data member of the
4007     // constructor's class or a direct or virtual base of that class, the
4008     // mem-initializer is ill-formed.
4009     if (!DirectBaseSpec && !VirtualBaseSpec) {
4010       // If the class has any dependent bases, then it's possible that
4011       // one of those types will resolve to the same type as
4012       // BaseType. Therefore, just treat this as a dependent base
4013       // class initialization.  FIXME: Should we try to check the
4014       // initialization anyway? It seems odd.
4015       if (ClassDecl->hasAnyDependentBases())
4016         Dependent = true;
4017       else
4018         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4019           << BaseType << Context.getTypeDeclType(ClassDecl)
4020           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4021     }
4022   }
4023 
4024   if (Dependent) {
4025     DiscardCleanupsInEvaluationContext();
4026 
4027     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4028                                             /*IsVirtual=*/false,
4029                                             InitRange.getBegin(), Init,
4030                                             InitRange.getEnd(), EllipsisLoc);
4031   }
4032 
4033   // C++ [base.class.init]p2:
4034   //   If a mem-initializer-id is ambiguous because it designates both
4035   //   a direct non-virtual base class and an inherited virtual base
4036   //   class, the mem-initializer is ill-formed.
4037   if (DirectBaseSpec && VirtualBaseSpec)
4038     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4039       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4040 
4041   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4042   if (!BaseSpec)
4043     BaseSpec = VirtualBaseSpec;
4044 
4045   // Initialize the base.
4046   bool InitList = true;
4047   MultiExprArg Args = Init;
4048   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4049     InitList = false;
4050     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4051   }
4052 
4053   InitializedEntity BaseEntity =
4054     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4055   InitializationKind Kind =
4056     InitList ? InitializationKind::CreateDirectList(BaseLoc)
4057              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4058                                                 InitRange.getEnd());
4059   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4060   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4061   if (BaseInit.isInvalid())
4062     return true;
4063 
4064   // C++11 [class.base.init]p7:
4065   //   The initialization of each base and member constitutes a
4066   //   full-expression.
4067   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4068   if (BaseInit.isInvalid())
4069     return true;
4070 
4071   // If we are in a dependent context, template instantiation will
4072   // perform this type-checking again. Just save the arguments that we
4073   // received in a ParenListExpr.
4074   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4075   // of the information that we have about the base
4076   // initializer. However, deconstructing the ASTs is a dicey process,
4077   // and this approach is far more likely to get the corner cases right.
4078   if (CurContext->isDependentContext())
4079     BaseInit = Init;
4080 
4081   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4082                                           BaseSpec->isVirtual(),
4083                                           InitRange.getBegin(),
4084                                           BaseInit.getAs<Expr>(),
4085                                           InitRange.getEnd(), EllipsisLoc);
4086 }
4087 
4088 // Create a static_cast\<T&&>(expr).
4089 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4090   if (T.isNull()) T = E->getType();
4091   QualType TargetType = SemaRef.BuildReferenceType(
4092       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4093   SourceLocation ExprLoc = E->getLocStart();
4094   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4095       TargetType, ExprLoc);
4096 
4097   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4098                                    SourceRange(ExprLoc, ExprLoc),
4099                                    E->getSourceRange()).get();
4100 }
4101 
4102 /// ImplicitInitializerKind - How an implicit base or member initializer should
4103 /// initialize its base or member.
4104 enum ImplicitInitializerKind {
4105   IIK_Default,
4106   IIK_Copy,
4107   IIK_Move,
4108   IIK_Inherit
4109 };
4110 
4111 static bool
4112 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4113                              ImplicitInitializerKind ImplicitInitKind,
4114                              CXXBaseSpecifier *BaseSpec,
4115                              bool IsInheritedVirtualBase,
4116                              CXXCtorInitializer *&CXXBaseInit) {
4117   InitializedEntity InitEntity
4118     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4119                                         IsInheritedVirtualBase);
4120 
4121   ExprResult BaseInit;
4122 
4123   switch (ImplicitInitKind) {
4124   case IIK_Inherit:
4125   case IIK_Default: {
4126     InitializationKind InitKind
4127       = InitializationKind::CreateDefault(Constructor->getLocation());
4128     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4129     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4130     break;
4131   }
4132 
4133   case IIK_Move:
4134   case IIK_Copy: {
4135     bool Moving = ImplicitInitKind == IIK_Move;
4136     ParmVarDecl *Param = Constructor->getParamDecl(0);
4137     QualType ParamType = Param->getType().getNonReferenceType();
4138 
4139     Expr *CopyCtorArg =
4140       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4141                           SourceLocation(), Param, false,
4142                           Constructor->getLocation(), ParamType,
4143                           VK_LValue, nullptr);
4144 
4145     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4146 
4147     // Cast to the base class to avoid ambiguities.
4148     QualType ArgTy =
4149       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4150                                        ParamType.getQualifiers());
4151 
4152     if (Moving) {
4153       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4154     }
4155 
4156     CXXCastPath BasePath;
4157     BasePath.push_back(BaseSpec);
4158     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4159                                             CK_UncheckedDerivedToBase,
4160                                             Moving ? VK_XValue : VK_LValue,
4161                                             &BasePath).get();
4162 
4163     InitializationKind InitKind
4164       = InitializationKind::CreateDirect(Constructor->getLocation(),
4165                                          SourceLocation(), SourceLocation());
4166     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4167     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4168     break;
4169   }
4170   }
4171 
4172   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4173   if (BaseInit.isInvalid())
4174     return true;
4175 
4176   CXXBaseInit =
4177     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4178                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4179                                                         SourceLocation()),
4180                                              BaseSpec->isVirtual(),
4181                                              SourceLocation(),
4182                                              BaseInit.getAs<Expr>(),
4183                                              SourceLocation(),
4184                                              SourceLocation());
4185 
4186   return false;
4187 }
4188 
4189 static bool RefersToRValueRef(Expr *MemRef) {
4190   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4191   return Referenced->getType()->isRValueReferenceType();
4192 }
4193 
4194 static bool
4195 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4196                                ImplicitInitializerKind ImplicitInitKind,
4197                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4198                                CXXCtorInitializer *&CXXMemberInit) {
4199   if (Field->isInvalidDecl())
4200     return true;
4201 
4202   SourceLocation Loc = Constructor->getLocation();
4203 
4204   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4205     bool Moving = ImplicitInitKind == IIK_Move;
4206     ParmVarDecl *Param = Constructor->getParamDecl(0);
4207     QualType ParamType = Param->getType().getNonReferenceType();
4208 
4209     // Suppress copying zero-width bitfields.
4210     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4211       return false;
4212 
4213     Expr *MemberExprBase =
4214       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4215                           SourceLocation(), Param, false,
4216                           Loc, ParamType, VK_LValue, nullptr);
4217 
4218     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4219 
4220     if (Moving) {
4221       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4222     }
4223 
4224     // Build a reference to this field within the parameter.
4225     CXXScopeSpec SS;
4226     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4227                               Sema::LookupMemberName);
4228     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4229                                   : cast<ValueDecl>(Field), AS_public);
4230     MemberLookup.resolveKind();
4231     ExprResult CtorArg
4232       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4233                                          ParamType, Loc,
4234                                          /*IsArrow=*/false,
4235                                          SS,
4236                                          /*TemplateKWLoc=*/SourceLocation(),
4237                                          /*FirstQualifierInScope=*/nullptr,
4238                                          MemberLookup,
4239                                          /*TemplateArgs=*/nullptr,
4240                                          /*S*/nullptr);
4241     if (CtorArg.isInvalid())
4242       return true;
4243 
4244     // C++11 [class.copy]p15:
4245     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4246     //     with static_cast<T&&>(x.m);
4247     if (RefersToRValueRef(CtorArg.get())) {
4248       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4249     }
4250 
4251     // When the field we are copying is an array, create index variables for
4252     // each dimension of the array. We use these index variables to subscript
4253     // the source array, and other clients (e.g., CodeGen) will perform the
4254     // necessary iteration with these index variables.
4255     SmallVector<VarDecl *, 4> IndexVariables;
4256     QualType BaseType = Field->getType();
4257     QualType SizeType = SemaRef.Context.getSizeType();
4258     bool InitializingArray = false;
4259     while (const ConstantArrayType *Array
4260                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
4261       InitializingArray = true;
4262       // Create the iteration variable for this array index.
4263       IdentifierInfo *IterationVarName = nullptr;
4264       {
4265         SmallString<8> Str;
4266         llvm::raw_svector_ostream OS(Str);
4267         OS << "__i" << IndexVariables.size();
4268         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
4269       }
4270       VarDecl *IterationVar
4271         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
4272                           IterationVarName, SizeType,
4273                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4274                           SC_None);
4275       IndexVariables.push_back(IterationVar);
4276 
4277       // Create a reference to the iteration variable.
4278       ExprResult IterationVarRef
4279         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
4280       assert(!IterationVarRef.isInvalid() &&
4281              "Reference to invented variable cannot fail!");
4282       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
4283       assert(!IterationVarRef.isInvalid() &&
4284              "Conversion of invented variable cannot fail!");
4285 
4286       // Subscript the array with this iteration variable.
4287       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
4288                                                         IterationVarRef.get(),
4289                                                         Loc);
4290       if (CtorArg.isInvalid())
4291         return true;
4292 
4293       BaseType = Array->getElementType();
4294     }
4295 
4296     // The array subscript expression is an lvalue, which is wrong for moving.
4297     if (Moving && InitializingArray)
4298       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4299 
4300     // Construct the entity that we will be initializing. For an array, this
4301     // will be first element in the array, which may require several levels
4302     // of array-subscript entities.
4303     SmallVector<InitializedEntity, 4> Entities;
4304     Entities.reserve(1 + IndexVariables.size());
4305     if (Indirect)
4306       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
4307     else
4308       Entities.push_back(InitializedEntity::InitializeMember(Field));
4309     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
4310       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
4311                                                               0,
4312                                                               Entities.back()));
4313 
4314     // Direct-initialize to use the copy constructor.
4315     InitializationKind InitKind =
4316       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4317 
4318     Expr *CtorArgE = CtorArg.getAs<Expr>();
4319     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
4320                                    CtorArgE);
4321 
4322     ExprResult MemberInit
4323       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
4324                         MultiExprArg(&CtorArgE, 1));
4325     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4326     if (MemberInit.isInvalid())
4327       return true;
4328 
4329     if (Indirect) {
4330       assert(IndexVariables.size() == 0 &&
4331              "Indirect field improperly initialized");
4332       CXXMemberInit
4333         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
4334                                                    Loc, Loc,
4335                                                    MemberInit.getAs<Expr>(),
4336                                                    Loc);
4337     } else
4338       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
4339                                                  Loc, MemberInit.getAs<Expr>(),
4340                                                  Loc,
4341                                                  IndexVariables.data(),
4342                                                  IndexVariables.size());
4343     return false;
4344   }
4345 
4346   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4347          "Unhandled implicit init kind!");
4348 
4349   QualType FieldBaseElementType =
4350     SemaRef.Context.getBaseElementType(Field->getType());
4351 
4352   if (FieldBaseElementType->isRecordType()) {
4353     InitializedEntity InitEntity
4354       = Indirect? InitializedEntity::InitializeMember(Indirect)
4355                 : InitializedEntity::InitializeMember(Field);
4356     InitializationKind InitKind =
4357       InitializationKind::CreateDefault(Loc);
4358 
4359     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4360     ExprResult MemberInit =
4361       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4362 
4363     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4364     if (MemberInit.isInvalid())
4365       return true;
4366 
4367     if (Indirect)
4368       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4369                                                                Indirect, Loc,
4370                                                                Loc,
4371                                                                MemberInit.get(),
4372                                                                Loc);
4373     else
4374       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4375                                                                Field, Loc, Loc,
4376                                                                MemberInit.get(),
4377                                                                Loc);
4378     return false;
4379   }
4380 
4381   if (!Field->getParent()->isUnion()) {
4382     if (FieldBaseElementType->isReferenceType()) {
4383       SemaRef.Diag(Constructor->getLocation(),
4384                    diag::err_uninitialized_member_in_ctor)
4385       << (int)Constructor->isImplicit()
4386       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4387       << 0 << Field->getDeclName();
4388       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4389       return true;
4390     }
4391 
4392     if (FieldBaseElementType.isConstQualified()) {
4393       SemaRef.Diag(Constructor->getLocation(),
4394                    diag::err_uninitialized_member_in_ctor)
4395       << (int)Constructor->isImplicit()
4396       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4397       << 1 << Field->getDeclName();
4398       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4399       return true;
4400     }
4401   }
4402 
4403   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
4404       FieldBaseElementType->isObjCRetainableType() &&
4405       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4406       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
4407     // ARC:
4408     //   Default-initialize Objective-C pointers to NULL.
4409     CXXMemberInit
4410       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4411                                                  Loc, Loc,
4412                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4413                                                  Loc);
4414     return false;
4415   }
4416 
4417   // Nothing to initialize.
4418   CXXMemberInit = nullptr;
4419   return false;
4420 }
4421 
4422 namespace {
4423 struct BaseAndFieldInfo {
4424   Sema &S;
4425   CXXConstructorDecl *Ctor;
4426   bool AnyErrorsInInits;
4427   ImplicitInitializerKind IIK;
4428   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4429   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4430   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4431 
4432   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4433     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4434     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4435     if (Ctor->getInheritedConstructor())
4436       IIK = IIK_Inherit;
4437     else if (Generated && Ctor->isCopyConstructor())
4438       IIK = IIK_Copy;
4439     else if (Generated && Ctor->isMoveConstructor())
4440       IIK = IIK_Move;
4441     else
4442       IIK = IIK_Default;
4443   }
4444 
4445   bool isImplicitCopyOrMove() const {
4446     switch (IIK) {
4447     case IIK_Copy:
4448     case IIK_Move:
4449       return true;
4450 
4451     case IIK_Default:
4452     case IIK_Inherit:
4453       return false;
4454     }
4455 
4456     llvm_unreachable("Invalid ImplicitInitializerKind!");
4457   }
4458 
4459   bool addFieldInitializer(CXXCtorInitializer *Init) {
4460     AllToInit.push_back(Init);
4461 
4462     // Check whether this initializer makes the field "used".
4463     if (Init->getInit()->HasSideEffects(S.Context))
4464       S.UnusedPrivateFields.remove(Init->getAnyMember());
4465 
4466     return false;
4467   }
4468 
4469   bool isInactiveUnionMember(FieldDecl *Field) {
4470     RecordDecl *Record = Field->getParent();
4471     if (!Record->isUnion())
4472       return false;
4473 
4474     if (FieldDecl *Active =
4475             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4476       return Active != Field->getCanonicalDecl();
4477 
4478     // In an implicit copy or move constructor, ignore any in-class initializer.
4479     if (isImplicitCopyOrMove())
4480       return true;
4481 
4482     // If there's no explicit initialization, the field is active only if it
4483     // has an in-class initializer...
4484     if (Field->hasInClassInitializer())
4485       return false;
4486     // ... or it's an anonymous struct or union whose class has an in-class
4487     // initializer.
4488     if (!Field->isAnonymousStructOrUnion())
4489       return true;
4490     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4491     return !FieldRD->hasInClassInitializer();
4492   }
4493 
4494   /// \brief Determine whether the given field is, or is within, a union member
4495   /// that is inactive (because there was an initializer given for a different
4496   /// member of the union, or because the union was not initialized at all).
4497   bool isWithinInactiveUnionMember(FieldDecl *Field,
4498                                    IndirectFieldDecl *Indirect) {
4499     if (!Indirect)
4500       return isInactiveUnionMember(Field);
4501 
4502     for (auto *C : Indirect->chain()) {
4503       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4504       if (Field && isInactiveUnionMember(Field))
4505         return true;
4506     }
4507     return false;
4508   }
4509 };
4510 }
4511 
4512 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
4513 /// array type.
4514 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4515   if (T->isIncompleteArrayType())
4516     return true;
4517 
4518   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4519     if (!ArrayT->getSize())
4520       return true;
4521 
4522     T = ArrayT->getElementType();
4523   }
4524 
4525   return false;
4526 }
4527 
4528 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4529                                     FieldDecl *Field,
4530                                     IndirectFieldDecl *Indirect = nullptr) {
4531   if (Field->isInvalidDecl())
4532     return false;
4533 
4534   // Overwhelmingly common case: we have a direct initializer for this field.
4535   if (CXXCtorInitializer *Init =
4536           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4537     return Info.addFieldInitializer(Init);
4538 
4539   // C++11 [class.base.init]p8:
4540   //   if the entity is a non-static data member that has a
4541   //   brace-or-equal-initializer and either
4542   //   -- the constructor's class is a union and no other variant member of that
4543   //      union is designated by a mem-initializer-id or
4544   //   -- the constructor's class is not a union, and, if the entity is a member
4545   //      of an anonymous union, no other member of that union is designated by
4546   //      a mem-initializer-id,
4547   //   the entity is initialized as specified in [dcl.init].
4548   //
4549   // We also apply the same rules to handle anonymous structs within anonymous
4550   // unions.
4551   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4552     return false;
4553 
4554   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4555     ExprResult DIE =
4556         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4557     if (DIE.isInvalid())
4558       return true;
4559     CXXCtorInitializer *Init;
4560     if (Indirect)
4561       Init = new (SemaRef.Context)
4562           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4563                              SourceLocation(), DIE.get(), SourceLocation());
4564     else
4565       Init = new (SemaRef.Context)
4566           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4567                              SourceLocation(), DIE.get(), SourceLocation());
4568     return Info.addFieldInitializer(Init);
4569   }
4570 
4571   // Don't initialize incomplete or zero-length arrays.
4572   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4573     return false;
4574 
4575   // Don't try to build an implicit initializer if there were semantic
4576   // errors in any of the initializers (and therefore we might be
4577   // missing some that the user actually wrote).
4578   if (Info.AnyErrorsInInits)
4579     return false;
4580 
4581   CXXCtorInitializer *Init = nullptr;
4582   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4583                                      Indirect, Init))
4584     return true;
4585 
4586   if (!Init)
4587     return false;
4588 
4589   return Info.addFieldInitializer(Init);
4590 }
4591 
4592 bool
4593 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4594                                CXXCtorInitializer *Initializer) {
4595   assert(Initializer->isDelegatingInitializer());
4596   Constructor->setNumCtorInitializers(1);
4597   CXXCtorInitializer **initializer =
4598     new (Context) CXXCtorInitializer*[1];
4599   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4600   Constructor->setCtorInitializers(initializer);
4601 
4602   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4603     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4604     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4605   }
4606 
4607   DelegatingCtorDecls.push_back(Constructor);
4608 
4609   DiagnoseUninitializedFields(*this, Constructor);
4610 
4611   return false;
4612 }
4613 
4614 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4615                                ArrayRef<CXXCtorInitializer *> Initializers) {
4616   if (Constructor->isDependentContext()) {
4617     // Just store the initializers as written, they will be checked during
4618     // instantiation.
4619     if (!Initializers.empty()) {
4620       Constructor->setNumCtorInitializers(Initializers.size());
4621       CXXCtorInitializer **baseOrMemberInitializers =
4622         new (Context) CXXCtorInitializer*[Initializers.size()];
4623       memcpy(baseOrMemberInitializers, Initializers.data(),
4624              Initializers.size() * sizeof(CXXCtorInitializer*));
4625       Constructor->setCtorInitializers(baseOrMemberInitializers);
4626     }
4627 
4628     // Let template instantiation know whether we had errors.
4629     if (AnyErrors)
4630       Constructor->setInvalidDecl();
4631 
4632     return false;
4633   }
4634 
4635   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4636 
4637   // We need to build the initializer AST according to order of construction
4638   // and not what user specified in the Initializers list.
4639   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4640   if (!ClassDecl)
4641     return true;
4642 
4643   bool HadError = false;
4644 
4645   for (unsigned i = 0; i < Initializers.size(); i++) {
4646     CXXCtorInitializer *Member = Initializers[i];
4647 
4648     if (Member->isBaseInitializer())
4649       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4650     else {
4651       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4652 
4653       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4654         for (auto *C : F->chain()) {
4655           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4656           if (FD && FD->getParent()->isUnion())
4657             Info.ActiveUnionMember.insert(std::make_pair(
4658                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4659         }
4660       } else if (FieldDecl *FD = Member->getMember()) {
4661         if (FD->getParent()->isUnion())
4662           Info.ActiveUnionMember.insert(std::make_pair(
4663               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4664       }
4665     }
4666   }
4667 
4668   // Keep track of the direct virtual bases.
4669   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4670   for (auto &I : ClassDecl->bases()) {
4671     if (I.isVirtual())
4672       DirectVBases.insert(&I);
4673   }
4674 
4675   // Push virtual bases before others.
4676   for (auto &VBase : ClassDecl->vbases()) {
4677     if (CXXCtorInitializer *Value
4678         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4679       // [class.base.init]p7, per DR257:
4680       //   A mem-initializer where the mem-initializer-id names a virtual base
4681       //   class is ignored during execution of a constructor of any class that
4682       //   is not the most derived class.
4683       if (ClassDecl->isAbstract()) {
4684         // FIXME: Provide a fixit to remove the base specifier. This requires
4685         // tracking the location of the associated comma for a base specifier.
4686         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4687           << VBase.getType() << ClassDecl;
4688         DiagnoseAbstractType(ClassDecl);
4689       }
4690 
4691       Info.AllToInit.push_back(Value);
4692     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4693       // [class.base.init]p8, per DR257:
4694       //   If a given [...] base class is not named by a mem-initializer-id
4695       //   [...] and the entity is not a virtual base class of an abstract
4696       //   class, then [...] the entity is default-initialized.
4697       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4698       CXXCtorInitializer *CXXBaseInit;
4699       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4700                                        &VBase, IsInheritedVirtualBase,
4701                                        CXXBaseInit)) {
4702         HadError = true;
4703         continue;
4704       }
4705 
4706       Info.AllToInit.push_back(CXXBaseInit);
4707     }
4708   }
4709 
4710   // Non-virtual bases.
4711   for (auto &Base : ClassDecl->bases()) {
4712     // Virtuals are in the virtual base list and already constructed.
4713     if (Base.isVirtual())
4714       continue;
4715 
4716     if (CXXCtorInitializer *Value
4717           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4718       Info.AllToInit.push_back(Value);
4719     } else if (!AnyErrors) {
4720       CXXCtorInitializer *CXXBaseInit;
4721       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4722                                        &Base, /*IsInheritedVirtualBase=*/false,
4723                                        CXXBaseInit)) {
4724         HadError = true;
4725         continue;
4726       }
4727 
4728       Info.AllToInit.push_back(CXXBaseInit);
4729     }
4730   }
4731 
4732   // Fields.
4733   for (auto *Mem : ClassDecl->decls()) {
4734     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4735       // C++ [class.bit]p2:
4736       //   A declaration for a bit-field that omits the identifier declares an
4737       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4738       //   initialized.
4739       if (F->isUnnamedBitfield())
4740         continue;
4741 
4742       // If we're not generating the implicit copy/move constructor, then we'll
4743       // handle anonymous struct/union fields based on their individual
4744       // indirect fields.
4745       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4746         continue;
4747 
4748       if (CollectFieldInitializer(*this, Info, F))
4749         HadError = true;
4750       continue;
4751     }
4752 
4753     // Beyond this point, we only consider default initialization.
4754     if (Info.isImplicitCopyOrMove())
4755       continue;
4756 
4757     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4758       if (F->getType()->isIncompleteArrayType()) {
4759         assert(ClassDecl->hasFlexibleArrayMember() &&
4760                "Incomplete array type is not valid");
4761         continue;
4762       }
4763 
4764       // Initialize each field of an anonymous struct individually.
4765       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4766         HadError = true;
4767 
4768       continue;
4769     }
4770   }
4771 
4772   unsigned NumInitializers = Info.AllToInit.size();
4773   if (NumInitializers > 0) {
4774     Constructor->setNumCtorInitializers(NumInitializers);
4775     CXXCtorInitializer **baseOrMemberInitializers =
4776       new (Context) CXXCtorInitializer*[NumInitializers];
4777     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4778            NumInitializers * sizeof(CXXCtorInitializer*));
4779     Constructor->setCtorInitializers(baseOrMemberInitializers);
4780 
4781     // Constructors implicitly reference the base and member
4782     // destructors.
4783     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4784                                            Constructor->getParent());
4785   }
4786 
4787   return HadError;
4788 }
4789 
4790 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4791   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4792     const RecordDecl *RD = RT->getDecl();
4793     if (RD->isAnonymousStructOrUnion()) {
4794       for (auto *Field : RD->fields())
4795         PopulateKeysForFields(Field, IdealInits);
4796       return;
4797     }
4798   }
4799   IdealInits.push_back(Field->getCanonicalDecl());
4800 }
4801 
4802 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4803   return Context.getCanonicalType(BaseType).getTypePtr();
4804 }
4805 
4806 static const void *GetKeyForMember(ASTContext &Context,
4807                                    CXXCtorInitializer *Member) {
4808   if (!Member->isAnyMemberInitializer())
4809     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4810 
4811   return Member->getAnyMember()->getCanonicalDecl();
4812 }
4813 
4814 static void DiagnoseBaseOrMemInitializerOrder(
4815     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4816     ArrayRef<CXXCtorInitializer *> Inits) {
4817   if (Constructor->getDeclContext()->isDependentContext())
4818     return;
4819 
4820   // Don't check initializers order unless the warning is enabled at the
4821   // location of at least one initializer.
4822   bool ShouldCheckOrder = false;
4823   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4824     CXXCtorInitializer *Init = Inits[InitIndex];
4825     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4826                                  Init->getSourceLocation())) {
4827       ShouldCheckOrder = true;
4828       break;
4829     }
4830   }
4831   if (!ShouldCheckOrder)
4832     return;
4833 
4834   // Build the list of bases and members in the order that they'll
4835   // actually be initialized.  The explicit initializers should be in
4836   // this same order but may be missing things.
4837   SmallVector<const void*, 32> IdealInitKeys;
4838 
4839   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4840 
4841   // 1. Virtual bases.
4842   for (const auto &VBase : ClassDecl->vbases())
4843     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4844 
4845   // 2. Non-virtual bases.
4846   for (const auto &Base : ClassDecl->bases()) {
4847     if (Base.isVirtual())
4848       continue;
4849     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4850   }
4851 
4852   // 3. Direct fields.
4853   for (auto *Field : ClassDecl->fields()) {
4854     if (Field->isUnnamedBitfield())
4855       continue;
4856 
4857     PopulateKeysForFields(Field, IdealInitKeys);
4858   }
4859 
4860   unsigned NumIdealInits = IdealInitKeys.size();
4861   unsigned IdealIndex = 0;
4862 
4863   CXXCtorInitializer *PrevInit = nullptr;
4864   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4865     CXXCtorInitializer *Init = Inits[InitIndex];
4866     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4867 
4868     // Scan forward to try to find this initializer in the idealized
4869     // initializers list.
4870     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4871       if (InitKey == IdealInitKeys[IdealIndex])
4872         break;
4873 
4874     // If we didn't find this initializer, it must be because we
4875     // scanned past it on a previous iteration.  That can only
4876     // happen if we're out of order;  emit a warning.
4877     if (IdealIndex == NumIdealInits && PrevInit) {
4878       Sema::SemaDiagnosticBuilder D =
4879         SemaRef.Diag(PrevInit->getSourceLocation(),
4880                      diag::warn_initializer_out_of_order);
4881 
4882       if (PrevInit->isAnyMemberInitializer())
4883         D << 0 << PrevInit->getAnyMember()->getDeclName();
4884       else
4885         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4886 
4887       if (Init->isAnyMemberInitializer())
4888         D << 0 << Init->getAnyMember()->getDeclName();
4889       else
4890         D << 1 << Init->getTypeSourceInfo()->getType();
4891 
4892       // Move back to the initializer's location in the ideal list.
4893       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4894         if (InitKey == IdealInitKeys[IdealIndex])
4895           break;
4896 
4897       assert(IdealIndex < NumIdealInits &&
4898              "initializer not found in initializer list");
4899     }
4900 
4901     PrevInit = Init;
4902   }
4903 }
4904 
4905 namespace {
4906 bool CheckRedundantInit(Sema &S,
4907                         CXXCtorInitializer *Init,
4908                         CXXCtorInitializer *&PrevInit) {
4909   if (!PrevInit) {
4910     PrevInit = Init;
4911     return false;
4912   }
4913 
4914   if (FieldDecl *Field = Init->getAnyMember())
4915     S.Diag(Init->getSourceLocation(),
4916            diag::err_multiple_mem_initialization)
4917       << Field->getDeclName()
4918       << Init->getSourceRange();
4919   else {
4920     const Type *BaseClass = Init->getBaseClass();
4921     assert(BaseClass && "neither field nor base");
4922     S.Diag(Init->getSourceLocation(),
4923            diag::err_multiple_base_initialization)
4924       << QualType(BaseClass, 0)
4925       << Init->getSourceRange();
4926   }
4927   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4928     << 0 << PrevInit->getSourceRange();
4929 
4930   return true;
4931 }
4932 
4933 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4934 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4935 
4936 bool CheckRedundantUnionInit(Sema &S,
4937                              CXXCtorInitializer *Init,
4938                              RedundantUnionMap &Unions) {
4939   FieldDecl *Field = Init->getAnyMember();
4940   RecordDecl *Parent = Field->getParent();
4941   NamedDecl *Child = Field;
4942 
4943   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4944     if (Parent->isUnion()) {
4945       UnionEntry &En = Unions[Parent];
4946       if (En.first && En.first != Child) {
4947         S.Diag(Init->getSourceLocation(),
4948                diag::err_multiple_mem_union_initialization)
4949           << Field->getDeclName()
4950           << Init->getSourceRange();
4951         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4952           << 0 << En.second->getSourceRange();
4953         return true;
4954       }
4955       if (!En.first) {
4956         En.first = Child;
4957         En.second = Init;
4958       }
4959       if (!Parent->isAnonymousStructOrUnion())
4960         return false;
4961     }
4962 
4963     Child = Parent;
4964     Parent = cast<RecordDecl>(Parent->getDeclContext());
4965   }
4966 
4967   return false;
4968 }
4969 }
4970 
4971 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4972 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4973                                 SourceLocation ColonLoc,
4974                                 ArrayRef<CXXCtorInitializer*> MemInits,
4975                                 bool AnyErrors) {
4976   if (!ConstructorDecl)
4977     return;
4978 
4979   AdjustDeclIfTemplate(ConstructorDecl);
4980 
4981   CXXConstructorDecl *Constructor
4982     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4983 
4984   if (!Constructor) {
4985     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4986     return;
4987   }
4988 
4989   // Mapping for the duplicate initializers check.
4990   // For member initializers, this is keyed with a FieldDecl*.
4991   // For base initializers, this is keyed with a Type*.
4992   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4993 
4994   // Mapping for the inconsistent anonymous-union initializers check.
4995   RedundantUnionMap MemberUnions;
4996 
4997   bool HadError = false;
4998   for (unsigned i = 0; i < MemInits.size(); i++) {
4999     CXXCtorInitializer *Init = MemInits[i];
5000 
5001     // Set the source order index.
5002     Init->setSourceOrder(i);
5003 
5004     if (Init->isAnyMemberInitializer()) {
5005       const void *Key = GetKeyForMember(Context, Init);
5006       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5007           CheckRedundantUnionInit(*this, Init, MemberUnions))
5008         HadError = true;
5009     } else if (Init->isBaseInitializer()) {
5010       const void *Key = GetKeyForMember(Context, Init);
5011       if (CheckRedundantInit(*this, Init, Members[Key]))
5012         HadError = true;
5013     } else {
5014       assert(Init->isDelegatingInitializer());
5015       // This must be the only initializer
5016       if (MemInits.size() != 1) {
5017         Diag(Init->getSourceLocation(),
5018              diag::err_delegating_initializer_alone)
5019           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5020         // We will treat this as being the only initializer.
5021       }
5022       SetDelegatingInitializer(Constructor, MemInits[i]);
5023       // Return immediately as the initializer is set.
5024       return;
5025     }
5026   }
5027 
5028   if (HadError)
5029     return;
5030 
5031   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5032 
5033   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5034 
5035   DiagnoseUninitializedFields(*this, Constructor);
5036 }
5037 
5038 void
5039 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5040                                              CXXRecordDecl *ClassDecl) {
5041   // Ignore dependent contexts. Also ignore unions, since their members never
5042   // have destructors implicitly called.
5043   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5044     return;
5045 
5046   // FIXME: all the access-control diagnostics are positioned on the
5047   // field/base declaration.  That's probably good; that said, the
5048   // user might reasonably want to know why the destructor is being
5049   // emitted, and we currently don't say.
5050 
5051   // Non-static data members.
5052   for (auto *Field : ClassDecl->fields()) {
5053     if (Field->isInvalidDecl())
5054       continue;
5055 
5056     // Don't destroy incomplete or zero-length arrays.
5057     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5058       continue;
5059 
5060     QualType FieldType = Context.getBaseElementType(Field->getType());
5061 
5062     const RecordType* RT = FieldType->getAs<RecordType>();
5063     if (!RT)
5064       continue;
5065 
5066     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5067     if (FieldClassDecl->isInvalidDecl())
5068       continue;
5069     if (FieldClassDecl->hasIrrelevantDestructor())
5070       continue;
5071     // The destructor for an implicit anonymous union member is never invoked.
5072     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5073       continue;
5074 
5075     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5076     assert(Dtor && "No dtor found for FieldClassDecl!");
5077     CheckDestructorAccess(Field->getLocation(), Dtor,
5078                           PDiag(diag::err_access_dtor_field)
5079                             << Field->getDeclName()
5080                             << FieldType);
5081 
5082     MarkFunctionReferenced(Location, Dtor);
5083     DiagnoseUseOfDecl(Dtor, Location);
5084   }
5085 
5086   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5087 
5088   // Bases.
5089   for (const auto &Base : ClassDecl->bases()) {
5090     // Bases are always records in a well-formed non-dependent class.
5091     const RecordType *RT = Base.getType()->getAs<RecordType>();
5092 
5093     // Remember direct virtual bases.
5094     if (Base.isVirtual())
5095       DirectVirtualBases.insert(RT);
5096 
5097     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5098     // If our base class is invalid, we probably can't get its dtor anyway.
5099     if (BaseClassDecl->isInvalidDecl())
5100       continue;
5101     if (BaseClassDecl->hasIrrelevantDestructor())
5102       continue;
5103 
5104     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5105     assert(Dtor && "No dtor found for BaseClassDecl!");
5106 
5107     // FIXME: caret should be on the start of the class name
5108     CheckDestructorAccess(Base.getLocStart(), Dtor,
5109                           PDiag(diag::err_access_dtor_base)
5110                             << Base.getType()
5111                             << Base.getSourceRange(),
5112                           Context.getTypeDeclType(ClassDecl));
5113 
5114     MarkFunctionReferenced(Location, Dtor);
5115     DiagnoseUseOfDecl(Dtor, Location);
5116   }
5117 
5118   // Virtual bases.
5119   for (const auto &VBase : ClassDecl->vbases()) {
5120     // Bases are always records in a well-formed non-dependent class.
5121     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5122 
5123     // Ignore direct virtual bases.
5124     if (DirectVirtualBases.count(RT))
5125       continue;
5126 
5127     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5128     // If our base class is invalid, we probably can't get its dtor anyway.
5129     if (BaseClassDecl->isInvalidDecl())
5130       continue;
5131     if (BaseClassDecl->hasIrrelevantDestructor())
5132       continue;
5133 
5134     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5135     assert(Dtor && "No dtor found for BaseClassDecl!");
5136     if (CheckDestructorAccess(
5137             ClassDecl->getLocation(), Dtor,
5138             PDiag(diag::err_access_dtor_vbase)
5139                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5140             Context.getTypeDeclType(ClassDecl)) ==
5141         AR_accessible) {
5142       CheckDerivedToBaseConversion(
5143           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5144           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5145           SourceRange(), DeclarationName(), nullptr);
5146     }
5147 
5148     MarkFunctionReferenced(Location, Dtor);
5149     DiagnoseUseOfDecl(Dtor, Location);
5150   }
5151 }
5152 
5153 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5154   if (!CDtorDecl)
5155     return;
5156 
5157   if (CXXConstructorDecl *Constructor
5158       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5159     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5160     DiagnoseUninitializedFields(*this, Constructor);
5161   }
5162 }
5163 
5164 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5165   if (!getLangOpts().CPlusPlus)
5166     return false;
5167 
5168   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5169   if (!RD)
5170     return false;
5171 
5172   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5173   // class template specialization here, but doing so breaks a lot of code.
5174 
5175   // We can't answer whether something is abstract until it has a
5176   // definition. If it's currently being defined, we'll walk back
5177   // over all the declarations when we have a full definition.
5178   const CXXRecordDecl *Def = RD->getDefinition();
5179   if (!Def || Def->isBeingDefined())
5180     return false;
5181 
5182   return RD->isAbstract();
5183 }
5184 
5185 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5186                                   TypeDiagnoser &Diagnoser) {
5187   if (!isAbstractType(Loc, T))
5188     return false;
5189 
5190   T = Context.getBaseElementType(T);
5191   Diagnoser.diagnose(*this, Loc, T);
5192   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5193   return true;
5194 }
5195 
5196 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5197   // Check if we've already emitted the list of pure virtual functions
5198   // for this class.
5199   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5200     return;
5201 
5202   // If the diagnostic is suppressed, don't emit the notes. We're only
5203   // going to emit them once, so try to attach them to a diagnostic we're
5204   // actually going to show.
5205   if (Diags.isLastDiagnosticIgnored())
5206     return;
5207 
5208   CXXFinalOverriderMap FinalOverriders;
5209   RD->getFinalOverriders(FinalOverriders);
5210 
5211   // Keep a set of seen pure methods so we won't diagnose the same method
5212   // more than once.
5213   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5214 
5215   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5216                                    MEnd = FinalOverriders.end();
5217        M != MEnd;
5218        ++M) {
5219     for (OverridingMethods::iterator SO = M->second.begin(),
5220                                   SOEnd = M->second.end();
5221          SO != SOEnd; ++SO) {
5222       // C++ [class.abstract]p4:
5223       //   A class is abstract if it contains or inherits at least one
5224       //   pure virtual function for which the final overrider is pure
5225       //   virtual.
5226 
5227       //
5228       if (SO->second.size() != 1)
5229         continue;
5230 
5231       if (!SO->second.front().Method->isPure())
5232         continue;
5233 
5234       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5235         continue;
5236 
5237       Diag(SO->second.front().Method->getLocation(),
5238            diag::note_pure_virtual_function)
5239         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5240     }
5241   }
5242 
5243   if (!PureVirtualClassDiagSet)
5244     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5245   PureVirtualClassDiagSet->insert(RD);
5246 }
5247 
5248 namespace {
5249 struct AbstractUsageInfo {
5250   Sema &S;
5251   CXXRecordDecl *Record;
5252   CanQualType AbstractType;
5253   bool Invalid;
5254 
5255   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5256     : S(S), Record(Record),
5257       AbstractType(S.Context.getCanonicalType(
5258                    S.Context.getTypeDeclType(Record))),
5259       Invalid(false) {}
5260 
5261   void DiagnoseAbstractType() {
5262     if (Invalid) return;
5263     S.DiagnoseAbstractType(Record);
5264     Invalid = true;
5265   }
5266 
5267   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5268 };
5269 
5270 struct CheckAbstractUsage {
5271   AbstractUsageInfo &Info;
5272   const NamedDecl *Ctx;
5273 
5274   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5275     : Info(Info), Ctx(Ctx) {}
5276 
5277   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5278     switch (TL.getTypeLocClass()) {
5279 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5280 #define TYPELOC(CLASS, PARENT) \
5281     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5282 #include "clang/AST/TypeLocNodes.def"
5283     }
5284   }
5285 
5286   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5287     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5288     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5289       if (!TL.getParam(I))
5290         continue;
5291 
5292       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5293       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5294     }
5295   }
5296 
5297   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5298     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5299   }
5300 
5301   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5302     // Visit the type parameters from a permissive context.
5303     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5304       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5305       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5306         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5307           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5308       // TODO: other template argument types?
5309     }
5310   }
5311 
5312   // Visit pointee types from a permissive context.
5313 #define CheckPolymorphic(Type) \
5314   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5315     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5316   }
5317   CheckPolymorphic(PointerTypeLoc)
5318   CheckPolymorphic(ReferenceTypeLoc)
5319   CheckPolymorphic(MemberPointerTypeLoc)
5320   CheckPolymorphic(BlockPointerTypeLoc)
5321   CheckPolymorphic(AtomicTypeLoc)
5322 
5323   /// Handle all the types we haven't given a more specific
5324   /// implementation for above.
5325   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5326     // Every other kind of type that we haven't called out already
5327     // that has an inner type is either (1) sugar or (2) contains that
5328     // inner type in some way as a subobject.
5329     if (TypeLoc Next = TL.getNextTypeLoc())
5330       return Visit(Next, Sel);
5331 
5332     // If there's no inner type and we're in a permissive context,
5333     // don't diagnose.
5334     if (Sel == Sema::AbstractNone) return;
5335 
5336     // Check whether the type matches the abstract type.
5337     QualType T = TL.getType();
5338     if (T->isArrayType()) {
5339       Sel = Sema::AbstractArrayType;
5340       T = Info.S.Context.getBaseElementType(T);
5341     }
5342     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5343     if (CT != Info.AbstractType) return;
5344 
5345     // It matched; do some magic.
5346     if (Sel == Sema::AbstractArrayType) {
5347       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5348         << T << TL.getSourceRange();
5349     } else {
5350       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5351         << Sel << T << TL.getSourceRange();
5352     }
5353     Info.DiagnoseAbstractType();
5354   }
5355 };
5356 
5357 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5358                                   Sema::AbstractDiagSelID Sel) {
5359   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5360 }
5361 
5362 }
5363 
5364 /// Check for invalid uses of an abstract type in a method declaration.
5365 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5366                                     CXXMethodDecl *MD) {
5367   // No need to do the check on definitions, which require that
5368   // the return/param types be complete.
5369   if (MD->doesThisDeclarationHaveABody())
5370     return;
5371 
5372   // For safety's sake, just ignore it if we don't have type source
5373   // information.  This should never happen for non-implicit methods,
5374   // but...
5375   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5376     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5377 }
5378 
5379 /// Check for invalid uses of an abstract type within a class definition.
5380 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5381                                     CXXRecordDecl *RD) {
5382   for (auto *D : RD->decls()) {
5383     if (D->isImplicit()) continue;
5384 
5385     // Methods and method templates.
5386     if (isa<CXXMethodDecl>(D)) {
5387       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5388     } else if (isa<FunctionTemplateDecl>(D)) {
5389       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5390       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5391 
5392     // Fields and static variables.
5393     } else if (isa<FieldDecl>(D)) {
5394       FieldDecl *FD = cast<FieldDecl>(D);
5395       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5396         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5397     } else if (isa<VarDecl>(D)) {
5398       VarDecl *VD = cast<VarDecl>(D);
5399       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5400         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5401 
5402     // Nested classes and class templates.
5403     } else if (isa<CXXRecordDecl>(D)) {
5404       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5405     } else if (isa<ClassTemplateDecl>(D)) {
5406       CheckAbstractClassUsage(Info,
5407                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5408     }
5409   }
5410 }
5411 
5412 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5413   Attr *ClassAttr = getDLLAttr(Class);
5414   if (!ClassAttr)
5415     return;
5416 
5417   assert(ClassAttr->getKind() == attr::DLLExport);
5418 
5419   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5420 
5421   if (TSK == TSK_ExplicitInstantiationDeclaration)
5422     // Don't go any further if this is just an explicit instantiation
5423     // declaration.
5424     return;
5425 
5426   for (Decl *Member : Class->decls()) {
5427     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5428     if (!MD)
5429       continue;
5430 
5431     if (Member->getAttr<DLLExportAttr>()) {
5432       if (MD->isUserProvided()) {
5433         // Instantiate non-default class member functions ...
5434 
5435         // .. except for certain kinds of template specializations.
5436         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5437           continue;
5438 
5439         S.MarkFunctionReferenced(Class->getLocation(), MD);
5440 
5441         // The function will be passed to the consumer when its definition is
5442         // encountered.
5443       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5444                  MD->isCopyAssignmentOperator() ||
5445                  MD->isMoveAssignmentOperator()) {
5446         // Synthesize and instantiate non-trivial implicit methods, explicitly
5447         // defaulted methods, and the copy and move assignment operators. The
5448         // latter are exported even if they are trivial, because the address of
5449         // an operator can be taken and should compare equal accross libraries.
5450         DiagnosticErrorTrap Trap(S.Diags);
5451         S.MarkFunctionReferenced(Class->getLocation(), MD);
5452         if (Trap.hasErrorOccurred()) {
5453           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5454               << Class->getName() << !S.getLangOpts().CPlusPlus11;
5455           break;
5456         }
5457 
5458         // There is no later point when we will see the definition of this
5459         // function, so pass it to the consumer now.
5460         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5461       }
5462     }
5463   }
5464 }
5465 
5466 /// \brief Check class-level dllimport/dllexport attribute.
5467 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5468   Attr *ClassAttr = getDLLAttr(Class);
5469 
5470   // MSVC inherits DLL attributes to partial class template specializations.
5471   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5472     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5473       if (Attr *TemplateAttr =
5474               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5475         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5476         A->setInherited(true);
5477         ClassAttr = A;
5478       }
5479     }
5480   }
5481 
5482   if (!ClassAttr)
5483     return;
5484 
5485   if (!Class->isExternallyVisible()) {
5486     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5487         << Class << ClassAttr;
5488     return;
5489   }
5490 
5491   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5492       !ClassAttr->isInherited()) {
5493     // Diagnose dll attributes on members of class with dll attribute.
5494     for (Decl *Member : Class->decls()) {
5495       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5496         continue;
5497       InheritableAttr *MemberAttr = getDLLAttr(Member);
5498       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5499         continue;
5500 
5501       Diag(MemberAttr->getLocation(),
5502              diag::err_attribute_dll_member_of_dll_class)
5503           << MemberAttr << ClassAttr;
5504       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5505       Member->setInvalidDecl();
5506     }
5507   }
5508 
5509   if (Class->getDescribedClassTemplate())
5510     // Don't inherit dll attribute until the template is instantiated.
5511     return;
5512 
5513   // The class is either imported or exported.
5514   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5515 
5516   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5517 
5518   // Ignore explicit dllexport on explicit class template instantiation declarations.
5519   if (ClassExported && !ClassAttr->isInherited() &&
5520       TSK == TSK_ExplicitInstantiationDeclaration) {
5521     Class->dropAttr<DLLExportAttr>();
5522     return;
5523   }
5524 
5525   // Force declaration of implicit members so they can inherit the attribute.
5526   ForceDeclarationOfImplicitMembers(Class);
5527 
5528   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5529   // seem to be true in practice?
5530 
5531   for (Decl *Member : Class->decls()) {
5532     VarDecl *VD = dyn_cast<VarDecl>(Member);
5533     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5534 
5535     // Only methods and static fields inherit the attributes.
5536     if (!VD && !MD)
5537       continue;
5538 
5539     if (MD) {
5540       // Don't process deleted methods.
5541       if (MD->isDeleted())
5542         continue;
5543 
5544       if (MD->isInlined()) {
5545         // MinGW does not import or export inline methods.
5546         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5547             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5548           continue;
5549 
5550         // MSVC versions before 2015 don't export the move assignment operators
5551         // and move constructor, so don't attempt to import/export them if
5552         // we have a definition.
5553         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5554         if ((MD->isMoveAssignmentOperator() ||
5555              (Ctor && Ctor->isMoveConstructor())) &&
5556             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5557           continue;
5558 
5559         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5560         // operator is exported anyway.
5561         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5562             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5563           continue;
5564       }
5565     }
5566 
5567     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5568       continue;
5569 
5570     if (!getDLLAttr(Member)) {
5571       auto *NewAttr =
5572           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5573       NewAttr->setInherited(true);
5574       Member->addAttr(NewAttr);
5575     }
5576   }
5577 
5578   if (ClassExported)
5579     DelayedDllExportClasses.push_back(Class);
5580 }
5581 
5582 /// \brief Perform propagation of DLL attributes from a derived class to a
5583 /// templated base class for MS compatibility.
5584 void Sema::propagateDLLAttrToBaseClassTemplate(
5585     CXXRecordDecl *Class, Attr *ClassAttr,
5586     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5587   if (getDLLAttr(
5588           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5589     // If the base class template has a DLL attribute, don't try to change it.
5590     return;
5591   }
5592 
5593   auto TSK = BaseTemplateSpec->getSpecializationKind();
5594   if (!getDLLAttr(BaseTemplateSpec) &&
5595       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5596        TSK == TSK_ImplicitInstantiation)) {
5597     // The template hasn't been instantiated yet (or it has, but only as an
5598     // explicit instantiation declaration or implicit instantiation, which means
5599     // we haven't codegenned any members yet), so propagate the attribute.
5600     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5601     NewAttr->setInherited(true);
5602     BaseTemplateSpec->addAttr(NewAttr);
5603 
5604     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5605     // needs to be run again to work see the new attribute. Otherwise this will
5606     // get run whenever the template is instantiated.
5607     if (TSK != TSK_Undeclared)
5608       checkClassLevelDLLAttribute(BaseTemplateSpec);
5609 
5610     return;
5611   }
5612 
5613   if (getDLLAttr(BaseTemplateSpec)) {
5614     // The template has already been specialized or instantiated with an
5615     // attribute, explicitly or through propagation. We should not try to change
5616     // it.
5617     return;
5618   }
5619 
5620   // The template was previously instantiated or explicitly specialized without
5621   // a dll attribute, It's too late for us to add an attribute, so warn that
5622   // this is unsupported.
5623   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5624       << BaseTemplateSpec->isExplicitSpecialization();
5625   Diag(ClassAttr->getLocation(), diag::note_attribute);
5626   if (BaseTemplateSpec->isExplicitSpecialization()) {
5627     Diag(BaseTemplateSpec->getLocation(),
5628            diag::note_template_class_explicit_specialization_was_here)
5629         << BaseTemplateSpec;
5630   } else {
5631     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5632            diag::note_template_class_instantiation_was_here)
5633         << BaseTemplateSpec;
5634   }
5635 }
5636 
5637 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5638                                         SourceLocation DefaultLoc) {
5639   switch (S.getSpecialMember(MD)) {
5640   case Sema::CXXDefaultConstructor:
5641     S.DefineImplicitDefaultConstructor(DefaultLoc,
5642                                        cast<CXXConstructorDecl>(MD));
5643     break;
5644   case Sema::CXXCopyConstructor:
5645     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5646     break;
5647   case Sema::CXXCopyAssignment:
5648     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5649     break;
5650   case Sema::CXXDestructor:
5651     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5652     break;
5653   case Sema::CXXMoveConstructor:
5654     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5655     break;
5656   case Sema::CXXMoveAssignment:
5657     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5658     break;
5659   case Sema::CXXInvalid:
5660     llvm_unreachable("Invalid special member.");
5661   }
5662 }
5663 
5664 /// \brief Perform semantic checks on a class definition that has been
5665 /// completing, introducing implicitly-declared members, checking for
5666 /// abstract types, etc.
5667 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5668   if (!Record)
5669     return;
5670 
5671   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5672     AbstractUsageInfo Info(*this, Record);
5673     CheckAbstractClassUsage(Info, Record);
5674   }
5675 
5676   // If this is not an aggregate type and has no user-declared constructor,
5677   // complain about any non-static data members of reference or const scalar
5678   // type, since they will never get initializers.
5679   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5680       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5681       !Record->isLambda()) {
5682     bool Complained = false;
5683     for (const auto *F : Record->fields()) {
5684       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5685         continue;
5686 
5687       if (F->getType()->isReferenceType() ||
5688           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5689         if (!Complained) {
5690           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5691             << Record->getTagKind() << Record;
5692           Complained = true;
5693         }
5694 
5695         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5696           << F->getType()->isReferenceType()
5697           << F->getDeclName();
5698       }
5699     }
5700   }
5701 
5702   if (Record->getIdentifier()) {
5703     // C++ [class.mem]p13:
5704     //   If T is the name of a class, then each of the following shall have a
5705     //   name different from T:
5706     //     - every member of every anonymous union that is a member of class T.
5707     //
5708     // C++ [class.mem]p14:
5709     //   In addition, if class T has a user-declared constructor (12.1), every
5710     //   non-static data member of class T shall have a name different from T.
5711     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5712     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5713          ++I) {
5714       NamedDecl *D = *I;
5715       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5716           isa<IndirectFieldDecl>(D)) {
5717         Diag(D->getLocation(), diag::err_member_name_of_class)
5718           << D->getDeclName();
5719         break;
5720       }
5721     }
5722   }
5723 
5724   // Warn if the class has virtual methods but non-virtual public destructor.
5725   if (Record->isPolymorphic() && !Record->isDependentType()) {
5726     CXXDestructorDecl *dtor = Record->getDestructor();
5727     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5728         !Record->hasAttr<FinalAttr>())
5729       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5730            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5731   }
5732 
5733   if (Record->isAbstract()) {
5734     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5735       Diag(Record->getLocation(), diag::warn_abstract_final_class)
5736         << FA->isSpelledAsSealed();
5737       DiagnoseAbstractType(Record);
5738     }
5739   }
5740 
5741   bool HasMethodWithOverrideControl = false,
5742        HasOverridingMethodWithoutOverrideControl = false;
5743   if (!Record->isDependentType()) {
5744     for (auto *M : Record->methods()) {
5745       // See if a method overloads virtual methods in a base
5746       // class without overriding any.
5747       if (!M->isStatic())
5748         DiagnoseHiddenVirtualMethods(M);
5749       if (M->hasAttr<OverrideAttr>())
5750         HasMethodWithOverrideControl = true;
5751       else if (M->size_overridden_methods() > 0)
5752         HasOverridingMethodWithoutOverrideControl = true;
5753       // Check whether the explicitly-defaulted special members are valid.
5754       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5755         CheckExplicitlyDefaultedSpecialMember(M);
5756 
5757       // For an explicitly defaulted or deleted special member, we defer
5758       // determining triviality until the class is complete. That time is now!
5759       CXXSpecialMember CSM = getSpecialMember(M);
5760       if (!M->isImplicit() && !M->isUserProvided()) {
5761         if (CSM != CXXInvalid) {
5762           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5763 
5764           // Inform the class that we've finished declaring this member.
5765           Record->finishedDefaultedOrDeletedMember(M);
5766         }
5767       }
5768 
5769       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5770           M->hasAttr<DLLExportAttr>()) {
5771         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5772             M->isTrivial() &&
5773             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5774              CSM == CXXDestructor))
5775           M->dropAttr<DLLExportAttr>();
5776 
5777         if (M->hasAttr<DLLExportAttr>()) {
5778           DefineImplicitSpecialMember(*this, M, M->getLocation());
5779           ActOnFinishInlineFunctionDef(M);
5780         }
5781       }
5782     }
5783   }
5784 
5785   if (HasMethodWithOverrideControl &&
5786       HasOverridingMethodWithoutOverrideControl) {
5787     // At least one method has the 'override' control declared.
5788     // Diagnose all other overridden methods which do not have 'override' specified on them.
5789     for (auto *M : Record->methods())
5790       DiagnoseAbsenceOfOverrideControl(M);
5791   }
5792 
5793   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5794   // whether this class uses any C++ features that are implemented
5795   // completely differently in MSVC, and if so, emit a diagnostic.
5796   // That diagnostic defaults to an error, but we allow projects to
5797   // map it down to a warning (or ignore it).  It's a fairly common
5798   // practice among users of the ms_struct pragma to mass-annotate
5799   // headers, sweeping up a bunch of types that the project doesn't
5800   // really rely on MSVC-compatible layout for.  We must therefore
5801   // support "ms_struct except for C++ stuff" as a secondary ABI.
5802   if (Record->isMsStruct(Context) &&
5803       (Record->isPolymorphic() || Record->getNumBases())) {
5804     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5805   }
5806 
5807   checkClassLevelDLLAttribute(Record);
5808 }
5809 
5810 /// Look up the special member function that would be called by a special
5811 /// member function for a subobject of class type.
5812 ///
5813 /// \param Class The class type of the subobject.
5814 /// \param CSM The kind of special member function.
5815 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5816 /// \param ConstRHS True if this is a copy operation with a const object
5817 ///        on its RHS, that is, if the argument to the outer special member
5818 ///        function is 'const' and this is not a field marked 'mutable'.
5819 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5820     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5821     unsigned FieldQuals, bool ConstRHS) {
5822   unsigned LHSQuals = 0;
5823   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5824     LHSQuals = FieldQuals;
5825 
5826   unsigned RHSQuals = FieldQuals;
5827   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5828     RHSQuals = 0;
5829   else if (ConstRHS)
5830     RHSQuals |= Qualifiers::Const;
5831 
5832   return S.LookupSpecialMember(Class, CSM,
5833                                RHSQuals & Qualifiers::Const,
5834                                RHSQuals & Qualifiers::Volatile,
5835                                false,
5836                                LHSQuals & Qualifiers::Const,
5837                                LHSQuals & Qualifiers::Volatile);
5838 }
5839 
5840 class Sema::InheritedConstructorInfo {
5841   Sema &S;
5842   SourceLocation UseLoc;
5843 
5844   /// A mapping from the base classes through which the constructor was
5845   /// inherited to the using shadow declaration in that base class (or a null
5846   /// pointer if the constructor was declared in that base class).
5847   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5848       InheritedFromBases;
5849 
5850 public:
5851   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5852                            ConstructorUsingShadowDecl *Shadow)
5853       : S(S), UseLoc(UseLoc) {
5854     bool DiagnosedMultipleConstructedBases = false;
5855     CXXRecordDecl *ConstructedBase = nullptr;
5856     UsingDecl *ConstructedBaseUsing = nullptr;
5857 
5858     // Find the set of such base class subobjects and check that there's a
5859     // unique constructed subobject.
5860     for (auto *D : Shadow->redecls()) {
5861       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5862       auto *DNominatedBase = DShadow->getNominatedBaseClass();
5863       auto *DConstructedBase = DShadow->getConstructedBaseClass();
5864 
5865       InheritedFromBases.insert(
5866           std::make_pair(DNominatedBase->getCanonicalDecl(),
5867                          DShadow->getNominatedBaseClassShadowDecl()));
5868       if (DShadow->constructsVirtualBase())
5869         InheritedFromBases.insert(
5870             std::make_pair(DConstructedBase->getCanonicalDecl(),
5871                            DShadow->getConstructedBaseClassShadowDecl()));
5872       else
5873         assert(DNominatedBase == DConstructedBase);
5874 
5875       // [class.inhctor.init]p2:
5876       //   If the constructor was inherited from multiple base class subobjects
5877       //   of type B, the program is ill-formed.
5878       if (!ConstructedBase) {
5879         ConstructedBase = DConstructedBase;
5880         ConstructedBaseUsing = D->getUsingDecl();
5881       } else if (ConstructedBase != DConstructedBase &&
5882                  !Shadow->isInvalidDecl()) {
5883         if (!DiagnosedMultipleConstructedBases) {
5884           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5885               << Shadow->getTargetDecl();
5886           S.Diag(ConstructedBaseUsing->getLocation(),
5887                diag::note_ambiguous_inherited_constructor_using)
5888               << ConstructedBase;
5889           DiagnosedMultipleConstructedBases = true;
5890         }
5891         S.Diag(D->getUsingDecl()->getLocation(),
5892                diag::note_ambiguous_inherited_constructor_using)
5893             << DConstructedBase;
5894       }
5895     }
5896 
5897     if (DiagnosedMultipleConstructedBases)
5898       Shadow->setInvalidDecl();
5899   }
5900 
5901   /// Find the constructor to use for inherited construction of a base class,
5902   /// and whether that base class constructor inherits the constructor from a
5903   /// virtual base class (in which case it won't actually invoke it).
5904   std::pair<CXXConstructorDecl *, bool>
5905   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5906     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5907     if (It == InheritedFromBases.end())
5908       return std::make_pair(nullptr, false);
5909 
5910     // This is an intermediary class.
5911     if (It->second)
5912       return std::make_pair(
5913           S.findInheritingConstructor(UseLoc, Ctor, It->second),
5914           It->second->constructsVirtualBase());
5915 
5916     // This is the base class from which the constructor was inherited.
5917     return std::make_pair(Ctor, false);
5918   }
5919 };
5920 
5921 /// Is the special member function which would be selected to perform the
5922 /// specified operation on the specified class type a constexpr constructor?
5923 static bool
5924 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5925                          Sema::CXXSpecialMember CSM, unsigned Quals,
5926                          bool ConstRHS,
5927                          CXXConstructorDecl *InheritedCtor = nullptr,
5928                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
5929   // If we're inheriting a constructor, see if we need to call it for this base
5930   // class.
5931   if (InheritedCtor) {
5932     assert(CSM == Sema::CXXDefaultConstructor);
5933     auto BaseCtor =
5934         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5935     if (BaseCtor)
5936       return BaseCtor->isConstexpr();
5937   }
5938 
5939   if (CSM == Sema::CXXDefaultConstructor)
5940     return ClassDecl->hasConstexprDefaultConstructor();
5941 
5942   Sema::SpecialMemberOverloadResult *SMOR =
5943       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5944   if (!SMOR || !SMOR->getMethod())
5945     // A constructor we wouldn't select can't be "involved in initializing"
5946     // anything.
5947     return true;
5948   return SMOR->getMethod()->isConstexpr();
5949 }
5950 
5951 /// Determine whether the specified special member function would be constexpr
5952 /// if it were implicitly defined.
5953 static bool defaultedSpecialMemberIsConstexpr(
5954     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5955     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
5956     Sema::InheritedConstructorInfo *Inherited = nullptr) {
5957   if (!S.getLangOpts().CPlusPlus11)
5958     return false;
5959 
5960   // C++11 [dcl.constexpr]p4:
5961   // In the definition of a constexpr constructor [...]
5962   bool Ctor = true;
5963   switch (CSM) {
5964   case Sema::CXXDefaultConstructor:
5965     if (Inherited)
5966       break;
5967     // Since default constructor lookup is essentially trivial (and cannot
5968     // involve, for instance, template instantiation), we compute whether a
5969     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5970     //
5971     // This is important for performance; we need to know whether the default
5972     // constructor is constexpr to determine whether the type is a literal type.
5973     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5974 
5975   case Sema::CXXCopyConstructor:
5976   case Sema::CXXMoveConstructor:
5977     // For copy or move constructors, we need to perform overload resolution.
5978     break;
5979 
5980   case Sema::CXXCopyAssignment:
5981   case Sema::CXXMoveAssignment:
5982     if (!S.getLangOpts().CPlusPlus14)
5983       return false;
5984     // In C++1y, we need to perform overload resolution.
5985     Ctor = false;
5986     break;
5987 
5988   case Sema::CXXDestructor:
5989   case Sema::CXXInvalid:
5990     return false;
5991   }
5992 
5993   //   -- if the class is a non-empty union, or for each non-empty anonymous
5994   //      union member of a non-union class, exactly one non-static data member
5995   //      shall be initialized; [DR1359]
5996   //
5997   // If we squint, this is guaranteed, since exactly one non-static data member
5998   // will be initialized (if the constructor isn't deleted), we just don't know
5999   // which one.
6000   if (Ctor && ClassDecl->isUnion())
6001     return CSM == Sema::CXXDefaultConstructor
6002                ? ClassDecl->hasInClassInitializer() ||
6003                      !ClassDecl->hasVariantMembers()
6004                : true;
6005 
6006   //   -- the class shall not have any virtual base classes;
6007   if (Ctor && ClassDecl->getNumVBases())
6008     return false;
6009 
6010   // C++1y [class.copy]p26:
6011   //   -- [the class] is a literal type, and
6012   if (!Ctor && !ClassDecl->isLiteral())
6013     return false;
6014 
6015   //   -- every constructor involved in initializing [...] base class
6016   //      sub-objects shall be a constexpr constructor;
6017   //   -- the assignment operator selected to copy/move each direct base
6018   //      class is a constexpr function, and
6019   for (const auto &B : ClassDecl->bases()) {
6020     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6021     if (!BaseType) continue;
6022 
6023     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6024     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6025                                   InheritedCtor, Inherited))
6026       return false;
6027   }
6028 
6029   //   -- every constructor involved in initializing non-static data members
6030   //      [...] shall be a constexpr constructor;
6031   //   -- every non-static data member and base class sub-object shall be
6032   //      initialized
6033   //   -- for each non-static data member of X that is of class type (or array
6034   //      thereof), the assignment operator selected to copy/move that member is
6035   //      a constexpr function
6036   for (const auto *F : ClassDecl->fields()) {
6037     if (F->isInvalidDecl())
6038       continue;
6039     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6040       continue;
6041     QualType BaseType = S.Context.getBaseElementType(F->getType());
6042     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6043       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6044       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6045                                     BaseType.getCVRQualifiers(),
6046                                     ConstArg && !F->isMutable()))
6047         return false;
6048     } else if (CSM == Sema::CXXDefaultConstructor) {
6049       return false;
6050     }
6051   }
6052 
6053   // All OK, it's constexpr!
6054   return true;
6055 }
6056 
6057 static Sema::ImplicitExceptionSpecification
6058 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6059   switch (S.getSpecialMember(MD)) {
6060   case Sema::CXXDefaultConstructor:
6061     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
6062   case Sema::CXXCopyConstructor:
6063     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
6064   case Sema::CXXCopyAssignment:
6065     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
6066   case Sema::CXXMoveConstructor:
6067     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
6068   case Sema::CXXMoveAssignment:
6069     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
6070   case Sema::CXXDestructor:
6071     return S.ComputeDefaultedDtorExceptionSpec(MD);
6072   case Sema::CXXInvalid:
6073     break;
6074   }
6075   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
6076          "only special members have implicit exception specs");
6077   return S.ComputeInheritingCtorExceptionSpec(Loc,
6078                                               cast<CXXConstructorDecl>(MD));
6079 }
6080 
6081 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6082                                                             CXXMethodDecl *MD) {
6083   FunctionProtoType::ExtProtoInfo EPI;
6084 
6085   // Build an exception specification pointing back at this member.
6086   EPI.ExceptionSpec.Type = EST_Unevaluated;
6087   EPI.ExceptionSpec.SourceDecl = MD;
6088 
6089   // Set the calling convention to the default for C++ instance methods.
6090   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6091       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6092                                             /*IsCXXMethod=*/true));
6093   return EPI;
6094 }
6095 
6096 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6097   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6098   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6099     return;
6100 
6101   // Evaluate the exception specification.
6102   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
6103 
6104   // Update the type of the special member to use it.
6105   UpdateExceptionSpec(MD, ESI);
6106 
6107   // A user-provided destructor can be defined outside the class. When that
6108   // happens, be sure to update the exception specification on both
6109   // declarations.
6110   const FunctionProtoType *CanonicalFPT =
6111     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6112   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6113     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6114 }
6115 
6116 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6117   CXXRecordDecl *RD = MD->getParent();
6118   CXXSpecialMember CSM = getSpecialMember(MD);
6119 
6120   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6121          "not an explicitly-defaulted special member");
6122 
6123   // Whether this was the first-declared instance of the constructor.
6124   // This affects whether we implicitly add an exception spec and constexpr.
6125   bool First = MD == MD->getCanonicalDecl();
6126 
6127   bool HadError = false;
6128 
6129   // C++11 [dcl.fct.def.default]p1:
6130   //   A function that is explicitly defaulted shall
6131   //     -- be a special member function (checked elsewhere),
6132   //     -- have the same type (except for ref-qualifiers, and except that a
6133   //        copy operation can take a non-const reference) as an implicit
6134   //        declaration, and
6135   //     -- not have default arguments.
6136   unsigned ExpectedParams = 1;
6137   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6138     ExpectedParams = 0;
6139   if (MD->getNumParams() != ExpectedParams) {
6140     // This also checks for default arguments: a copy or move constructor with a
6141     // default argument is classified as a default constructor, and assignment
6142     // operations and destructors can't have default arguments.
6143     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6144       << CSM << MD->getSourceRange();
6145     HadError = true;
6146   } else if (MD->isVariadic()) {
6147     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6148       << CSM << MD->getSourceRange();
6149     HadError = true;
6150   }
6151 
6152   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6153 
6154   bool CanHaveConstParam = false;
6155   if (CSM == CXXCopyConstructor)
6156     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6157   else if (CSM == CXXCopyAssignment)
6158     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6159 
6160   QualType ReturnType = Context.VoidTy;
6161   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6162     // Check for return type matching.
6163     ReturnType = Type->getReturnType();
6164     QualType ExpectedReturnType =
6165         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6166     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6167       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6168         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6169       HadError = true;
6170     }
6171 
6172     // A defaulted special member cannot have cv-qualifiers.
6173     if (Type->getTypeQuals()) {
6174       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6175         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6176       HadError = true;
6177     }
6178   }
6179 
6180   // Check for parameter type matching.
6181   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6182   bool HasConstParam = false;
6183   if (ExpectedParams && ArgType->isReferenceType()) {
6184     // Argument must be reference to possibly-const T.
6185     QualType ReferentType = ArgType->getPointeeType();
6186     HasConstParam = ReferentType.isConstQualified();
6187 
6188     if (ReferentType.isVolatileQualified()) {
6189       Diag(MD->getLocation(),
6190            diag::err_defaulted_special_member_volatile_param) << CSM;
6191       HadError = true;
6192     }
6193 
6194     if (HasConstParam && !CanHaveConstParam) {
6195       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6196         Diag(MD->getLocation(),
6197              diag::err_defaulted_special_member_copy_const_param)
6198           << (CSM == CXXCopyAssignment);
6199         // FIXME: Explain why this special member can't be const.
6200       } else {
6201         Diag(MD->getLocation(),
6202              diag::err_defaulted_special_member_move_const_param)
6203           << (CSM == CXXMoveAssignment);
6204       }
6205       HadError = true;
6206     }
6207   } else if (ExpectedParams) {
6208     // A copy assignment operator can take its argument by value, but a
6209     // defaulted one cannot.
6210     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6211     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6212     HadError = true;
6213   }
6214 
6215   // C++11 [dcl.fct.def.default]p2:
6216   //   An explicitly-defaulted function may be declared constexpr only if it
6217   //   would have been implicitly declared as constexpr,
6218   // Do not apply this rule to members of class templates, since core issue 1358
6219   // makes such functions always instantiate to constexpr functions. For
6220   // functions which cannot be constexpr (for non-constructors in C++11 and for
6221   // destructors in C++1y), this is checked elsewhere.
6222   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6223                                                      HasConstParam);
6224   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6225                                  : isa<CXXConstructorDecl>(MD)) &&
6226       MD->isConstexpr() && !Constexpr &&
6227       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6228     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6229     // FIXME: Explain why the special member can't be constexpr.
6230     HadError = true;
6231   }
6232 
6233   //   and may have an explicit exception-specification only if it is compatible
6234   //   with the exception-specification on the implicit declaration.
6235   if (Type->hasExceptionSpec()) {
6236     // Delay the check if this is the first declaration of the special member,
6237     // since we may not have parsed some necessary in-class initializers yet.
6238     if (First) {
6239       // If the exception specification needs to be instantiated, do so now,
6240       // before we clobber it with an EST_Unevaluated specification below.
6241       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6242         InstantiateExceptionSpec(MD->getLocStart(), MD);
6243         Type = MD->getType()->getAs<FunctionProtoType>();
6244       }
6245       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6246     } else
6247       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6248   }
6249 
6250   //   If a function is explicitly defaulted on its first declaration,
6251   if (First) {
6252     //  -- it is implicitly considered to be constexpr if the implicit
6253     //     definition would be,
6254     MD->setConstexpr(Constexpr);
6255 
6256     //  -- it is implicitly considered to have the same exception-specification
6257     //     as if it had been implicitly declared,
6258     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6259     EPI.ExceptionSpec.Type = EST_Unevaluated;
6260     EPI.ExceptionSpec.SourceDecl = MD;
6261     MD->setType(Context.getFunctionType(ReturnType,
6262                                         llvm::makeArrayRef(&ArgType,
6263                                                            ExpectedParams),
6264                                         EPI));
6265   }
6266 
6267   if (ShouldDeleteSpecialMember(MD, CSM)) {
6268     if (First) {
6269       SetDeclDeleted(MD, MD->getLocation());
6270     } else {
6271       // C++11 [dcl.fct.def.default]p4:
6272       //   [For a] user-provided explicitly-defaulted function [...] if such a
6273       //   function is implicitly defined as deleted, the program is ill-formed.
6274       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6275       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6276       HadError = true;
6277     }
6278   }
6279 
6280   if (HadError)
6281     MD->setInvalidDecl();
6282 }
6283 
6284 /// Check whether the exception specification provided for an
6285 /// explicitly-defaulted special member matches the exception specification
6286 /// that would have been generated for an implicit special member, per
6287 /// C++11 [dcl.fct.def.default]p2.
6288 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6289     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6290   // If the exception specification was explicitly specified but hadn't been
6291   // parsed when the method was defaulted, grab it now.
6292   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6293     SpecifiedType =
6294         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6295 
6296   // Compute the implicit exception specification.
6297   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6298                                                        /*IsCXXMethod=*/true);
6299   FunctionProtoType::ExtProtoInfo EPI(CC);
6300   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
6301                           .getExceptionSpec();
6302   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6303     Context.getFunctionType(Context.VoidTy, None, EPI));
6304 
6305   // Ensure that it matches.
6306   CheckEquivalentExceptionSpec(
6307     PDiag(diag::err_incorrect_defaulted_exception_spec)
6308       << getSpecialMember(MD), PDiag(),
6309     ImplicitType, SourceLocation(),
6310     SpecifiedType, MD->getLocation());
6311 }
6312 
6313 void Sema::CheckDelayedMemberExceptionSpecs() {
6314   decltype(DelayedExceptionSpecChecks) Checks;
6315   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6316 
6317   std::swap(Checks, DelayedExceptionSpecChecks);
6318   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6319 
6320   // Perform any deferred checking of exception specifications for virtual
6321   // destructors.
6322   for (auto &Check : Checks)
6323     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6324 
6325   // Check that any explicitly-defaulted methods have exception specifications
6326   // compatible with their implicit exception specifications.
6327   for (auto &Spec : Specs)
6328     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6329 }
6330 
6331 namespace {
6332 struct SpecialMemberDeletionInfo {
6333   Sema &S;
6334   CXXMethodDecl *MD;
6335   Sema::CXXSpecialMember CSM;
6336   Sema::InheritedConstructorInfo *ICI;
6337   bool Diagnose;
6338 
6339   // Properties of the special member, computed for convenience.
6340   bool IsConstructor, IsAssignment, IsMove, ConstArg;
6341   SourceLocation Loc;
6342 
6343   bool AllFieldsAreConst;
6344 
6345   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6346                             Sema::CXXSpecialMember CSM,
6347                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6348       : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
6349         IsConstructor(false), IsAssignment(false), IsMove(false),
6350         ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
6351     switch (CSM) {
6352       case Sema::CXXDefaultConstructor:
6353       case Sema::CXXCopyConstructor:
6354         IsConstructor = true;
6355         break;
6356       case Sema::CXXMoveConstructor:
6357         IsConstructor = true;
6358         IsMove = true;
6359         break;
6360       case Sema::CXXCopyAssignment:
6361         IsAssignment = true;
6362         break;
6363       case Sema::CXXMoveAssignment:
6364         IsAssignment = true;
6365         IsMove = true;
6366         break;
6367       case Sema::CXXDestructor:
6368         break;
6369       case Sema::CXXInvalid:
6370         llvm_unreachable("invalid special member kind");
6371     }
6372 
6373     if (MD->getNumParams()) {
6374       if (const ReferenceType *RT =
6375               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6376         ConstArg = RT->getPointeeType().isConstQualified();
6377     }
6378   }
6379 
6380   bool inUnion() const { return MD->getParent()->isUnion(); }
6381 
6382   Sema::CXXSpecialMember getEffectiveCSM() {
6383     return ICI ? Sema::CXXInvalid : CSM;
6384   }
6385 
6386   /// Look up the corresponding special member in the given class.
6387   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
6388                                               unsigned Quals, bool IsMutable) {
6389     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6390                                        ConstArg && !IsMutable);
6391   }
6392 
6393   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6394 
6395   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6396   bool shouldDeleteForField(FieldDecl *FD);
6397   bool shouldDeleteForAllConstMembers();
6398 
6399   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6400                                      unsigned Quals);
6401   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6402                                     Sema::SpecialMemberOverloadResult *SMOR,
6403                                     bool IsDtorCallInCtor);
6404 
6405   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6406 };
6407 }
6408 
6409 /// Is the given special member inaccessible when used on the given
6410 /// sub-object.
6411 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6412                                              CXXMethodDecl *target) {
6413   /// If we're operating on a base class, the object type is the
6414   /// type of this special member.
6415   QualType objectTy;
6416   AccessSpecifier access = target->getAccess();
6417   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6418     objectTy = S.Context.getTypeDeclType(MD->getParent());
6419     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6420 
6421   // If we're operating on a field, the object type is the type of the field.
6422   } else {
6423     objectTy = S.Context.getTypeDeclType(target->getParent());
6424   }
6425 
6426   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6427 }
6428 
6429 /// Check whether we should delete a special member due to the implicit
6430 /// definition containing a call to a special member of a subobject.
6431 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6432     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
6433     bool IsDtorCallInCtor) {
6434   CXXMethodDecl *Decl = SMOR->getMethod();
6435   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6436 
6437   int DiagKind = -1;
6438 
6439   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6440     DiagKind = !Decl ? 0 : 1;
6441   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6442     DiagKind = 2;
6443   else if (!isAccessible(Subobj, Decl))
6444     DiagKind = 3;
6445   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6446            !Decl->isTrivial()) {
6447     // A member of a union must have a trivial corresponding special member.
6448     // As a weird special case, a destructor call from a union's constructor
6449     // must be accessible and non-deleted, but need not be trivial. Such a
6450     // destructor is never actually called, but is semantically checked as
6451     // if it were.
6452     DiagKind = 4;
6453   }
6454 
6455   if (DiagKind == -1)
6456     return false;
6457 
6458   if (Diagnose) {
6459     if (Field) {
6460       S.Diag(Field->getLocation(),
6461              diag::note_deleted_special_member_class_subobject)
6462         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6463         << Field << DiagKind << IsDtorCallInCtor;
6464     } else {
6465       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6466       S.Diag(Base->getLocStart(),
6467              diag::note_deleted_special_member_class_subobject)
6468         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6469         << Base->getType() << DiagKind << IsDtorCallInCtor;
6470     }
6471 
6472     if (DiagKind == 1)
6473       S.NoteDeletedFunction(Decl);
6474     // FIXME: Explain inaccessibility if DiagKind == 3.
6475   }
6476 
6477   return true;
6478 }
6479 
6480 /// Check whether we should delete a special member function due to having a
6481 /// direct or virtual base class or non-static data member of class type M.
6482 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6483     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6484   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6485   bool IsMutable = Field && Field->isMutable();
6486 
6487   // C++11 [class.ctor]p5:
6488   // -- any direct or virtual base class, or non-static data member with no
6489   //    brace-or-equal-initializer, has class type M (or array thereof) and
6490   //    either M has no default constructor or overload resolution as applied
6491   //    to M's default constructor results in an ambiguity or in a function
6492   //    that is deleted or inaccessible
6493   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6494   // -- a direct or virtual base class B that cannot be copied/moved because
6495   //    overload resolution, as applied to B's corresponding special member,
6496   //    results in an ambiguity or a function that is deleted or inaccessible
6497   //    from the defaulted special member
6498   // C++11 [class.dtor]p5:
6499   // -- any direct or virtual base class [...] has a type with a destructor
6500   //    that is deleted or inaccessible
6501   if (!(CSM == Sema::CXXDefaultConstructor &&
6502         Field && Field->hasInClassInitializer()) &&
6503       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6504                                    false))
6505     return true;
6506 
6507   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6508   // -- any direct or virtual base class or non-static data member has a
6509   //    type with a destructor that is deleted or inaccessible
6510   if (IsConstructor) {
6511     Sema::SpecialMemberOverloadResult *SMOR =
6512         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6513                               false, false, false, false, false);
6514     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6515       return true;
6516   }
6517 
6518   return false;
6519 }
6520 
6521 /// Check whether we should delete a special member function due to the class
6522 /// having a particular direct or virtual base class.
6523 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6524   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6525   // If program is correct, BaseClass cannot be null, but if it is, the error
6526   // must be reported elsewhere.
6527   if (!BaseClass)
6528     return false;
6529   // If we have an inheriting constructor, check whether we're calling an
6530   // inherited constructor instead of a default constructor.
6531   if (ICI) {
6532     assert(CSM == Sema::CXXDefaultConstructor);
6533     auto *BaseCtor =
6534         ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
6535                                                    ->getInheritedConstructor()
6536                                                    .getConstructor())
6537             .first;
6538     if (BaseCtor) {
6539       if (BaseCtor->isDeleted() && Diagnose) {
6540         S.Diag(Base->getLocStart(),
6541                diag::note_deleted_special_member_class_subobject)
6542           << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6543           << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6544         S.NoteDeletedFunction(BaseCtor);
6545       }
6546       return BaseCtor->isDeleted();
6547     }
6548   }
6549   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6550 }
6551 
6552 /// Check whether we should delete a special member function due to the class
6553 /// having a particular non-static data member.
6554 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6555   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6556   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6557 
6558   if (CSM == Sema::CXXDefaultConstructor) {
6559     // For a default constructor, all references must be initialized in-class
6560     // and, if a union, it must have a non-const member.
6561     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6562       if (Diagnose)
6563         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6564           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6565       return true;
6566     }
6567     // C++11 [class.ctor]p5: any non-variant non-static data member of
6568     // const-qualified type (or array thereof) with no
6569     // brace-or-equal-initializer does not have a user-provided default
6570     // constructor.
6571     if (!inUnion() && FieldType.isConstQualified() &&
6572         !FD->hasInClassInitializer() &&
6573         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6574       if (Diagnose)
6575         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6576           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6577       return true;
6578     }
6579 
6580     if (inUnion() && !FieldType.isConstQualified())
6581       AllFieldsAreConst = false;
6582   } else if (CSM == Sema::CXXCopyConstructor) {
6583     // For a copy constructor, data members must not be of rvalue reference
6584     // type.
6585     if (FieldType->isRValueReferenceType()) {
6586       if (Diagnose)
6587         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6588           << MD->getParent() << FD << FieldType;
6589       return true;
6590     }
6591   } else if (IsAssignment) {
6592     // For an assignment operator, data members must not be of reference type.
6593     if (FieldType->isReferenceType()) {
6594       if (Diagnose)
6595         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6596           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
6597       return true;
6598     }
6599     if (!FieldRecord && FieldType.isConstQualified()) {
6600       // C++11 [class.copy]p23:
6601       // -- a non-static data member of const non-class type (or array thereof)
6602       if (Diagnose)
6603         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6604           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
6605       return true;
6606     }
6607   }
6608 
6609   if (FieldRecord) {
6610     // Some additional restrictions exist on the variant members.
6611     if (!inUnion() && FieldRecord->isUnion() &&
6612         FieldRecord->isAnonymousStructOrUnion()) {
6613       bool AllVariantFieldsAreConst = true;
6614 
6615       // FIXME: Handle anonymous unions declared within anonymous unions.
6616       for (auto *UI : FieldRecord->fields()) {
6617         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6618 
6619         if (!UnionFieldType.isConstQualified())
6620           AllVariantFieldsAreConst = false;
6621 
6622         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6623         if (UnionFieldRecord &&
6624             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6625                                           UnionFieldType.getCVRQualifiers()))
6626           return true;
6627       }
6628 
6629       // At least one member in each anonymous union must be non-const
6630       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6631           !FieldRecord->field_empty()) {
6632         if (Diagnose)
6633           S.Diag(FieldRecord->getLocation(),
6634                  diag::note_deleted_default_ctor_all_const)
6635             << !!ICI << MD->getParent() << /*anonymous union*/1;
6636         return true;
6637       }
6638 
6639       // Don't check the implicit member of the anonymous union type.
6640       // This is technically non-conformant, but sanity demands it.
6641       return false;
6642     }
6643 
6644     if (shouldDeleteForClassSubobject(FieldRecord, FD,
6645                                       FieldType.getCVRQualifiers()))
6646       return true;
6647   }
6648 
6649   return false;
6650 }
6651 
6652 /// C++11 [class.ctor] p5:
6653 ///   A defaulted default constructor for a class X is defined as deleted if
6654 /// X is a union and all of its variant members are of const-qualified type.
6655 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6656   // This is a silly definition, because it gives an empty union a deleted
6657   // default constructor. Don't do that.
6658   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
6659       !MD->getParent()->field_empty()) {
6660     if (Diagnose)
6661       S.Diag(MD->getParent()->getLocation(),
6662              diag::note_deleted_default_ctor_all_const)
6663         << !!ICI << MD->getParent() << /*not anonymous union*/0;
6664     return true;
6665   }
6666   return false;
6667 }
6668 
6669 /// Determine whether a defaulted special member function should be defined as
6670 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6671 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6672 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6673                                      InheritedConstructorInfo *ICI,
6674                                      bool Diagnose) {
6675   if (MD->isInvalidDecl())
6676     return false;
6677   CXXRecordDecl *RD = MD->getParent();
6678   assert(!RD->isDependentType() && "do deletion after instantiation");
6679   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6680     return false;
6681 
6682   // C++11 [expr.lambda.prim]p19:
6683   //   The closure type associated with a lambda-expression has a
6684   //   deleted (8.4.3) default constructor and a deleted copy
6685   //   assignment operator.
6686   if (RD->isLambda() &&
6687       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6688     if (Diagnose)
6689       Diag(RD->getLocation(), diag::note_lambda_decl);
6690     return true;
6691   }
6692 
6693   // For an anonymous struct or union, the copy and assignment special members
6694   // will never be used, so skip the check. For an anonymous union declared at
6695   // namespace scope, the constructor and destructor are used.
6696   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6697       RD->isAnonymousStructOrUnion())
6698     return false;
6699 
6700   // C++11 [class.copy]p7, p18:
6701   //   If the class definition declares a move constructor or move assignment
6702   //   operator, an implicitly declared copy constructor or copy assignment
6703   //   operator is defined as deleted.
6704   if (MD->isImplicit() &&
6705       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6706     CXXMethodDecl *UserDeclaredMove = nullptr;
6707 
6708     // In Microsoft mode, a user-declared move only causes the deletion of the
6709     // corresponding copy operation, not both copy operations.
6710     if (RD->hasUserDeclaredMoveConstructor() &&
6711         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
6712       if (!Diagnose) return true;
6713 
6714       // Find any user-declared move constructor.
6715       for (auto *I : RD->ctors()) {
6716         if (I->isMoveConstructor()) {
6717           UserDeclaredMove = I;
6718           break;
6719         }
6720       }
6721       assert(UserDeclaredMove);
6722     } else if (RD->hasUserDeclaredMoveAssignment() &&
6723                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
6724       if (!Diagnose) return true;
6725 
6726       // Find any user-declared move assignment operator.
6727       for (auto *I : RD->methods()) {
6728         if (I->isMoveAssignmentOperator()) {
6729           UserDeclaredMove = I;
6730           break;
6731         }
6732       }
6733       assert(UserDeclaredMove);
6734     }
6735 
6736     if (UserDeclaredMove) {
6737       Diag(UserDeclaredMove->getLocation(),
6738            diag::note_deleted_copy_user_declared_move)
6739         << (CSM == CXXCopyAssignment) << RD
6740         << UserDeclaredMove->isMoveAssignmentOperator();
6741       return true;
6742     }
6743   }
6744 
6745   // Do access control from the special member function
6746   ContextRAII MethodContext(*this, MD);
6747 
6748   // C++11 [class.dtor]p5:
6749   // -- for a virtual destructor, lookup of the non-array deallocation function
6750   //    results in an ambiguity or in a function that is deleted or inaccessible
6751   if (CSM == CXXDestructor && MD->isVirtual()) {
6752     FunctionDecl *OperatorDelete = nullptr;
6753     DeclarationName Name =
6754       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6755     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
6756                                  OperatorDelete, /*Diagnose*/false)) {
6757       if (Diagnose)
6758         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
6759       return true;
6760     }
6761   }
6762 
6763   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
6764 
6765   for (auto &BI : RD->bases())
6766     if ((SMI.IsAssignment || !BI.isVirtual()) &&
6767         SMI.shouldDeleteForBase(&BI))
6768       return true;
6769 
6770   // Per DR1611, do not consider virtual bases of constructors of abstract
6771   // classes, since we are not going to construct them. For assignment
6772   // operators, we only assign (and thus only consider) direct bases.
6773   if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) {
6774     for (auto &BI : RD->vbases())
6775       if (SMI.shouldDeleteForBase(&BI))
6776         return true;
6777   }
6778 
6779   for (auto *FI : RD->fields())
6780     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
6781         SMI.shouldDeleteForField(FI))
6782       return true;
6783 
6784   if (SMI.shouldDeleteForAllConstMembers())
6785     return true;
6786 
6787   if (getLangOpts().CUDA) {
6788     // We should delete the special member in CUDA mode if target inference
6789     // failed.
6790     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6791                                                    Diagnose);
6792   }
6793 
6794   return false;
6795 }
6796 
6797 /// Perform lookup for a special member of the specified kind, and determine
6798 /// whether it is trivial. If the triviality can be determined without the
6799 /// lookup, skip it. This is intended for use when determining whether a
6800 /// special member of a containing object is trivial, and thus does not ever
6801 /// perform overload resolution for default constructors.
6802 ///
6803 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6804 /// member that was most likely to be intended to be trivial, if any.
6805 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6806                                      Sema::CXXSpecialMember CSM, unsigned Quals,
6807                                      bool ConstRHS, CXXMethodDecl **Selected) {
6808   if (Selected)
6809     *Selected = nullptr;
6810 
6811   switch (CSM) {
6812   case Sema::CXXInvalid:
6813     llvm_unreachable("not a special member");
6814 
6815   case Sema::CXXDefaultConstructor:
6816     // C++11 [class.ctor]p5:
6817     //   A default constructor is trivial if:
6818     //    - all the [direct subobjects] have trivial default constructors
6819     //
6820     // Note, no overload resolution is performed in this case.
6821     if (RD->hasTrivialDefaultConstructor())
6822       return true;
6823 
6824     if (Selected) {
6825       // If there's a default constructor which could have been trivial, dig it
6826       // out. Otherwise, if there's any user-provided default constructor, point
6827       // to that as an example of why there's not a trivial one.
6828       CXXConstructorDecl *DefCtor = nullptr;
6829       if (RD->needsImplicitDefaultConstructor())
6830         S.DeclareImplicitDefaultConstructor(RD);
6831       for (auto *CI : RD->ctors()) {
6832         if (!CI->isDefaultConstructor())
6833           continue;
6834         DefCtor = CI;
6835         if (!DefCtor->isUserProvided())
6836           break;
6837       }
6838 
6839       *Selected = DefCtor;
6840     }
6841 
6842     return false;
6843 
6844   case Sema::CXXDestructor:
6845     // C++11 [class.dtor]p5:
6846     //   A destructor is trivial if:
6847     //    - all the direct [subobjects] have trivial destructors
6848     if (RD->hasTrivialDestructor())
6849       return true;
6850 
6851     if (Selected) {
6852       if (RD->needsImplicitDestructor())
6853         S.DeclareImplicitDestructor(RD);
6854       *Selected = RD->getDestructor();
6855     }
6856 
6857     return false;
6858 
6859   case Sema::CXXCopyConstructor:
6860     // C++11 [class.copy]p12:
6861     //   A copy constructor is trivial if:
6862     //    - the constructor selected to copy each direct [subobject] is trivial
6863     if (RD->hasTrivialCopyConstructor()) {
6864       if (Quals == Qualifiers::Const)
6865         // We must either select the trivial copy constructor or reach an
6866         // ambiguity; no need to actually perform overload resolution.
6867         return true;
6868     } else if (!Selected) {
6869       return false;
6870     }
6871     // In C++98, we are not supposed to perform overload resolution here, but we
6872     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6873     // cases like B as having a non-trivial copy constructor:
6874     //   struct A { template<typename T> A(T&); };
6875     //   struct B { mutable A a; };
6876     goto NeedOverloadResolution;
6877 
6878   case Sema::CXXCopyAssignment:
6879     // C++11 [class.copy]p25:
6880     //   A copy assignment operator is trivial if:
6881     //    - the assignment operator selected to copy each direct [subobject] is
6882     //      trivial
6883     if (RD->hasTrivialCopyAssignment()) {
6884       if (Quals == Qualifiers::Const)
6885         return true;
6886     } else if (!Selected) {
6887       return false;
6888     }
6889     // In C++98, we are not supposed to perform overload resolution here, but we
6890     // treat that as a language defect.
6891     goto NeedOverloadResolution;
6892 
6893   case Sema::CXXMoveConstructor:
6894   case Sema::CXXMoveAssignment:
6895   NeedOverloadResolution:
6896     Sema::SpecialMemberOverloadResult *SMOR =
6897         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
6898 
6899     // The standard doesn't describe how to behave if the lookup is ambiguous.
6900     // We treat it as not making the member non-trivial, just like the standard
6901     // mandates for the default constructor. This should rarely matter, because
6902     // the member will also be deleted.
6903     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6904       return true;
6905 
6906     if (!SMOR->getMethod()) {
6907       assert(SMOR->getKind() ==
6908              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6909       return false;
6910     }
6911 
6912     // We deliberately don't check if we found a deleted special member. We're
6913     // not supposed to!
6914     if (Selected)
6915       *Selected = SMOR->getMethod();
6916     return SMOR->getMethod()->isTrivial();
6917   }
6918 
6919   llvm_unreachable("unknown special method kind");
6920 }
6921 
6922 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6923   for (auto *CI : RD->ctors())
6924     if (!CI->isImplicit())
6925       return CI;
6926 
6927   // Look for constructor templates.
6928   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6929   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6930     if (CXXConstructorDecl *CD =
6931           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6932       return CD;
6933   }
6934 
6935   return nullptr;
6936 }
6937 
6938 /// The kind of subobject we are checking for triviality. The values of this
6939 /// enumeration are used in diagnostics.
6940 enum TrivialSubobjectKind {
6941   /// The subobject is a base class.
6942   TSK_BaseClass,
6943   /// The subobject is a non-static data member.
6944   TSK_Field,
6945   /// The object is actually the complete object.
6946   TSK_CompleteObject
6947 };
6948 
6949 /// Check whether the special member selected for a given type would be trivial.
6950 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6951                                       QualType SubType, bool ConstRHS,
6952                                       Sema::CXXSpecialMember CSM,
6953                                       TrivialSubobjectKind Kind,
6954                                       bool Diagnose) {
6955   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6956   if (!SubRD)
6957     return true;
6958 
6959   CXXMethodDecl *Selected;
6960   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6961                                ConstRHS, Diagnose ? &Selected : nullptr))
6962     return true;
6963 
6964   if (Diagnose) {
6965     if (ConstRHS)
6966       SubType.addConst();
6967 
6968     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6969       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6970         << Kind << SubType.getUnqualifiedType();
6971       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6972         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6973     } else if (!Selected)
6974       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6975         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6976     else if (Selected->isUserProvided()) {
6977       if (Kind == TSK_CompleteObject)
6978         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6979           << Kind << SubType.getUnqualifiedType() << CSM;
6980       else {
6981         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6982           << Kind << SubType.getUnqualifiedType() << CSM;
6983         S.Diag(Selected->getLocation(), diag::note_declared_at);
6984       }
6985     } else {
6986       if (Kind != TSK_CompleteObject)
6987         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6988           << Kind << SubType.getUnqualifiedType() << CSM;
6989 
6990       // Explain why the defaulted or deleted special member isn't trivial.
6991       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6992     }
6993   }
6994 
6995   return false;
6996 }
6997 
6998 /// Check whether the members of a class type allow a special member to be
6999 /// trivial.
7000 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7001                                      Sema::CXXSpecialMember CSM,
7002                                      bool ConstArg, bool Diagnose) {
7003   for (const auto *FI : RD->fields()) {
7004     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7005       continue;
7006 
7007     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7008 
7009     // Pretend anonymous struct or union members are members of this class.
7010     if (FI->isAnonymousStructOrUnion()) {
7011       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7012                                     CSM, ConstArg, Diagnose))
7013         return false;
7014       continue;
7015     }
7016 
7017     // C++11 [class.ctor]p5:
7018     //   A default constructor is trivial if [...]
7019     //    -- no non-static data member of its class has a
7020     //       brace-or-equal-initializer
7021     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7022       if (Diagnose)
7023         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7024       return false;
7025     }
7026 
7027     // Objective C ARC 4.3.5:
7028     //   [...] nontrivally ownership-qualified types are [...] not trivially
7029     //   default constructible, copy constructible, move constructible, copy
7030     //   assignable, move assignable, or destructible [...]
7031     if (S.getLangOpts().ObjCAutoRefCount &&
7032         FieldType.hasNonTrivialObjCLifetime()) {
7033       if (Diagnose)
7034         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7035           << RD << FieldType.getObjCLifetime();
7036       return false;
7037     }
7038 
7039     bool ConstRHS = ConstArg && !FI->isMutable();
7040     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7041                                    CSM, TSK_Field, Diagnose))
7042       return false;
7043   }
7044 
7045   return true;
7046 }
7047 
7048 /// Diagnose why the specified class does not have a trivial special member of
7049 /// the given kind.
7050 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7051   QualType Ty = Context.getRecordType(RD);
7052 
7053   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7054   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7055                             TSK_CompleteObject, /*Diagnose*/true);
7056 }
7057 
7058 /// Determine whether a defaulted or deleted special member function is trivial,
7059 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7060 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7061 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7062                                   bool Diagnose) {
7063   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7064 
7065   CXXRecordDecl *RD = MD->getParent();
7066 
7067   bool ConstArg = false;
7068 
7069   // C++11 [class.copy]p12, p25: [DR1593]
7070   //   A [special member] is trivial if [...] its parameter-type-list is
7071   //   equivalent to the parameter-type-list of an implicit declaration [...]
7072   switch (CSM) {
7073   case CXXDefaultConstructor:
7074   case CXXDestructor:
7075     // Trivial default constructors and destructors cannot have parameters.
7076     break;
7077 
7078   case CXXCopyConstructor:
7079   case CXXCopyAssignment: {
7080     // Trivial copy operations always have const, non-volatile parameter types.
7081     ConstArg = true;
7082     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7083     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7084     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7085       if (Diagnose)
7086         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7087           << Param0->getSourceRange() << Param0->getType()
7088           << Context.getLValueReferenceType(
7089                Context.getRecordType(RD).withConst());
7090       return false;
7091     }
7092     break;
7093   }
7094 
7095   case CXXMoveConstructor:
7096   case CXXMoveAssignment: {
7097     // Trivial move operations always have non-cv-qualified parameters.
7098     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7099     const RValueReferenceType *RT =
7100       Param0->getType()->getAs<RValueReferenceType>();
7101     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7102       if (Diagnose)
7103         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7104           << Param0->getSourceRange() << Param0->getType()
7105           << Context.getRValueReferenceType(Context.getRecordType(RD));
7106       return false;
7107     }
7108     break;
7109   }
7110 
7111   case CXXInvalid:
7112     llvm_unreachable("not a special member");
7113   }
7114 
7115   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7116     if (Diagnose)
7117       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7118            diag::note_nontrivial_default_arg)
7119         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7120     return false;
7121   }
7122   if (MD->isVariadic()) {
7123     if (Diagnose)
7124       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7125     return false;
7126   }
7127 
7128   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7129   //   A copy/move [constructor or assignment operator] is trivial if
7130   //    -- the [member] selected to copy/move each direct base class subobject
7131   //       is trivial
7132   //
7133   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7134   //   A [default constructor or destructor] is trivial if
7135   //    -- all the direct base classes have trivial [default constructors or
7136   //       destructors]
7137   for (const auto &BI : RD->bases())
7138     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7139                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
7140       return false;
7141 
7142   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7143   //   A copy/move [constructor or assignment operator] for a class X is
7144   //   trivial if
7145   //    -- for each non-static data member of X that is of class type (or array
7146   //       thereof), the constructor selected to copy/move that member is
7147   //       trivial
7148   //
7149   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7150   //   A [default constructor or destructor] is trivial if
7151   //    -- for all of the non-static data members of its class that are of class
7152   //       type (or array thereof), each such class has a trivial [default
7153   //       constructor or destructor]
7154   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7155     return false;
7156 
7157   // C++11 [class.dtor]p5:
7158   //   A destructor is trivial if [...]
7159   //    -- the destructor is not virtual
7160   if (CSM == CXXDestructor && MD->isVirtual()) {
7161     if (Diagnose)
7162       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7163     return false;
7164   }
7165 
7166   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7167   //   A [special member] for class X is trivial if [...]
7168   //    -- class X has no virtual functions and no virtual base classes
7169   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7170     if (!Diagnose)
7171       return false;
7172 
7173     if (RD->getNumVBases()) {
7174       // Check for virtual bases. We already know that the corresponding
7175       // member in all bases is trivial, so vbases must all be direct.
7176       CXXBaseSpecifier &BS = *RD->vbases_begin();
7177       assert(BS.isVirtual());
7178       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7179       return false;
7180     }
7181 
7182     // Must have a virtual method.
7183     for (const auto *MI : RD->methods()) {
7184       if (MI->isVirtual()) {
7185         SourceLocation MLoc = MI->getLocStart();
7186         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7187         return false;
7188       }
7189     }
7190 
7191     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7192   }
7193 
7194   // Looks like it's trivial!
7195   return true;
7196 }
7197 
7198 namespace {
7199 struct FindHiddenVirtualMethod {
7200   Sema *S;
7201   CXXMethodDecl *Method;
7202   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7203   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7204 
7205 private:
7206   /// Check whether any most overriden method from MD in Methods
7207   static bool CheckMostOverridenMethods(
7208       const CXXMethodDecl *MD,
7209       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7210     if (MD->size_overridden_methods() == 0)
7211       return Methods.count(MD->getCanonicalDecl());
7212     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7213                                         E = MD->end_overridden_methods();
7214          I != E; ++I)
7215       if (CheckMostOverridenMethods(*I, Methods))
7216         return true;
7217     return false;
7218   }
7219 
7220 public:
7221   /// Member lookup function that determines whether a given C++
7222   /// method overloads virtual methods in a base class without overriding any,
7223   /// to be used with CXXRecordDecl::lookupInBases().
7224   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7225     RecordDecl *BaseRecord =
7226         Specifier->getType()->getAs<RecordType>()->getDecl();
7227 
7228     DeclarationName Name = Method->getDeclName();
7229     assert(Name.getNameKind() == DeclarationName::Identifier);
7230 
7231     bool foundSameNameMethod = false;
7232     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7233     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7234          Path.Decls = Path.Decls.slice(1)) {
7235       NamedDecl *D = Path.Decls.front();
7236       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7237         MD = MD->getCanonicalDecl();
7238         foundSameNameMethod = true;
7239         // Interested only in hidden virtual methods.
7240         if (!MD->isVirtual())
7241           continue;
7242         // If the method we are checking overrides a method from its base
7243         // don't warn about the other overloaded methods. Clang deviates from
7244         // GCC by only diagnosing overloads of inherited virtual functions that
7245         // do not override any other virtual functions in the base. GCC's
7246         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7247         // function from a base class. These cases may be better served by a
7248         // warning (not specific to virtual functions) on call sites when the
7249         // call would select a different function from the base class, were it
7250         // visible.
7251         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7252         if (!S->IsOverload(Method, MD, false))
7253           return true;
7254         // Collect the overload only if its hidden.
7255         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7256           overloadedMethods.push_back(MD);
7257       }
7258     }
7259 
7260     if (foundSameNameMethod)
7261       OverloadedMethods.append(overloadedMethods.begin(),
7262                                overloadedMethods.end());
7263     return foundSameNameMethod;
7264   }
7265 };
7266 } // end anonymous namespace
7267 
7268 /// \brief Add the most overriden methods from MD to Methods
7269 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7270                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7271   if (MD->size_overridden_methods() == 0)
7272     Methods.insert(MD->getCanonicalDecl());
7273   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7274                                       E = MD->end_overridden_methods();
7275        I != E; ++I)
7276     AddMostOverridenMethods(*I, Methods);
7277 }
7278 
7279 /// \brief Check if a method overloads virtual methods in a base class without
7280 /// overriding any.
7281 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7282                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7283   if (!MD->getDeclName().isIdentifier())
7284     return;
7285 
7286   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7287                      /*bool RecordPaths=*/false,
7288                      /*bool DetectVirtual=*/false);
7289   FindHiddenVirtualMethod FHVM;
7290   FHVM.Method = MD;
7291   FHVM.S = this;
7292 
7293   // Keep the base methods that were overriden or introduced in the subclass
7294   // by 'using' in a set. A base method not in this set is hidden.
7295   CXXRecordDecl *DC = MD->getParent();
7296   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7297   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7298     NamedDecl *ND = *I;
7299     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7300       ND = shad->getTargetDecl();
7301     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7302       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7303   }
7304 
7305   if (DC->lookupInBases(FHVM, Paths))
7306     OverloadedMethods = FHVM.OverloadedMethods;
7307 }
7308 
7309 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7310                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7311   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7312     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7313     PartialDiagnostic PD = PDiag(
7314          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7315     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7316     Diag(overloadedMD->getLocation(), PD);
7317   }
7318 }
7319 
7320 /// \brief Diagnose methods which overload virtual methods in a base class
7321 /// without overriding any.
7322 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7323   if (MD->isInvalidDecl())
7324     return;
7325 
7326   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7327     return;
7328 
7329   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7330   FindHiddenVirtualMethods(MD, OverloadedMethods);
7331   if (!OverloadedMethods.empty()) {
7332     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7333       << MD << (OverloadedMethods.size() > 1);
7334 
7335     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7336   }
7337 }
7338 
7339 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7340                                              Decl *TagDecl,
7341                                              SourceLocation LBrac,
7342                                              SourceLocation RBrac,
7343                                              AttributeList *AttrList) {
7344   if (!TagDecl)
7345     return;
7346 
7347   AdjustDeclIfTemplate(TagDecl);
7348 
7349   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7350     if (l->getKind() != AttributeList::AT_Visibility)
7351       continue;
7352     l->setInvalid();
7353     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7354       l->getName();
7355   }
7356 
7357   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7358               // strict aliasing violation!
7359               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7360               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7361 
7362   CheckCompletedCXXClass(
7363                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
7364 }
7365 
7366 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7367 /// special functions, such as the default constructor, copy
7368 /// constructor, or destructor, to the given C++ class (C++
7369 /// [special]p1).  This routine can only be executed just before the
7370 /// definition of the class is complete.
7371 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7372   if (ClassDecl->needsImplicitDefaultConstructor()) {
7373     ++ASTContext::NumImplicitDefaultConstructors;
7374 
7375     if (ClassDecl->hasInheritedConstructor())
7376       DeclareImplicitDefaultConstructor(ClassDecl);
7377   }
7378 
7379   if (ClassDecl->needsImplicitCopyConstructor()) {
7380     ++ASTContext::NumImplicitCopyConstructors;
7381 
7382     // If the properties or semantics of the copy constructor couldn't be
7383     // determined while the class was being declared, force a declaration
7384     // of it now.
7385     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7386         ClassDecl->hasInheritedConstructor())
7387       DeclareImplicitCopyConstructor(ClassDecl);
7388   }
7389 
7390   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7391     ++ASTContext::NumImplicitMoveConstructors;
7392 
7393     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7394         ClassDecl->hasInheritedConstructor())
7395       DeclareImplicitMoveConstructor(ClassDecl);
7396   }
7397 
7398   if (ClassDecl->needsImplicitCopyAssignment()) {
7399     ++ASTContext::NumImplicitCopyAssignmentOperators;
7400 
7401     // If we have a dynamic class, then the copy assignment operator may be
7402     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7403     // it shows up in the right place in the vtable and that we diagnose
7404     // problems with the implicit exception specification.
7405     if (ClassDecl->isDynamicClass() ||
7406         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7407         ClassDecl->hasInheritedAssignment())
7408       DeclareImplicitCopyAssignment(ClassDecl);
7409   }
7410 
7411   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7412     ++ASTContext::NumImplicitMoveAssignmentOperators;
7413 
7414     // Likewise for the move assignment operator.
7415     if (ClassDecl->isDynamicClass() ||
7416         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7417         ClassDecl->hasInheritedAssignment())
7418       DeclareImplicitMoveAssignment(ClassDecl);
7419   }
7420 
7421   if (ClassDecl->needsImplicitDestructor()) {
7422     ++ASTContext::NumImplicitDestructors;
7423 
7424     // If we have a dynamic class, then the destructor may be virtual, so we
7425     // have to declare the destructor immediately. This ensures that, e.g., it
7426     // shows up in the right place in the vtable and that we diagnose problems
7427     // with the implicit exception specification.
7428     if (ClassDecl->isDynamicClass() ||
7429         ClassDecl->needsOverloadResolutionForDestructor())
7430       DeclareImplicitDestructor(ClassDecl);
7431   }
7432 }
7433 
7434 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7435   if (!D)
7436     return 0;
7437 
7438   // The order of template parameters is not important here. All names
7439   // get added to the same scope.
7440   SmallVector<TemplateParameterList *, 4> ParameterLists;
7441 
7442   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7443     D = TD->getTemplatedDecl();
7444 
7445   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7446     ParameterLists.push_back(PSD->getTemplateParameters());
7447 
7448   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7449     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7450       ParameterLists.push_back(DD->getTemplateParameterList(i));
7451 
7452     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7453       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7454         ParameterLists.push_back(FTD->getTemplateParameters());
7455     }
7456   }
7457 
7458   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7459     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7460       ParameterLists.push_back(TD->getTemplateParameterList(i));
7461 
7462     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7463       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7464         ParameterLists.push_back(CTD->getTemplateParameters());
7465     }
7466   }
7467 
7468   unsigned Count = 0;
7469   for (TemplateParameterList *Params : ParameterLists) {
7470     if (Params->size() > 0)
7471       // Ignore explicit specializations; they don't contribute to the template
7472       // depth.
7473       ++Count;
7474     for (NamedDecl *Param : *Params) {
7475       if (Param->getDeclName()) {
7476         S->AddDecl(Param);
7477         IdResolver.AddDecl(Param);
7478       }
7479     }
7480   }
7481 
7482   return Count;
7483 }
7484 
7485 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7486   if (!RecordD) return;
7487   AdjustDeclIfTemplate(RecordD);
7488   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7489   PushDeclContext(S, Record);
7490 }
7491 
7492 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7493   if (!RecordD) return;
7494   PopDeclContext();
7495 }
7496 
7497 /// This is used to implement the constant expression evaluation part of the
7498 /// attribute enable_if extension. There is nothing in standard C++ which would
7499 /// require reentering parameters.
7500 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7501   if (!Param)
7502     return;
7503 
7504   S->AddDecl(Param);
7505   if (Param->getDeclName())
7506     IdResolver.AddDecl(Param);
7507 }
7508 
7509 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7510 /// parsing a top-level (non-nested) C++ class, and we are now
7511 /// parsing those parts of the given Method declaration that could
7512 /// not be parsed earlier (C++ [class.mem]p2), such as default
7513 /// arguments. This action should enter the scope of the given
7514 /// Method declaration as if we had just parsed the qualified method
7515 /// name. However, it should not bring the parameters into scope;
7516 /// that will be performed by ActOnDelayedCXXMethodParameter.
7517 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7518 }
7519 
7520 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7521 /// C++ method declaration. We're (re-)introducing the given
7522 /// function parameter into scope for use in parsing later parts of
7523 /// the method declaration. For example, we could see an
7524 /// ActOnParamDefaultArgument event for this parameter.
7525 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7526   if (!ParamD)
7527     return;
7528 
7529   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7530 
7531   // If this parameter has an unparsed default argument, clear it out
7532   // to make way for the parsed default argument.
7533   if (Param->hasUnparsedDefaultArg())
7534     Param->setDefaultArg(nullptr);
7535 
7536   S->AddDecl(Param);
7537   if (Param->getDeclName())
7538     IdResolver.AddDecl(Param);
7539 }
7540 
7541 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7542 /// processing the delayed method declaration for Method. The method
7543 /// declaration is now considered finished. There may be a separate
7544 /// ActOnStartOfFunctionDef action later (not necessarily
7545 /// immediately!) for this method, if it was also defined inside the
7546 /// class body.
7547 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7548   if (!MethodD)
7549     return;
7550 
7551   AdjustDeclIfTemplate(MethodD);
7552 
7553   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7554 
7555   // Now that we have our default arguments, check the constructor
7556   // again. It could produce additional diagnostics or affect whether
7557   // the class has implicitly-declared destructors, among other
7558   // things.
7559   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7560     CheckConstructor(Constructor);
7561 
7562   // Check the default arguments, which we may have added.
7563   if (!Method->isInvalidDecl())
7564     CheckCXXDefaultArguments(Method);
7565 }
7566 
7567 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7568 /// the well-formedness of the constructor declarator @p D with type @p
7569 /// R. If there are any errors in the declarator, this routine will
7570 /// emit diagnostics and set the invalid bit to true.  In any case, the type
7571 /// will be updated to reflect a well-formed type for the constructor and
7572 /// returned.
7573 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7574                                           StorageClass &SC) {
7575   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7576 
7577   // C++ [class.ctor]p3:
7578   //   A constructor shall not be virtual (10.3) or static (9.4). A
7579   //   constructor can be invoked for a const, volatile or const
7580   //   volatile object. A constructor shall not be declared const,
7581   //   volatile, or const volatile (9.3.2).
7582   if (isVirtual) {
7583     if (!D.isInvalidType())
7584       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7585         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7586         << SourceRange(D.getIdentifierLoc());
7587     D.setInvalidType();
7588   }
7589   if (SC == SC_Static) {
7590     if (!D.isInvalidType())
7591       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7592         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7593         << SourceRange(D.getIdentifierLoc());
7594     D.setInvalidType();
7595     SC = SC_None;
7596   }
7597 
7598   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7599     diagnoseIgnoredQualifiers(
7600         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7601         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7602         D.getDeclSpec().getRestrictSpecLoc(),
7603         D.getDeclSpec().getAtomicSpecLoc());
7604     D.setInvalidType();
7605   }
7606 
7607   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7608   if (FTI.TypeQuals != 0) {
7609     if (FTI.TypeQuals & Qualifiers::Const)
7610       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7611         << "const" << SourceRange(D.getIdentifierLoc());
7612     if (FTI.TypeQuals & Qualifiers::Volatile)
7613       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7614         << "volatile" << SourceRange(D.getIdentifierLoc());
7615     if (FTI.TypeQuals & Qualifiers::Restrict)
7616       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7617         << "restrict" << SourceRange(D.getIdentifierLoc());
7618     D.setInvalidType();
7619   }
7620 
7621   // C++0x [class.ctor]p4:
7622   //   A constructor shall not be declared with a ref-qualifier.
7623   if (FTI.hasRefQualifier()) {
7624     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7625       << FTI.RefQualifierIsLValueRef
7626       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7627     D.setInvalidType();
7628   }
7629 
7630   // Rebuild the function type "R" without any type qualifiers (in
7631   // case any of the errors above fired) and with "void" as the
7632   // return type, since constructors don't have return types.
7633   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7634   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7635     return R;
7636 
7637   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7638   EPI.TypeQuals = 0;
7639   EPI.RefQualifier = RQ_None;
7640 
7641   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7642 }
7643 
7644 /// CheckConstructor - Checks a fully-formed constructor for
7645 /// well-formedness, issuing any diagnostics required. Returns true if
7646 /// the constructor declarator is invalid.
7647 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7648   CXXRecordDecl *ClassDecl
7649     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7650   if (!ClassDecl)
7651     return Constructor->setInvalidDecl();
7652 
7653   // C++ [class.copy]p3:
7654   //   A declaration of a constructor for a class X is ill-formed if
7655   //   its first parameter is of type (optionally cv-qualified) X and
7656   //   either there are no other parameters or else all other
7657   //   parameters have default arguments.
7658   if (!Constructor->isInvalidDecl() &&
7659       ((Constructor->getNumParams() == 1) ||
7660        (Constructor->getNumParams() > 1 &&
7661         Constructor->getParamDecl(1)->hasDefaultArg())) &&
7662       Constructor->getTemplateSpecializationKind()
7663                                               != TSK_ImplicitInstantiation) {
7664     QualType ParamType = Constructor->getParamDecl(0)->getType();
7665     QualType ClassTy = Context.getTagDeclType(ClassDecl);
7666     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7667       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7668       const char *ConstRef
7669         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7670                                                         : " const &";
7671       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7672         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7673 
7674       // FIXME: Rather that making the constructor invalid, we should endeavor
7675       // to fix the type.
7676       Constructor->setInvalidDecl();
7677     }
7678   }
7679 }
7680 
7681 /// CheckDestructor - Checks a fully-formed destructor definition for
7682 /// well-formedness, issuing any diagnostics required.  Returns true
7683 /// on error.
7684 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
7685   CXXRecordDecl *RD = Destructor->getParent();
7686 
7687   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
7688     SourceLocation Loc;
7689 
7690     if (!Destructor->isImplicit())
7691       Loc = Destructor->getLocation();
7692     else
7693       Loc = RD->getLocation();
7694 
7695     // If we have a virtual destructor, look up the deallocation function
7696     if (FunctionDecl *OperatorDelete =
7697             FindDeallocationFunctionForDestructor(Loc, RD)) {
7698       MarkFunctionReferenced(Loc, OperatorDelete);
7699       Destructor->setOperatorDelete(OperatorDelete);
7700     }
7701   }
7702 
7703   return false;
7704 }
7705 
7706 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7707 /// the well-formednes of the destructor declarator @p D with type @p
7708 /// R. If there are any errors in the declarator, this routine will
7709 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
7710 /// will be updated to reflect a well-formed type for the destructor and
7711 /// returned.
7712 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
7713                                          StorageClass& SC) {
7714   // C++ [class.dtor]p1:
7715   //   [...] A typedef-name that names a class is a class-name
7716   //   (7.1.3); however, a typedef-name that names a class shall not
7717   //   be used as the identifier in the declarator for a destructor
7718   //   declaration.
7719   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
7720   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
7721     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7722       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
7723   else if (const TemplateSpecializationType *TST =
7724              DeclaratorType->getAs<TemplateSpecializationType>())
7725     if (TST->isTypeAlias())
7726       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7727         << DeclaratorType << 1;
7728 
7729   // C++ [class.dtor]p2:
7730   //   A destructor is used to destroy objects of its class type. A
7731   //   destructor takes no parameters, and no return type can be
7732   //   specified for it (not even void). The address of a destructor
7733   //   shall not be taken. A destructor shall not be static. A
7734   //   destructor can be invoked for a const, volatile or const
7735   //   volatile object. A destructor shall not be declared const,
7736   //   volatile or const volatile (9.3.2).
7737   if (SC == SC_Static) {
7738     if (!D.isInvalidType())
7739       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7740         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7741         << SourceRange(D.getIdentifierLoc())
7742         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7743 
7744     SC = SC_None;
7745   }
7746   if (!D.isInvalidType()) {
7747     // Destructors don't have return types, but the parser will
7748     // happily parse something like:
7749     //
7750     //   class X {
7751     //     float ~X();
7752     //   };
7753     //
7754     // The return type will be eliminated later.
7755     if (D.getDeclSpec().hasTypeSpecifier())
7756       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7757         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7758         << SourceRange(D.getIdentifierLoc());
7759     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7760       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7761                                 SourceLocation(),
7762                                 D.getDeclSpec().getConstSpecLoc(),
7763                                 D.getDeclSpec().getVolatileSpecLoc(),
7764                                 D.getDeclSpec().getRestrictSpecLoc(),
7765                                 D.getDeclSpec().getAtomicSpecLoc());
7766       D.setInvalidType();
7767     }
7768   }
7769 
7770   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7771   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7772     if (FTI.TypeQuals & Qualifiers::Const)
7773       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7774         << "const" << SourceRange(D.getIdentifierLoc());
7775     if (FTI.TypeQuals & Qualifiers::Volatile)
7776       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7777         << "volatile" << SourceRange(D.getIdentifierLoc());
7778     if (FTI.TypeQuals & Qualifiers::Restrict)
7779       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7780         << "restrict" << SourceRange(D.getIdentifierLoc());
7781     D.setInvalidType();
7782   }
7783 
7784   // C++0x [class.dtor]p2:
7785   //   A destructor shall not be declared with a ref-qualifier.
7786   if (FTI.hasRefQualifier()) {
7787     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7788       << FTI.RefQualifierIsLValueRef
7789       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7790     D.setInvalidType();
7791   }
7792 
7793   // Make sure we don't have any parameters.
7794   if (FTIHasNonVoidParameters(FTI)) {
7795     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7796 
7797     // Delete the parameters.
7798     FTI.freeParams();
7799     D.setInvalidType();
7800   }
7801 
7802   // Make sure the destructor isn't variadic.
7803   if (FTI.isVariadic) {
7804     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
7805     D.setInvalidType();
7806   }
7807 
7808   // Rebuild the function type "R" without any type qualifiers or
7809   // parameters (in case any of the errors above fired) and with
7810   // "void" as the return type, since destructors don't have return
7811   // types.
7812   if (!D.isInvalidType())
7813     return R;
7814 
7815   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7816   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7817   EPI.Variadic = false;
7818   EPI.TypeQuals = 0;
7819   EPI.RefQualifier = RQ_None;
7820   return Context.getFunctionType(Context.VoidTy, None, EPI);
7821 }
7822 
7823 static void extendLeft(SourceRange &R, SourceRange Before) {
7824   if (Before.isInvalid())
7825     return;
7826   R.setBegin(Before.getBegin());
7827   if (R.getEnd().isInvalid())
7828     R.setEnd(Before.getEnd());
7829 }
7830 
7831 static void extendRight(SourceRange &R, SourceRange After) {
7832   if (After.isInvalid())
7833     return;
7834   if (R.getBegin().isInvalid())
7835     R.setBegin(After.getBegin());
7836   R.setEnd(After.getEnd());
7837 }
7838 
7839 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7840 /// well-formednes of the conversion function declarator @p D with
7841 /// type @p R. If there are any errors in the declarator, this routine
7842 /// will emit diagnostics and return true. Otherwise, it will return
7843 /// false. Either way, the type @p R will be updated to reflect a
7844 /// well-formed type for the conversion operator.
7845 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
7846                                      StorageClass& SC) {
7847   // C++ [class.conv.fct]p1:
7848   //   Neither parameter types nor return type can be specified. The
7849   //   type of a conversion function (8.3.5) is "function taking no
7850   //   parameter returning conversion-type-id."
7851   if (SC == SC_Static) {
7852     if (!D.isInvalidType())
7853       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
7854         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7855         << D.getName().getSourceRange();
7856     D.setInvalidType();
7857     SC = SC_None;
7858   }
7859 
7860   TypeSourceInfo *ConvTSI = nullptr;
7861   QualType ConvType =
7862       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
7863 
7864   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
7865     // Conversion functions don't have return types, but the parser will
7866     // happily parse something like:
7867     //
7868     //   class X {
7869     //     float operator bool();
7870     //   };
7871     //
7872     // The return type will be changed later anyway.
7873     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7874       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7875       << SourceRange(D.getIdentifierLoc());
7876     D.setInvalidType();
7877   }
7878 
7879   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7880 
7881   // Make sure we don't have any parameters.
7882   if (Proto->getNumParams() > 0) {
7883     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7884 
7885     // Delete the parameters.
7886     D.getFunctionTypeInfo().freeParams();
7887     D.setInvalidType();
7888   } else if (Proto->isVariadic()) {
7889     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
7890     D.setInvalidType();
7891   }
7892 
7893   // Diagnose "&operator bool()" and other such nonsense.  This
7894   // is actually a gcc extension which we don't support.
7895   if (Proto->getReturnType() != ConvType) {
7896     bool NeedsTypedef = false;
7897     SourceRange Before, After;
7898 
7899     // Walk the chunks and extract information on them for our diagnostic.
7900     bool PastFunctionChunk = false;
7901     for (auto &Chunk : D.type_objects()) {
7902       switch (Chunk.Kind) {
7903       case DeclaratorChunk::Function:
7904         if (!PastFunctionChunk) {
7905           if (Chunk.Fun.HasTrailingReturnType) {
7906             TypeSourceInfo *TRT = nullptr;
7907             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7908             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7909           }
7910           PastFunctionChunk = true;
7911           break;
7912         }
7913         // Fall through.
7914       case DeclaratorChunk::Array:
7915         NeedsTypedef = true;
7916         extendRight(After, Chunk.getSourceRange());
7917         break;
7918 
7919       case DeclaratorChunk::Pointer:
7920       case DeclaratorChunk::BlockPointer:
7921       case DeclaratorChunk::Reference:
7922       case DeclaratorChunk::MemberPointer:
7923       case DeclaratorChunk::Pipe:
7924         extendLeft(Before, Chunk.getSourceRange());
7925         break;
7926 
7927       case DeclaratorChunk::Paren:
7928         extendLeft(Before, Chunk.Loc);
7929         extendRight(After, Chunk.EndLoc);
7930         break;
7931       }
7932     }
7933 
7934     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7935                          After.isValid()  ? After.getBegin() :
7936                                             D.getIdentifierLoc();
7937     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7938     DB << Before << After;
7939 
7940     if (!NeedsTypedef) {
7941       DB << /*don't need a typedef*/0;
7942 
7943       // If we can provide a correct fix-it hint, do so.
7944       if (After.isInvalid() && ConvTSI) {
7945         SourceLocation InsertLoc =
7946             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7947         DB << FixItHint::CreateInsertion(InsertLoc, " ")
7948            << FixItHint::CreateInsertionFromRange(
7949                   InsertLoc, CharSourceRange::getTokenRange(Before))
7950            << FixItHint::CreateRemoval(Before);
7951       }
7952     } else if (!Proto->getReturnType()->isDependentType()) {
7953       DB << /*typedef*/1 << Proto->getReturnType();
7954     } else if (getLangOpts().CPlusPlus11) {
7955       DB << /*alias template*/2 << Proto->getReturnType();
7956     } else {
7957       DB << /*might not be fixable*/3;
7958     }
7959 
7960     // Recover by incorporating the other type chunks into the result type.
7961     // Note, this does *not* change the name of the function. This is compatible
7962     // with the GCC extension:
7963     //   struct S { &operator int(); } s;
7964     //   int &r = s.operator int(); // ok in GCC
7965     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
7966     ConvType = Proto->getReturnType();
7967   }
7968 
7969   // C++ [class.conv.fct]p4:
7970   //   The conversion-type-id shall not represent a function type nor
7971   //   an array type.
7972   if (ConvType->isArrayType()) {
7973     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7974     ConvType = Context.getPointerType(ConvType);
7975     D.setInvalidType();
7976   } else if (ConvType->isFunctionType()) {
7977     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7978     ConvType = Context.getPointerType(ConvType);
7979     D.setInvalidType();
7980   }
7981 
7982   // Rebuild the function type "R" without any parameters (in case any
7983   // of the errors above fired) and with the conversion type as the
7984   // return type.
7985   if (D.isInvalidType())
7986     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7987 
7988   // C++0x explicit conversion operators.
7989   if (D.getDeclSpec().isExplicitSpecified())
7990     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7991          getLangOpts().CPlusPlus11 ?
7992            diag::warn_cxx98_compat_explicit_conversion_functions :
7993            diag::ext_explicit_conversion_functions)
7994       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7995 }
7996 
7997 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7998 /// the declaration of the given C++ conversion function. This routine
7999 /// is responsible for recording the conversion function in the C++
8000 /// class, if possible.
8001 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8002   assert(Conversion && "Expected to receive a conversion function declaration");
8003 
8004   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8005 
8006   // Make sure we aren't redeclaring the conversion function.
8007   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8008 
8009   // C++ [class.conv.fct]p1:
8010   //   [...] A conversion function is never used to convert a
8011   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8012   //   same object type (or a reference to it), to a (possibly
8013   //   cv-qualified) base class of that type (or a reference to it),
8014   //   or to (possibly cv-qualified) void.
8015   // FIXME: Suppress this warning if the conversion function ends up being a
8016   // virtual function that overrides a virtual function in a base class.
8017   QualType ClassType
8018     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8019   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8020     ConvType = ConvTypeRef->getPointeeType();
8021   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8022       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8023     /* Suppress diagnostics for instantiations. */;
8024   else if (ConvType->isRecordType()) {
8025     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8026     if (ConvType == ClassType)
8027       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8028         << ClassType;
8029     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8030       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8031         <<  ClassType << ConvType;
8032   } else if (ConvType->isVoidType()) {
8033     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8034       << ClassType << ConvType;
8035   }
8036 
8037   if (FunctionTemplateDecl *ConversionTemplate
8038                                 = Conversion->getDescribedFunctionTemplate())
8039     return ConversionTemplate;
8040 
8041   return Conversion;
8042 }
8043 
8044 //===----------------------------------------------------------------------===//
8045 // Namespace Handling
8046 //===----------------------------------------------------------------------===//
8047 
8048 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8049 /// reopened.
8050 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8051                                             SourceLocation Loc,
8052                                             IdentifierInfo *II, bool *IsInline,
8053                                             NamespaceDecl *PrevNS) {
8054   assert(*IsInline != PrevNS->isInline());
8055 
8056   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8057   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8058   // inline namespaces, with the intention of bringing names into namespace std.
8059   //
8060   // We support this just well enough to get that case working; this is not
8061   // sufficient to support reopening namespaces as inline in general.
8062   if (*IsInline && II && II->getName().startswith("__atomic") &&
8063       S.getSourceManager().isInSystemHeader(Loc)) {
8064     // Mark all prior declarations of the namespace as inline.
8065     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8066          NS = NS->getPreviousDecl())
8067       NS->setInline(*IsInline);
8068     // Patch up the lookup table for the containing namespace. This isn't really
8069     // correct, but it's good enough for this particular case.
8070     for (auto *I : PrevNS->decls())
8071       if (auto *ND = dyn_cast<NamedDecl>(I))
8072         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8073     return;
8074   }
8075 
8076   if (PrevNS->isInline())
8077     // The user probably just forgot the 'inline', so suggest that it
8078     // be added back.
8079     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8080       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8081   else
8082     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8083 
8084   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8085   *IsInline = PrevNS->isInline();
8086 }
8087 
8088 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8089 /// definition.
8090 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8091                                    SourceLocation InlineLoc,
8092                                    SourceLocation NamespaceLoc,
8093                                    SourceLocation IdentLoc,
8094                                    IdentifierInfo *II,
8095                                    SourceLocation LBrace,
8096                                    AttributeList *AttrList,
8097                                    UsingDirectiveDecl *&UD) {
8098   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8099   // For anonymous namespace, take the location of the left brace.
8100   SourceLocation Loc = II ? IdentLoc : LBrace;
8101   bool IsInline = InlineLoc.isValid();
8102   bool IsInvalid = false;
8103   bool IsStd = false;
8104   bool AddToKnown = false;
8105   Scope *DeclRegionScope = NamespcScope->getParent();
8106 
8107   NamespaceDecl *PrevNS = nullptr;
8108   if (II) {
8109     // C++ [namespace.def]p2:
8110     //   The identifier in an original-namespace-definition shall not
8111     //   have been previously defined in the declarative region in
8112     //   which the original-namespace-definition appears. The
8113     //   identifier in an original-namespace-definition is the name of
8114     //   the namespace. Subsequently in that declarative region, it is
8115     //   treated as an original-namespace-name.
8116     //
8117     // Since namespace names are unique in their scope, and we don't
8118     // look through using directives, just look for any ordinary names
8119     // as if by qualified name lookup.
8120     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8121     LookupQualifiedName(R, CurContext->getRedeclContext());
8122     NamedDecl *PrevDecl =
8123         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8124     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8125 
8126     if (PrevNS) {
8127       // This is an extended namespace definition.
8128       if (IsInline != PrevNS->isInline())
8129         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8130                                         &IsInline, PrevNS);
8131     } else if (PrevDecl) {
8132       // This is an invalid name redefinition.
8133       Diag(Loc, diag::err_redefinition_different_kind)
8134         << II;
8135       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8136       IsInvalid = true;
8137       // Continue on to push Namespc as current DeclContext and return it.
8138     } else if (II->isStr("std") &&
8139                CurContext->getRedeclContext()->isTranslationUnit()) {
8140       // This is the first "real" definition of the namespace "std", so update
8141       // our cache of the "std" namespace to point at this definition.
8142       PrevNS = getStdNamespace();
8143       IsStd = true;
8144       AddToKnown = !IsInline;
8145     } else {
8146       // We've seen this namespace for the first time.
8147       AddToKnown = !IsInline;
8148     }
8149   } else {
8150     // Anonymous namespaces.
8151 
8152     // Determine whether the parent already has an anonymous namespace.
8153     DeclContext *Parent = CurContext->getRedeclContext();
8154     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8155       PrevNS = TU->getAnonymousNamespace();
8156     } else {
8157       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8158       PrevNS = ND->getAnonymousNamespace();
8159     }
8160 
8161     if (PrevNS && IsInline != PrevNS->isInline())
8162       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8163                                       &IsInline, PrevNS);
8164   }
8165 
8166   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8167                                                  StartLoc, Loc, II, PrevNS);
8168   if (IsInvalid)
8169     Namespc->setInvalidDecl();
8170 
8171   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8172 
8173   // FIXME: Should we be merging attributes?
8174   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8175     PushNamespaceVisibilityAttr(Attr, Loc);
8176 
8177   if (IsStd)
8178     StdNamespace = Namespc;
8179   if (AddToKnown)
8180     KnownNamespaces[Namespc] = false;
8181 
8182   if (II) {
8183     PushOnScopeChains(Namespc, DeclRegionScope);
8184   } else {
8185     // Link the anonymous namespace into its parent.
8186     DeclContext *Parent = CurContext->getRedeclContext();
8187     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8188       TU->setAnonymousNamespace(Namespc);
8189     } else {
8190       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8191     }
8192 
8193     CurContext->addDecl(Namespc);
8194 
8195     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8196     //   behaves as if it were replaced by
8197     //     namespace unique { /* empty body */ }
8198     //     using namespace unique;
8199     //     namespace unique { namespace-body }
8200     //   where all occurrences of 'unique' in a translation unit are
8201     //   replaced by the same identifier and this identifier differs
8202     //   from all other identifiers in the entire program.
8203 
8204     // We just create the namespace with an empty name and then add an
8205     // implicit using declaration, just like the standard suggests.
8206     //
8207     // CodeGen enforces the "universally unique" aspect by giving all
8208     // declarations semantically contained within an anonymous
8209     // namespace internal linkage.
8210 
8211     if (!PrevNS) {
8212       UD = UsingDirectiveDecl::Create(Context, Parent,
8213                                       /* 'using' */ LBrace,
8214                                       /* 'namespace' */ SourceLocation(),
8215                                       /* qualifier */ NestedNameSpecifierLoc(),
8216                                       /* identifier */ SourceLocation(),
8217                                       Namespc,
8218                                       /* Ancestor */ Parent);
8219       UD->setImplicit();
8220       Parent->addDecl(UD);
8221     }
8222   }
8223 
8224   ActOnDocumentableDecl(Namespc);
8225 
8226   // Although we could have an invalid decl (i.e. the namespace name is a
8227   // redefinition), push it as current DeclContext and try to continue parsing.
8228   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8229   // for the namespace has the declarations that showed up in that particular
8230   // namespace definition.
8231   PushDeclContext(NamespcScope, Namespc);
8232   return Namespc;
8233 }
8234 
8235 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8236 /// is a namespace alias, returns the namespace it points to.
8237 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8238   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8239     return AD->getNamespace();
8240   return dyn_cast_or_null<NamespaceDecl>(D);
8241 }
8242 
8243 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8244 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8245 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8246   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8247   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8248   Namespc->setRBraceLoc(RBrace);
8249   PopDeclContext();
8250   if (Namespc->hasAttr<VisibilityAttr>())
8251     PopPragmaVisibility(true, RBrace);
8252 }
8253 
8254 CXXRecordDecl *Sema::getStdBadAlloc() const {
8255   return cast_or_null<CXXRecordDecl>(
8256                                   StdBadAlloc.get(Context.getExternalSource()));
8257 }
8258 
8259 EnumDecl *Sema::getStdAlignValT() const {
8260   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8261 }
8262 
8263 NamespaceDecl *Sema::getStdNamespace() const {
8264   return cast_or_null<NamespaceDecl>(
8265                                  StdNamespace.get(Context.getExternalSource()));
8266 }
8267 
8268 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8269   if (!StdExperimentalNamespaceCache) {
8270     if (auto Std = getStdNamespace()) {
8271       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8272                           SourceLocation(), LookupNamespaceName);
8273       if (!LookupQualifiedName(Result, Std) ||
8274           !(StdExperimentalNamespaceCache =
8275                 Result.getAsSingle<NamespaceDecl>()))
8276         Result.suppressDiagnostics();
8277     }
8278   }
8279   return StdExperimentalNamespaceCache;
8280 }
8281 
8282 /// \brief Retrieve the special "std" namespace, which may require us to
8283 /// implicitly define the namespace.
8284 NamespaceDecl *Sema::getOrCreateStdNamespace() {
8285   if (!StdNamespace) {
8286     // The "std" namespace has not yet been defined, so build one implicitly.
8287     StdNamespace = NamespaceDecl::Create(Context,
8288                                          Context.getTranslationUnitDecl(),
8289                                          /*Inline=*/false,
8290                                          SourceLocation(), SourceLocation(),
8291                                          &PP.getIdentifierTable().get("std"),
8292                                          /*PrevDecl=*/nullptr);
8293     getStdNamespace()->setImplicit(true);
8294   }
8295 
8296   return getStdNamespace();
8297 }
8298 
8299 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8300   assert(getLangOpts().CPlusPlus &&
8301          "Looking for std::initializer_list outside of C++.");
8302 
8303   // We're looking for implicit instantiations of
8304   // template <typename E> class std::initializer_list.
8305 
8306   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8307     return false;
8308 
8309   ClassTemplateDecl *Template = nullptr;
8310   const TemplateArgument *Arguments = nullptr;
8311 
8312   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8313 
8314     ClassTemplateSpecializationDecl *Specialization =
8315         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8316     if (!Specialization)
8317       return false;
8318 
8319     Template = Specialization->getSpecializedTemplate();
8320     Arguments = Specialization->getTemplateArgs().data();
8321   } else if (const TemplateSpecializationType *TST =
8322                  Ty->getAs<TemplateSpecializationType>()) {
8323     Template = dyn_cast_or_null<ClassTemplateDecl>(
8324         TST->getTemplateName().getAsTemplateDecl());
8325     Arguments = TST->getArgs();
8326   }
8327   if (!Template)
8328     return false;
8329 
8330   if (!StdInitializerList) {
8331     // Haven't recognized std::initializer_list yet, maybe this is it.
8332     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8333     if (TemplateClass->getIdentifier() !=
8334             &PP.getIdentifierTable().get("initializer_list") ||
8335         !getStdNamespace()->InEnclosingNamespaceSetOf(
8336             TemplateClass->getDeclContext()))
8337       return false;
8338     // This is a template called std::initializer_list, but is it the right
8339     // template?
8340     TemplateParameterList *Params = Template->getTemplateParameters();
8341     if (Params->getMinRequiredArguments() != 1)
8342       return false;
8343     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8344       return false;
8345 
8346     // It's the right template.
8347     StdInitializerList = Template;
8348   }
8349 
8350   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8351     return false;
8352 
8353   // This is an instance of std::initializer_list. Find the argument type.
8354   if (Element)
8355     *Element = Arguments[0].getAsType();
8356   return true;
8357 }
8358 
8359 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8360   NamespaceDecl *Std = S.getStdNamespace();
8361   if (!Std) {
8362     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8363     return nullptr;
8364   }
8365 
8366   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8367                       Loc, Sema::LookupOrdinaryName);
8368   if (!S.LookupQualifiedName(Result, Std)) {
8369     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8370     return nullptr;
8371   }
8372   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8373   if (!Template) {
8374     Result.suppressDiagnostics();
8375     // We found something weird. Complain about the first thing we found.
8376     NamedDecl *Found = *Result.begin();
8377     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8378     return nullptr;
8379   }
8380 
8381   // We found some template called std::initializer_list. Now verify that it's
8382   // correct.
8383   TemplateParameterList *Params = Template->getTemplateParameters();
8384   if (Params->getMinRequiredArguments() != 1 ||
8385       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8386     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8387     return nullptr;
8388   }
8389 
8390   return Template;
8391 }
8392 
8393 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8394   if (!StdInitializerList) {
8395     StdInitializerList = LookupStdInitializerList(*this, Loc);
8396     if (!StdInitializerList)
8397       return QualType();
8398   }
8399 
8400   TemplateArgumentListInfo Args(Loc, Loc);
8401   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8402                                        Context.getTrivialTypeSourceInfo(Element,
8403                                                                         Loc)));
8404   return Context.getCanonicalType(
8405       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8406 }
8407 
8408 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
8409   // C++ [dcl.init.list]p2:
8410   //   A constructor is an initializer-list constructor if its first parameter
8411   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
8412   //   std::initializer_list<E> for some type E, and either there are no other
8413   //   parameters or else all other parameters have default arguments.
8414   if (Ctor->getNumParams() < 1 ||
8415       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8416     return false;
8417 
8418   QualType ArgType = Ctor->getParamDecl(0)->getType();
8419   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8420     ArgType = RT->getPointeeType().getUnqualifiedType();
8421 
8422   return isStdInitializerList(ArgType, nullptr);
8423 }
8424 
8425 /// \brief Determine whether a using statement is in a context where it will be
8426 /// apply in all contexts.
8427 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8428   switch (CurContext->getDeclKind()) {
8429     case Decl::TranslationUnit:
8430       return true;
8431     case Decl::LinkageSpec:
8432       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8433     default:
8434       return false;
8435   }
8436 }
8437 
8438 namespace {
8439 
8440 // Callback to only accept typo corrections that are namespaces.
8441 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
8442 public:
8443   bool ValidateCandidate(const TypoCorrection &candidate) override {
8444     if (NamedDecl *ND = candidate.getCorrectionDecl())
8445       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
8446     return false;
8447   }
8448 };
8449 
8450 }
8451 
8452 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8453                                        CXXScopeSpec &SS,
8454                                        SourceLocation IdentLoc,
8455                                        IdentifierInfo *Ident) {
8456   R.clear();
8457   if (TypoCorrection Corrected =
8458           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8459                         llvm::make_unique<NamespaceValidatorCCC>(),
8460                         Sema::CTK_ErrorRecovery)) {
8461     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
8462       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8463       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
8464                               Ident->getName().equals(CorrectedStr);
8465       S.diagnoseTypo(Corrected,
8466                      S.PDiag(diag::err_using_directive_member_suggest)
8467                        << Ident << DC << DroppedSpecifier << SS.getRange(),
8468                      S.PDiag(diag::note_namespace_defined_here));
8469     } else {
8470       S.diagnoseTypo(Corrected,
8471                      S.PDiag(diag::err_using_directive_suggest) << Ident,
8472                      S.PDiag(diag::note_namespace_defined_here));
8473     }
8474     R.addDecl(Corrected.getFoundDecl());
8475     return true;
8476   }
8477   return false;
8478 }
8479 
8480 Decl *Sema::ActOnUsingDirective(Scope *S,
8481                                           SourceLocation UsingLoc,
8482                                           SourceLocation NamespcLoc,
8483                                           CXXScopeSpec &SS,
8484                                           SourceLocation IdentLoc,
8485                                           IdentifierInfo *NamespcName,
8486                                           AttributeList *AttrList) {
8487   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8488   assert(NamespcName && "Invalid NamespcName.");
8489   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
8490 
8491   // This can only happen along a recovery path.
8492   while (S->isTemplateParamScope())
8493     S = S->getParent();
8494   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8495 
8496   UsingDirectiveDecl *UDir = nullptr;
8497   NestedNameSpecifier *Qualifier = nullptr;
8498   if (SS.isSet())
8499     Qualifier = SS.getScopeRep();
8500 
8501   // Lookup namespace name.
8502   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8503   LookupParsedName(R, S, &SS);
8504   if (R.isAmbiguous())
8505     return nullptr;
8506 
8507   if (R.empty()) {
8508     R.clear();
8509     // Allow "using namespace std;" or "using namespace ::std;" even if
8510     // "std" hasn't been defined yet, for GCC compatibility.
8511     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8512         NamespcName->isStr("std")) {
8513       Diag(IdentLoc, diag::ext_using_undefined_std);
8514       R.addDecl(getOrCreateStdNamespace());
8515       R.resolveKind();
8516     }
8517     // Otherwise, attempt typo correction.
8518     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
8519   }
8520 
8521   if (!R.empty()) {
8522     NamedDecl *Named = R.getRepresentativeDecl();
8523     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8524     assert(NS && "expected namespace decl");
8525 
8526     // The use of a nested name specifier may trigger deprecation warnings.
8527     DiagnoseUseOfDecl(Named, IdentLoc);
8528 
8529     // C++ [namespace.udir]p1:
8530     //   A using-directive specifies that the names in the nominated
8531     //   namespace can be used in the scope in which the
8532     //   using-directive appears after the using-directive. During
8533     //   unqualified name lookup (3.4.1), the names appear as if they
8534     //   were declared in the nearest enclosing namespace which
8535     //   contains both the using-directive and the nominated
8536     //   namespace. [Note: in this context, "contains" means "contains
8537     //   directly or indirectly". ]
8538 
8539     // Find enclosing context containing both using-directive and
8540     // nominated namespace.
8541     DeclContext *CommonAncestor = cast<DeclContext>(NS);
8542     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8543       CommonAncestor = CommonAncestor->getParent();
8544 
8545     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
8546                                       SS.getWithLocInContext(Context),
8547                                       IdentLoc, Named, CommonAncestor);
8548 
8549     if (IsUsingDirectiveInToplevelContext(CurContext) &&
8550         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
8551       Diag(IdentLoc, diag::warn_using_directive_in_header);
8552     }
8553 
8554     PushUsingDirective(S, UDir);
8555   } else {
8556     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8557   }
8558 
8559   if (UDir)
8560     ProcessDeclAttributeList(S, UDir, AttrList);
8561 
8562   return UDir;
8563 }
8564 
8565 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
8566   // If the scope has an associated entity and the using directive is at
8567   // namespace or translation unit scope, add the UsingDirectiveDecl into
8568   // its lookup structure so qualified name lookup can find it.
8569   DeclContext *Ctx = S->getEntity();
8570   if (Ctx && !Ctx->isFunctionOrMethod())
8571     Ctx->addDecl(UDir);
8572   else
8573     // Otherwise, it is at block scope. The using-directives will affect lookup
8574     // only to the end of the scope.
8575     S->PushUsingDirective(UDir);
8576 }
8577 
8578 
8579 Decl *Sema::ActOnUsingDeclaration(Scope *S,
8580                                   AccessSpecifier AS,
8581                                   bool HasUsingKeyword,
8582                                   SourceLocation UsingLoc,
8583                                   CXXScopeSpec &SS,
8584                                   UnqualifiedId &Name,
8585                                   AttributeList *AttrList,
8586                                   bool HasTypenameKeyword,
8587                                   SourceLocation TypenameLoc) {
8588   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8589 
8590   switch (Name.getKind()) {
8591   case UnqualifiedId::IK_ImplicitSelfParam:
8592   case UnqualifiedId::IK_Identifier:
8593   case UnqualifiedId::IK_OperatorFunctionId:
8594   case UnqualifiedId::IK_LiteralOperatorId:
8595   case UnqualifiedId::IK_ConversionFunctionId:
8596     break;
8597 
8598   case UnqualifiedId::IK_ConstructorName:
8599   case UnqualifiedId::IK_ConstructorTemplateId:
8600     // C++11 inheriting constructors.
8601     Diag(Name.getLocStart(),
8602          getLangOpts().CPlusPlus11 ?
8603            diag::warn_cxx98_compat_using_decl_constructor :
8604            diag::err_using_decl_constructor)
8605       << SS.getRange();
8606 
8607     if (getLangOpts().CPlusPlus11) break;
8608 
8609     return nullptr;
8610 
8611   case UnqualifiedId::IK_DestructorName:
8612     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
8613       << SS.getRange();
8614     return nullptr;
8615 
8616   case UnqualifiedId::IK_TemplateId:
8617     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
8618       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
8619     return nullptr;
8620   }
8621 
8622   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8623   DeclarationName TargetName = TargetNameInfo.getName();
8624   if (!TargetName)
8625     return nullptr;
8626 
8627   // Warn about access declarations.
8628   if (!HasUsingKeyword) {
8629     Diag(Name.getLocStart(),
8630          getLangOpts().CPlusPlus11 ? diag::err_access_decl
8631                                    : diag::warn_access_decl_deprecated)
8632       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
8633   }
8634 
8635   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8636       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8637     return nullptr;
8638 
8639   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
8640                                         TargetNameInfo, AttrList,
8641                                         /* IsInstantiation */ false,
8642                                         HasTypenameKeyword, TypenameLoc);
8643   if (UD)
8644     PushOnScopeChains(UD, S, /*AddToContext*/ false);
8645 
8646   return UD;
8647 }
8648 
8649 /// \brief Determine whether a using declaration considers the given
8650 /// declarations as "equivalent", e.g., if they are redeclarations of
8651 /// the same entity or are both typedefs of the same type.
8652 static bool
8653 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8654   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
8655     return true;
8656 
8657   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
8658     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
8659       return Context.hasSameType(TD1->getUnderlyingType(),
8660                                  TD2->getUnderlyingType());
8661 
8662   return false;
8663 }
8664 
8665 
8666 /// Determines whether to create a using shadow decl for a particular
8667 /// decl, given the set of decls existing prior to this using lookup.
8668 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
8669                                 const LookupResult &Previous,
8670                                 UsingShadowDecl *&PrevShadow) {
8671   // Diagnose finding a decl which is not from a base class of the
8672   // current class.  We do this now because there are cases where this
8673   // function will silently decide not to build a shadow decl, which
8674   // will pre-empt further diagnostics.
8675   //
8676   // We don't need to do this in C++11 because we do the check once on
8677   // the qualifier.
8678   //
8679   // FIXME: diagnose the following if we care enough:
8680   //   struct A { int foo; };
8681   //   struct B : A { using A::foo; };
8682   //   template <class T> struct C : A {};
8683   //   template <class T> struct D : C<T> { using B::foo; } // <---
8684   // This is invalid (during instantiation) in C++03 because B::foo
8685   // resolves to the using decl in B, which is not a base class of D<T>.
8686   // We can't diagnose it immediately because C<T> is an unknown
8687   // specialization.  The UsingShadowDecl in D<T> then points directly
8688   // to A::foo, which will look well-formed when we instantiate.
8689   // The right solution is to not collapse the shadow-decl chain.
8690   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
8691     DeclContext *OrigDC = Orig->getDeclContext();
8692 
8693     // Handle enums and anonymous structs.
8694     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8695     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8696     while (OrigRec->isAnonymousStructOrUnion())
8697       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8698 
8699     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8700       if (OrigDC == CurContext) {
8701         Diag(Using->getLocation(),
8702              diag::err_using_decl_nested_name_specifier_is_current_class)
8703           << Using->getQualifierLoc().getSourceRange();
8704         Diag(Orig->getLocation(), diag::note_using_decl_target);
8705         return true;
8706       }
8707 
8708       Diag(Using->getQualifierLoc().getBeginLoc(),
8709            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8710         << Using->getQualifier()
8711         << cast<CXXRecordDecl>(CurContext)
8712         << Using->getQualifierLoc().getSourceRange();
8713       Diag(Orig->getLocation(), diag::note_using_decl_target);
8714       return true;
8715     }
8716   }
8717 
8718   if (Previous.empty()) return false;
8719 
8720   NamedDecl *Target = Orig;
8721   if (isa<UsingShadowDecl>(Target))
8722     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8723 
8724   // If the target happens to be one of the previous declarations, we
8725   // don't have a conflict.
8726   //
8727   // FIXME: but we might be increasing its access, in which case we
8728   // should redeclare it.
8729   NamedDecl *NonTag = nullptr, *Tag = nullptr;
8730   bool FoundEquivalentDecl = false;
8731   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8732          I != E; ++I) {
8733     NamedDecl *D = (*I)->getUnderlyingDecl();
8734     // We can have UsingDecls in our Previous results because we use the same
8735     // LookupResult for checking whether the UsingDecl itself is a valid
8736     // redeclaration.
8737     if (isa<UsingDecl>(D))
8738       continue;
8739 
8740     if (IsEquivalentForUsingDecl(Context, D, Target)) {
8741       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
8742         PrevShadow = Shadow;
8743       FoundEquivalentDecl = true;
8744     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
8745       // We don't conflict with an existing using shadow decl of an equivalent
8746       // declaration, but we're not a redeclaration of it.
8747       FoundEquivalentDecl = true;
8748     }
8749 
8750     if (isVisible(D))
8751       (isa<TagDecl>(D) ? Tag : NonTag) = D;
8752   }
8753 
8754   if (FoundEquivalentDecl)
8755     return false;
8756 
8757   if (FunctionDecl *FD = Target->getAsFunction()) {
8758     NamedDecl *OldDecl = nullptr;
8759     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
8760                           /*IsForUsingDecl*/ true)) {
8761     case Ovl_Overload:
8762       return false;
8763 
8764     case Ovl_NonFunction:
8765       Diag(Using->getLocation(), diag::err_using_decl_conflict);
8766       break;
8767 
8768     // We found a decl with the exact signature.
8769     case Ovl_Match:
8770       // If we're in a record, we want to hide the target, so we
8771       // return true (without a diagnostic) to tell the caller not to
8772       // build a shadow decl.
8773       if (CurContext->isRecord())
8774         return true;
8775 
8776       // If we're not in a record, this is an error.
8777       Diag(Using->getLocation(), diag::err_using_decl_conflict);
8778       break;
8779     }
8780 
8781     Diag(Target->getLocation(), diag::note_using_decl_target);
8782     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
8783     return true;
8784   }
8785 
8786   // Target is not a function.
8787 
8788   if (isa<TagDecl>(Target)) {
8789     // No conflict between a tag and a non-tag.
8790     if (!Tag) return false;
8791 
8792     Diag(Using->getLocation(), diag::err_using_decl_conflict);
8793     Diag(Target->getLocation(), diag::note_using_decl_target);
8794     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
8795     return true;
8796   }
8797 
8798   // No conflict between a tag and a non-tag.
8799   if (!NonTag) return false;
8800 
8801   Diag(Using->getLocation(), diag::err_using_decl_conflict);
8802   Diag(Target->getLocation(), diag::note_using_decl_target);
8803   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
8804   return true;
8805 }
8806 
8807 /// Determine whether a direct base class is a virtual base class.
8808 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
8809   if (!Derived->getNumVBases())
8810     return false;
8811   for (auto &B : Derived->bases())
8812     if (B.getType()->getAsCXXRecordDecl() == Base)
8813       return B.isVirtual();
8814   llvm_unreachable("not a direct base class");
8815 }
8816 
8817 /// Builds a shadow declaration corresponding to a 'using' declaration.
8818 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
8819                                             UsingDecl *UD,
8820                                             NamedDecl *Orig,
8821                                             UsingShadowDecl *PrevDecl) {
8822   // If we resolved to another shadow declaration, just coalesce them.
8823   NamedDecl *Target = Orig;
8824   if (isa<UsingShadowDecl>(Target)) {
8825     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8826     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
8827   }
8828 
8829   NamedDecl *NonTemplateTarget = Target;
8830   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
8831     NonTemplateTarget = TargetTD->getTemplatedDecl();
8832 
8833   UsingShadowDecl *Shadow;
8834   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
8835     bool IsVirtualBase =
8836         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
8837                             UD->getQualifier()->getAsRecordDecl());
8838     Shadow = ConstructorUsingShadowDecl::Create(
8839         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
8840   } else {
8841     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
8842                                      Target);
8843   }
8844   UD->addShadowDecl(Shadow);
8845 
8846   Shadow->setAccess(UD->getAccess());
8847   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
8848     Shadow->setInvalidDecl();
8849 
8850   Shadow->setPreviousDecl(PrevDecl);
8851 
8852   if (S)
8853     PushOnScopeChains(Shadow, S);
8854   else
8855     CurContext->addDecl(Shadow);
8856 
8857 
8858   return Shadow;
8859 }
8860 
8861 /// Hides a using shadow declaration.  This is required by the current
8862 /// using-decl implementation when a resolvable using declaration in a
8863 /// class is followed by a declaration which would hide or override
8864 /// one or more of the using decl's targets; for example:
8865 ///
8866 ///   struct Base { void foo(int); };
8867 ///   struct Derived : Base {
8868 ///     using Base::foo;
8869 ///     void foo(int);
8870 ///   };
8871 ///
8872 /// The governing language is C++03 [namespace.udecl]p12:
8873 ///
8874 ///   When a using-declaration brings names from a base class into a
8875 ///   derived class scope, member functions in the derived class
8876 ///   override and/or hide member functions with the same name and
8877 ///   parameter types in a base class (rather than conflicting).
8878 ///
8879 /// There are two ways to implement this:
8880 ///   (1) optimistically create shadow decls when they're not hidden
8881 ///       by existing declarations, or
8882 ///   (2) don't create any shadow decls (or at least don't make them
8883 ///       visible) until we've fully parsed/instantiated the class.
8884 /// The problem with (1) is that we might have to retroactively remove
8885 /// a shadow decl, which requires several O(n) operations because the
8886 /// decl structures are (very reasonably) not designed for removal.
8887 /// (2) avoids this but is very fiddly and phase-dependent.
8888 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
8889   if (Shadow->getDeclName().getNameKind() ==
8890         DeclarationName::CXXConversionFunctionName)
8891     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
8892 
8893   // Remove it from the DeclContext...
8894   Shadow->getDeclContext()->removeDecl(Shadow);
8895 
8896   // ...and the scope, if applicable...
8897   if (S) {
8898     S->RemoveDecl(Shadow);
8899     IdResolver.RemoveDecl(Shadow);
8900   }
8901 
8902   // ...and the using decl.
8903   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
8904 
8905   // TODO: complain somehow if Shadow was used.  It shouldn't
8906   // be possible for this to happen, because...?
8907 }
8908 
8909 /// Find the base specifier for a base class with the given type.
8910 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
8911                                                 QualType DesiredBase,
8912                                                 bool &AnyDependentBases) {
8913   // Check whether the named type is a direct base class.
8914   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
8915   for (auto &Base : Derived->bases()) {
8916     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
8917     if (CanonicalDesiredBase == BaseType)
8918       return &Base;
8919     if (BaseType->isDependentType())
8920       AnyDependentBases = true;
8921   }
8922   return nullptr;
8923 }
8924 
8925 namespace {
8926 class UsingValidatorCCC : public CorrectionCandidateCallback {
8927 public:
8928   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
8929                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
8930       : HasTypenameKeyword(HasTypenameKeyword),
8931         IsInstantiation(IsInstantiation), OldNNS(NNS),
8932         RequireMemberOf(RequireMemberOf) {}
8933 
8934   bool ValidateCandidate(const TypoCorrection &Candidate) override {
8935     NamedDecl *ND = Candidate.getCorrectionDecl();
8936 
8937     // Keywords are not valid here.
8938     if (!ND || isa<NamespaceDecl>(ND))
8939       return false;
8940 
8941     // Completely unqualified names are invalid for a 'using' declaration.
8942     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
8943       return false;
8944 
8945     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
8946     // reject.
8947 
8948     if (RequireMemberOf) {
8949       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8950       if (FoundRecord && FoundRecord->isInjectedClassName()) {
8951         // No-one ever wants a using-declaration to name an injected-class-name
8952         // of a base class, unless they're declaring an inheriting constructor.
8953         ASTContext &Ctx = ND->getASTContext();
8954         if (!Ctx.getLangOpts().CPlusPlus11)
8955           return false;
8956         QualType FoundType = Ctx.getRecordType(FoundRecord);
8957 
8958         // Check that the injected-class-name is named as a member of its own
8959         // type; we don't want to suggest 'using Derived::Base;', since that
8960         // means something else.
8961         NestedNameSpecifier *Specifier =
8962             Candidate.WillReplaceSpecifier()
8963                 ? Candidate.getCorrectionSpecifier()
8964                 : OldNNS;
8965         if (!Specifier->getAsType() ||
8966             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8967           return false;
8968 
8969         // Check that this inheriting constructor declaration actually names a
8970         // direct base class of the current class.
8971         bool AnyDependentBases = false;
8972         if (!findDirectBaseWithType(RequireMemberOf,
8973                                     Ctx.getRecordType(FoundRecord),
8974                                     AnyDependentBases) &&
8975             !AnyDependentBases)
8976           return false;
8977       } else {
8978         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8979         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8980           return false;
8981 
8982         // FIXME: Check that the base class member is accessible?
8983       }
8984     } else {
8985       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8986       if (FoundRecord && FoundRecord->isInjectedClassName())
8987         return false;
8988     }
8989 
8990     if (isa<TypeDecl>(ND))
8991       return HasTypenameKeyword || !IsInstantiation;
8992 
8993     return !HasTypenameKeyword;
8994   }
8995 
8996 private:
8997   bool HasTypenameKeyword;
8998   bool IsInstantiation;
8999   NestedNameSpecifier *OldNNS;
9000   CXXRecordDecl *RequireMemberOf;
9001 };
9002 } // end anonymous namespace
9003 
9004 /// Builds a using declaration.
9005 ///
9006 /// \param IsInstantiation - Whether this call arises from an
9007 ///   instantiation of an unresolved using declaration.  We treat
9008 ///   the lookup differently for these declarations.
9009 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9010                                        SourceLocation UsingLoc,
9011                                        CXXScopeSpec &SS,
9012                                        DeclarationNameInfo NameInfo,
9013                                        AttributeList *AttrList,
9014                                        bool IsInstantiation,
9015                                        bool HasTypenameKeyword,
9016                                        SourceLocation TypenameLoc) {
9017   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9018   SourceLocation IdentLoc = NameInfo.getLoc();
9019   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9020 
9021   // FIXME: We ignore attributes for now.
9022 
9023   if (SS.isEmpty()) {
9024     Diag(IdentLoc, diag::err_using_requires_qualname);
9025     return nullptr;
9026   }
9027 
9028   // For an inheriting constructor declaration, the name of the using
9029   // declaration is the name of a constructor in this class, not in the
9030   // base class.
9031   DeclarationNameInfo UsingName = NameInfo;
9032   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9033     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9034       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9035           Context.getCanonicalType(Context.getRecordType(RD))));
9036 
9037   // Do the redeclaration lookup in the current scope.
9038   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9039                         ForRedeclaration);
9040   Previous.setHideTags(false);
9041   if (S) {
9042     LookupName(Previous, S);
9043 
9044     // It is really dumb that we have to do this.
9045     LookupResult::Filter F = Previous.makeFilter();
9046     while (F.hasNext()) {
9047       NamedDecl *D = F.next();
9048       if (!isDeclInScope(D, CurContext, S))
9049         F.erase();
9050       // If we found a local extern declaration that's not ordinarily visible,
9051       // and this declaration is being added to a non-block scope, ignore it.
9052       // We're only checking for scope conflicts here, not also for violations
9053       // of the linkage rules.
9054       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9055                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9056         F.erase();
9057     }
9058     F.done();
9059   } else {
9060     assert(IsInstantiation && "no scope in non-instantiation");
9061     assert(CurContext->isRecord() && "scope not record in instantiation");
9062     LookupQualifiedName(Previous, CurContext);
9063   }
9064 
9065   // Check for invalid redeclarations.
9066   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9067                                   SS, IdentLoc, Previous))
9068     return nullptr;
9069 
9070   // Check for bad qualifiers.
9071   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
9072     return nullptr;
9073 
9074   DeclContext *LookupContext = computeDeclContext(SS);
9075   NamedDecl *D;
9076   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9077   if (!LookupContext) {
9078     if (HasTypenameKeyword) {
9079       // FIXME: not all declaration name kinds are legal here
9080       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9081                                               UsingLoc, TypenameLoc,
9082                                               QualifierLoc,
9083                                               IdentLoc, NameInfo.getName());
9084     } else {
9085       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9086                                            QualifierLoc, NameInfo);
9087     }
9088     D->setAccess(AS);
9089     CurContext->addDecl(D);
9090     return D;
9091   }
9092 
9093   auto Build = [&](bool Invalid) {
9094     UsingDecl *UD =
9095         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9096                           UsingName, HasTypenameKeyword);
9097     UD->setAccess(AS);
9098     CurContext->addDecl(UD);
9099     UD->setInvalidDecl(Invalid);
9100     return UD;
9101   };
9102   auto BuildInvalid = [&]{ return Build(true); };
9103   auto BuildValid = [&]{ return Build(false); };
9104 
9105   if (RequireCompleteDeclContext(SS, LookupContext))
9106     return BuildInvalid();
9107 
9108   // Look up the target name.
9109   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9110 
9111   // Unlike most lookups, we don't always want to hide tag
9112   // declarations: tag names are visible through the using declaration
9113   // even if hidden by ordinary names, *except* in a dependent context
9114   // where it's important for the sanity of two-phase lookup.
9115   if (!IsInstantiation)
9116     R.setHideTags(false);
9117 
9118   // For the purposes of this lookup, we have a base object type
9119   // equal to that of the current context.
9120   if (CurContext->isRecord()) {
9121     R.setBaseObjectType(
9122                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9123   }
9124 
9125   LookupQualifiedName(R, LookupContext);
9126 
9127   // Try to correct typos if possible. If constructor name lookup finds no
9128   // results, that means the named class has no explicit constructors, and we
9129   // suppressed declaring implicit ones (probably because it's dependent or
9130   // invalid).
9131   if (R.empty() &&
9132       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9133     if (TypoCorrection Corrected = CorrectTypo(
9134             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9135             llvm::make_unique<UsingValidatorCCC>(
9136                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9137                 dyn_cast<CXXRecordDecl>(CurContext)),
9138             CTK_ErrorRecovery)) {
9139       // We reject any correction for which ND would be NULL.
9140       NamedDecl *ND = Corrected.getCorrectionDecl();
9141 
9142       // We reject candidates where DroppedSpecifier == true, hence the
9143       // literal '0' below.
9144       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9145                                 << NameInfo.getName() << LookupContext << 0
9146                                 << SS.getRange());
9147 
9148       // If we corrected to an inheriting constructor, handle it as one.
9149       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9150       if (RD && RD->isInjectedClassName()) {
9151         // The parent of the injected class name is the class itself.
9152         RD = cast<CXXRecordDecl>(RD->getParent());
9153 
9154         // Fix up the information we'll use to build the using declaration.
9155         if (Corrected.WillReplaceSpecifier()) {
9156           NestedNameSpecifierLocBuilder Builder;
9157           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9158                               QualifierLoc.getSourceRange());
9159           QualifierLoc = Builder.getWithLocInContext(Context);
9160         }
9161 
9162         // In this case, the name we introduce is the name of a derived class
9163         // constructor.
9164         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9165         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9166             Context.getCanonicalType(Context.getRecordType(CurClass))));
9167         UsingName.setNamedTypeInfo(nullptr);
9168         for (auto *Ctor : LookupConstructors(RD))
9169           R.addDecl(Ctor);
9170         R.resolveKind();
9171       } else {
9172         // FIXME: Pick up all the declarations if we found an overloaded
9173         // function.
9174         UsingName.setName(ND->getDeclName());
9175         R.addDecl(ND);
9176       }
9177     } else {
9178       Diag(IdentLoc, diag::err_no_member)
9179         << NameInfo.getName() << LookupContext << SS.getRange();
9180       return BuildInvalid();
9181     }
9182   }
9183 
9184   if (R.isAmbiguous())
9185     return BuildInvalid();
9186 
9187   if (HasTypenameKeyword) {
9188     // If we asked for a typename and got a non-type decl, error out.
9189     if (!R.getAsSingle<TypeDecl>()) {
9190       Diag(IdentLoc, diag::err_using_typename_non_type);
9191       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9192         Diag((*I)->getUnderlyingDecl()->getLocation(),
9193              diag::note_using_decl_target);
9194       return BuildInvalid();
9195     }
9196   } else {
9197     // If we asked for a non-typename and we got a type, error out,
9198     // but only if this is an instantiation of an unresolved using
9199     // decl.  Otherwise just silently find the type name.
9200     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9201       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9202       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9203       return BuildInvalid();
9204     }
9205   }
9206 
9207   // C++14 [namespace.udecl]p6:
9208   // A using-declaration shall not name a namespace.
9209   if (R.getAsSingle<NamespaceDecl>()) {
9210     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9211       << SS.getRange();
9212     return BuildInvalid();
9213   }
9214 
9215   // C++14 [namespace.udecl]p7:
9216   // A using-declaration shall not name a scoped enumerator.
9217   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9218     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9219       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9220         << SS.getRange();
9221       return BuildInvalid();
9222     }
9223   }
9224 
9225   UsingDecl *UD = BuildValid();
9226 
9227   // Some additional rules apply to inheriting constructors.
9228   if (UsingName.getName().getNameKind() ==
9229         DeclarationName::CXXConstructorName) {
9230     // Suppress access diagnostics; the access check is instead performed at the
9231     // point of use for an inheriting constructor.
9232     R.suppressDiagnostics();
9233     if (CheckInheritingConstructorUsingDecl(UD))
9234       return UD;
9235   }
9236 
9237   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9238     UsingShadowDecl *PrevDecl = nullptr;
9239     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9240       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9241   }
9242 
9243   return UD;
9244 }
9245 
9246 /// Additional checks for a using declaration referring to a constructor name.
9247 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9248   assert(!UD->hasTypename() && "expecting a constructor name");
9249 
9250   const Type *SourceType = UD->getQualifier()->getAsType();
9251   assert(SourceType &&
9252          "Using decl naming constructor doesn't have type in scope spec.");
9253   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9254 
9255   // Check whether the named type is a direct base class.
9256   bool AnyDependentBases = false;
9257   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9258                                       AnyDependentBases);
9259   if (!Base && !AnyDependentBases) {
9260     Diag(UD->getUsingLoc(),
9261          diag::err_using_decl_constructor_not_in_direct_base)
9262       << UD->getNameInfo().getSourceRange()
9263       << QualType(SourceType, 0) << TargetClass;
9264     UD->setInvalidDecl();
9265     return true;
9266   }
9267 
9268   if (Base)
9269     Base->setInheritConstructors();
9270 
9271   return false;
9272 }
9273 
9274 /// Checks that the given using declaration is not an invalid
9275 /// redeclaration.  Note that this is checking only for the using decl
9276 /// itself, not for any ill-formedness among the UsingShadowDecls.
9277 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9278                                        bool HasTypenameKeyword,
9279                                        const CXXScopeSpec &SS,
9280                                        SourceLocation NameLoc,
9281                                        const LookupResult &Prev) {
9282   // C++03 [namespace.udecl]p8:
9283   // C++0x [namespace.udecl]p10:
9284   //   A using-declaration is a declaration and can therefore be used
9285   //   repeatedly where (and only where) multiple declarations are
9286   //   allowed.
9287   //
9288   // That's in non-member contexts.
9289   if (!CurContext->getRedeclContext()->isRecord())
9290     return false;
9291 
9292   NestedNameSpecifier *Qual = SS.getScopeRep();
9293 
9294   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9295     NamedDecl *D = *I;
9296 
9297     bool DTypename;
9298     NestedNameSpecifier *DQual;
9299     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9300       DTypename = UD->hasTypename();
9301       DQual = UD->getQualifier();
9302     } else if (UnresolvedUsingValueDecl *UD
9303                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9304       DTypename = false;
9305       DQual = UD->getQualifier();
9306     } else if (UnresolvedUsingTypenameDecl *UD
9307                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9308       DTypename = true;
9309       DQual = UD->getQualifier();
9310     } else continue;
9311 
9312     // using decls differ if one says 'typename' and the other doesn't.
9313     // FIXME: non-dependent using decls?
9314     if (HasTypenameKeyword != DTypename) continue;
9315 
9316     // using decls differ if they name different scopes (but note that
9317     // template instantiation can cause this check to trigger when it
9318     // didn't before instantiation).
9319     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9320         Context.getCanonicalNestedNameSpecifier(DQual))
9321       continue;
9322 
9323     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
9324     Diag(D->getLocation(), diag::note_using_decl) << 1;
9325     return true;
9326   }
9327 
9328   return false;
9329 }
9330 
9331 
9332 /// Checks that the given nested-name qualifier used in a using decl
9333 /// in the current context is appropriately related to the current
9334 /// scope.  If an error is found, diagnoses it and returns true.
9335 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9336                                    const CXXScopeSpec &SS,
9337                                    const DeclarationNameInfo &NameInfo,
9338                                    SourceLocation NameLoc) {
9339   DeclContext *NamedContext = computeDeclContext(SS);
9340 
9341   if (!CurContext->isRecord()) {
9342     // C++03 [namespace.udecl]p3:
9343     // C++0x [namespace.udecl]p8:
9344     //   A using-declaration for a class member shall be a member-declaration.
9345 
9346     // If we weren't able to compute a valid scope, it must be a
9347     // dependent class scope.
9348     if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) {
9349       auto *RD = NamedContext
9350                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9351                      : nullptr;
9352       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
9353         RD = nullptr;
9354 
9355       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9356         << SS.getRange();
9357 
9358       // If we have a complete, non-dependent source type, try to suggest a
9359       // way to get the same effect.
9360       if (!RD)
9361         return true;
9362 
9363       // Find what this using-declaration was referring to.
9364       LookupResult R(*this, NameInfo, LookupOrdinaryName);
9365       R.setHideTags(false);
9366       R.suppressDiagnostics();
9367       LookupQualifiedName(R, RD);
9368 
9369       if (R.getAsSingle<TypeDecl>()) {
9370         if (getLangOpts().CPlusPlus11) {
9371           // Convert 'using X::Y;' to 'using Y = X::Y;'.
9372           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9373             << 0 // alias declaration
9374             << FixItHint::CreateInsertion(SS.getBeginLoc(),
9375                                           NameInfo.getName().getAsString() +
9376                                               " = ");
9377         } else {
9378           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9379           SourceLocation InsertLoc =
9380               getLocForEndOfToken(NameInfo.getLocEnd());
9381           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9382             << 1 // typedef declaration
9383             << FixItHint::CreateReplacement(UsingLoc, "typedef")
9384             << FixItHint::CreateInsertion(
9385                    InsertLoc, " " + NameInfo.getName().getAsString());
9386         }
9387       } else if (R.getAsSingle<VarDecl>()) {
9388         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9389         // repeating the type of the static data member here.
9390         FixItHint FixIt;
9391         if (getLangOpts().CPlusPlus11) {
9392           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9393           FixIt = FixItHint::CreateReplacement(
9394               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9395         }
9396 
9397         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9398           << 2 // reference declaration
9399           << FixIt;
9400       } else if (R.getAsSingle<EnumConstantDecl>()) {
9401         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9402         // repeating the type of the enumeration here, and we can't do so if
9403         // the type is anonymous.
9404         FixItHint FixIt;
9405         if (getLangOpts().CPlusPlus11) {
9406           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9407           FixIt = FixItHint::CreateReplacement(
9408               UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9409         }
9410 
9411         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9412           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9413           << FixIt;
9414       }
9415       return true;
9416     }
9417 
9418     // Otherwise, everything is known to be fine.
9419     return false;
9420   }
9421 
9422   // The current scope is a record.
9423 
9424   // If the named context is dependent, we can't decide much.
9425   if (!NamedContext) {
9426     // FIXME: in C++0x, we can diagnose if we can prove that the
9427     // nested-name-specifier does not refer to a base class, which is
9428     // still possible in some cases.
9429 
9430     // Otherwise we have to conservatively report that things might be
9431     // okay.
9432     return false;
9433   }
9434 
9435   if (!NamedContext->isRecord()) {
9436     // Ideally this would point at the last name in the specifier,
9437     // but we don't have that level of source info.
9438     Diag(SS.getRange().getBegin(),
9439          diag::err_using_decl_nested_name_specifier_is_not_class)
9440       << SS.getScopeRep() << SS.getRange();
9441     return true;
9442   }
9443 
9444   if (!NamedContext->isDependentContext() &&
9445       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9446     return true;
9447 
9448   if (getLangOpts().CPlusPlus11) {
9449     // C++11 [namespace.udecl]p3:
9450     //   In a using-declaration used as a member-declaration, the
9451     //   nested-name-specifier shall name a base class of the class
9452     //   being defined.
9453 
9454     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9455                                  cast<CXXRecordDecl>(NamedContext))) {
9456       if (CurContext == NamedContext) {
9457         Diag(NameLoc,
9458              diag::err_using_decl_nested_name_specifier_is_current_class)
9459           << SS.getRange();
9460         return true;
9461       }
9462 
9463       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9464         Diag(SS.getRange().getBegin(),
9465              diag::err_using_decl_nested_name_specifier_is_not_base_class)
9466           << SS.getScopeRep()
9467           << cast<CXXRecordDecl>(CurContext)
9468           << SS.getRange();
9469       }
9470       return true;
9471     }
9472 
9473     return false;
9474   }
9475 
9476   // C++03 [namespace.udecl]p4:
9477   //   A using-declaration used as a member-declaration shall refer
9478   //   to a member of a base class of the class being defined [etc.].
9479 
9480   // Salient point: SS doesn't have to name a base class as long as
9481   // lookup only finds members from base classes.  Therefore we can
9482   // diagnose here only if we can prove that that can't happen,
9483   // i.e. if the class hierarchies provably don't intersect.
9484 
9485   // TODO: it would be nice if "definitely valid" results were cached
9486   // in the UsingDecl and UsingShadowDecl so that these checks didn't
9487   // need to be repeated.
9488 
9489   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9490   auto Collect = [&Bases](const CXXRecordDecl *Base) {
9491     Bases.insert(Base);
9492     return true;
9493   };
9494 
9495   // Collect all bases. Return false if we find a dependent base.
9496   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
9497     return false;
9498 
9499   // Returns true if the base is dependent or is one of the accumulated base
9500   // classes.
9501   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9502     return !Bases.count(Base);
9503   };
9504 
9505   // Return false if the class has a dependent base or if it or one
9506   // of its bases is present in the base set of the current context.
9507   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9508       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
9509     return false;
9510 
9511   Diag(SS.getRange().getBegin(),
9512        diag::err_using_decl_nested_name_specifier_is_not_base_class)
9513     << SS.getScopeRep()
9514     << cast<CXXRecordDecl>(CurContext)
9515     << SS.getRange();
9516 
9517   return true;
9518 }
9519 
9520 Decl *Sema::ActOnAliasDeclaration(Scope *S,
9521                                   AccessSpecifier AS,
9522                                   MultiTemplateParamsArg TemplateParamLists,
9523                                   SourceLocation UsingLoc,
9524                                   UnqualifiedId &Name,
9525                                   AttributeList *AttrList,
9526                                   TypeResult Type,
9527                                   Decl *DeclFromDeclSpec) {
9528   // Skip up to the relevant declaration scope.
9529   while (S->isTemplateParamScope())
9530     S = S->getParent();
9531   assert((S->getFlags() & Scope::DeclScope) &&
9532          "got alias-declaration outside of declaration scope");
9533 
9534   if (Type.isInvalid())
9535     return nullptr;
9536 
9537   bool Invalid = false;
9538   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
9539   TypeSourceInfo *TInfo = nullptr;
9540   GetTypeFromParser(Type.get(), &TInfo);
9541 
9542   if (DiagnoseClassNameShadow(CurContext, NameInfo))
9543     return nullptr;
9544 
9545   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
9546                                       UPPC_DeclarationType)) {
9547     Invalid = true;
9548     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9549                                              TInfo->getTypeLoc().getBeginLoc());
9550   }
9551 
9552   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9553   LookupName(Previous, S);
9554 
9555   // Warn about shadowing the name of a template parameter.
9556   if (Previous.isSingleResult() &&
9557       Previous.getFoundDecl()->isTemplateParameter()) {
9558     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
9559     Previous.clear();
9560   }
9561 
9562   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9563          "name in alias declaration must be an identifier");
9564   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9565                                                Name.StartLocation,
9566                                                Name.Identifier, TInfo);
9567 
9568   NewTD->setAccess(AS);
9569 
9570   if (Invalid)
9571     NewTD->setInvalidDecl();
9572 
9573   ProcessDeclAttributeList(S, NewTD, AttrList);
9574 
9575   CheckTypedefForVariablyModifiedType(S, NewTD);
9576   Invalid |= NewTD->isInvalidDecl();
9577 
9578   bool Redeclaration = false;
9579 
9580   NamedDecl *NewND;
9581   if (TemplateParamLists.size()) {
9582     TypeAliasTemplateDecl *OldDecl = nullptr;
9583     TemplateParameterList *OldTemplateParams = nullptr;
9584 
9585     if (TemplateParamLists.size() != 1) {
9586       Diag(UsingLoc, diag::err_alias_template_extra_headers)
9587         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9588          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
9589     }
9590     TemplateParameterList *TemplateParams = TemplateParamLists[0];
9591 
9592     // Check that we can declare a template here.
9593     if (CheckTemplateDeclScope(S, TemplateParams))
9594       return nullptr;
9595 
9596     // Only consider previous declarations in the same scope.
9597     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9598                          /*ExplicitInstantiationOrSpecialization*/false);
9599     if (!Previous.empty()) {
9600       Redeclaration = true;
9601 
9602       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9603       if (!OldDecl && !Invalid) {
9604         Diag(UsingLoc, diag::err_redefinition_different_kind)
9605           << Name.Identifier;
9606 
9607         NamedDecl *OldD = Previous.getRepresentativeDecl();
9608         if (OldD->getLocation().isValid())
9609           Diag(OldD->getLocation(), diag::note_previous_definition);
9610 
9611         Invalid = true;
9612       }
9613 
9614       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9615         if (TemplateParameterListsAreEqual(TemplateParams,
9616                                            OldDecl->getTemplateParameters(),
9617                                            /*Complain=*/true,
9618                                            TPL_TemplateMatch))
9619           OldTemplateParams = OldDecl->getTemplateParameters();
9620         else
9621           Invalid = true;
9622 
9623         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9624         if (!Invalid &&
9625             !Context.hasSameType(OldTD->getUnderlyingType(),
9626                                  NewTD->getUnderlyingType())) {
9627           // FIXME: The C++0x standard does not clearly say this is ill-formed,
9628           // but we can't reasonably accept it.
9629           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9630             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9631           if (OldTD->getLocation().isValid())
9632             Diag(OldTD->getLocation(), diag::note_previous_definition);
9633           Invalid = true;
9634         }
9635       }
9636     }
9637 
9638     // Merge any previous default template arguments into our parameters,
9639     // and check the parameter list.
9640     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
9641                                    TPC_TypeAliasTemplate))
9642       return nullptr;
9643 
9644     TypeAliasTemplateDecl *NewDecl =
9645       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
9646                                     Name.Identifier, TemplateParams,
9647                                     NewTD);
9648     NewTD->setDescribedAliasTemplate(NewDecl);
9649 
9650     NewDecl->setAccess(AS);
9651 
9652     if (Invalid)
9653       NewDecl->setInvalidDecl();
9654     else if (OldDecl)
9655       NewDecl->setPreviousDecl(OldDecl);
9656 
9657     NewND = NewDecl;
9658   } else {
9659     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
9660       setTagNameForLinkagePurposes(TD, NewTD);
9661       handleTagNumbering(TD, S);
9662     }
9663     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
9664     NewND = NewTD;
9665   }
9666 
9667   PushOnScopeChains(NewND, S);
9668   ActOnDocumentableDecl(NewND);
9669   return NewND;
9670 }
9671 
9672 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
9673                                    SourceLocation AliasLoc,
9674                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
9675                                    SourceLocation IdentLoc,
9676                                    IdentifierInfo *Ident) {
9677 
9678   // Lookup the namespace name.
9679   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
9680   LookupParsedName(R, S, &SS);
9681 
9682   if (R.isAmbiguous())
9683     return nullptr;
9684 
9685   if (R.empty()) {
9686     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
9687       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9688       return nullptr;
9689     }
9690   }
9691   assert(!R.isAmbiguous() && !R.empty());
9692   NamedDecl *ND = R.getRepresentativeDecl();
9693 
9694   // Check if we have a previous declaration with the same name.
9695   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
9696                      ForRedeclaration);
9697   LookupName(PrevR, S);
9698 
9699   // Check we're not shadowing a template parameter.
9700   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
9701     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
9702     PrevR.clear();
9703   }
9704 
9705   // Filter out any other lookup result from an enclosing scope.
9706   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
9707                        /*AllowInlineNamespace*/false);
9708 
9709   // Find the previous declaration and check that we can redeclare it.
9710   NamespaceAliasDecl *Prev = nullptr;
9711   if (PrevR.isSingleResult()) {
9712     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
9713     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
9714       // We already have an alias with the same name that points to the same
9715       // namespace; check that it matches.
9716       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
9717         Prev = AD;
9718       } else if (isVisible(PrevDecl)) {
9719         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
9720           << Alias;
9721         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
9722           << AD->getNamespace();
9723         return nullptr;
9724       }
9725     } else if (isVisible(PrevDecl)) {
9726       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
9727                             ? diag::err_redefinition
9728                             : diag::err_redefinition_different_kind;
9729       Diag(AliasLoc, DiagID) << Alias;
9730       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9731       return nullptr;
9732     }
9733   }
9734 
9735   // The use of a nested name specifier may trigger deprecation warnings.
9736   DiagnoseUseOfDecl(ND, IdentLoc);
9737 
9738   NamespaceAliasDecl *AliasDecl =
9739     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
9740                                Alias, SS.getWithLocInContext(Context),
9741                                IdentLoc, ND);
9742   if (Prev)
9743     AliasDecl->setPreviousDecl(Prev);
9744 
9745   PushOnScopeChains(AliasDecl, S);
9746   return AliasDecl;
9747 }
9748 
9749 Sema::ImplicitExceptionSpecification
9750 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
9751                                                CXXMethodDecl *MD) {
9752   CXXRecordDecl *ClassDecl = MD->getParent();
9753 
9754   // C++ [except.spec]p14:
9755   //   An implicitly declared special member function (Clause 12) shall have an
9756   //   exception-specification. [...]
9757   ImplicitExceptionSpecification ExceptSpec(*this);
9758   if (ClassDecl->isInvalidDecl())
9759     return ExceptSpec;
9760 
9761   // Direct base-class constructors.
9762   for (const auto &B : ClassDecl->bases()) {
9763     if (B.isVirtual()) // Handled below.
9764       continue;
9765 
9766     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
9767       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9768       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9769       // If this is a deleted function, add it anyway. This might be conformant
9770       // with the standard. This might not. I'm not sure. It might not matter.
9771       if (Constructor)
9772         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9773     }
9774   }
9775 
9776   // Virtual base-class constructors.
9777   for (const auto &B : ClassDecl->vbases()) {
9778     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
9779       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9780       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9781       // If this is a deleted function, add it anyway. This might be conformant
9782       // with the standard. This might not. I'm not sure. It might not matter.
9783       if (Constructor)
9784         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9785     }
9786   }
9787 
9788   // Field constructors.
9789   for (const auto *F : ClassDecl->fields()) {
9790     if (F->hasInClassInitializer()) {
9791       if (Expr *E = F->getInClassInitializer())
9792         ExceptSpec.CalledExpr(E);
9793     } else if (const RecordType *RecordTy
9794               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9795       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9796       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9797       // If this is a deleted function, add it anyway. This might be conformant
9798       // with the standard. This might not. I'm not sure. It might not matter.
9799       // In particular, the problem is that this function never gets called. It
9800       // might just be ill-formed because this function attempts to refer to
9801       // a deleted function here.
9802       if (Constructor)
9803         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9804     }
9805   }
9806 
9807   return ExceptSpec;
9808 }
9809 
9810 Sema::ImplicitExceptionSpecification
9811 Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
9812                                          CXXConstructorDecl *CD) {
9813   CXXRecordDecl *ClassDecl = CD->getParent();
9814 
9815   // C++ [except.spec]p14:
9816   //   An inheriting constructor [...] shall have an exception-specification. [...]
9817   ImplicitExceptionSpecification ExceptSpec(*this);
9818   if (ClassDecl->isInvalidDecl())
9819     return ExceptSpec;
9820 
9821   auto Inherited = CD->getInheritedConstructor();
9822   InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
9823 
9824   // Direct and virtual base-class constructors.
9825   for (bool VBase : {false, true}) {
9826     for (CXXBaseSpecifier &B :
9827          VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
9828       // Don't visit direct vbases twice.
9829       if (B.isVirtual() != VBase)
9830         continue;
9831 
9832       CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
9833       if (!BaseClass)
9834         continue;
9835 
9836       CXXConstructorDecl *Constructor =
9837           ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
9838               .first;
9839       if (!Constructor)
9840         Constructor = LookupDefaultConstructor(BaseClass);
9841       if (Constructor)
9842         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9843     }
9844   }
9845 
9846   // Field constructors.
9847   for (const auto *F : ClassDecl->fields()) {
9848     if (F->hasInClassInitializer()) {
9849       if (Expr *E = F->getInClassInitializer())
9850         ExceptSpec.CalledExpr(E);
9851     } else if (const RecordType *RecordTy
9852               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9853       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9854       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9855       if (Constructor)
9856         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9857     }
9858   }
9859 
9860   return ExceptSpec;
9861 }
9862 
9863 namespace {
9864 /// RAII object to register a special member as being currently declared.
9865 struct DeclaringSpecialMember {
9866   Sema &S;
9867   Sema::SpecialMemberDecl D;
9868   Sema::ContextRAII SavedContext;
9869   bool WasAlreadyBeingDeclared;
9870 
9871   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
9872     : S(S), D(RD, CSM), SavedContext(S, RD) {
9873     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
9874     if (WasAlreadyBeingDeclared)
9875       // This almost never happens, but if it does, ensure that our cache
9876       // doesn't contain a stale result.
9877       S.SpecialMemberCache.clear();
9878 
9879     // FIXME: Register a note to be produced if we encounter an error while
9880     // declaring the special member.
9881   }
9882   ~DeclaringSpecialMember() {
9883     if (!WasAlreadyBeingDeclared)
9884       S.SpecialMembersBeingDeclared.erase(D);
9885   }
9886 
9887   /// \brief Are we already trying to declare this special member?
9888   bool isAlreadyBeingDeclared() const {
9889     return WasAlreadyBeingDeclared;
9890   }
9891 };
9892 }
9893 
9894 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
9895   // Look up any existing declarations, but don't trigger declaration of all
9896   // implicit special members with this name.
9897   DeclarationName Name = FD->getDeclName();
9898   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
9899                  ForRedeclaration);
9900   for (auto *D : FD->getParent()->lookup(Name))
9901     if (auto *Acceptable = R.getAcceptableDecl(D))
9902       R.addDecl(Acceptable);
9903   R.resolveKind();
9904   R.suppressDiagnostics();
9905 
9906   CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
9907 }
9908 
9909 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
9910                                                      CXXRecordDecl *ClassDecl) {
9911   // C++ [class.ctor]p5:
9912   //   A default constructor for a class X is a constructor of class X
9913   //   that can be called without an argument. If there is no
9914   //   user-declared constructor for class X, a default constructor is
9915   //   implicitly declared. An implicitly-declared default constructor
9916   //   is an inline public member of its class.
9917   assert(ClassDecl->needsImplicitDefaultConstructor() &&
9918          "Should not build implicit default constructor!");
9919 
9920   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
9921   if (DSM.isAlreadyBeingDeclared())
9922     return nullptr;
9923 
9924   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9925                                                      CXXDefaultConstructor,
9926                                                      false);
9927 
9928   // Create the actual constructor declaration.
9929   CanQualType ClassType
9930     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9931   SourceLocation ClassLoc = ClassDecl->getLocation();
9932   DeclarationName Name
9933     = Context.DeclarationNames.getCXXConstructorName(ClassType);
9934   DeclarationNameInfo NameInfo(Name, ClassLoc);
9935   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
9936       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
9937       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
9938       /*isImplicitlyDeclared=*/true, Constexpr);
9939   DefaultCon->setAccess(AS_public);
9940   DefaultCon->setDefaulted();
9941 
9942   if (getLangOpts().CUDA) {
9943     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
9944                                             DefaultCon,
9945                                             /* ConstRHS */ false,
9946                                             /* Diagnose */ false);
9947   }
9948 
9949   // Build an exception specification pointing back at this constructor.
9950   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
9951   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9952 
9953   // We don't need to use SpecialMemberIsTrivial here; triviality for default
9954   // constructors is easy to compute.
9955   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
9956 
9957   // Note that we have declared this constructor.
9958   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
9959 
9960   Scope *S = getScopeForContext(ClassDecl);
9961   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
9962 
9963   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
9964     SetDeclDeleted(DefaultCon, ClassLoc);
9965 
9966   if (S)
9967     PushOnScopeChains(DefaultCon, S, false);
9968   ClassDecl->addDecl(DefaultCon);
9969 
9970   return DefaultCon;
9971 }
9972 
9973 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
9974                                             CXXConstructorDecl *Constructor) {
9975   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
9976           !Constructor->doesThisDeclarationHaveABody() &&
9977           !Constructor->isDeleted()) &&
9978     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
9979 
9980   CXXRecordDecl *ClassDecl = Constructor->getParent();
9981   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
9982 
9983   SynthesizedFunctionScope Scope(*this, Constructor);
9984   DiagnosticErrorTrap Trap(Diags);
9985   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9986       Trap.hasErrorOccurred()) {
9987     Diag(CurrentLocation, diag::note_member_synthesized_at)
9988       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
9989     Constructor->setInvalidDecl();
9990     return;
9991   }
9992 
9993   // The exception specification is needed because we are defining the
9994   // function.
9995   ResolveExceptionSpec(CurrentLocation,
9996                        Constructor->getType()->castAs<FunctionProtoType>());
9997 
9998   SourceLocation Loc = Constructor->getLocEnd().isValid()
9999                            ? Constructor->getLocEnd()
10000                            : Constructor->getLocation();
10001   Constructor->setBody(new (Context) CompoundStmt(Loc));
10002 
10003   Constructor->markUsed(Context);
10004   MarkVTableUsed(CurrentLocation, ClassDecl);
10005 
10006   if (ASTMutationListener *L = getASTMutationListener()) {
10007     L->CompletedImplicitDefinition(Constructor);
10008   }
10009 
10010   DiagnoseUninitializedFields(*this, Constructor);
10011 }
10012 
10013 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10014   // Perform any delayed checks on exception specifications.
10015   CheckDelayedMemberExceptionSpecs();
10016 }
10017 
10018 /// Find or create the fake constructor we synthesize to model constructing an
10019 /// object of a derived class via a constructor of a base class.
10020 CXXConstructorDecl *
10021 Sema::findInheritingConstructor(SourceLocation Loc,
10022                                 CXXConstructorDecl *BaseCtor,
10023                                 ConstructorUsingShadowDecl *Shadow) {
10024   CXXRecordDecl *Derived = Shadow->getParent();
10025   SourceLocation UsingLoc = Shadow->getLocation();
10026 
10027   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10028   // For now we use the name of the base class constructor as a member of the
10029   // derived class to indicate a (fake) inherited constructor name.
10030   DeclarationName Name = BaseCtor->getDeclName();
10031 
10032   // Check to see if we already have a fake constructor for this inherited
10033   // constructor call.
10034   for (NamedDecl *Ctor : Derived->lookup(Name))
10035     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10036                                ->getInheritedConstructor()
10037                                .getConstructor(),
10038                            BaseCtor))
10039       return cast<CXXConstructorDecl>(Ctor);
10040 
10041   DeclarationNameInfo NameInfo(Name, UsingLoc);
10042   TypeSourceInfo *TInfo =
10043       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10044   FunctionProtoTypeLoc ProtoLoc =
10045       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10046 
10047   // Check the inherited constructor is valid and find the list of base classes
10048   // from which it was inherited.
10049   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10050 
10051   bool Constexpr =
10052       BaseCtor->isConstexpr() &&
10053       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10054                                         false, BaseCtor, &ICI);
10055 
10056   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10057       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10058       BaseCtor->isExplicit(), /*Inline=*/true,
10059       /*ImplicitlyDeclared=*/true, Constexpr,
10060       InheritedConstructor(Shadow, BaseCtor));
10061   if (Shadow->isInvalidDecl())
10062     DerivedCtor->setInvalidDecl();
10063 
10064   // Build an unevaluated exception specification for this fake constructor.
10065   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10066   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10067   EPI.ExceptionSpec.Type = EST_Unevaluated;
10068   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10069   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10070                                                FPT->getParamTypes(), EPI));
10071 
10072   // Build the parameter declarations.
10073   SmallVector<ParmVarDecl *, 16> ParamDecls;
10074   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10075     TypeSourceInfo *TInfo =
10076         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10077     ParmVarDecl *PD = ParmVarDecl::Create(
10078         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10079         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10080     PD->setScopeInfo(0, I);
10081     PD->setImplicit();
10082     // Ensure attributes are propagated onto parameters (this matters for
10083     // format, pass_object_size, ...).
10084     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10085     ParamDecls.push_back(PD);
10086     ProtoLoc.setParam(I, PD);
10087   }
10088 
10089   // Set up the new constructor.
10090   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10091   DerivedCtor->setAccess(BaseCtor->getAccess());
10092   DerivedCtor->setParams(ParamDecls);
10093   Derived->addDecl(DerivedCtor);
10094 
10095   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10096     SetDeclDeleted(DerivedCtor, UsingLoc);
10097 
10098   return DerivedCtor;
10099 }
10100 
10101 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10102   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10103                                Ctor->getInheritedConstructor().getShadowDecl());
10104   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10105                             /*Diagnose*/true);
10106 }
10107 
10108 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10109                                        CXXConstructorDecl *Constructor) {
10110   CXXRecordDecl *ClassDecl = Constructor->getParent();
10111   assert(Constructor->getInheritedConstructor() &&
10112          !Constructor->doesThisDeclarationHaveABody() &&
10113          !Constructor->isDeleted());
10114   if (Constructor->isInvalidDecl())
10115     return;
10116 
10117   ConstructorUsingShadowDecl *Shadow =
10118       Constructor->getInheritedConstructor().getShadowDecl();
10119   CXXConstructorDecl *InheritedCtor =
10120       Constructor->getInheritedConstructor().getConstructor();
10121 
10122   // [class.inhctor.init]p1:
10123   //   initialization proceeds as if a defaulted default constructor is used to
10124   //   initialize the D object and each base class subobject from which the
10125   //   constructor was inherited
10126 
10127   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10128   CXXRecordDecl *RD = Shadow->getParent();
10129   SourceLocation InitLoc = Shadow->getLocation();
10130 
10131   // Initializations are performed "as if by a defaulted default constructor",
10132   // so enter the appropriate scope.
10133   SynthesizedFunctionScope Scope(*this, Constructor);
10134   DiagnosticErrorTrap Trap(Diags);
10135 
10136   // Build explicit initializers for all base classes from which the
10137   // constructor was inherited.
10138   SmallVector<CXXCtorInitializer*, 8> Inits;
10139   for (bool VBase : {false, true}) {
10140     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10141       if (B.isVirtual() != VBase)
10142         continue;
10143 
10144       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10145       if (!BaseRD)
10146         continue;
10147 
10148       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10149       if (!BaseCtor.first)
10150         continue;
10151 
10152       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10153       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10154           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10155 
10156       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10157       Inits.push_back(new (Context) CXXCtorInitializer(
10158           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10159           SourceLocation()));
10160     }
10161   }
10162 
10163   // We now proceed as if for a defaulted default constructor, with the relevant
10164   // initializers replaced.
10165 
10166   bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10167   if (HadError || Trap.hasErrorOccurred()) {
10168     Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
10169     Constructor->setInvalidDecl();
10170     return;
10171   }
10172 
10173   // The exception specification is needed because we are defining the
10174   // function.
10175   ResolveExceptionSpec(CurrentLocation,
10176                        Constructor->getType()->castAs<FunctionProtoType>());
10177 
10178   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10179 
10180   Constructor->markUsed(Context);
10181   MarkVTableUsed(CurrentLocation, ClassDecl);
10182 
10183   if (ASTMutationListener *L = getASTMutationListener()) {
10184     L->CompletedImplicitDefinition(Constructor);
10185   }
10186 
10187   DiagnoseUninitializedFields(*this, Constructor);
10188 }
10189 
10190 Sema::ImplicitExceptionSpecification
10191 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
10192   CXXRecordDecl *ClassDecl = MD->getParent();
10193 
10194   // C++ [except.spec]p14:
10195   //   An implicitly declared special member function (Clause 12) shall have
10196   //   an exception-specification.
10197   ImplicitExceptionSpecification ExceptSpec(*this);
10198   if (ClassDecl->isInvalidDecl())
10199     return ExceptSpec;
10200 
10201   // Direct base-class destructors.
10202   for (const auto &B : ClassDecl->bases()) {
10203     if (B.isVirtual()) // Handled below.
10204       continue;
10205 
10206     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10207       ExceptSpec.CalledDecl(B.getLocStart(),
10208                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
10209   }
10210 
10211   // Virtual base-class destructors.
10212   for (const auto &B : ClassDecl->vbases()) {
10213     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10214       ExceptSpec.CalledDecl(B.getLocStart(),
10215                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
10216   }
10217 
10218   // Field destructors.
10219   for (const auto *F : ClassDecl->fields()) {
10220     if (const RecordType *RecordTy
10221         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
10222       ExceptSpec.CalledDecl(F->getLocation(),
10223                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
10224   }
10225 
10226   return ExceptSpec;
10227 }
10228 
10229 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10230   // C++ [class.dtor]p2:
10231   //   If a class has no user-declared destructor, a destructor is
10232   //   declared implicitly. An implicitly-declared destructor is an
10233   //   inline public member of its class.
10234   assert(ClassDecl->needsImplicitDestructor());
10235 
10236   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10237   if (DSM.isAlreadyBeingDeclared())
10238     return nullptr;
10239 
10240   // Create the actual destructor declaration.
10241   CanQualType ClassType
10242     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10243   SourceLocation ClassLoc = ClassDecl->getLocation();
10244   DeclarationName Name
10245     = Context.DeclarationNames.getCXXDestructorName(ClassType);
10246   DeclarationNameInfo NameInfo(Name, ClassLoc);
10247   CXXDestructorDecl *Destructor
10248       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10249                                   QualType(), nullptr, /*isInline=*/true,
10250                                   /*isImplicitlyDeclared=*/true);
10251   Destructor->setAccess(AS_public);
10252   Destructor->setDefaulted();
10253 
10254   if (getLangOpts().CUDA) {
10255     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10256                                             Destructor,
10257                                             /* ConstRHS */ false,
10258                                             /* Diagnose */ false);
10259   }
10260 
10261   // Build an exception specification pointing back at this destructor.
10262   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10263   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10264 
10265   // We don't need to use SpecialMemberIsTrivial here; triviality for
10266   // destructors is easy to compute.
10267   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10268 
10269   // Note that we have declared this destructor.
10270   ++ASTContext::NumImplicitDestructorsDeclared;
10271 
10272   Scope *S = getScopeForContext(ClassDecl);
10273   CheckImplicitSpecialMemberDeclaration(S, Destructor);
10274 
10275   // We can't check whether an implicit destructor is deleted before we complete
10276   // the definition of the class, because its validity depends on the alignment
10277   // of the class. We'll check this from ActOnFields once the class is complete.
10278   if (ClassDecl->isCompleteDefinition() &&
10279       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10280     SetDeclDeleted(Destructor, ClassLoc);
10281 
10282   // Introduce this destructor into its scope.
10283   if (S)
10284     PushOnScopeChains(Destructor, S, false);
10285   ClassDecl->addDecl(Destructor);
10286 
10287   return Destructor;
10288 }
10289 
10290 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10291                                     CXXDestructorDecl *Destructor) {
10292   assert((Destructor->isDefaulted() &&
10293           !Destructor->doesThisDeclarationHaveABody() &&
10294           !Destructor->isDeleted()) &&
10295          "DefineImplicitDestructor - call it for implicit default dtor");
10296   CXXRecordDecl *ClassDecl = Destructor->getParent();
10297   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
10298 
10299   if (Destructor->isInvalidDecl())
10300     return;
10301 
10302   SynthesizedFunctionScope Scope(*this, Destructor);
10303 
10304   DiagnosticErrorTrap Trap(Diags);
10305   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10306                                          Destructor->getParent());
10307 
10308   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
10309     Diag(CurrentLocation, diag::note_member_synthesized_at)
10310       << CXXDestructor << Context.getTagDeclType(ClassDecl);
10311 
10312     Destructor->setInvalidDecl();
10313     return;
10314   }
10315 
10316   // The exception specification is needed because we are defining the
10317   // function.
10318   ResolveExceptionSpec(CurrentLocation,
10319                        Destructor->getType()->castAs<FunctionProtoType>());
10320 
10321   SourceLocation Loc = Destructor->getLocEnd().isValid()
10322                            ? Destructor->getLocEnd()
10323                            : Destructor->getLocation();
10324   Destructor->setBody(new (Context) CompoundStmt(Loc));
10325   Destructor->markUsed(Context);
10326   MarkVTableUsed(CurrentLocation, ClassDecl);
10327 
10328   if (ASTMutationListener *L = getASTMutationListener()) {
10329     L->CompletedImplicitDefinition(Destructor);
10330   }
10331 }
10332 
10333 /// \brief Perform any semantic analysis which needs to be delayed until all
10334 /// pending class member declarations have been parsed.
10335 void Sema::ActOnFinishCXXMemberDecls() {
10336   // If the context is an invalid C++ class, just suppress these checks.
10337   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10338     if (Record->isInvalidDecl()) {
10339       DelayedDefaultedMemberExceptionSpecs.clear();
10340       DelayedExceptionSpecChecks.clear();
10341       return;
10342     }
10343   }
10344 }
10345 
10346 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
10347   // Don't do anything for template patterns.
10348   if (Class->getDescribedClassTemplate())
10349     return;
10350 
10351   CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
10352       /*IsVariadic=*/false, /*IsCXXMethod=*/true);
10353 
10354   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
10355   for (Decl *Member : Class->decls()) {
10356     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
10357     if (!CD) {
10358       // Recurse on nested classes.
10359       if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
10360         getDefaultArgExprsForConstructors(S, NestedRD);
10361       continue;
10362     } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
10363       continue;
10364     }
10365 
10366     CallingConv ActualCallingConv =
10367         CD->getType()->getAs<FunctionProtoType>()->getCallConv();
10368 
10369     // Skip default constructors with typical calling conventions and no default
10370     // arguments.
10371     unsigned NumParams = CD->getNumParams();
10372     if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
10373       continue;
10374 
10375     if (LastExportedDefaultCtor) {
10376       S.Diag(LastExportedDefaultCtor->getLocation(),
10377              diag::err_attribute_dll_ambiguous_default_ctor) << Class;
10378       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
10379           << CD->getDeclName();
10380       return;
10381     }
10382     LastExportedDefaultCtor = CD;
10383 
10384     for (unsigned I = 0; I != NumParams; ++I) {
10385       // Skip any default arguments that we've already instantiated.
10386       if (S.Context.getDefaultArgExprForConstructor(CD, I))
10387         continue;
10388 
10389       Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
10390                                                   CD->getParamDecl(I)).get();
10391       S.DiscardCleanupsInEvaluationContext();
10392       S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
10393     }
10394   }
10395 }
10396 
10397 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
10398   auto *RD = dyn_cast<CXXRecordDecl>(D);
10399 
10400   // Default constructors that are annotated with __declspec(dllexport) which
10401   // have default arguments or don't use the standard calling convention are
10402   // wrapped with a thunk called the default constructor closure.
10403   if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
10404     getDefaultArgExprsForConstructors(*this, RD);
10405 
10406   referenceDLLExportedClassMethods();
10407 }
10408 
10409 void Sema::referenceDLLExportedClassMethods() {
10410   if (!DelayedDllExportClasses.empty()) {
10411     // Calling ReferenceDllExportedMethods might cause the current function to
10412     // be called again, so use a local copy of DelayedDllExportClasses.
10413     SmallVector<CXXRecordDecl *, 4> WorkList;
10414     std::swap(DelayedDllExportClasses, WorkList);
10415     for (CXXRecordDecl *Class : WorkList)
10416       ReferenceDllExportedMethods(*this, Class);
10417   }
10418 }
10419 
10420 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10421                                          CXXDestructorDecl *Destructor) {
10422   assert(getLangOpts().CPlusPlus11 &&
10423          "adjusting dtor exception specs was introduced in c++11");
10424 
10425   // C++11 [class.dtor]p3:
10426   //   A declaration of a destructor that does not have an exception-
10427   //   specification is implicitly considered to have the same exception-
10428   //   specification as an implicit declaration.
10429   const FunctionProtoType *DtorType = Destructor->getType()->
10430                                         getAs<FunctionProtoType>();
10431   if (DtorType->hasExceptionSpec())
10432     return;
10433 
10434   // Replace the destructor's type, building off the existing one. Fortunately,
10435   // the only thing of interest in the destructor type is its extended info.
10436   // The return and arguments are fixed.
10437   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
10438   EPI.ExceptionSpec.Type = EST_Unevaluated;
10439   EPI.ExceptionSpec.SourceDecl = Destructor;
10440   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10441 
10442   // FIXME: If the destructor has a body that could throw, and the newly created
10443   // spec doesn't allow exceptions, we should emit a warning, because this
10444   // change in behavior can break conforming C++03 programs at runtime.
10445   // However, we don't have a body or an exception specification yet, so it
10446   // needs to be done somewhere else.
10447 }
10448 
10449 namespace {
10450 /// \brief An abstract base class for all helper classes used in building the
10451 //  copy/move operators. These classes serve as factory functions and help us
10452 //  avoid using the same Expr* in the AST twice.
10453 class ExprBuilder {
10454   ExprBuilder(const ExprBuilder&) = delete;
10455   ExprBuilder &operator=(const ExprBuilder&) = delete;
10456 
10457 protected:
10458   static Expr *assertNotNull(Expr *E) {
10459     assert(E && "Expression construction must not fail.");
10460     return E;
10461   }
10462 
10463 public:
10464   ExprBuilder() {}
10465   virtual ~ExprBuilder() {}
10466 
10467   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10468 };
10469 
10470 class RefBuilder: public ExprBuilder {
10471   VarDecl *Var;
10472   QualType VarType;
10473 
10474 public:
10475   Expr *build(Sema &S, SourceLocation Loc) const override {
10476     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
10477   }
10478 
10479   RefBuilder(VarDecl *Var, QualType VarType)
10480       : Var(Var), VarType(VarType) {}
10481 };
10482 
10483 class ThisBuilder: public ExprBuilder {
10484 public:
10485   Expr *build(Sema &S, SourceLocation Loc) const override {
10486     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
10487   }
10488 };
10489 
10490 class CastBuilder: public ExprBuilder {
10491   const ExprBuilder &Builder;
10492   QualType Type;
10493   ExprValueKind Kind;
10494   const CXXCastPath &Path;
10495 
10496 public:
10497   Expr *build(Sema &S, SourceLocation Loc) const override {
10498     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10499                                              CK_UncheckedDerivedToBase, Kind,
10500                                              &Path).get());
10501   }
10502 
10503   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10504               const CXXCastPath &Path)
10505       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10506 };
10507 
10508 class DerefBuilder: public ExprBuilder {
10509   const ExprBuilder &Builder;
10510 
10511 public:
10512   Expr *build(Sema &S, SourceLocation Loc) const override {
10513     return assertNotNull(
10514         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
10515   }
10516 
10517   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10518 };
10519 
10520 class MemberBuilder: public ExprBuilder {
10521   const ExprBuilder &Builder;
10522   QualType Type;
10523   CXXScopeSpec SS;
10524   bool IsArrow;
10525   LookupResult &MemberLookup;
10526 
10527 public:
10528   Expr *build(Sema &S, SourceLocation Loc) const override {
10529     return assertNotNull(S.BuildMemberReferenceExpr(
10530         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
10531         nullptr, MemberLookup, nullptr, nullptr).get());
10532   }
10533 
10534   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10535                 LookupResult &MemberLookup)
10536       : Builder(Builder), Type(Type), IsArrow(IsArrow),
10537         MemberLookup(MemberLookup) {}
10538 };
10539 
10540 class MoveCastBuilder: public ExprBuilder {
10541   const ExprBuilder &Builder;
10542 
10543 public:
10544   Expr *build(Sema &S, SourceLocation Loc) const override {
10545     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10546   }
10547 
10548   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10549 };
10550 
10551 class LvalueConvBuilder: public ExprBuilder {
10552   const ExprBuilder &Builder;
10553 
10554 public:
10555   Expr *build(Sema &S, SourceLocation Loc) const override {
10556     return assertNotNull(
10557         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
10558   }
10559 
10560   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10561 };
10562 
10563 class SubscriptBuilder: public ExprBuilder {
10564   const ExprBuilder &Base;
10565   const ExprBuilder &Index;
10566 
10567 public:
10568   Expr *build(Sema &S, SourceLocation Loc) const override {
10569     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
10570         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
10571   }
10572 
10573   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10574       : Base(Base), Index(Index) {}
10575 };
10576 
10577 } // end anonymous namespace
10578 
10579 /// When generating a defaulted copy or move assignment operator, if a field
10580 /// should be copied with __builtin_memcpy rather than via explicit assignments,
10581 /// do so. This optimization only applies for arrays of scalars, and for arrays
10582 /// of class type where the selected copy/move-assignment operator is trivial.
10583 static StmtResult
10584 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
10585                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
10586   // Compute the size of the memory buffer to be copied.
10587   QualType SizeType = S.Context.getSizeType();
10588   llvm::APInt Size(S.Context.getTypeSize(SizeType),
10589                    S.Context.getTypeSizeInChars(T).getQuantity());
10590 
10591   // Take the address of the field references for "from" and "to". We
10592   // directly construct UnaryOperators here because semantic analysis
10593   // does not permit us to take the address of an xvalue.
10594   Expr *From = FromB.build(S, Loc);
10595   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10596                          S.Context.getPointerType(From->getType()),
10597                          VK_RValue, OK_Ordinary, Loc);
10598   Expr *To = ToB.build(S, Loc);
10599   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10600                        S.Context.getPointerType(To->getType()),
10601                        VK_RValue, OK_Ordinary, Loc);
10602 
10603   const Type *E = T->getBaseElementTypeUnsafe();
10604   bool NeedsCollectableMemCpy =
10605     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10606 
10607   // Create a reference to the __builtin_objc_memmove_collectable function
10608   StringRef MemCpyName = NeedsCollectableMemCpy ?
10609     "__builtin_objc_memmove_collectable" :
10610     "__builtin_memcpy";
10611   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10612                  Sema::LookupOrdinaryName);
10613   S.LookupName(R, S.TUScope, true);
10614 
10615   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10616   if (!MemCpy)
10617     // Something went horribly wrong earlier, and we will have complained
10618     // about it.
10619     return StmtError();
10620 
10621   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
10622                                             VK_RValue, Loc, nullptr);
10623   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10624 
10625   Expr *CallArgs[] = {
10626     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10627   };
10628   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
10629                                     Loc, CallArgs, Loc);
10630 
10631   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
10632   return Call.getAs<Stmt>();
10633 }
10634 
10635 /// \brief Builds a statement that copies/moves the given entity from \p From to
10636 /// \c To.
10637 ///
10638 /// This routine is used to copy/move the members of a class with an
10639 /// implicitly-declared copy/move assignment operator. When the entities being
10640 /// copied are arrays, this routine builds for loops to copy them.
10641 ///
10642 /// \param S The Sema object used for type-checking.
10643 ///
10644 /// \param Loc The location where the implicit copy/move is being generated.
10645 ///
10646 /// \param T The type of the expressions being copied/moved. Both expressions
10647 /// must have this type.
10648 ///
10649 /// \param To The expression we are copying/moving to.
10650 ///
10651 /// \param From The expression we are copying/moving from.
10652 ///
10653 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
10654 /// Otherwise, it's a non-static member subobject.
10655 ///
10656 /// \param Copying Whether we're copying or moving.
10657 ///
10658 /// \param Depth Internal parameter recording the depth of the recursion.
10659 ///
10660 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10661 /// if a memcpy should be used instead.
10662 static StmtResult
10663 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
10664                                  const ExprBuilder &To, const ExprBuilder &From,
10665                                  bool CopyingBaseSubobject, bool Copying,
10666                                  unsigned Depth = 0) {
10667   // C++11 [class.copy]p28:
10668   //   Each subobject is assigned in the manner appropriate to its type:
10669   //
10670   //     - if the subobject is of class type, as if by a call to operator= with
10671   //       the subobject as the object expression and the corresponding
10672   //       subobject of x as a single function argument (as if by explicit
10673   //       qualification; that is, ignoring any possible virtual overriding
10674   //       functions in more derived classes);
10675   //
10676   // C++03 [class.copy]p13:
10677   //     - if the subobject is of class type, the copy assignment operator for
10678   //       the class is used (as if by explicit qualification; that is,
10679   //       ignoring any possible virtual overriding functions in more derived
10680   //       classes);
10681   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10682     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10683 
10684     // Look for operator=.
10685     DeclarationName Name
10686       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10687     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10688     S.LookupQualifiedName(OpLookup, ClassDecl, false);
10689 
10690     // Prior to C++11, filter out any result that isn't a copy/move-assignment
10691     // operator.
10692     if (!S.getLangOpts().CPlusPlus11) {
10693       LookupResult::Filter F = OpLookup.makeFilter();
10694       while (F.hasNext()) {
10695         NamedDecl *D = F.next();
10696         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10697           if (Method->isCopyAssignmentOperator() ||
10698               (!Copying && Method->isMoveAssignmentOperator()))
10699             continue;
10700 
10701         F.erase();
10702       }
10703       F.done();
10704     }
10705 
10706     // Suppress the protected check (C++ [class.protected]) for each of the
10707     // assignment operators we found. This strange dance is required when
10708     // we're assigning via a base classes's copy-assignment operator. To
10709     // ensure that we're getting the right base class subobject (without
10710     // ambiguities), we need to cast "this" to that subobject type; to
10711     // ensure that we don't go through the virtual call mechanism, we need
10712     // to qualify the operator= name with the base class (see below). However,
10713     // this means that if the base class has a protected copy assignment
10714     // operator, the protected member access check will fail. So, we
10715     // rewrite "protected" access to "public" access in this case, since we
10716     // know by construction that we're calling from a derived class.
10717     if (CopyingBaseSubobject) {
10718       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10719            L != LEnd; ++L) {
10720         if (L.getAccess() == AS_protected)
10721           L.setAccess(AS_public);
10722       }
10723     }
10724 
10725     // Create the nested-name-specifier that will be used to qualify the
10726     // reference to operator=; this is required to suppress the virtual
10727     // call mechanism.
10728     CXXScopeSpec SS;
10729     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
10730     SS.MakeTrivial(S.Context,
10731                    NestedNameSpecifier::Create(S.Context, nullptr, false,
10732                                                CanonicalT),
10733                    Loc);
10734 
10735     // Create the reference to operator=.
10736     ExprResult OpEqualRef
10737       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
10738                                    SS, /*TemplateKWLoc=*/SourceLocation(),
10739                                    /*FirstQualifierInScope=*/nullptr,
10740                                    OpLookup,
10741                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
10742                                    /*SuppressQualifierCheck=*/true);
10743     if (OpEqualRef.isInvalid())
10744       return StmtError();
10745 
10746     // Build the call to the assignment operator.
10747 
10748     Expr *FromInst = From.build(S, Loc);
10749     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
10750                                                   OpEqualRef.getAs<Expr>(),
10751                                                   Loc, FromInst, Loc);
10752     if (Call.isInvalid())
10753       return StmtError();
10754 
10755     // If we built a call to a trivial 'operator=' while copying an array,
10756     // bail out. We'll replace the whole shebang with a memcpy.
10757     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
10758     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
10759       return StmtResult((Stmt*)nullptr);
10760 
10761     // Convert to an expression-statement, and clean up any produced
10762     // temporaries.
10763     return S.ActOnExprStmt(Call);
10764   }
10765 
10766   //     - if the subobject is of scalar type, the built-in assignment
10767   //       operator is used.
10768   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
10769   if (!ArrayTy) {
10770     ExprResult Assignment = S.CreateBuiltinBinOp(
10771         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
10772     if (Assignment.isInvalid())
10773       return StmtError();
10774     return S.ActOnExprStmt(Assignment);
10775   }
10776 
10777   //     - if the subobject is an array, each element is assigned, in the
10778   //       manner appropriate to the element type;
10779 
10780   // Construct a loop over the array bounds, e.g.,
10781   //
10782   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
10783   //
10784   // that will copy each of the array elements.
10785   QualType SizeType = S.Context.getSizeType();
10786 
10787   // Create the iteration variable.
10788   IdentifierInfo *IterationVarName = nullptr;
10789   {
10790     SmallString<8> Str;
10791     llvm::raw_svector_ostream OS(Str);
10792     OS << "__i" << Depth;
10793     IterationVarName = &S.Context.Idents.get(OS.str());
10794   }
10795   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10796                                           IterationVarName, SizeType,
10797                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10798                                           SC_None);
10799 
10800   // Initialize the iteration variable to zero.
10801   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
10802   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
10803 
10804   // Creates a reference to the iteration variable.
10805   RefBuilder IterationVarRef(IterationVar, SizeType);
10806   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
10807 
10808   // Create the DeclStmt that holds the iteration variable.
10809   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
10810 
10811   // Subscript the "from" and "to" expressions with the iteration variable.
10812   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10813   MoveCastBuilder FromIndexMove(FromIndexCopy);
10814   const ExprBuilder *FromIndex;
10815   if (Copying)
10816     FromIndex = &FromIndexCopy;
10817   else
10818     FromIndex = &FromIndexMove;
10819 
10820   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
10821 
10822   // Build the copy/move for an individual element of the array.
10823   StmtResult Copy =
10824     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
10825                                      ToIndex, *FromIndex, CopyingBaseSubobject,
10826                                      Copying, Depth + 1);
10827   // Bail out if copying fails or if we determined that we should use memcpy.
10828   if (Copy.isInvalid() || !Copy.get())
10829     return Copy;
10830 
10831   // Create the comparison against the array bound.
10832   llvm::APInt Upper
10833     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10834   Expr *Comparison
10835     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
10836                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10837                                      BO_NE, S.Context.BoolTy,
10838                                      VK_RValue, OK_Ordinary, Loc, false);
10839 
10840   // Create the pre-increment of the iteration variable.
10841   Expr *Increment
10842     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10843                                     SizeType, VK_LValue, OK_Ordinary, Loc);
10844 
10845   // Construct the loop that copies all elements of this array.
10846   return S.ActOnForStmt(
10847       Loc, Loc, InitStmt,
10848       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
10849       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
10850 }
10851 
10852 static StmtResult
10853 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
10854                       const ExprBuilder &To, const ExprBuilder &From,
10855                       bool CopyingBaseSubobject, bool Copying) {
10856   // Maybe we should use a memcpy?
10857   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10858       T.isTriviallyCopyableType(S.Context))
10859     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10860 
10861   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10862                                                      CopyingBaseSubobject,
10863                                                      Copying, 0));
10864 
10865   // If we ended up picking a trivial assignment operator for an array of a
10866   // non-trivially-copyable class type, just emit a memcpy.
10867   if (!Result.isInvalid() && !Result.get())
10868     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10869 
10870   return Result;
10871 }
10872 
10873 Sema::ImplicitExceptionSpecification
10874 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10875   CXXRecordDecl *ClassDecl = MD->getParent();
10876 
10877   ImplicitExceptionSpecification ExceptSpec(*this);
10878   if (ClassDecl->isInvalidDecl())
10879     return ExceptSpec;
10880 
10881   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10882   assert(T->getNumParams() == 1 && "not a copy assignment op");
10883   unsigned ArgQuals =
10884       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10885 
10886   // C++ [except.spec]p14:
10887   //   An implicitly declared special member function (Clause 12) shall have an
10888   //   exception-specification. [...]
10889 
10890   // It is unspecified whether or not an implicit copy assignment operator
10891   // attempts to deduplicate calls to assignment operators of virtual bases are
10892   // made. As such, this exception specification is effectively unspecified.
10893   // Based on a similar decision made for constness in C++0x, we're erring on
10894   // the side of assuming such calls to be made regardless of whether they
10895   // actually happen.
10896   for (const auto &Base : ClassDecl->bases()) {
10897     if (Base.isVirtual())
10898       continue;
10899 
10900     CXXRecordDecl *BaseClassDecl
10901       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10902     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10903                                                             ArgQuals, false, 0))
10904       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10905   }
10906 
10907   for (const auto &Base : ClassDecl->vbases()) {
10908     CXXRecordDecl *BaseClassDecl
10909       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10910     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10911                                                             ArgQuals, false, 0))
10912       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10913   }
10914 
10915   for (const auto *Field : ClassDecl->fields()) {
10916     QualType FieldType = Context.getBaseElementType(Field->getType());
10917     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10918       if (CXXMethodDecl *CopyAssign =
10919           LookupCopyingAssignment(FieldClassDecl,
10920                                   ArgQuals | FieldType.getCVRQualifiers(),
10921                                   false, 0))
10922         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10923     }
10924   }
10925 
10926   return ExceptSpec;
10927 }
10928 
10929 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10930   // Note: The following rules are largely analoguous to the copy
10931   // constructor rules. Note that virtual bases are not taken into account
10932   // for determining the argument type of the operator. Note also that
10933   // operators taking an object instead of a reference are allowed.
10934   assert(ClassDecl->needsImplicitCopyAssignment());
10935 
10936   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10937   if (DSM.isAlreadyBeingDeclared())
10938     return nullptr;
10939 
10940   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10941   QualType RetType = Context.getLValueReferenceType(ArgType);
10942   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10943   if (Const)
10944     ArgType = ArgType.withConst();
10945   ArgType = Context.getLValueReferenceType(ArgType);
10946 
10947   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10948                                                      CXXCopyAssignment,
10949                                                      Const);
10950 
10951   //   An implicitly-declared copy assignment operator is an inline public
10952   //   member of its class.
10953   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10954   SourceLocation ClassLoc = ClassDecl->getLocation();
10955   DeclarationNameInfo NameInfo(Name, ClassLoc);
10956   CXXMethodDecl *CopyAssignment =
10957       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10958                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10959                             /*isInline=*/true, Constexpr, SourceLocation());
10960   CopyAssignment->setAccess(AS_public);
10961   CopyAssignment->setDefaulted();
10962   CopyAssignment->setImplicit();
10963 
10964   if (getLangOpts().CUDA) {
10965     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10966                                             CopyAssignment,
10967                                             /* ConstRHS */ Const,
10968                                             /* Diagnose */ false);
10969   }
10970 
10971   // Build an exception specification pointing back at this member.
10972   FunctionProtoType::ExtProtoInfo EPI =
10973       getImplicitMethodEPI(*this, CopyAssignment);
10974   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10975 
10976   // Add the parameter to the operator.
10977   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10978                                                ClassLoc, ClassLoc,
10979                                                /*Id=*/nullptr, ArgType,
10980                                                /*TInfo=*/nullptr, SC_None,
10981                                                nullptr);
10982   CopyAssignment->setParams(FromParam);
10983 
10984   CopyAssignment->setTrivial(
10985     ClassDecl->needsOverloadResolutionForCopyAssignment()
10986       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10987       : ClassDecl->hasTrivialCopyAssignment());
10988 
10989   // Note that we have added this copy-assignment operator.
10990   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10991 
10992   Scope *S = getScopeForContext(ClassDecl);
10993   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
10994 
10995   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10996     SetDeclDeleted(CopyAssignment, ClassLoc);
10997 
10998   if (S)
10999     PushOnScopeChains(CopyAssignment, S, false);
11000   ClassDecl->addDecl(CopyAssignment);
11001 
11002   return CopyAssignment;
11003 }
11004 
11005 /// Diagnose an implicit copy operation for a class which is odr-used, but
11006 /// which is deprecated because the class has a user-declared copy constructor,
11007 /// copy assignment operator, or destructor.
11008 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11009                                             SourceLocation UseLoc) {
11010   assert(CopyOp->isImplicit());
11011 
11012   CXXRecordDecl *RD = CopyOp->getParent();
11013   CXXMethodDecl *UserDeclaredOperation = nullptr;
11014 
11015   // In Microsoft mode, assignment operations don't affect constructors and
11016   // vice versa.
11017   if (RD->hasUserDeclaredDestructor()) {
11018     UserDeclaredOperation = RD->getDestructor();
11019   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11020              RD->hasUserDeclaredCopyConstructor() &&
11021              !S.getLangOpts().MSVCCompat) {
11022     // Find any user-declared copy constructor.
11023     for (auto *I : RD->ctors()) {
11024       if (I->isCopyConstructor()) {
11025         UserDeclaredOperation = I;
11026         break;
11027       }
11028     }
11029     assert(UserDeclaredOperation);
11030   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11031              RD->hasUserDeclaredCopyAssignment() &&
11032              !S.getLangOpts().MSVCCompat) {
11033     // Find any user-declared move assignment operator.
11034     for (auto *I : RD->methods()) {
11035       if (I->isCopyAssignmentOperator()) {
11036         UserDeclaredOperation = I;
11037         break;
11038       }
11039     }
11040     assert(UserDeclaredOperation);
11041   }
11042 
11043   if (UserDeclaredOperation) {
11044     S.Diag(UserDeclaredOperation->getLocation(),
11045          diag::warn_deprecated_copy_operation)
11046       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11047       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11048     S.Diag(UseLoc, diag::note_member_synthesized_at)
11049       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11050                                           : Sema::CXXCopyAssignment)
11051       << RD;
11052   }
11053 }
11054 
11055 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11056                                         CXXMethodDecl *CopyAssignOperator) {
11057   assert((CopyAssignOperator->isDefaulted() &&
11058           CopyAssignOperator->isOverloadedOperator() &&
11059           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11060           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11061           !CopyAssignOperator->isDeleted()) &&
11062          "DefineImplicitCopyAssignment called for wrong function");
11063 
11064   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11065 
11066   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11067     CopyAssignOperator->setInvalidDecl();
11068     return;
11069   }
11070 
11071   // C++11 [class.copy]p18:
11072   //   The [definition of an implicitly declared copy assignment operator] is
11073   //   deprecated if the class has a user-declared copy constructor or a
11074   //   user-declared destructor.
11075   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11076     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11077 
11078   CopyAssignOperator->markUsed(Context);
11079 
11080   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11081   DiagnosticErrorTrap Trap(Diags);
11082 
11083   // C++0x [class.copy]p30:
11084   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11085   //   for a non-union class X performs memberwise copy assignment of its
11086   //   subobjects. The direct base classes of X are assigned first, in the
11087   //   order of their declaration in the base-specifier-list, and then the
11088   //   immediate non-static data members of X are assigned, in the order in
11089   //   which they were declared in the class definition.
11090 
11091   // The statements that form the synthesized function body.
11092   SmallVector<Stmt*, 8> Statements;
11093 
11094   // The parameter for the "other" object, which we are copying from.
11095   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11096   Qualifiers OtherQuals = Other->getType().getQualifiers();
11097   QualType OtherRefType = Other->getType();
11098   if (const LValueReferenceType *OtherRef
11099                                 = OtherRefType->getAs<LValueReferenceType>()) {
11100     OtherRefType = OtherRef->getPointeeType();
11101     OtherQuals = OtherRefType.getQualifiers();
11102   }
11103 
11104   // Our location for everything implicitly-generated.
11105   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11106                            ? CopyAssignOperator->getLocEnd()
11107                            : CopyAssignOperator->getLocation();
11108 
11109   // Builds a DeclRefExpr for the "other" object.
11110   RefBuilder OtherRef(Other, OtherRefType);
11111 
11112   // Builds the "this" pointer.
11113   ThisBuilder This;
11114 
11115   // Assign base classes.
11116   bool Invalid = false;
11117   for (auto &Base : ClassDecl->bases()) {
11118     // Form the assignment:
11119     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11120     QualType BaseType = Base.getType().getUnqualifiedType();
11121     if (!BaseType->isRecordType()) {
11122       Invalid = true;
11123       continue;
11124     }
11125 
11126     CXXCastPath BasePath;
11127     BasePath.push_back(&Base);
11128 
11129     // Construct the "from" expression, which is an implicit cast to the
11130     // appropriately-qualified base type.
11131     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11132                      VK_LValue, BasePath);
11133 
11134     // Dereference "this".
11135     DerefBuilder DerefThis(This);
11136     CastBuilder To(DerefThis,
11137                    Context.getCVRQualifiedType(
11138                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11139                    VK_LValue, BasePath);
11140 
11141     // Build the copy.
11142     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11143                                             To, From,
11144                                             /*CopyingBaseSubobject=*/true,
11145                                             /*Copying=*/true);
11146     if (Copy.isInvalid()) {
11147       Diag(CurrentLocation, diag::note_member_synthesized_at)
11148         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11149       CopyAssignOperator->setInvalidDecl();
11150       return;
11151     }
11152 
11153     // Success! Record the copy.
11154     Statements.push_back(Copy.getAs<Expr>());
11155   }
11156 
11157   // Assign non-static members.
11158   for (auto *Field : ClassDecl->fields()) {
11159     // FIXME: We should form some kind of AST representation for the implied
11160     // memcpy in a union copy operation.
11161     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11162       continue;
11163 
11164     if (Field->isInvalidDecl()) {
11165       Invalid = true;
11166       continue;
11167     }
11168 
11169     // Check for members of reference type; we can't copy those.
11170     if (Field->getType()->isReferenceType()) {
11171       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11172         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11173       Diag(Field->getLocation(), diag::note_declared_at);
11174       Diag(CurrentLocation, diag::note_member_synthesized_at)
11175         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11176       Invalid = true;
11177       continue;
11178     }
11179 
11180     // Check for members of const-qualified, non-class type.
11181     QualType BaseType = Context.getBaseElementType(Field->getType());
11182     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11183       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11184         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11185       Diag(Field->getLocation(), diag::note_declared_at);
11186       Diag(CurrentLocation, diag::note_member_synthesized_at)
11187         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11188       Invalid = true;
11189       continue;
11190     }
11191 
11192     // Suppress assigning zero-width bitfields.
11193     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11194       continue;
11195 
11196     QualType FieldType = Field->getType().getNonReferenceType();
11197     if (FieldType->isIncompleteArrayType()) {
11198       assert(ClassDecl->hasFlexibleArrayMember() &&
11199              "Incomplete array type is not valid");
11200       continue;
11201     }
11202 
11203     // Build references to the field in the object we're copying from and to.
11204     CXXScopeSpec SS; // Intentionally empty
11205     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11206                               LookupMemberName);
11207     MemberLookup.addDecl(Field);
11208     MemberLookup.resolveKind();
11209 
11210     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11211 
11212     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11213 
11214     // Build the copy of this field.
11215     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11216                                             To, From,
11217                                             /*CopyingBaseSubobject=*/false,
11218                                             /*Copying=*/true);
11219     if (Copy.isInvalid()) {
11220       Diag(CurrentLocation, diag::note_member_synthesized_at)
11221         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11222       CopyAssignOperator->setInvalidDecl();
11223       return;
11224     }
11225 
11226     // Success! Record the copy.
11227     Statements.push_back(Copy.getAs<Stmt>());
11228   }
11229 
11230   if (!Invalid) {
11231     // Add a "return *this;"
11232     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11233 
11234     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11235     if (Return.isInvalid())
11236       Invalid = true;
11237     else {
11238       Statements.push_back(Return.getAs<Stmt>());
11239 
11240       if (Trap.hasErrorOccurred()) {
11241         Diag(CurrentLocation, diag::note_member_synthesized_at)
11242           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11243         Invalid = true;
11244       }
11245     }
11246   }
11247 
11248   // The exception specification is needed because we are defining the
11249   // function.
11250   ResolveExceptionSpec(CurrentLocation,
11251                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11252 
11253   if (Invalid) {
11254     CopyAssignOperator->setInvalidDecl();
11255     return;
11256   }
11257 
11258   StmtResult Body;
11259   {
11260     CompoundScopeRAII CompoundScope(*this);
11261     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11262                              /*isStmtExpr=*/false);
11263     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11264   }
11265   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11266 
11267   if (ASTMutationListener *L = getASTMutationListener()) {
11268     L->CompletedImplicitDefinition(CopyAssignOperator);
11269   }
11270 }
11271 
11272 Sema::ImplicitExceptionSpecification
11273 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
11274   CXXRecordDecl *ClassDecl = MD->getParent();
11275 
11276   ImplicitExceptionSpecification ExceptSpec(*this);
11277   if (ClassDecl->isInvalidDecl())
11278     return ExceptSpec;
11279 
11280   // C++0x [except.spec]p14:
11281   //   An implicitly declared special member function (Clause 12) shall have an
11282   //   exception-specification. [...]
11283 
11284   // It is unspecified whether or not an implicit move assignment operator
11285   // attempts to deduplicate calls to assignment operators of virtual bases are
11286   // made. As such, this exception specification is effectively unspecified.
11287   // Based on a similar decision made for constness in C++0x, we're erring on
11288   // the side of assuming such calls to be made regardless of whether they
11289   // actually happen.
11290   // Note that a move constructor is not implicitly declared when there are
11291   // virtual bases, but it can still be user-declared and explicitly defaulted.
11292   for (const auto &Base : ClassDecl->bases()) {
11293     if (Base.isVirtual())
11294       continue;
11295 
11296     CXXRecordDecl *BaseClassDecl
11297       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11298     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
11299                                                            0, false, 0))
11300       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
11301   }
11302 
11303   for (const auto &Base : ClassDecl->vbases()) {
11304     CXXRecordDecl *BaseClassDecl
11305       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11306     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
11307                                                            0, false, 0))
11308       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
11309   }
11310 
11311   for (const auto *Field : ClassDecl->fields()) {
11312     QualType FieldType = Context.getBaseElementType(Field->getType());
11313     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11314       if (CXXMethodDecl *MoveAssign =
11315               LookupMovingAssignment(FieldClassDecl,
11316                                      FieldType.getCVRQualifiers(),
11317                                      false, 0))
11318         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
11319     }
11320   }
11321 
11322   return ExceptSpec;
11323 }
11324 
11325 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11326   assert(ClassDecl->needsImplicitMoveAssignment());
11327 
11328   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11329   if (DSM.isAlreadyBeingDeclared())
11330     return nullptr;
11331 
11332   // Note: The following rules are largely analoguous to the move
11333   // constructor rules.
11334 
11335   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11336   QualType RetType = Context.getLValueReferenceType(ArgType);
11337   ArgType = Context.getRValueReferenceType(ArgType);
11338 
11339   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11340                                                      CXXMoveAssignment,
11341                                                      false);
11342 
11343   //   An implicitly-declared move assignment operator is an inline public
11344   //   member of its class.
11345   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11346   SourceLocation ClassLoc = ClassDecl->getLocation();
11347   DeclarationNameInfo NameInfo(Name, ClassLoc);
11348   CXXMethodDecl *MoveAssignment =
11349       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11350                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11351                             /*isInline=*/true, Constexpr, SourceLocation());
11352   MoveAssignment->setAccess(AS_public);
11353   MoveAssignment->setDefaulted();
11354   MoveAssignment->setImplicit();
11355 
11356   if (getLangOpts().CUDA) {
11357     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11358                                             MoveAssignment,
11359                                             /* ConstRHS */ false,
11360                                             /* Diagnose */ false);
11361   }
11362 
11363   // Build an exception specification pointing back at this member.
11364   FunctionProtoType::ExtProtoInfo EPI =
11365       getImplicitMethodEPI(*this, MoveAssignment);
11366   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11367 
11368   // Add the parameter to the operator.
11369   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11370                                                ClassLoc, ClassLoc,
11371                                                /*Id=*/nullptr, ArgType,
11372                                                /*TInfo=*/nullptr, SC_None,
11373                                                nullptr);
11374   MoveAssignment->setParams(FromParam);
11375 
11376   MoveAssignment->setTrivial(
11377     ClassDecl->needsOverloadResolutionForMoveAssignment()
11378       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11379       : ClassDecl->hasTrivialMoveAssignment());
11380 
11381   // Note that we have added this copy-assignment operator.
11382   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11383 
11384   Scope *S = getScopeForContext(ClassDecl);
11385   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11386 
11387   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11388     ClassDecl->setImplicitMoveAssignmentIsDeleted();
11389     SetDeclDeleted(MoveAssignment, ClassLoc);
11390   }
11391 
11392   if (S)
11393     PushOnScopeChains(MoveAssignment, S, false);
11394   ClassDecl->addDecl(MoveAssignment);
11395 
11396   return MoveAssignment;
11397 }
11398 
11399 /// Check if we're implicitly defining a move assignment operator for a class
11400 /// with virtual bases. Such a move assignment might move-assign the virtual
11401 /// base multiple times.
11402 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11403                                                SourceLocation CurrentLocation) {
11404   assert(!Class->isDependentContext() && "should not define dependent move");
11405 
11406   // Only a virtual base could get implicitly move-assigned multiple times.
11407   // Only a non-trivial move assignment can observe this. We only want to
11408   // diagnose if we implicitly define an assignment operator that assigns
11409   // two base classes, both of which move-assign the same virtual base.
11410   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11411       Class->getNumBases() < 2)
11412     return;
11413 
11414   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11415   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11416   VBaseMap VBases;
11417 
11418   for (auto &BI : Class->bases()) {
11419     Worklist.push_back(&BI);
11420     while (!Worklist.empty()) {
11421       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11422       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11423 
11424       // If the base has no non-trivial move assignment operators,
11425       // we don't care about moves from it.
11426       if (!Base->hasNonTrivialMoveAssignment())
11427         continue;
11428 
11429       // If there's nothing virtual here, skip it.
11430       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11431         continue;
11432 
11433       // If we're not actually going to call a move assignment for this base,
11434       // or the selected move assignment is trivial, skip it.
11435       Sema::SpecialMemberOverloadResult *SMOR =
11436         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11437                               /*ConstArg*/false, /*VolatileArg*/false,
11438                               /*RValueThis*/true, /*ConstThis*/false,
11439                               /*VolatileThis*/false);
11440       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
11441           !SMOR->getMethod()->isMoveAssignmentOperator())
11442         continue;
11443 
11444       if (BaseSpec->isVirtual()) {
11445         // We're going to move-assign this virtual base, and its move
11446         // assignment operator is not trivial. If this can happen for
11447         // multiple distinct direct bases of Class, diagnose it. (If it
11448         // only happens in one base, we'll diagnose it when synthesizing
11449         // that base class's move assignment operator.)
11450         CXXBaseSpecifier *&Existing =
11451             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11452                 .first->second;
11453         if (Existing && Existing != &BI) {
11454           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11455             << Class << Base;
11456           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11457             << (Base->getCanonicalDecl() ==
11458                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11459             << Base << Existing->getType() << Existing->getSourceRange();
11460           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11461             << (Base->getCanonicalDecl() ==
11462                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11463             << Base << BI.getType() << BaseSpec->getSourceRange();
11464 
11465           // Only diagnose each vbase once.
11466           Existing = nullptr;
11467         }
11468       } else {
11469         // Only walk over bases that have defaulted move assignment operators.
11470         // We assume that any user-provided move assignment operator handles
11471         // the multiple-moves-of-vbase case itself somehow.
11472         if (!SMOR->getMethod()->isDefaulted())
11473           continue;
11474 
11475         // We're going to move the base classes of Base. Add them to the list.
11476         for (auto &BI : Base->bases())
11477           Worklist.push_back(&BI);
11478       }
11479     }
11480   }
11481 }
11482 
11483 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11484                                         CXXMethodDecl *MoveAssignOperator) {
11485   assert((MoveAssignOperator->isDefaulted() &&
11486           MoveAssignOperator->isOverloadedOperator() &&
11487           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
11488           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11489           !MoveAssignOperator->isDeleted()) &&
11490          "DefineImplicitMoveAssignment called for wrong function");
11491 
11492   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11493 
11494   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11495     MoveAssignOperator->setInvalidDecl();
11496     return;
11497   }
11498 
11499   MoveAssignOperator->markUsed(Context);
11500 
11501   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11502   DiagnosticErrorTrap Trap(Diags);
11503 
11504   // C++0x [class.copy]p28:
11505   //   The implicitly-defined or move assignment operator for a non-union class
11506   //   X performs memberwise move assignment of its subobjects. The direct base
11507   //   classes of X are assigned first, in the order of their declaration in the
11508   //   base-specifier-list, and then the immediate non-static data members of X
11509   //   are assigned, in the order in which they were declared in the class
11510   //   definition.
11511 
11512   // Issue a warning if our implicit move assignment operator will move
11513   // from a virtual base more than once.
11514   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11515 
11516   // The statements that form the synthesized function body.
11517   SmallVector<Stmt*, 8> Statements;
11518 
11519   // The parameter for the "other" object, which we are move from.
11520   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11521   QualType OtherRefType = Other->getType()->
11522       getAs<RValueReferenceType>()->getPointeeType();
11523   assert(!OtherRefType.getQualifiers() &&
11524          "Bad argument type of defaulted move assignment");
11525 
11526   // Our location for everything implicitly-generated.
11527   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11528                            ? MoveAssignOperator->getLocEnd()
11529                            : MoveAssignOperator->getLocation();
11530 
11531   // Builds a reference to the "other" object.
11532   RefBuilder OtherRef(Other, OtherRefType);
11533   // Cast to rvalue.
11534   MoveCastBuilder MoveOther(OtherRef);
11535 
11536   // Builds the "this" pointer.
11537   ThisBuilder This;
11538 
11539   // Assign base classes.
11540   bool Invalid = false;
11541   for (auto &Base : ClassDecl->bases()) {
11542     // C++11 [class.copy]p28:
11543     //   It is unspecified whether subobjects representing virtual base classes
11544     //   are assigned more than once by the implicitly-defined copy assignment
11545     //   operator.
11546     // FIXME: Do not assign to a vbase that will be assigned by some other base
11547     // class. For a move-assignment, this can result in the vbase being moved
11548     // multiple times.
11549 
11550     // Form the assignment:
11551     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
11552     QualType BaseType = Base.getType().getUnqualifiedType();
11553     if (!BaseType->isRecordType()) {
11554       Invalid = true;
11555       continue;
11556     }
11557 
11558     CXXCastPath BasePath;
11559     BasePath.push_back(&Base);
11560 
11561     // Construct the "from" expression, which is an implicit cast to the
11562     // appropriately-qualified base type.
11563     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
11564 
11565     // Dereference "this".
11566     DerefBuilder DerefThis(This);
11567 
11568     // Implicitly cast "this" to the appropriately-qualified base type.
11569     CastBuilder To(DerefThis,
11570                    Context.getCVRQualifiedType(
11571                        BaseType, MoveAssignOperator->getTypeQualifiers()),
11572                    VK_LValue, BasePath);
11573 
11574     // Build the move.
11575     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
11576                                             To, From,
11577                                             /*CopyingBaseSubobject=*/true,
11578                                             /*Copying=*/false);
11579     if (Move.isInvalid()) {
11580       Diag(CurrentLocation, diag::note_member_synthesized_at)
11581         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11582       MoveAssignOperator->setInvalidDecl();
11583       return;
11584     }
11585 
11586     // Success! Record the move.
11587     Statements.push_back(Move.getAs<Expr>());
11588   }
11589 
11590   // Assign non-static members.
11591   for (auto *Field : ClassDecl->fields()) {
11592     // FIXME: We should form some kind of AST representation for the implied
11593     // memcpy in a union copy operation.
11594     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11595       continue;
11596 
11597     if (Field->isInvalidDecl()) {
11598       Invalid = true;
11599       continue;
11600     }
11601 
11602     // Check for members of reference type; we can't move those.
11603     if (Field->getType()->isReferenceType()) {
11604       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11605         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11606       Diag(Field->getLocation(), diag::note_declared_at);
11607       Diag(CurrentLocation, diag::note_member_synthesized_at)
11608         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11609       Invalid = true;
11610       continue;
11611     }
11612 
11613     // Check for members of const-qualified, non-class type.
11614     QualType BaseType = Context.getBaseElementType(Field->getType());
11615     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11616       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11617         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11618       Diag(Field->getLocation(), diag::note_declared_at);
11619       Diag(CurrentLocation, diag::note_member_synthesized_at)
11620         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11621       Invalid = true;
11622       continue;
11623     }
11624 
11625     // Suppress assigning zero-width bitfields.
11626     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11627       continue;
11628 
11629     QualType FieldType = Field->getType().getNonReferenceType();
11630     if (FieldType->isIncompleteArrayType()) {
11631       assert(ClassDecl->hasFlexibleArrayMember() &&
11632              "Incomplete array type is not valid");
11633       continue;
11634     }
11635 
11636     // Build references to the field in the object we're copying from and to.
11637     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11638                               LookupMemberName);
11639     MemberLookup.addDecl(Field);
11640     MemberLookup.resolveKind();
11641     MemberBuilder From(MoveOther, OtherRefType,
11642                        /*IsArrow=*/false, MemberLookup);
11643     MemberBuilder To(This, getCurrentThisType(),
11644                      /*IsArrow=*/true, MemberLookup);
11645 
11646     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
11647         "Member reference with rvalue base must be rvalue except for reference "
11648         "members, which aren't allowed for move assignment.");
11649 
11650     // Build the move of this field.
11651     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
11652                                             To, From,
11653                                             /*CopyingBaseSubobject=*/false,
11654                                             /*Copying=*/false);
11655     if (Move.isInvalid()) {
11656       Diag(CurrentLocation, diag::note_member_synthesized_at)
11657         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11658       MoveAssignOperator->setInvalidDecl();
11659       return;
11660     }
11661 
11662     // Success! Record the copy.
11663     Statements.push_back(Move.getAs<Stmt>());
11664   }
11665 
11666   if (!Invalid) {
11667     // Add a "return *this;"
11668     ExprResult ThisObj =
11669         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11670 
11671     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11672     if (Return.isInvalid())
11673       Invalid = true;
11674     else {
11675       Statements.push_back(Return.getAs<Stmt>());
11676 
11677       if (Trap.hasErrorOccurred()) {
11678         Diag(CurrentLocation, diag::note_member_synthesized_at)
11679           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11680         Invalid = true;
11681       }
11682     }
11683   }
11684 
11685   // The exception specification is needed because we are defining the
11686   // function.
11687   ResolveExceptionSpec(CurrentLocation,
11688                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11689 
11690   if (Invalid) {
11691     MoveAssignOperator->setInvalidDecl();
11692     return;
11693   }
11694 
11695   StmtResult Body;
11696   {
11697     CompoundScopeRAII CompoundScope(*this);
11698     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11699                              /*isStmtExpr=*/false);
11700     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11701   }
11702   MoveAssignOperator->setBody(Body.getAs<Stmt>());
11703 
11704   if (ASTMutationListener *L = getASTMutationListener()) {
11705     L->CompletedImplicitDefinition(MoveAssignOperator);
11706   }
11707 }
11708 
11709 Sema::ImplicitExceptionSpecification
11710 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
11711   CXXRecordDecl *ClassDecl = MD->getParent();
11712 
11713   ImplicitExceptionSpecification ExceptSpec(*this);
11714   if (ClassDecl->isInvalidDecl())
11715     return ExceptSpec;
11716 
11717   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
11718   assert(T->getNumParams() >= 1 && "not a copy ctor");
11719   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
11720 
11721   // C++ [except.spec]p14:
11722   //   An implicitly declared special member function (Clause 12) shall have an
11723   //   exception-specification. [...]
11724   for (const auto &Base : ClassDecl->bases()) {
11725     // Virtual bases are handled below.
11726     if (Base.isVirtual())
11727       continue;
11728 
11729     CXXRecordDecl *BaseClassDecl
11730       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11731     if (CXXConstructorDecl *CopyConstructor =
11732           LookupCopyingConstructor(BaseClassDecl, Quals))
11733       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
11734   }
11735   for (const auto &Base : ClassDecl->vbases()) {
11736     CXXRecordDecl *BaseClassDecl
11737       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11738     if (CXXConstructorDecl *CopyConstructor =
11739           LookupCopyingConstructor(BaseClassDecl, Quals))
11740       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
11741   }
11742   for (const auto *Field : ClassDecl->fields()) {
11743     QualType FieldType = Context.getBaseElementType(Field->getType());
11744     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11745       if (CXXConstructorDecl *CopyConstructor =
11746               LookupCopyingConstructor(FieldClassDecl,
11747                                        Quals | FieldType.getCVRQualifiers()))
11748       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
11749     }
11750   }
11751 
11752   return ExceptSpec;
11753 }
11754 
11755 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11756                                                     CXXRecordDecl *ClassDecl) {
11757   // C++ [class.copy]p4:
11758   //   If the class definition does not explicitly declare a copy
11759   //   constructor, one is declared implicitly.
11760   assert(ClassDecl->needsImplicitCopyConstructor());
11761 
11762   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11763   if (DSM.isAlreadyBeingDeclared())
11764     return nullptr;
11765 
11766   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11767   QualType ArgType = ClassType;
11768   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
11769   if (Const)
11770     ArgType = ArgType.withConst();
11771   ArgType = Context.getLValueReferenceType(ArgType);
11772 
11773   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11774                                                      CXXCopyConstructor,
11775                                                      Const);
11776 
11777   DeclarationName Name
11778     = Context.DeclarationNames.getCXXConstructorName(
11779                                            Context.getCanonicalType(ClassType));
11780   SourceLocation ClassLoc = ClassDecl->getLocation();
11781   DeclarationNameInfo NameInfo(Name, ClassLoc);
11782 
11783   //   An implicitly-declared copy constructor is an inline public
11784   //   member of its class.
11785   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
11786       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11787       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11788       Constexpr);
11789   CopyConstructor->setAccess(AS_public);
11790   CopyConstructor->setDefaulted();
11791 
11792   if (getLangOpts().CUDA) {
11793     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11794                                             CopyConstructor,
11795                                             /* ConstRHS */ Const,
11796                                             /* Diagnose */ false);
11797   }
11798 
11799   // Build an exception specification pointing back at this member.
11800   FunctionProtoType::ExtProtoInfo EPI =
11801       getImplicitMethodEPI(*this, CopyConstructor);
11802   CopyConstructor->setType(
11803       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11804 
11805   // Add the parameter to the constructor.
11806   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
11807                                                ClassLoc, ClassLoc,
11808                                                /*IdentifierInfo=*/nullptr,
11809                                                ArgType, /*TInfo=*/nullptr,
11810                                                SC_None, nullptr);
11811   CopyConstructor->setParams(FromParam);
11812 
11813   CopyConstructor->setTrivial(
11814     ClassDecl->needsOverloadResolutionForCopyConstructor()
11815       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11816       : ClassDecl->hasTrivialCopyConstructor());
11817 
11818   // Note that we have declared this constructor.
11819   ++ASTContext::NumImplicitCopyConstructorsDeclared;
11820 
11821   Scope *S = getScopeForContext(ClassDecl);
11822   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11823 
11824   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11825     SetDeclDeleted(CopyConstructor, ClassLoc);
11826 
11827   if (S)
11828     PushOnScopeChains(CopyConstructor, S, false);
11829   ClassDecl->addDecl(CopyConstructor);
11830 
11831   return CopyConstructor;
11832 }
11833 
11834 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
11835                                    CXXConstructorDecl *CopyConstructor) {
11836   assert((CopyConstructor->isDefaulted() &&
11837           CopyConstructor->isCopyConstructor() &&
11838           !CopyConstructor->doesThisDeclarationHaveABody() &&
11839           !CopyConstructor->isDeleted()) &&
11840          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
11841 
11842   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
11843   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
11844 
11845   // C++11 [class.copy]p7:
11846   //   The [definition of an implicitly declared copy constructor] is
11847   //   deprecated if the class has a user-declared copy assignment operator
11848   //   or a user-declared destructor.
11849   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11850     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11851 
11852   SynthesizedFunctionScope Scope(*this, CopyConstructor);
11853   DiagnosticErrorTrap Trap(Diags);
11854 
11855   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
11856       Trap.hasErrorOccurred()) {
11857     Diag(CurrentLocation, diag::note_member_synthesized_at)
11858       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
11859     CopyConstructor->setInvalidDecl();
11860   }  else {
11861     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11862                              ? CopyConstructor->getLocEnd()
11863                              : CopyConstructor->getLocation();
11864     Sema::CompoundScopeRAII CompoundScope(*this);
11865     CopyConstructor->setBody(
11866         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
11867   }
11868 
11869   // The exception specification is needed because we are defining the
11870   // function.
11871   ResolveExceptionSpec(CurrentLocation,
11872                        CopyConstructor->getType()->castAs<FunctionProtoType>());
11873 
11874   CopyConstructor->markUsed(Context);
11875   MarkVTableUsed(CurrentLocation, ClassDecl);
11876 
11877   if (ASTMutationListener *L = getASTMutationListener()) {
11878     L->CompletedImplicitDefinition(CopyConstructor);
11879   }
11880 }
11881 
11882 Sema::ImplicitExceptionSpecification
11883 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11884   CXXRecordDecl *ClassDecl = MD->getParent();
11885 
11886   // C++ [except.spec]p14:
11887   //   An implicitly declared special member function (Clause 12) shall have an
11888   //   exception-specification. [...]
11889   ImplicitExceptionSpecification ExceptSpec(*this);
11890   if (ClassDecl->isInvalidDecl())
11891     return ExceptSpec;
11892 
11893   // Direct base-class constructors.
11894   for (const auto &B : ClassDecl->bases()) {
11895     if (B.isVirtual()) // Handled below.
11896       continue;
11897 
11898     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11899       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11900       CXXConstructorDecl *Constructor =
11901           LookupMovingConstructor(BaseClassDecl, 0);
11902       // If this is a deleted function, add it anyway. This might be conformant
11903       // with the standard. This might not. I'm not sure. It might not matter.
11904       if (Constructor)
11905         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11906     }
11907   }
11908 
11909   // Virtual base-class constructors.
11910   for (const auto &B : ClassDecl->vbases()) {
11911     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11912       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11913       CXXConstructorDecl *Constructor =
11914           LookupMovingConstructor(BaseClassDecl, 0);
11915       // If this is a deleted function, add it anyway. This might be conformant
11916       // with the standard. This might not. I'm not sure. It might not matter.
11917       if (Constructor)
11918         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11919     }
11920   }
11921 
11922   // Field constructors.
11923   for (const auto *F : ClassDecl->fields()) {
11924     QualType FieldType = Context.getBaseElementType(F->getType());
11925     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11926       CXXConstructorDecl *Constructor =
11927           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11928       // If this is a deleted function, add it anyway. This might be conformant
11929       // with the standard. This might not. I'm not sure. It might not matter.
11930       // In particular, the problem is that this function never gets called. It
11931       // might just be ill-formed because this function attempts to refer to
11932       // a deleted function here.
11933       if (Constructor)
11934         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11935     }
11936   }
11937 
11938   return ExceptSpec;
11939 }
11940 
11941 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11942                                                     CXXRecordDecl *ClassDecl) {
11943   assert(ClassDecl->needsImplicitMoveConstructor());
11944 
11945   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11946   if (DSM.isAlreadyBeingDeclared())
11947     return nullptr;
11948 
11949   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11950   QualType ArgType = Context.getRValueReferenceType(ClassType);
11951 
11952   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11953                                                      CXXMoveConstructor,
11954                                                      false);
11955 
11956   DeclarationName Name
11957     = Context.DeclarationNames.getCXXConstructorName(
11958                                            Context.getCanonicalType(ClassType));
11959   SourceLocation ClassLoc = ClassDecl->getLocation();
11960   DeclarationNameInfo NameInfo(Name, ClassLoc);
11961 
11962   // C++11 [class.copy]p11:
11963   //   An implicitly-declared copy/move constructor is an inline public
11964   //   member of its class.
11965   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11966       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11967       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11968       Constexpr);
11969   MoveConstructor->setAccess(AS_public);
11970   MoveConstructor->setDefaulted();
11971 
11972   if (getLangOpts().CUDA) {
11973     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11974                                             MoveConstructor,
11975                                             /* ConstRHS */ false,
11976                                             /* Diagnose */ false);
11977   }
11978 
11979   // Build an exception specification pointing back at this member.
11980   FunctionProtoType::ExtProtoInfo EPI =
11981       getImplicitMethodEPI(*this, MoveConstructor);
11982   MoveConstructor->setType(
11983       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11984 
11985   // Add the parameter to the constructor.
11986   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11987                                                ClassLoc, ClassLoc,
11988                                                /*IdentifierInfo=*/nullptr,
11989                                                ArgType, /*TInfo=*/nullptr,
11990                                                SC_None, nullptr);
11991   MoveConstructor->setParams(FromParam);
11992 
11993   MoveConstructor->setTrivial(
11994     ClassDecl->needsOverloadResolutionForMoveConstructor()
11995       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11996       : ClassDecl->hasTrivialMoveConstructor());
11997 
11998   // Note that we have declared this constructor.
11999   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12000 
12001   Scope *S = getScopeForContext(ClassDecl);
12002   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12003 
12004   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12005     ClassDecl->setImplicitMoveConstructorIsDeleted();
12006     SetDeclDeleted(MoveConstructor, ClassLoc);
12007   }
12008 
12009   if (S)
12010     PushOnScopeChains(MoveConstructor, S, false);
12011   ClassDecl->addDecl(MoveConstructor);
12012 
12013   return MoveConstructor;
12014 }
12015 
12016 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12017                                    CXXConstructorDecl *MoveConstructor) {
12018   assert((MoveConstructor->isDefaulted() &&
12019           MoveConstructor->isMoveConstructor() &&
12020           !MoveConstructor->doesThisDeclarationHaveABody() &&
12021           !MoveConstructor->isDeleted()) &&
12022          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12023 
12024   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12025   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12026 
12027   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12028   DiagnosticErrorTrap Trap(Diags);
12029 
12030   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
12031       Trap.hasErrorOccurred()) {
12032     Diag(CurrentLocation, diag::note_member_synthesized_at)
12033       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12034     MoveConstructor->setInvalidDecl();
12035   }  else {
12036     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12037                              ? MoveConstructor->getLocEnd()
12038                              : MoveConstructor->getLocation();
12039     Sema::CompoundScopeRAII CompoundScope(*this);
12040     MoveConstructor->setBody(ActOnCompoundStmt(
12041         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12042   }
12043 
12044   // The exception specification is needed because we are defining the
12045   // function.
12046   ResolveExceptionSpec(CurrentLocation,
12047                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12048 
12049   MoveConstructor->markUsed(Context);
12050   MarkVTableUsed(CurrentLocation, ClassDecl);
12051 
12052   if (ASTMutationListener *L = getASTMutationListener()) {
12053     L->CompletedImplicitDefinition(MoveConstructor);
12054   }
12055 }
12056 
12057 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12058   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12059 }
12060 
12061 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12062                             SourceLocation CurrentLocation,
12063                             CXXConversionDecl *Conv) {
12064   CXXRecordDecl *Lambda = Conv->getParent();
12065   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12066   // If we are defining a specialization of a conversion to function-ptr
12067   // cache the deduced template arguments for this specialization
12068   // so that we can use them to retrieve the corresponding call-operator
12069   // and static-invoker.
12070   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12071 
12072   // Retrieve the corresponding call-operator specialization.
12073   if (Lambda->isGenericLambda()) {
12074     assert(Conv->isFunctionTemplateSpecialization());
12075     FunctionTemplateDecl *CallOpTemplate =
12076         CallOp->getDescribedFunctionTemplate();
12077     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
12078     void *InsertPos = nullptr;
12079     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
12080                                                 DeducedTemplateArgs->asArray(),
12081                                                 InsertPos);
12082     assert(CallOpSpec &&
12083           "Conversion operator must have a corresponding call operator");
12084     CallOp = cast<CXXMethodDecl>(CallOpSpec);
12085   }
12086   // Mark the call operator referenced (and add to pending instantiations
12087   // if necessary).
12088   // For both the conversion and static-invoker template specializations
12089   // we construct their body's in this function, so no need to add them
12090   // to the PendingInstantiations.
12091   MarkFunctionReferenced(CurrentLocation, CallOp);
12092 
12093   SynthesizedFunctionScope Scope(*this, Conv);
12094   DiagnosticErrorTrap Trap(Diags);
12095 
12096   // Retrieve the static invoker...
12097   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12098   // ... and get the corresponding specialization for a generic lambda.
12099   if (Lambda->isGenericLambda()) {
12100     assert(DeducedTemplateArgs &&
12101       "Must have deduced template arguments from Conversion Operator");
12102     FunctionTemplateDecl *InvokeTemplate =
12103                           Invoker->getDescribedFunctionTemplate();
12104     void *InsertPos = nullptr;
12105     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
12106                                                 DeducedTemplateArgs->asArray(),
12107                                                 InsertPos);
12108     assert(InvokeSpec &&
12109       "Must have a corresponding static invoker specialization");
12110     Invoker = cast<CXXMethodDecl>(InvokeSpec);
12111   }
12112   // Construct the body of the conversion function { return __invoke; }.
12113   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12114                                         VK_LValue, Conv->getLocation()).get();
12115    assert(FunctionRef && "Can't refer to __invoke function?");
12116    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12117    Conv->setBody(new (Context) CompoundStmt(Context, Return,
12118                                             Conv->getLocation(),
12119                                             Conv->getLocation()));
12120 
12121   Conv->markUsed(Context);
12122   Conv->setReferenced();
12123 
12124   // Fill in the __invoke function with a dummy implementation. IR generation
12125   // will fill in the actual details.
12126   Invoker->markUsed(Context);
12127   Invoker->setReferenced();
12128   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12129 
12130   if (ASTMutationListener *L = getASTMutationListener()) {
12131     L->CompletedImplicitDefinition(Conv);
12132     L->CompletedImplicitDefinition(Invoker);
12133    }
12134 }
12135 
12136 
12137 
12138 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12139        SourceLocation CurrentLocation,
12140        CXXConversionDecl *Conv)
12141 {
12142   assert(!Conv->getParent()->isGenericLambda());
12143 
12144   Conv->markUsed(Context);
12145 
12146   SynthesizedFunctionScope Scope(*this, Conv);
12147   DiagnosticErrorTrap Trap(Diags);
12148 
12149   // Copy-initialize the lambda object as needed to capture it.
12150   Expr *This = ActOnCXXThis(CurrentLocation).get();
12151   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12152 
12153   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12154                                                         Conv->getLocation(),
12155                                                         Conv, DerefThis);
12156 
12157   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12158   // behavior.  Note that only the general conversion function does this
12159   // (since it's unusable otherwise); in the case where we inline the
12160   // block literal, it has block literal lifetime semantics.
12161   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12162     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12163                                           CK_CopyAndAutoreleaseBlockObject,
12164                                           BuildBlock.get(), nullptr, VK_RValue);
12165 
12166   if (BuildBlock.isInvalid()) {
12167     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12168     Conv->setInvalidDecl();
12169     return;
12170   }
12171 
12172   // Create the return statement that returns the block from the conversion
12173   // function.
12174   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12175   if (Return.isInvalid()) {
12176     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12177     Conv->setInvalidDecl();
12178     return;
12179   }
12180 
12181   // Set the body of the conversion function.
12182   Stmt *ReturnS = Return.get();
12183   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
12184                                            Conv->getLocation(),
12185                                            Conv->getLocation()));
12186 
12187   // We're done; notify the mutation listener, if any.
12188   if (ASTMutationListener *L = getASTMutationListener()) {
12189     L->CompletedImplicitDefinition(Conv);
12190   }
12191 }
12192 
12193 /// \brief Determine whether the given list arguments contains exactly one
12194 /// "real" (non-default) argument.
12195 static bool hasOneRealArgument(MultiExprArg Args) {
12196   switch (Args.size()) {
12197   case 0:
12198     return false;
12199 
12200   default:
12201     if (!Args[1]->isDefaultArgument())
12202       return false;
12203 
12204     // fall through
12205   case 1:
12206     return !Args[0]->isDefaultArgument();
12207   }
12208 
12209   return false;
12210 }
12211 
12212 ExprResult
12213 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12214                             NamedDecl *FoundDecl,
12215                             CXXConstructorDecl *Constructor,
12216                             MultiExprArg ExprArgs,
12217                             bool HadMultipleCandidates,
12218                             bool IsListInitialization,
12219                             bool IsStdInitListInitialization,
12220                             bool RequiresZeroInit,
12221                             unsigned ConstructKind,
12222                             SourceRange ParenRange) {
12223   bool Elidable = false;
12224 
12225   // C++0x [class.copy]p34:
12226   //   When certain criteria are met, an implementation is allowed to
12227   //   omit the copy/move construction of a class object, even if the
12228   //   copy/move constructor and/or destructor for the object have
12229   //   side effects. [...]
12230   //     - when a temporary class object that has not been bound to a
12231   //       reference (12.2) would be copied/moved to a class object
12232   //       with the same cv-unqualified type, the copy/move operation
12233   //       can be omitted by constructing the temporary object
12234   //       directly into the target of the omitted copy/move
12235   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12236       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12237     Expr *SubExpr = ExprArgs[0];
12238     Elidable = SubExpr->isTemporaryObject(
12239         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12240   }
12241 
12242   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12243                                FoundDecl, Constructor,
12244                                Elidable, ExprArgs, HadMultipleCandidates,
12245                                IsListInitialization,
12246                                IsStdInitListInitialization, RequiresZeroInit,
12247                                ConstructKind, ParenRange);
12248 }
12249 
12250 ExprResult
12251 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12252                             NamedDecl *FoundDecl,
12253                             CXXConstructorDecl *Constructor,
12254                             bool Elidable,
12255                             MultiExprArg ExprArgs,
12256                             bool HadMultipleCandidates,
12257                             bool IsListInitialization,
12258                             bool IsStdInitListInitialization,
12259                             bool RequiresZeroInit,
12260                             unsigned ConstructKind,
12261                             SourceRange ParenRange) {
12262   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12263     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12264     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12265       return ExprError();
12266   }
12267 
12268   return BuildCXXConstructExpr(
12269       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12270       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12271       RequiresZeroInit, ConstructKind, ParenRange);
12272 }
12273 
12274 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12275 /// including handling of its default argument expressions.
12276 ExprResult
12277 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12278                             CXXConstructorDecl *Constructor,
12279                             bool Elidable,
12280                             MultiExprArg ExprArgs,
12281                             bool HadMultipleCandidates,
12282                             bool IsListInitialization,
12283                             bool IsStdInitListInitialization,
12284                             bool RequiresZeroInit,
12285                             unsigned ConstructKind,
12286                             SourceRange ParenRange) {
12287   assert(declaresSameEntity(
12288              Constructor->getParent(),
12289              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12290          "given constructor for wrong type");
12291   MarkFunctionReferenced(ConstructLoc, Constructor);
12292   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12293     return ExprError();
12294 
12295   return CXXConstructExpr::Create(
12296       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12297       ExprArgs, HadMultipleCandidates, IsListInitialization,
12298       IsStdInitListInitialization, RequiresZeroInit,
12299       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12300       ParenRange);
12301 }
12302 
12303 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12304   assert(Field->hasInClassInitializer());
12305 
12306   // If we already have the in-class initializer nothing needs to be done.
12307   if (Field->getInClassInitializer())
12308     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12309 
12310   // Maybe we haven't instantiated the in-class initializer. Go check the
12311   // pattern FieldDecl to see if it has one.
12312   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12313 
12314   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12315     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12316     DeclContext::lookup_result Lookup =
12317         ClassPattern->lookup(Field->getDeclName());
12318 
12319     // Lookup can return at most two results: the pattern for the field, or the
12320     // injected class name of the parent record. No other member can have the
12321     // same name as the field.
12322     assert(!Lookup.empty() && Lookup.size() <= 2 &&
12323            "more than two lookup results for field name");
12324     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12325     if (!Pattern) {
12326       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12327              "cannot have other non-field member with same name");
12328       Pattern = cast<FieldDecl>(Lookup[1]);
12329     }
12330 
12331     if (InstantiateInClassInitializer(Loc, Field, Pattern,
12332                                       getTemplateInstantiationArgs(Field)))
12333       return ExprError();
12334     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12335   }
12336 
12337   // DR1351:
12338   //   If the brace-or-equal-initializer of a non-static data member
12339   //   invokes a defaulted default constructor of its class or of an
12340   //   enclosing class in a potentially evaluated subexpression, the
12341   //   program is ill-formed.
12342   //
12343   // This resolution is unworkable: the exception specification of the
12344   // default constructor can be needed in an unevaluated context, in
12345   // particular, in the operand of a noexcept-expression, and we can be
12346   // unable to compute an exception specification for an enclosed class.
12347   //
12348   // Any attempt to resolve the exception specification of a defaulted default
12349   // constructor before the initializer is lexically complete will ultimately
12350   // come here at which point we can diagnose it.
12351   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12352   if (OutermostClass == ParentRD) {
12353     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
12354         << ParentRD << Field;
12355   } else {
12356     Diag(Field->getLocEnd(),
12357          diag::err_in_class_initializer_not_yet_parsed_outer_class)
12358         << ParentRD << OutermostClass << Field;
12359   }
12360 
12361   return ExprError();
12362 }
12363 
12364 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12365   if (VD->isInvalidDecl()) return;
12366 
12367   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12368   if (ClassDecl->isInvalidDecl()) return;
12369   if (ClassDecl->hasIrrelevantDestructor()) return;
12370   if (ClassDecl->isDependentContext()) return;
12371 
12372   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12373   MarkFunctionReferenced(VD->getLocation(), Destructor);
12374   CheckDestructorAccess(VD->getLocation(), Destructor,
12375                         PDiag(diag::err_access_dtor_var)
12376                         << VD->getDeclName()
12377                         << VD->getType());
12378   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12379 
12380   if (Destructor->isTrivial()) return;
12381   if (!VD->hasGlobalStorage()) return;
12382 
12383   // Emit warning for non-trivial dtor in global scope (a real global,
12384   // class-static, function-static).
12385   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12386 
12387   // TODO: this should be re-enabled for static locals by !CXAAtExit
12388   if (!VD->isStaticLocal())
12389     Diag(VD->getLocation(), diag::warn_global_destructor);
12390 }
12391 
12392 /// \brief Given a constructor and the set of arguments provided for the
12393 /// constructor, convert the arguments and add any required default arguments
12394 /// to form a proper call to this constructor.
12395 ///
12396 /// \returns true if an error occurred, false otherwise.
12397 bool
12398 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12399                               MultiExprArg ArgsPtr,
12400                               SourceLocation Loc,
12401                               SmallVectorImpl<Expr*> &ConvertedArgs,
12402                               bool AllowExplicit,
12403                               bool IsListInitialization) {
12404   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12405   unsigned NumArgs = ArgsPtr.size();
12406   Expr **Args = ArgsPtr.data();
12407 
12408   const FunctionProtoType *Proto
12409     = Constructor->getType()->getAs<FunctionProtoType>();
12410   assert(Proto && "Constructor without a prototype?");
12411   unsigned NumParams = Proto->getNumParams();
12412 
12413   // If too few arguments are available, we'll fill in the rest with defaults.
12414   if (NumArgs < NumParams)
12415     ConvertedArgs.reserve(NumParams);
12416   else
12417     ConvertedArgs.reserve(NumArgs);
12418 
12419   VariadicCallType CallType =
12420     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12421   SmallVector<Expr *, 8> AllArgs;
12422   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12423                                         Proto, 0,
12424                                         llvm::makeArrayRef(Args, NumArgs),
12425                                         AllArgs,
12426                                         CallType, AllowExplicit,
12427                                         IsListInitialization);
12428   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12429 
12430   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12431 
12432   CheckConstructorCall(Constructor,
12433                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12434                        Proto, Loc);
12435 
12436   return Invalid;
12437 }
12438 
12439 static inline bool
12440 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12441                                        const FunctionDecl *FnDecl) {
12442   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12443   if (isa<NamespaceDecl>(DC)) {
12444     return SemaRef.Diag(FnDecl->getLocation(),
12445                         diag::err_operator_new_delete_declared_in_namespace)
12446       << FnDecl->getDeclName();
12447   }
12448 
12449   if (isa<TranslationUnitDecl>(DC) &&
12450       FnDecl->getStorageClass() == SC_Static) {
12451     return SemaRef.Diag(FnDecl->getLocation(),
12452                         diag::err_operator_new_delete_declared_static)
12453       << FnDecl->getDeclName();
12454   }
12455 
12456   return false;
12457 }
12458 
12459 static inline bool
12460 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12461                             CanQualType ExpectedResultType,
12462                             CanQualType ExpectedFirstParamType,
12463                             unsigned DependentParamTypeDiag,
12464                             unsigned InvalidParamTypeDiag) {
12465   QualType ResultType =
12466       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12467 
12468   // Check that the result type is not dependent.
12469   if (ResultType->isDependentType())
12470     return SemaRef.Diag(FnDecl->getLocation(),
12471                         diag::err_operator_new_delete_dependent_result_type)
12472     << FnDecl->getDeclName() << ExpectedResultType;
12473 
12474   // Check that the result type is what we expect.
12475   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12476     return SemaRef.Diag(FnDecl->getLocation(),
12477                         diag::err_operator_new_delete_invalid_result_type)
12478     << FnDecl->getDeclName() << ExpectedResultType;
12479 
12480   // A function template must have at least 2 parameters.
12481   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12482     return SemaRef.Diag(FnDecl->getLocation(),
12483                       diag::err_operator_new_delete_template_too_few_parameters)
12484         << FnDecl->getDeclName();
12485 
12486   // The function decl must have at least 1 parameter.
12487   if (FnDecl->getNumParams() == 0)
12488     return SemaRef.Diag(FnDecl->getLocation(),
12489                         diag::err_operator_new_delete_too_few_parameters)
12490       << FnDecl->getDeclName();
12491 
12492   // Check the first parameter type is not dependent.
12493   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12494   if (FirstParamType->isDependentType())
12495     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12496       << FnDecl->getDeclName() << ExpectedFirstParamType;
12497 
12498   // Check that the first parameter type is what we expect.
12499   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
12500       ExpectedFirstParamType)
12501     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12502     << FnDecl->getDeclName() << ExpectedFirstParamType;
12503 
12504   return false;
12505 }
12506 
12507 static bool
12508 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12509   // C++ [basic.stc.dynamic.allocation]p1:
12510   //   A program is ill-formed if an allocation function is declared in a
12511   //   namespace scope other than global scope or declared static in global
12512   //   scope.
12513   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12514     return true;
12515 
12516   CanQualType SizeTy =
12517     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12518 
12519   // C++ [basic.stc.dynamic.allocation]p1:
12520   //  The return type shall be void*. The first parameter shall have type
12521   //  std::size_t.
12522   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12523                                   SizeTy,
12524                                   diag::err_operator_new_dependent_param_type,
12525                                   diag::err_operator_new_param_type))
12526     return true;
12527 
12528   // C++ [basic.stc.dynamic.allocation]p1:
12529   //  The first parameter shall not have an associated default argument.
12530   if (FnDecl->getParamDecl(0)->hasDefaultArg())
12531     return SemaRef.Diag(FnDecl->getLocation(),
12532                         diag::err_operator_new_default_arg)
12533       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12534 
12535   return false;
12536 }
12537 
12538 static bool
12539 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12540   // C++ [basic.stc.dynamic.deallocation]p1:
12541   //   A program is ill-formed if deallocation functions are declared in a
12542   //   namespace scope other than global scope or declared static in global
12543   //   scope.
12544   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12545     return true;
12546 
12547   // C++ [basic.stc.dynamic.deallocation]p2:
12548   //   Each deallocation function shall return void and its first parameter
12549   //   shall be void*.
12550   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12551                                   SemaRef.Context.VoidPtrTy,
12552                                  diag::err_operator_delete_dependent_param_type,
12553                                  diag::err_operator_delete_param_type))
12554     return true;
12555 
12556   return false;
12557 }
12558 
12559 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
12560 /// of this overloaded operator is well-formed. If so, returns false;
12561 /// otherwise, emits appropriate diagnostics and returns true.
12562 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12563   assert(FnDecl && FnDecl->isOverloadedOperator() &&
12564          "Expected an overloaded operator declaration");
12565 
12566   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12567 
12568   // C++ [over.oper]p5:
12569   //   The allocation and deallocation functions, operator new,
12570   //   operator new[], operator delete and operator delete[], are
12571   //   described completely in 3.7.3. The attributes and restrictions
12572   //   found in the rest of this subclause do not apply to them unless
12573   //   explicitly stated in 3.7.3.
12574   if (Op == OO_Delete || Op == OO_Array_Delete)
12575     return CheckOperatorDeleteDeclaration(*this, FnDecl);
12576 
12577   if (Op == OO_New || Op == OO_Array_New)
12578     return CheckOperatorNewDeclaration(*this, FnDecl);
12579 
12580   // C++ [over.oper]p6:
12581   //   An operator function shall either be a non-static member
12582   //   function or be a non-member function and have at least one
12583   //   parameter whose type is a class, a reference to a class, an
12584   //   enumeration, or a reference to an enumeration.
12585   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12586     if (MethodDecl->isStatic())
12587       return Diag(FnDecl->getLocation(),
12588                   diag::err_operator_overload_static) << FnDecl->getDeclName();
12589   } else {
12590     bool ClassOrEnumParam = false;
12591     for (auto Param : FnDecl->parameters()) {
12592       QualType ParamType = Param->getType().getNonReferenceType();
12593       if (ParamType->isDependentType() || ParamType->isRecordType() ||
12594           ParamType->isEnumeralType()) {
12595         ClassOrEnumParam = true;
12596         break;
12597       }
12598     }
12599 
12600     if (!ClassOrEnumParam)
12601       return Diag(FnDecl->getLocation(),
12602                   diag::err_operator_overload_needs_class_or_enum)
12603         << FnDecl->getDeclName();
12604   }
12605 
12606   // C++ [over.oper]p8:
12607   //   An operator function cannot have default arguments (8.3.6),
12608   //   except where explicitly stated below.
12609   //
12610   // Only the function-call operator allows default arguments
12611   // (C++ [over.call]p1).
12612   if (Op != OO_Call) {
12613     for (auto Param : FnDecl->parameters()) {
12614       if (Param->hasDefaultArg())
12615         return Diag(Param->getLocation(),
12616                     diag::err_operator_overload_default_arg)
12617           << FnDecl->getDeclName() << Param->getDefaultArgRange();
12618     }
12619   }
12620 
12621   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12622     { false, false, false }
12623 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12624     , { Unary, Binary, MemberOnly }
12625 #include "clang/Basic/OperatorKinds.def"
12626   };
12627 
12628   bool CanBeUnaryOperator = OperatorUses[Op][0];
12629   bool CanBeBinaryOperator = OperatorUses[Op][1];
12630   bool MustBeMemberOperator = OperatorUses[Op][2];
12631 
12632   // C++ [over.oper]p8:
12633   //   [...] Operator functions cannot have more or fewer parameters
12634   //   than the number required for the corresponding operator, as
12635   //   described in the rest of this subclause.
12636   unsigned NumParams = FnDecl->getNumParams()
12637                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
12638   if (Op != OO_Call &&
12639       ((NumParams == 1 && !CanBeUnaryOperator) ||
12640        (NumParams == 2 && !CanBeBinaryOperator) ||
12641        (NumParams < 1) || (NumParams > 2))) {
12642     // We have the wrong number of parameters.
12643     unsigned ErrorKind;
12644     if (CanBeUnaryOperator && CanBeBinaryOperator) {
12645       ErrorKind = 2;  // 2 -> unary or binary.
12646     } else if (CanBeUnaryOperator) {
12647       ErrorKind = 0;  // 0 -> unary
12648     } else {
12649       assert(CanBeBinaryOperator &&
12650              "All non-call overloaded operators are unary or binary!");
12651       ErrorKind = 1;  // 1 -> binary
12652     }
12653 
12654     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
12655       << FnDecl->getDeclName() << NumParams << ErrorKind;
12656   }
12657 
12658   // Overloaded operators other than operator() cannot be variadic.
12659   if (Op != OO_Call &&
12660       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
12661     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
12662       << FnDecl->getDeclName();
12663   }
12664 
12665   // Some operators must be non-static member functions.
12666   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12667     return Diag(FnDecl->getLocation(),
12668                 diag::err_operator_overload_must_be_member)
12669       << FnDecl->getDeclName();
12670   }
12671 
12672   // C++ [over.inc]p1:
12673   //   The user-defined function called operator++ implements the
12674   //   prefix and postfix ++ operator. If this function is a member
12675   //   function with no parameters, or a non-member function with one
12676   //   parameter of class or enumeration type, it defines the prefix
12677   //   increment operator ++ for objects of that type. If the function
12678   //   is a member function with one parameter (which shall be of type
12679   //   int) or a non-member function with two parameters (the second
12680   //   of which shall be of type int), it defines the postfix
12681   //   increment operator ++ for objects of that type.
12682   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12683     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
12684     QualType ParamType = LastParam->getType();
12685 
12686     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12687         !ParamType->isDependentType())
12688       return Diag(LastParam->getLocation(),
12689                   diag::err_operator_overload_post_incdec_must_be_int)
12690         << LastParam->getType() << (Op == OO_MinusMinus);
12691   }
12692 
12693   return false;
12694 }
12695 
12696 static bool
12697 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12698                                           FunctionTemplateDecl *TpDecl) {
12699   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12700 
12701   // Must have one or two template parameters.
12702   if (TemplateParams->size() == 1) {
12703     NonTypeTemplateParmDecl *PmDecl =
12704         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12705 
12706     // The template parameter must be a char parameter pack.
12707     if (PmDecl && PmDecl->isTemplateParameterPack() &&
12708         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12709       return false;
12710 
12711   } else if (TemplateParams->size() == 2) {
12712     TemplateTypeParmDecl *PmType =
12713         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12714     NonTypeTemplateParmDecl *PmArgs =
12715         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12716 
12717     // The second template parameter must be a parameter pack with the
12718     // first template parameter as its type.
12719     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12720         PmArgs->isTemplateParameterPack()) {
12721       const TemplateTypeParmType *TArgs =
12722           PmArgs->getType()->getAs<TemplateTypeParmType>();
12723       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12724           TArgs->getIndex() == PmType->getIndex()) {
12725         if (SemaRef.ActiveTemplateInstantiations.empty())
12726           SemaRef.Diag(TpDecl->getLocation(),
12727                        diag::ext_string_literal_operator_template);
12728         return false;
12729       }
12730     }
12731   }
12732 
12733   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12734                diag::err_literal_operator_template)
12735       << TpDecl->getTemplateParameters()->getSourceRange();
12736   return true;
12737 }
12738 
12739 /// CheckLiteralOperatorDeclaration - Check whether the declaration
12740 /// of this literal operator function is well-formed. If so, returns
12741 /// false; otherwise, emits appropriate diagnostics and returns true.
12742 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
12743   if (isa<CXXMethodDecl>(FnDecl)) {
12744     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12745       << FnDecl->getDeclName();
12746     return true;
12747   }
12748 
12749   if (FnDecl->isExternC()) {
12750     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
12751     return true;
12752   }
12753 
12754   // This might be the definition of a literal operator template.
12755   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
12756 
12757   // This might be a specialization of a literal operator template.
12758   if (!TpDecl)
12759     TpDecl = FnDecl->getPrimaryTemplate();
12760 
12761   // template <char...> type operator "" name() and
12762   // template <class T, T...> type operator "" name() are the only valid
12763   // template signatures, and the only valid signatures with no parameters.
12764   if (TpDecl) {
12765     if (FnDecl->param_size() != 0) {
12766       Diag(FnDecl->getLocation(),
12767            diag::err_literal_operator_template_with_params);
12768       return true;
12769     }
12770 
12771     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12772       return true;
12773 
12774   } else if (FnDecl->param_size() == 1) {
12775     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12776 
12777     QualType ParamType = Param->getType().getUnqualifiedType();
12778 
12779     // Only unsigned long long int, long double, any character type, and const
12780     // char * are allowed as the only parameters.
12781     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12782         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12783         Context.hasSameType(ParamType, Context.CharTy) ||
12784         Context.hasSameType(ParamType, Context.WideCharTy) ||
12785         Context.hasSameType(ParamType, Context.Char16Ty) ||
12786         Context.hasSameType(ParamType, Context.Char32Ty)) {
12787     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12788       QualType InnerType = Ptr->getPointeeType();
12789 
12790       // Pointer parameter must be a const char *.
12791       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12792                                 Context.CharTy) &&
12793             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12794         Diag(Param->getSourceRange().getBegin(),
12795              diag::err_literal_operator_param)
12796             << ParamType << "'const char *'" << Param->getSourceRange();
12797         return true;
12798       }
12799 
12800     } else if (ParamType->isRealFloatingType()) {
12801       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12802           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12803       return true;
12804 
12805     } else if (ParamType->isIntegerType()) {
12806       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12807           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12808       return true;
12809 
12810     } else {
12811       Diag(Param->getSourceRange().getBegin(),
12812            diag::err_literal_operator_invalid_param)
12813           << ParamType << Param->getSourceRange();
12814       return true;
12815     }
12816 
12817   } else if (FnDecl->param_size() == 2) {
12818     FunctionDecl::param_iterator Param = FnDecl->param_begin();
12819 
12820     // First, verify that the first parameter is correct.
12821 
12822     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12823 
12824     // Two parameter function must have a pointer to const as a
12825     // first parameter; let's strip those qualifiers.
12826     const PointerType *PT = FirstParamType->getAs<PointerType>();
12827 
12828     if (!PT) {
12829       Diag((*Param)->getSourceRange().getBegin(),
12830            diag::err_literal_operator_param)
12831           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12832       return true;
12833     }
12834 
12835     QualType PointeeType = PT->getPointeeType();
12836     // First parameter must be const
12837     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12838       Diag((*Param)->getSourceRange().getBegin(),
12839            diag::err_literal_operator_param)
12840           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12841       return true;
12842     }
12843 
12844     QualType InnerType = PointeeType.getUnqualifiedType();
12845     // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12846     // are allowed as the first parameter to a two-parameter function
12847     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12848           Context.hasSameType(InnerType, Context.WideCharTy) ||
12849           Context.hasSameType(InnerType, Context.Char16Ty) ||
12850           Context.hasSameType(InnerType, Context.Char32Ty))) {
12851       Diag((*Param)->getSourceRange().getBegin(),
12852            diag::err_literal_operator_param)
12853           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12854       return true;
12855     }
12856 
12857     // Move on to the second and final parameter.
12858     ++Param;
12859 
12860     // The second parameter must be a std::size_t.
12861     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12862     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12863       Diag((*Param)->getSourceRange().getBegin(),
12864            diag::err_literal_operator_param)
12865           << SecondParamType << Context.getSizeType()
12866           << (*Param)->getSourceRange();
12867       return true;
12868     }
12869   } else {
12870     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
12871     return true;
12872   }
12873 
12874   // Parameters are good.
12875 
12876   // A parameter-declaration-clause containing a default argument is not
12877   // equivalent to any of the permitted forms.
12878   for (auto Param : FnDecl->parameters()) {
12879     if (Param->hasDefaultArg()) {
12880       Diag(Param->getDefaultArgRange().getBegin(),
12881            diag::err_literal_operator_default_argument)
12882         << Param->getDefaultArgRange();
12883       break;
12884     }
12885   }
12886 
12887   StringRef LiteralName
12888     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12889   if (LiteralName[0] != '_') {
12890     // C++11 [usrlit.suffix]p1:
12891     //   Literal suffix identifiers that do not start with an underscore
12892     //   are reserved for future standardization.
12893     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12894       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
12895   }
12896 
12897   return false;
12898 }
12899 
12900 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12901 /// linkage specification, including the language and (if present)
12902 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
12903 /// language string literal. LBraceLoc, if valid, provides the location of
12904 /// the '{' brace. Otherwise, this linkage specification does not
12905 /// have any braces.
12906 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
12907                                            Expr *LangStr,
12908                                            SourceLocation LBraceLoc) {
12909   StringLiteral *Lit = cast<StringLiteral>(LangStr);
12910   if (!Lit->isAscii()) {
12911     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12912       << LangStr->getSourceRange();
12913     return nullptr;
12914   }
12915 
12916   StringRef Lang = Lit->getString();
12917   LinkageSpecDecl::LanguageIDs Language;
12918   if (Lang == "C")
12919     Language = LinkageSpecDecl::lang_c;
12920   else if (Lang == "C++")
12921     Language = LinkageSpecDecl::lang_cxx;
12922   else {
12923     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12924       << LangStr->getSourceRange();
12925     return nullptr;
12926   }
12927 
12928   // FIXME: Add all the various semantics of linkage specifications
12929 
12930   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12931                                                LangStr->getExprLoc(), Language,
12932                                                LBraceLoc.isValid());
12933   CurContext->addDecl(D);
12934   PushDeclContext(S, D);
12935   return D;
12936 }
12937 
12938 /// ActOnFinishLinkageSpecification - Complete the definition of
12939 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
12940 /// valid, it's the position of the closing '}' brace in a linkage
12941 /// specification that uses braces.
12942 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
12943                                             Decl *LinkageSpec,
12944                                             SourceLocation RBraceLoc) {
12945   if (RBraceLoc.isValid()) {
12946     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12947     LSDecl->setRBraceLoc(RBraceLoc);
12948   }
12949   PopDeclContext();
12950   return LinkageSpec;
12951 }
12952 
12953 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12954                                   AttributeList *AttrList,
12955                                   SourceLocation SemiLoc) {
12956   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12957   // Attribute declarations appertain to empty declaration so we handle
12958   // them here.
12959   if (AttrList)
12960     ProcessDeclAttributeList(S, ED, AttrList);
12961 
12962   CurContext->addDecl(ED);
12963   return ED;
12964 }
12965 
12966 /// \brief Perform semantic analysis for the variable declaration that
12967 /// occurs within a C++ catch clause, returning the newly-created
12968 /// variable.
12969 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
12970                                          TypeSourceInfo *TInfo,
12971                                          SourceLocation StartLoc,
12972                                          SourceLocation Loc,
12973                                          IdentifierInfo *Name) {
12974   bool Invalid = false;
12975   QualType ExDeclType = TInfo->getType();
12976 
12977   // Arrays and functions decay.
12978   if (ExDeclType->isArrayType())
12979     ExDeclType = Context.getArrayDecayedType(ExDeclType);
12980   else if (ExDeclType->isFunctionType())
12981     ExDeclType = Context.getPointerType(ExDeclType);
12982 
12983   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
12984   // The exception-declaration shall not denote a pointer or reference to an
12985   // incomplete type, other than [cv] void*.
12986   // N2844 forbids rvalue references.
12987   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
12988     Diag(Loc, diag::err_catch_rvalue_ref);
12989     Invalid = true;
12990   }
12991 
12992   if (ExDeclType->isVariablyModifiedType()) {
12993     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
12994     Invalid = true;
12995   }
12996 
12997   QualType BaseType = ExDeclType;
12998   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
12999   unsigned DK = diag::err_catch_incomplete;
13000   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13001     BaseType = Ptr->getPointeeType();
13002     Mode = 1;
13003     DK = diag::err_catch_incomplete_ptr;
13004   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13005     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13006     BaseType = Ref->getPointeeType();
13007     Mode = 2;
13008     DK = diag::err_catch_incomplete_ref;
13009   }
13010   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13011       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13012     Invalid = true;
13013 
13014   if (!Invalid && !ExDeclType->isDependentType() &&
13015       RequireNonAbstractType(Loc, ExDeclType,
13016                              diag::err_abstract_type_in_decl,
13017                              AbstractVariableType))
13018     Invalid = true;
13019 
13020   // Only the non-fragile NeXT runtime currently supports C++ catches
13021   // of ObjC types, and no runtime supports catching ObjC types by value.
13022   if (!Invalid && getLangOpts().ObjC1) {
13023     QualType T = ExDeclType;
13024     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13025       T = RT->getPointeeType();
13026 
13027     if (T->isObjCObjectType()) {
13028       Diag(Loc, diag::err_objc_object_catch);
13029       Invalid = true;
13030     } else if (T->isObjCObjectPointerType()) {
13031       // FIXME: should this be a test for macosx-fragile specifically?
13032       if (getLangOpts().ObjCRuntime.isFragile())
13033         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13034     }
13035   }
13036 
13037   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13038                                     ExDeclType, TInfo, SC_None);
13039   ExDecl->setExceptionVariable(true);
13040 
13041   // In ARC, infer 'retaining' for variables of retainable type.
13042   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13043     Invalid = true;
13044 
13045   if (!Invalid && !ExDeclType->isDependentType()) {
13046     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13047       // Insulate this from anything else we might currently be parsing.
13048       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13049 
13050       // C++ [except.handle]p16:
13051       //   The object declared in an exception-declaration or, if the
13052       //   exception-declaration does not specify a name, a temporary (12.2) is
13053       //   copy-initialized (8.5) from the exception object. [...]
13054       //   The object is destroyed when the handler exits, after the destruction
13055       //   of any automatic objects initialized within the handler.
13056       //
13057       // We just pretend to initialize the object with itself, then make sure
13058       // it can be destroyed later.
13059       QualType initType = Context.getExceptionObjectType(ExDeclType);
13060 
13061       InitializedEntity entity =
13062         InitializedEntity::InitializeVariable(ExDecl);
13063       InitializationKind initKind =
13064         InitializationKind::CreateCopy(Loc, SourceLocation());
13065 
13066       Expr *opaqueValue =
13067         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13068       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13069       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13070       if (result.isInvalid())
13071         Invalid = true;
13072       else {
13073         // If the constructor used was non-trivial, set this as the
13074         // "initializer".
13075         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13076         if (!construct->getConstructor()->isTrivial()) {
13077           Expr *init = MaybeCreateExprWithCleanups(construct);
13078           ExDecl->setInit(init);
13079         }
13080 
13081         // And make sure it's destructable.
13082         FinalizeVarWithDestructor(ExDecl, recordType);
13083       }
13084     }
13085   }
13086 
13087   if (Invalid)
13088     ExDecl->setInvalidDecl();
13089 
13090   return ExDecl;
13091 }
13092 
13093 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13094 /// handler.
13095 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13096   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13097   bool Invalid = D.isInvalidType();
13098 
13099   // Check for unexpanded parameter packs.
13100   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13101                                       UPPC_ExceptionType)) {
13102     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13103                                              D.getIdentifierLoc());
13104     Invalid = true;
13105   }
13106 
13107   IdentifierInfo *II = D.getIdentifier();
13108   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13109                                              LookupOrdinaryName,
13110                                              ForRedeclaration)) {
13111     // The scope should be freshly made just for us. There is just no way
13112     // it contains any previous declaration, except for function parameters in
13113     // a function-try-block's catch statement.
13114     assert(!S->isDeclScope(PrevDecl));
13115     if (isDeclInScope(PrevDecl, CurContext, S)) {
13116       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13117         << D.getIdentifier();
13118       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13119       Invalid = true;
13120     } else if (PrevDecl->isTemplateParameter())
13121       // Maybe we will complain about the shadowed template parameter.
13122       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13123   }
13124 
13125   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13126     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13127       << D.getCXXScopeSpec().getRange();
13128     Invalid = true;
13129   }
13130 
13131   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13132                                               D.getLocStart(),
13133                                               D.getIdentifierLoc(),
13134                                               D.getIdentifier());
13135   if (Invalid)
13136     ExDecl->setInvalidDecl();
13137 
13138   // Add the exception declaration into this scope.
13139   if (II)
13140     PushOnScopeChains(ExDecl, S);
13141   else
13142     CurContext->addDecl(ExDecl);
13143 
13144   ProcessDeclAttributes(S, ExDecl, D);
13145   return ExDecl;
13146 }
13147 
13148 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13149                                          Expr *AssertExpr,
13150                                          Expr *AssertMessageExpr,
13151                                          SourceLocation RParenLoc) {
13152   StringLiteral *AssertMessage =
13153       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13154 
13155   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13156     return nullptr;
13157 
13158   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13159                                       AssertMessage, RParenLoc, false);
13160 }
13161 
13162 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13163                                          Expr *AssertExpr,
13164                                          StringLiteral *AssertMessage,
13165                                          SourceLocation RParenLoc,
13166                                          bool Failed) {
13167   assert(AssertExpr != nullptr && "Expected non-null condition");
13168   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13169       !Failed) {
13170     // In a static_assert-declaration, the constant-expression shall be a
13171     // constant expression that can be contextually converted to bool.
13172     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13173     if (Converted.isInvalid())
13174       Failed = true;
13175 
13176     llvm::APSInt Cond;
13177     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13178           diag::err_static_assert_expression_is_not_constant,
13179           /*AllowFold=*/false).isInvalid())
13180       Failed = true;
13181 
13182     if (!Failed && !Cond) {
13183       SmallString<256> MsgBuffer;
13184       llvm::raw_svector_ostream Msg(MsgBuffer);
13185       if (AssertMessage)
13186         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13187       Diag(StaticAssertLoc, diag::err_static_assert_failed)
13188         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13189       Failed = true;
13190     }
13191   }
13192 
13193   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13194                                         AssertExpr, AssertMessage, RParenLoc,
13195                                         Failed);
13196 
13197   CurContext->addDecl(Decl);
13198   return Decl;
13199 }
13200 
13201 /// \brief Perform semantic analysis of the given friend type declaration.
13202 ///
13203 /// \returns A friend declaration that.
13204 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13205                                       SourceLocation FriendLoc,
13206                                       TypeSourceInfo *TSInfo) {
13207   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13208 
13209   QualType T = TSInfo->getType();
13210   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13211 
13212   // C++03 [class.friend]p2:
13213   //   An elaborated-type-specifier shall be used in a friend declaration
13214   //   for a class.*
13215   //
13216   //   * The class-key of the elaborated-type-specifier is required.
13217   if (!ActiveTemplateInstantiations.empty()) {
13218     // Do not complain about the form of friend template types during
13219     // template instantiation; we will already have complained when the
13220     // template was declared.
13221   } else {
13222     if (!T->isElaboratedTypeSpecifier()) {
13223       // If we evaluated the type to a record type, suggest putting
13224       // a tag in front.
13225       if (const RecordType *RT = T->getAs<RecordType>()) {
13226         RecordDecl *RD = RT->getDecl();
13227 
13228         SmallString<16> InsertionText(" ");
13229         InsertionText += RD->getKindName();
13230 
13231         Diag(TypeRange.getBegin(),
13232              getLangOpts().CPlusPlus11 ?
13233                diag::warn_cxx98_compat_unelaborated_friend_type :
13234                diag::ext_unelaborated_friend_type)
13235           << (unsigned) RD->getTagKind()
13236           << T
13237           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13238                                         InsertionText);
13239       } else {
13240         Diag(FriendLoc,
13241              getLangOpts().CPlusPlus11 ?
13242                diag::warn_cxx98_compat_nonclass_type_friend :
13243                diag::ext_nonclass_type_friend)
13244           << T
13245           << TypeRange;
13246       }
13247     } else if (T->getAs<EnumType>()) {
13248       Diag(FriendLoc,
13249            getLangOpts().CPlusPlus11 ?
13250              diag::warn_cxx98_compat_enum_friend :
13251              diag::ext_enum_friend)
13252         << T
13253         << TypeRange;
13254     }
13255 
13256     // C++11 [class.friend]p3:
13257     //   A friend declaration that does not declare a function shall have one
13258     //   of the following forms:
13259     //     friend elaborated-type-specifier ;
13260     //     friend simple-type-specifier ;
13261     //     friend typename-specifier ;
13262     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13263       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13264   }
13265 
13266   //   If the type specifier in a friend declaration designates a (possibly
13267   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13268   //   the friend declaration is ignored.
13269   return FriendDecl::Create(Context, CurContext,
13270                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13271                             FriendLoc);
13272 }
13273 
13274 /// Handle a friend tag declaration where the scope specifier was
13275 /// templated.
13276 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13277                                     unsigned TagSpec, SourceLocation TagLoc,
13278                                     CXXScopeSpec &SS,
13279                                     IdentifierInfo *Name,
13280                                     SourceLocation NameLoc,
13281                                     AttributeList *Attr,
13282                                     MultiTemplateParamsArg TempParamLists) {
13283   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13284 
13285   bool isExplicitSpecialization = false;
13286   bool Invalid = false;
13287 
13288   if (TemplateParameterList *TemplateParams =
13289           MatchTemplateParametersToScopeSpecifier(
13290               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13291               isExplicitSpecialization, Invalid)) {
13292     if (TemplateParams->size() > 0) {
13293       // This is a declaration of a class template.
13294       if (Invalid)
13295         return nullptr;
13296 
13297       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13298                                 NameLoc, Attr, TemplateParams, AS_public,
13299                                 /*ModulePrivateLoc=*/SourceLocation(),
13300                                 FriendLoc, TempParamLists.size() - 1,
13301                                 TempParamLists.data()).get();
13302     } else {
13303       // The "template<>" header is extraneous.
13304       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13305         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13306       isExplicitSpecialization = true;
13307     }
13308   }
13309 
13310   if (Invalid) return nullptr;
13311 
13312   bool isAllExplicitSpecializations = true;
13313   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13314     if (TempParamLists[I]->size()) {
13315       isAllExplicitSpecializations = false;
13316       break;
13317     }
13318   }
13319 
13320   // FIXME: don't ignore attributes.
13321 
13322   // If it's explicit specializations all the way down, just forget
13323   // about the template header and build an appropriate non-templated
13324   // friend.  TODO: for source fidelity, remember the headers.
13325   if (isAllExplicitSpecializations) {
13326     if (SS.isEmpty()) {
13327       bool Owned = false;
13328       bool IsDependent = false;
13329       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13330                       Attr, AS_public,
13331                       /*ModulePrivateLoc=*/SourceLocation(),
13332                       MultiTemplateParamsArg(), Owned, IsDependent,
13333                       /*ScopedEnumKWLoc=*/SourceLocation(),
13334                       /*ScopedEnumUsesClassTag=*/false,
13335                       /*UnderlyingType=*/TypeResult(),
13336                       /*IsTypeSpecifier=*/false);
13337     }
13338 
13339     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13340     ElaboratedTypeKeyword Keyword
13341       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13342     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13343                                    *Name, NameLoc);
13344     if (T.isNull())
13345       return nullptr;
13346 
13347     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13348     if (isa<DependentNameType>(T)) {
13349       DependentNameTypeLoc TL =
13350           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13351       TL.setElaboratedKeywordLoc(TagLoc);
13352       TL.setQualifierLoc(QualifierLoc);
13353       TL.setNameLoc(NameLoc);
13354     } else {
13355       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13356       TL.setElaboratedKeywordLoc(TagLoc);
13357       TL.setQualifierLoc(QualifierLoc);
13358       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13359     }
13360 
13361     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13362                                             TSI, FriendLoc, TempParamLists);
13363     Friend->setAccess(AS_public);
13364     CurContext->addDecl(Friend);
13365     return Friend;
13366   }
13367 
13368   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13369 
13370 
13371 
13372   // Handle the case of a templated-scope friend class.  e.g.
13373   //   template <class T> class A<T>::B;
13374   // FIXME: we don't support these right now.
13375   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13376     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13377   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13378   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13379   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13380   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13381   TL.setElaboratedKeywordLoc(TagLoc);
13382   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13383   TL.setNameLoc(NameLoc);
13384 
13385   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13386                                           TSI, FriendLoc, TempParamLists);
13387   Friend->setAccess(AS_public);
13388   Friend->setUnsupportedFriend(true);
13389   CurContext->addDecl(Friend);
13390   return Friend;
13391 }
13392 
13393 
13394 /// Handle a friend type declaration.  This works in tandem with
13395 /// ActOnTag.
13396 ///
13397 /// Notes on friend class templates:
13398 ///
13399 /// We generally treat friend class declarations as if they were
13400 /// declaring a class.  So, for example, the elaborated type specifier
13401 /// in a friend declaration is required to obey the restrictions of a
13402 /// class-head (i.e. no typedefs in the scope chain), template
13403 /// parameters are required to match up with simple template-ids, &c.
13404 /// However, unlike when declaring a template specialization, it's
13405 /// okay to refer to a template specialization without an empty
13406 /// template parameter declaration, e.g.
13407 ///   friend class A<T>::B<unsigned>;
13408 /// We permit this as a special case; if there are any template
13409 /// parameters present at all, require proper matching, i.e.
13410 ///   template <> template \<class T> friend class A<int>::B;
13411 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13412                                 MultiTemplateParamsArg TempParams) {
13413   SourceLocation Loc = DS.getLocStart();
13414 
13415   assert(DS.isFriendSpecified());
13416   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13417 
13418   // Try to convert the decl specifier to a type.  This works for
13419   // friend templates because ActOnTag never produces a ClassTemplateDecl
13420   // for a TUK_Friend.
13421   Declarator TheDeclarator(DS, Declarator::MemberContext);
13422   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13423   QualType T = TSI->getType();
13424   if (TheDeclarator.isInvalidType())
13425     return nullptr;
13426 
13427   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13428     return nullptr;
13429 
13430   // This is definitely an error in C++98.  It's probably meant to
13431   // be forbidden in C++0x, too, but the specification is just
13432   // poorly written.
13433   //
13434   // The problem is with declarations like the following:
13435   //   template <T> friend A<T>::foo;
13436   // where deciding whether a class C is a friend or not now hinges
13437   // on whether there exists an instantiation of A that causes
13438   // 'foo' to equal C.  There are restrictions on class-heads
13439   // (which we declare (by fiat) elaborated friend declarations to
13440   // be) that makes this tractable.
13441   //
13442   // FIXME: handle "template <> friend class A<T>;", which
13443   // is possibly well-formed?  Who even knows?
13444   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13445     Diag(Loc, diag::err_tagless_friend_type_template)
13446       << DS.getSourceRange();
13447     return nullptr;
13448   }
13449 
13450   // C++98 [class.friend]p1: A friend of a class is a function
13451   //   or class that is not a member of the class . . .
13452   // This is fixed in DR77, which just barely didn't make the C++03
13453   // deadline.  It's also a very silly restriction that seriously
13454   // affects inner classes and which nobody else seems to implement;
13455   // thus we never diagnose it, not even in -pedantic.
13456   //
13457   // But note that we could warn about it: it's always useless to
13458   // friend one of your own members (it's not, however, worthless to
13459   // friend a member of an arbitrary specialization of your template).
13460 
13461   Decl *D;
13462   if (!TempParams.empty())
13463     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13464                                    TempParams,
13465                                    TSI,
13466                                    DS.getFriendSpecLoc());
13467   else
13468     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13469 
13470   if (!D)
13471     return nullptr;
13472 
13473   D->setAccess(AS_public);
13474   CurContext->addDecl(D);
13475 
13476   return D;
13477 }
13478 
13479 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13480                                         MultiTemplateParamsArg TemplateParams) {
13481   const DeclSpec &DS = D.getDeclSpec();
13482 
13483   assert(DS.isFriendSpecified());
13484   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13485 
13486   SourceLocation Loc = D.getIdentifierLoc();
13487   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13488 
13489   // C++ [class.friend]p1
13490   //   A friend of a class is a function or class....
13491   // Note that this sees through typedefs, which is intended.
13492   // It *doesn't* see through dependent types, which is correct
13493   // according to [temp.arg.type]p3:
13494   //   If a declaration acquires a function type through a
13495   //   type dependent on a template-parameter and this causes
13496   //   a declaration that does not use the syntactic form of a
13497   //   function declarator to have a function type, the program
13498   //   is ill-formed.
13499   if (!TInfo->getType()->isFunctionType()) {
13500     Diag(Loc, diag::err_unexpected_friend);
13501 
13502     // It might be worthwhile to try to recover by creating an
13503     // appropriate declaration.
13504     return nullptr;
13505   }
13506 
13507   // C++ [namespace.memdef]p3
13508   //  - If a friend declaration in a non-local class first declares a
13509   //    class or function, the friend class or function is a member
13510   //    of the innermost enclosing namespace.
13511   //  - The name of the friend is not found by simple name lookup
13512   //    until a matching declaration is provided in that namespace
13513   //    scope (either before or after the class declaration granting
13514   //    friendship).
13515   //  - If a friend function is called, its name may be found by the
13516   //    name lookup that considers functions from namespaces and
13517   //    classes associated with the types of the function arguments.
13518   //  - When looking for a prior declaration of a class or a function
13519   //    declared as a friend, scopes outside the innermost enclosing
13520   //    namespace scope are not considered.
13521 
13522   CXXScopeSpec &SS = D.getCXXScopeSpec();
13523   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13524   DeclarationName Name = NameInfo.getName();
13525   assert(Name);
13526 
13527   // Check for unexpanded parameter packs.
13528   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13529       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13530       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13531     return nullptr;
13532 
13533   // The context we found the declaration in, or in which we should
13534   // create the declaration.
13535   DeclContext *DC;
13536   Scope *DCScope = S;
13537   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13538                         ForRedeclaration);
13539 
13540   // There are five cases here.
13541   //   - There's no scope specifier and we're in a local class. Only look
13542   //     for functions declared in the immediately-enclosing block scope.
13543   // We recover from invalid scope qualifiers as if they just weren't there.
13544   FunctionDecl *FunctionContainingLocalClass = nullptr;
13545   if ((SS.isInvalid() || !SS.isSet()) &&
13546       (FunctionContainingLocalClass =
13547            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13548     // C++11 [class.friend]p11:
13549     //   If a friend declaration appears in a local class and the name
13550     //   specified is an unqualified name, a prior declaration is
13551     //   looked up without considering scopes that are outside the
13552     //   innermost enclosing non-class scope. For a friend function
13553     //   declaration, if there is no prior declaration, the program is
13554     //   ill-formed.
13555 
13556     // Find the innermost enclosing non-class scope. This is the block
13557     // scope containing the local class definition (or for a nested class,
13558     // the outer local class).
13559     DCScope = S->getFnParent();
13560 
13561     // Look up the function name in the scope.
13562     Previous.clear(LookupLocalFriendName);
13563     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13564 
13565     if (!Previous.empty()) {
13566       // All possible previous declarations must have the same context:
13567       // either they were declared at block scope or they are members of
13568       // one of the enclosing local classes.
13569       DC = Previous.getRepresentativeDecl()->getDeclContext();
13570     } else {
13571       // This is ill-formed, but provide the context that we would have
13572       // declared the function in, if we were permitted to, for error recovery.
13573       DC = FunctionContainingLocalClass;
13574     }
13575     adjustContextForLocalExternDecl(DC);
13576 
13577     // C++ [class.friend]p6:
13578     //   A function can be defined in a friend declaration of a class if and
13579     //   only if the class is a non-local class (9.8), the function name is
13580     //   unqualified, and the function has namespace scope.
13581     if (D.isFunctionDefinition()) {
13582       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13583     }
13584 
13585   //   - There's no scope specifier, in which case we just go to the
13586   //     appropriate scope and look for a function or function template
13587   //     there as appropriate.
13588   } else if (SS.isInvalid() || !SS.isSet()) {
13589     // C++11 [namespace.memdef]p3:
13590     //   If the name in a friend declaration is neither qualified nor
13591     //   a template-id and the declaration is a function or an
13592     //   elaborated-type-specifier, the lookup to determine whether
13593     //   the entity has been previously declared shall not consider
13594     //   any scopes outside the innermost enclosing namespace.
13595     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
13596 
13597     // Find the appropriate context according to the above.
13598     DC = CurContext;
13599 
13600     // Skip class contexts.  If someone can cite chapter and verse
13601     // for this behavior, that would be nice --- it's what GCC and
13602     // EDG do, and it seems like a reasonable intent, but the spec
13603     // really only says that checks for unqualified existing
13604     // declarations should stop at the nearest enclosing namespace,
13605     // not that they should only consider the nearest enclosing
13606     // namespace.
13607     while (DC->isRecord())
13608       DC = DC->getParent();
13609 
13610     DeclContext *LookupDC = DC;
13611     while (LookupDC->isTransparentContext())
13612       LookupDC = LookupDC->getParent();
13613 
13614     while (true) {
13615       LookupQualifiedName(Previous, LookupDC);
13616 
13617       if (!Previous.empty()) {
13618         DC = LookupDC;
13619         break;
13620       }
13621 
13622       if (isTemplateId) {
13623         if (isa<TranslationUnitDecl>(LookupDC)) break;
13624       } else {
13625         if (LookupDC->isFileContext()) break;
13626       }
13627       LookupDC = LookupDC->getParent();
13628     }
13629 
13630     DCScope = getScopeForDeclContext(S, DC);
13631 
13632   //   - There's a non-dependent scope specifier, in which case we
13633   //     compute it and do a previous lookup there for a function
13634   //     or function template.
13635   } else if (!SS.getScopeRep()->isDependent()) {
13636     DC = computeDeclContext(SS);
13637     if (!DC) return nullptr;
13638 
13639     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
13640 
13641     LookupQualifiedName(Previous, DC);
13642 
13643     // Ignore things found implicitly in the wrong scope.
13644     // TODO: better diagnostics for this case.  Suggesting the right
13645     // qualified scope would be nice...
13646     LookupResult::Filter F = Previous.makeFilter();
13647     while (F.hasNext()) {
13648       NamedDecl *D = F.next();
13649       if (!DC->InEnclosingNamespaceSetOf(
13650               D->getDeclContext()->getRedeclContext()))
13651         F.erase();
13652     }
13653     F.done();
13654 
13655     if (Previous.empty()) {
13656       D.setInvalidType();
13657       Diag(Loc, diag::err_qualified_friend_not_found)
13658           << Name << TInfo->getType();
13659       return nullptr;
13660     }
13661 
13662     // C++ [class.friend]p1: A friend of a class is a function or
13663     //   class that is not a member of the class . . .
13664     if (DC->Equals(CurContext))
13665       Diag(DS.getFriendSpecLoc(),
13666            getLangOpts().CPlusPlus11 ?
13667              diag::warn_cxx98_compat_friend_is_member :
13668              diag::err_friend_is_member);
13669 
13670     if (D.isFunctionDefinition()) {
13671       // C++ [class.friend]p6:
13672       //   A function can be defined in a friend declaration of a class if and
13673       //   only if the class is a non-local class (9.8), the function name is
13674       //   unqualified, and the function has namespace scope.
13675       SemaDiagnosticBuilder DB
13676         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13677 
13678       DB << SS.getScopeRep();
13679       if (DC->isFileContext())
13680         DB << FixItHint::CreateRemoval(SS.getRange());
13681       SS.clear();
13682     }
13683 
13684   //   - There's a scope specifier that does not match any template
13685   //     parameter lists, in which case we use some arbitrary context,
13686   //     create a method or method template, and wait for instantiation.
13687   //   - There's a scope specifier that does match some template
13688   //     parameter lists, which we don't handle right now.
13689   } else {
13690     if (D.isFunctionDefinition()) {
13691       // C++ [class.friend]p6:
13692       //   A function can be defined in a friend declaration of a class if and
13693       //   only if the class is a non-local class (9.8), the function name is
13694       //   unqualified, and the function has namespace scope.
13695       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13696         << SS.getScopeRep();
13697     }
13698 
13699     DC = CurContext;
13700     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
13701   }
13702 
13703   if (!DC->isRecord()) {
13704     int DiagArg = -1;
13705     switch (D.getName().getKind()) {
13706     case UnqualifiedId::IK_ConstructorTemplateId:
13707     case UnqualifiedId::IK_ConstructorName:
13708       DiagArg = 0;
13709       break;
13710     case UnqualifiedId::IK_DestructorName:
13711       DiagArg = 1;
13712       break;
13713     case UnqualifiedId::IK_ConversionFunctionId:
13714       DiagArg = 2;
13715       break;
13716     case UnqualifiedId::IK_Identifier:
13717     case UnqualifiedId::IK_ImplicitSelfParam:
13718     case UnqualifiedId::IK_LiteralOperatorId:
13719     case UnqualifiedId::IK_OperatorFunctionId:
13720     case UnqualifiedId::IK_TemplateId:
13721       break;
13722     }
13723     // This implies that it has to be an operator or function.
13724     if (DiagArg >= 0) {
13725       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
13726       return nullptr;
13727     }
13728   }
13729 
13730   // FIXME: This is an egregious hack to cope with cases where the scope stack
13731   // does not contain the declaration context, i.e., in an out-of-line
13732   // definition of a class.
13733   Scope FakeDCScope(S, Scope::DeclScope, Diags);
13734   if (!DCScope) {
13735     FakeDCScope.setEntity(DC);
13736     DCScope = &FakeDCScope;
13737   }
13738 
13739   bool AddToScope = true;
13740   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
13741                                           TemplateParams, AddToScope);
13742   if (!ND) return nullptr;
13743 
13744   assert(ND->getLexicalDeclContext() == CurContext);
13745 
13746   // If we performed typo correction, we might have added a scope specifier
13747   // and changed the decl context.
13748   DC = ND->getDeclContext();
13749 
13750   // Add the function declaration to the appropriate lookup tables,
13751   // adjusting the redeclarations list as necessary.  We don't
13752   // want to do this yet if the friending class is dependent.
13753   //
13754   // Also update the scope-based lookup if the target context's
13755   // lookup context is in lexical scope.
13756   if (!CurContext->isDependentContext()) {
13757     DC = DC->getRedeclContext();
13758     DC->makeDeclVisibleInContext(ND);
13759     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13760       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
13761   }
13762 
13763   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
13764                                        D.getIdentifierLoc(), ND,
13765                                        DS.getFriendSpecLoc());
13766   FrD->setAccess(AS_public);
13767   CurContext->addDecl(FrD);
13768 
13769   if (ND->isInvalidDecl()) {
13770     FrD->setInvalidDecl();
13771   } else {
13772     if (DC->isRecord()) CheckFriendAccess(ND);
13773 
13774     FunctionDecl *FD;
13775     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13776       FD = FTD->getTemplatedDecl();
13777     else
13778       FD = cast<FunctionDecl>(ND);
13779 
13780     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13781     // default argument expression, that declaration shall be a definition
13782     // and shall be the only declaration of the function or function
13783     // template in the translation unit.
13784     if (functionDeclHasDefaultArgument(FD)) {
13785       // We can't look at FD->getPreviousDecl() because it may not have been set
13786       // if we're in a dependent context. If we get this far with a non-empty
13787       // Previous set, we must have a valid previous declaration of this
13788       // function.
13789       if (!Previous.empty()) {
13790         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
13791         Diag(Previous.getRepresentativeDecl()->getLocation(),
13792              diag::note_previous_declaration);
13793       } else if (!D.isFunctionDefinition())
13794         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13795     }
13796 
13797     // Mark templated-scope function declarations as unsupported.
13798     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13799       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13800         << SS.getScopeRep() << SS.getRange()
13801         << cast<CXXRecordDecl>(CurContext);
13802       FrD->setUnsupportedFriend(true);
13803     }
13804   }
13805 
13806   return ND;
13807 }
13808 
13809 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13810   AdjustDeclIfTemplate(Dcl);
13811 
13812   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
13813   if (!Fn) {
13814     Diag(DelLoc, diag::err_deleted_non_function);
13815     return;
13816   }
13817 
13818   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
13819     // Don't consider the implicit declaration we generate for explicit
13820     // specializations. FIXME: Do not generate these implicit declarations.
13821     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13822          Prev->getPreviousDecl()) &&
13823         !Prev->isDefined()) {
13824       Diag(DelLoc, diag::err_deleted_decl_not_first);
13825       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13826            Prev->isImplicit() ? diag::note_previous_implicit_declaration
13827                               : diag::note_previous_declaration);
13828     }
13829     // If the declaration wasn't the first, we delete the function anyway for
13830     // recovery.
13831     Fn = Fn->getCanonicalDecl();
13832   }
13833 
13834   // dllimport/dllexport cannot be deleted.
13835   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13836     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13837     Fn->setInvalidDecl();
13838   }
13839 
13840   if (Fn->isDeleted())
13841     return;
13842 
13843   // See if we're deleting a function which is already known to override a
13844   // non-deleted virtual function.
13845   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13846     bool IssuedDiagnostic = false;
13847     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13848                                         E = MD->end_overridden_methods();
13849          I != E; ++I) {
13850       if (!(*MD->begin_overridden_methods())->isDeleted()) {
13851         if (!IssuedDiagnostic) {
13852           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13853           IssuedDiagnostic = true;
13854         }
13855         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13856       }
13857     }
13858   }
13859 
13860   // C++11 [basic.start.main]p3:
13861   //   A program that defines main as deleted [...] is ill-formed.
13862   if (Fn->isMain())
13863     Diag(DelLoc, diag::err_deleted_main);
13864 
13865   Fn->setDeletedAsWritten();
13866 }
13867 
13868 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
13869   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
13870 
13871   if (MD) {
13872     if (MD->getParent()->isDependentType()) {
13873       MD->setDefaulted();
13874       MD->setExplicitlyDefaulted();
13875       return;
13876     }
13877 
13878     CXXSpecialMember Member = getSpecialMember(MD);
13879     if (Member == CXXInvalid) {
13880       if (!MD->isInvalidDecl())
13881         Diag(DefaultLoc, diag::err_default_special_members);
13882       return;
13883     }
13884 
13885     MD->setDefaulted();
13886     MD->setExplicitlyDefaulted();
13887 
13888     // If this definition appears within the record, do the checking when
13889     // the record is complete.
13890     const FunctionDecl *Primary = MD;
13891     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
13892       // Ask the template instantiation pattern that actually had the
13893       // '= default' on it.
13894       Primary = Pattern;
13895 
13896     // If the method was defaulted on its first declaration, we will have
13897     // already performed the checking in CheckCompletedCXXClass. Such a
13898     // declaration doesn't trigger an implicit definition.
13899     if (Primary->getCanonicalDecl()->isDefaulted())
13900       return;
13901 
13902     CheckExplicitlyDefaultedSpecialMember(MD);
13903 
13904     if (!MD->isInvalidDecl())
13905       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
13906   } else {
13907     Diag(DefaultLoc, diag::err_default_special_members);
13908   }
13909 }
13910 
13911 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
13912   for (Stmt *SubStmt : S->children()) {
13913     if (!SubStmt)
13914       continue;
13915     if (isa<ReturnStmt>(SubStmt))
13916       Self.Diag(SubStmt->getLocStart(),
13917            diag::err_return_in_constructor_handler);
13918     if (!isa<Expr>(SubStmt))
13919       SearchForReturnInStmt(Self, SubStmt);
13920   }
13921 }
13922 
13923 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13924   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13925     CXXCatchStmt *Handler = TryBlock->getHandler(I);
13926     SearchForReturnInStmt(*this, Handler);
13927   }
13928 }
13929 
13930 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
13931                                              const CXXMethodDecl *Old) {
13932   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13933   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13934 
13935   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13936 
13937   // If the calling conventions match, everything is fine
13938   if (NewCC == OldCC)
13939     return false;
13940 
13941   // If the calling conventions mismatch because the new function is static,
13942   // suppress the calling convention mismatch error; the error about static
13943   // function override (err_static_overrides_virtual from
13944   // Sema::CheckFunctionDeclaration) is more clear.
13945   if (New->getStorageClass() == SC_Static)
13946     return false;
13947 
13948   Diag(New->getLocation(),
13949        diag::err_conflicting_overriding_cc_attributes)
13950     << New->getDeclName() << New->getType() << Old->getType();
13951   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13952   return true;
13953 }
13954 
13955 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
13956                                              const CXXMethodDecl *Old) {
13957   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13958   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
13959 
13960   if (Context.hasSameType(NewTy, OldTy) ||
13961       NewTy->isDependentType() || OldTy->isDependentType())
13962     return false;
13963 
13964   // Check if the return types are covariant
13965   QualType NewClassTy, OldClassTy;
13966 
13967   /// Both types must be pointers or references to classes.
13968   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13969     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
13970       NewClassTy = NewPT->getPointeeType();
13971       OldClassTy = OldPT->getPointeeType();
13972     }
13973   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
13974     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13975       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13976         NewClassTy = NewRT->getPointeeType();
13977         OldClassTy = OldRT->getPointeeType();
13978       }
13979     }
13980   }
13981 
13982   // The return types aren't either both pointers or references to a class type.
13983   if (NewClassTy.isNull()) {
13984     Diag(New->getLocation(),
13985          diag::err_different_return_type_for_overriding_virtual_function)
13986         << New->getDeclName() << NewTy << OldTy
13987         << New->getReturnTypeSourceRange();
13988     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13989         << Old->getReturnTypeSourceRange();
13990 
13991     return true;
13992   }
13993 
13994   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
13995     // C++14 [class.virtual]p8:
13996     //   If the class type in the covariant return type of D::f differs from
13997     //   that of B::f, the class type in the return type of D::f shall be
13998     //   complete at the point of declaration of D::f or shall be the class
13999     //   type D.
14000     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14001       if (!RT->isBeingDefined() &&
14002           RequireCompleteType(New->getLocation(), NewClassTy,
14003                               diag::err_covariant_return_incomplete,
14004                               New->getDeclName()))
14005         return true;
14006     }
14007 
14008     // Check if the new class derives from the old class.
14009     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14010       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14011           << New->getDeclName() << NewTy << OldTy
14012           << New->getReturnTypeSourceRange();
14013       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14014           << Old->getReturnTypeSourceRange();
14015       return true;
14016     }
14017 
14018     // Check if we the conversion from derived to base is valid.
14019     if (CheckDerivedToBaseConversion(
14020             NewClassTy, OldClassTy,
14021             diag::err_covariant_return_inaccessible_base,
14022             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14023             New->getLocation(), New->getReturnTypeSourceRange(),
14024             New->getDeclName(), nullptr)) {
14025       // FIXME: this note won't trigger for delayed access control
14026       // diagnostics, and it's impossible to get an undelayed error
14027       // here from access control during the original parse because
14028       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14029       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14030           << Old->getReturnTypeSourceRange();
14031       return true;
14032     }
14033   }
14034 
14035   // The qualifiers of the return types must be the same.
14036   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14037     Diag(New->getLocation(),
14038          diag::err_covariant_return_type_different_qualifications)
14039         << New->getDeclName() << NewTy << OldTy
14040         << New->getReturnTypeSourceRange();
14041     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14042         << Old->getReturnTypeSourceRange();
14043     return true;
14044   }
14045 
14046 
14047   // The new class type must have the same or less qualifiers as the old type.
14048   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14049     Diag(New->getLocation(),
14050          diag::err_covariant_return_type_class_type_more_qualified)
14051         << New->getDeclName() << NewTy << OldTy
14052         << New->getReturnTypeSourceRange();
14053     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14054         << Old->getReturnTypeSourceRange();
14055     return true;
14056   }
14057 
14058   return false;
14059 }
14060 
14061 /// \brief Mark the given method pure.
14062 ///
14063 /// \param Method the method to be marked pure.
14064 ///
14065 /// \param InitRange the source range that covers the "0" initializer.
14066 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14067   SourceLocation EndLoc = InitRange.getEnd();
14068   if (EndLoc.isValid())
14069     Method->setRangeEnd(EndLoc);
14070 
14071   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14072     Method->setPure();
14073     return false;
14074   }
14075 
14076   if (!Method->isInvalidDecl())
14077     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14078       << Method->getDeclName() << InitRange;
14079   return true;
14080 }
14081 
14082 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14083   if (D->getFriendObjectKind())
14084     Diag(D->getLocation(), diag::err_pure_friend);
14085   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14086     CheckPureMethod(M, ZeroLoc);
14087   else
14088     Diag(D->getLocation(), diag::err_illegal_initializer);
14089 }
14090 
14091 /// \brief Determine whether the given declaration is a static data member.
14092 static bool isStaticDataMember(const Decl *D) {
14093   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14094     return Var->isStaticDataMember();
14095 
14096   return false;
14097 }
14098 
14099 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14100 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
14101 /// is a fresh scope pushed for just this purpose.
14102 ///
14103 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14104 /// static data member of class X, names should be looked up in the scope of
14105 /// class X.
14106 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14107   // If there is no declaration, there was an error parsing it.
14108   if (!D || D->isInvalidDecl())
14109     return;
14110 
14111   // We will always have a nested name specifier here, but this declaration
14112   // might not be out of line if the specifier names the current namespace:
14113   //   extern int n;
14114   //   int ::n = 0;
14115   if (D->isOutOfLine())
14116     EnterDeclaratorContext(S, D->getDeclContext());
14117 
14118   // If we are parsing the initializer for a static data member, push a
14119   // new expression evaluation context that is associated with this static
14120   // data member.
14121   if (isStaticDataMember(D))
14122     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
14123 }
14124 
14125 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
14126 /// initializer for the out-of-line declaration 'D'.
14127 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14128   // If there is no declaration, there was an error parsing it.
14129   if (!D || D->isInvalidDecl())
14130     return;
14131 
14132   if (isStaticDataMember(D))
14133     PopExpressionEvaluationContext();
14134 
14135   if (D->isOutOfLine())
14136     ExitDeclaratorContext(S);
14137 }
14138 
14139 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14140 /// C++ if/switch/while/for statement.
14141 /// e.g: "if (int x = f()) {...}"
14142 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14143   // C++ 6.4p2:
14144   // The declarator shall not specify a function or an array.
14145   // The type-specifier-seq shall not contain typedef and shall not declare a
14146   // new class or enumeration.
14147   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14148          "Parser allowed 'typedef' as storage class of condition decl.");
14149 
14150   Decl *Dcl = ActOnDeclarator(S, D);
14151   if (!Dcl)
14152     return true;
14153 
14154   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14155     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14156       << D.getSourceRange();
14157     return true;
14158   }
14159 
14160   return Dcl;
14161 }
14162 
14163 void Sema::LoadExternalVTableUses() {
14164   if (!ExternalSource)
14165     return;
14166 
14167   SmallVector<ExternalVTableUse, 4> VTables;
14168   ExternalSource->ReadUsedVTables(VTables);
14169   SmallVector<VTableUse, 4> NewUses;
14170   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14171     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14172       = VTablesUsed.find(VTables[I].Record);
14173     // Even if a definition wasn't required before, it may be required now.
14174     if (Pos != VTablesUsed.end()) {
14175       if (!Pos->second && VTables[I].DefinitionRequired)
14176         Pos->second = true;
14177       continue;
14178     }
14179 
14180     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14181     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14182   }
14183 
14184   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14185 }
14186 
14187 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14188                           bool DefinitionRequired) {
14189   // Ignore any vtable uses in unevaluated operands or for classes that do
14190   // not have a vtable.
14191   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14192       CurContext->isDependentContext() || isUnevaluatedContext())
14193     return;
14194 
14195   // Try to insert this class into the map.
14196   LoadExternalVTableUses();
14197   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14198   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14199     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14200   if (!Pos.second) {
14201     // If we already had an entry, check to see if we are promoting this vtable
14202     // to require a definition. If so, we need to reappend to the VTableUses
14203     // list, since we may have already processed the first entry.
14204     if (DefinitionRequired && !Pos.first->second) {
14205       Pos.first->second = true;
14206     } else {
14207       // Otherwise, we can early exit.
14208       return;
14209     }
14210   } else {
14211     // The Microsoft ABI requires that we perform the destructor body
14212     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14213     // the deleting destructor is emitted with the vtable, not with the
14214     // destructor definition as in the Itanium ABI.
14215     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14216       CXXDestructorDecl *DD = Class->getDestructor();
14217       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14218         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14219           // If this is an out-of-line declaration, marking it referenced will
14220           // not do anything. Manually call CheckDestructor to look up operator
14221           // delete().
14222           ContextRAII SavedContext(*this, DD);
14223           CheckDestructor(DD);
14224         } else {
14225           MarkFunctionReferenced(Loc, Class->getDestructor());
14226         }
14227       }
14228     }
14229   }
14230 
14231   // Local classes need to have their virtual members marked
14232   // immediately. For all other classes, we mark their virtual members
14233   // at the end of the translation unit.
14234   if (Class->isLocalClass())
14235     MarkVirtualMembersReferenced(Loc, Class);
14236   else
14237     VTableUses.push_back(std::make_pair(Class, Loc));
14238 }
14239 
14240 bool Sema::DefineUsedVTables() {
14241   LoadExternalVTableUses();
14242   if (VTableUses.empty())
14243     return false;
14244 
14245   // Note: The VTableUses vector could grow as a result of marking
14246   // the members of a class as "used", so we check the size each
14247   // time through the loop and prefer indices (which are stable) to
14248   // iterators (which are not).
14249   bool DefinedAnything = false;
14250   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14251     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14252     if (!Class)
14253       continue;
14254 
14255     SourceLocation Loc = VTableUses[I].second;
14256 
14257     bool DefineVTable = true;
14258 
14259     // If this class has a key function, but that key function is
14260     // defined in another translation unit, we don't need to emit the
14261     // vtable even though we're using it.
14262     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14263     if (KeyFunction && !KeyFunction->hasBody()) {
14264       // The key function is in another translation unit.
14265       DefineVTable = false;
14266       TemplateSpecializationKind TSK =
14267           KeyFunction->getTemplateSpecializationKind();
14268       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14269              TSK != TSK_ImplicitInstantiation &&
14270              "Instantiations don't have key functions");
14271       (void)TSK;
14272     } else if (!KeyFunction) {
14273       // If we have a class with no key function that is the subject
14274       // of an explicit instantiation declaration, suppress the
14275       // vtable; it will live with the explicit instantiation
14276       // definition.
14277       bool IsExplicitInstantiationDeclaration
14278         = Class->getTemplateSpecializationKind()
14279                                       == TSK_ExplicitInstantiationDeclaration;
14280       for (auto R : Class->redecls()) {
14281         TemplateSpecializationKind TSK
14282           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14283         if (TSK == TSK_ExplicitInstantiationDeclaration)
14284           IsExplicitInstantiationDeclaration = true;
14285         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14286           IsExplicitInstantiationDeclaration = false;
14287           break;
14288         }
14289       }
14290 
14291       if (IsExplicitInstantiationDeclaration)
14292         DefineVTable = false;
14293     }
14294 
14295     // The exception specifications for all virtual members may be needed even
14296     // if we are not providing an authoritative form of the vtable in this TU.
14297     // We may choose to emit it available_externally anyway.
14298     if (!DefineVTable) {
14299       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14300       continue;
14301     }
14302 
14303     // Mark all of the virtual members of this class as referenced, so
14304     // that we can build a vtable. Then, tell the AST consumer that a
14305     // vtable for this class is required.
14306     DefinedAnything = true;
14307     MarkVirtualMembersReferenced(Loc, Class);
14308     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14309     if (VTablesUsed[Canonical])
14310       Consumer.HandleVTable(Class);
14311 
14312     // Optionally warn if we're emitting a weak vtable.
14313     if (Class->isExternallyVisible() &&
14314         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
14315       const FunctionDecl *KeyFunctionDef = nullptr;
14316       if (!KeyFunction ||
14317           (KeyFunction->hasBody(KeyFunctionDef) &&
14318            KeyFunctionDef->isInlined()))
14319         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
14320              TSK_ExplicitInstantiationDefinition
14321              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
14322           << Class;
14323     }
14324   }
14325   VTableUses.clear();
14326 
14327   return DefinedAnything;
14328 }
14329 
14330 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14331                                                  const CXXRecordDecl *RD) {
14332   for (const auto *I : RD->methods())
14333     if (I->isVirtual() && !I->isPure())
14334       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14335 }
14336 
14337 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14338                                         const CXXRecordDecl *RD) {
14339   // Mark all functions which will appear in RD's vtable as used.
14340   CXXFinalOverriderMap FinalOverriders;
14341   RD->getFinalOverriders(FinalOverriders);
14342   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14343                                             E = FinalOverriders.end();
14344        I != E; ++I) {
14345     for (OverridingMethods::const_iterator OI = I->second.begin(),
14346                                            OE = I->second.end();
14347          OI != OE; ++OI) {
14348       assert(OI->second.size() > 0 && "no final overrider");
14349       CXXMethodDecl *Overrider = OI->second.front().Method;
14350 
14351       // C++ [basic.def.odr]p2:
14352       //   [...] A virtual member function is used if it is not pure. [...]
14353       if (!Overrider->isPure())
14354         MarkFunctionReferenced(Loc, Overrider);
14355     }
14356   }
14357 
14358   // Only classes that have virtual bases need a VTT.
14359   if (RD->getNumVBases() == 0)
14360     return;
14361 
14362   for (const auto &I : RD->bases()) {
14363     const CXXRecordDecl *Base =
14364         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14365     if (Base->getNumVBases() == 0)
14366       continue;
14367     MarkVirtualMembersReferenced(Loc, Base);
14368   }
14369 }
14370 
14371 /// SetIvarInitializers - This routine builds initialization ASTs for the
14372 /// Objective-C implementation whose ivars need be initialized.
14373 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14374   if (!getLangOpts().CPlusPlus)
14375     return;
14376   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14377     SmallVector<ObjCIvarDecl*, 8> ivars;
14378     CollectIvarsToConstructOrDestruct(OID, ivars);
14379     if (ivars.empty())
14380       return;
14381     SmallVector<CXXCtorInitializer*, 32> AllToInit;
14382     for (unsigned i = 0; i < ivars.size(); i++) {
14383       FieldDecl *Field = ivars[i];
14384       if (Field->isInvalidDecl())
14385         continue;
14386 
14387       CXXCtorInitializer *Member;
14388       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14389       InitializationKind InitKind =
14390         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14391 
14392       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14393       ExprResult MemberInit =
14394         InitSeq.Perform(*this, InitEntity, InitKind, None);
14395       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14396       // Note, MemberInit could actually come back empty if no initialization
14397       // is required (e.g., because it would call a trivial default constructor)
14398       if (!MemberInit.get() || MemberInit.isInvalid())
14399         continue;
14400 
14401       Member =
14402         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14403                                          SourceLocation(),
14404                                          MemberInit.getAs<Expr>(),
14405                                          SourceLocation());
14406       AllToInit.push_back(Member);
14407 
14408       // Be sure that the destructor is accessible and is marked as referenced.
14409       if (const RecordType *RecordTy =
14410               Context.getBaseElementType(Field->getType())
14411                   ->getAs<RecordType>()) {
14412         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14413         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14414           MarkFunctionReferenced(Field->getLocation(), Destructor);
14415           CheckDestructorAccess(Field->getLocation(), Destructor,
14416                             PDiag(diag::err_access_dtor_ivar)
14417                               << Context.getBaseElementType(Field->getType()));
14418         }
14419       }
14420     }
14421     ObjCImplementation->setIvarInitializers(Context,
14422                                             AllToInit.data(), AllToInit.size());
14423   }
14424 }
14425 
14426 static
14427 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14428                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14429                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14430                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14431                            Sema &S) {
14432   if (Ctor->isInvalidDecl())
14433     return;
14434 
14435   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14436 
14437   // Target may not be determinable yet, for instance if this is a dependent
14438   // call in an uninstantiated template.
14439   if (Target) {
14440     const FunctionDecl *FNTarget = nullptr;
14441     (void)Target->hasBody(FNTarget);
14442     Target = const_cast<CXXConstructorDecl*>(
14443       cast_or_null<CXXConstructorDecl>(FNTarget));
14444   }
14445 
14446   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14447                      // Avoid dereferencing a null pointer here.
14448                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14449 
14450   if (!Current.insert(Canonical).second)
14451     return;
14452 
14453   // We know that beyond here, we aren't chaining into a cycle.
14454   if (!Target || !Target->isDelegatingConstructor() ||
14455       Target->isInvalidDecl() || Valid.count(TCanonical)) {
14456     Valid.insert(Current.begin(), Current.end());
14457     Current.clear();
14458   // We've hit a cycle.
14459   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14460              Current.count(TCanonical)) {
14461     // If we haven't diagnosed this cycle yet, do so now.
14462     if (!Invalid.count(TCanonical)) {
14463       S.Diag((*Ctor->init_begin())->getSourceLocation(),
14464              diag::warn_delegating_ctor_cycle)
14465         << Ctor;
14466 
14467       // Don't add a note for a function delegating directly to itself.
14468       if (TCanonical != Canonical)
14469         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14470 
14471       CXXConstructorDecl *C = Target;
14472       while (C->getCanonicalDecl() != Canonical) {
14473         const FunctionDecl *FNTarget = nullptr;
14474         (void)C->getTargetConstructor()->hasBody(FNTarget);
14475         assert(FNTarget && "Ctor cycle through bodiless function");
14476 
14477         C = const_cast<CXXConstructorDecl*>(
14478           cast<CXXConstructorDecl>(FNTarget));
14479         S.Diag(C->getLocation(), diag::note_which_delegates_to);
14480       }
14481     }
14482 
14483     Invalid.insert(Current.begin(), Current.end());
14484     Current.clear();
14485   } else {
14486     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14487   }
14488 }
14489 
14490 
14491 void Sema::CheckDelegatingCtorCycles() {
14492   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14493 
14494   for (DelegatingCtorDeclsType::iterator
14495          I = DelegatingCtorDecls.begin(ExternalSource),
14496          E = DelegatingCtorDecls.end();
14497        I != E; ++I)
14498     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14499 
14500   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14501                                                          CE = Invalid.end();
14502        CI != CE; ++CI)
14503     (*CI)->setInvalidDecl();
14504 }
14505 
14506 namespace {
14507   /// \brief AST visitor that finds references to the 'this' expression.
14508   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14509     Sema &S;
14510 
14511   public:
14512     explicit FindCXXThisExpr(Sema &S) : S(S) { }
14513 
14514     bool VisitCXXThisExpr(CXXThisExpr *E) {
14515       S.Diag(E->getLocation(), diag::err_this_static_member_func)
14516         << E->isImplicit();
14517       return false;
14518     }
14519   };
14520 }
14521 
14522 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14523   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14524   if (!TSInfo)
14525     return false;
14526 
14527   TypeLoc TL = TSInfo->getTypeLoc();
14528   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14529   if (!ProtoTL)
14530     return false;
14531 
14532   // C++11 [expr.prim.general]p3:
14533   //   [The expression this] shall not appear before the optional
14534   //   cv-qualifier-seq and it shall not appear within the declaration of a
14535   //   static member function (although its type and value category are defined
14536   //   within a static member function as they are within a non-static member
14537   //   function). [ Note: this is because declaration matching does not occur
14538   //  until the complete declarator is known. - end note ]
14539   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14540   FindCXXThisExpr Finder(*this);
14541 
14542   // If the return type came after the cv-qualifier-seq, check it now.
14543   if (Proto->hasTrailingReturn() &&
14544       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14545     return true;
14546 
14547   // Check the exception specification.
14548   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14549     return true;
14550 
14551   return checkThisInStaticMemberFunctionAttributes(Method);
14552 }
14553 
14554 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14555   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14556   if (!TSInfo)
14557     return false;
14558 
14559   TypeLoc TL = TSInfo->getTypeLoc();
14560   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14561   if (!ProtoTL)
14562     return false;
14563 
14564   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14565   FindCXXThisExpr Finder(*this);
14566 
14567   switch (Proto->getExceptionSpecType()) {
14568   case EST_Unparsed:
14569   case EST_Uninstantiated:
14570   case EST_Unevaluated:
14571   case EST_BasicNoexcept:
14572   case EST_DynamicNone:
14573   case EST_MSAny:
14574   case EST_None:
14575     break;
14576 
14577   case EST_ComputedNoexcept:
14578     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14579       return true;
14580 
14581   case EST_Dynamic:
14582     for (const auto &E : Proto->exceptions()) {
14583       if (!Finder.TraverseType(E))
14584         return true;
14585     }
14586     break;
14587   }
14588 
14589   return false;
14590 }
14591 
14592 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14593   FindCXXThisExpr Finder(*this);
14594 
14595   // Check attributes.
14596   for (const auto *A : Method->attrs()) {
14597     // FIXME: This should be emitted by tblgen.
14598     Expr *Arg = nullptr;
14599     ArrayRef<Expr *> Args;
14600     if (const auto *G = dyn_cast<GuardedByAttr>(A))
14601       Arg = G->getArg();
14602     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
14603       Arg = G->getArg();
14604     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
14605       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
14606     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
14607       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
14608     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
14609       Arg = ETLF->getSuccessValue();
14610       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
14611     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
14612       Arg = STLF->getSuccessValue();
14613       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
14614     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
14615       Arg = LR->getArg();
14616     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
14617       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
14618     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
14619       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14620     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
14621       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14622     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
14623       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14624     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
14625       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14626 
14627     if (Arg && !Finder.TraverseStmt(Arg))
14628       return true;
14629 
14630     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14631       if (!Finder.TraverseStmt(Args[I]))
14632         return true;
14633     }
14634   }
14635 
14636   return false;
14637 }
14638 
14639 void Sema::checkExceptionSpecification(
14640     bool IsTopLevel, ExceptionSpecificationType EST,
14641     ArrayRef<ParsedType> DynamicExceptions,
14642     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14643     SmallVectorImpl<QualType> &Exceptions,
14644     FunctionProtoType::ExceptionSpecInfo &ESI) {
14645   Exceptions.clear();
14646   ESI.Type = EST;
14647   if (EST == EST_Dynamic) {
14648     Exceptions.reserve(DynamicExceptions.size());
14649     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14650       // FIXME: Preserve type source info.
14651       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14652 
14653       if (IsTopLevel) {
14654         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14655         collectUnexpandedParameterPacks(ET, Unexpanded);
14656         if (!Unexpanded.empty()) {
14657           DiagnoseUnexpandedParameterPacks(
14658               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14659               Unexpanded);
14660           continue;
14661         }
14662       }
14663 
14664       // Check that the type is valid for an exception spec, and
14665       // drop it if not.
14666       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14667         Exceptions.push_back(ET);
14668     }
14669     ESI.Exceptions = Exceptions;
14670     return;
14671   }
14672 
14673   if (EST == EST_ComputedNoexcept) {
14674     // If an error occurred, there's no expression here.
14675     if (NoexceptExpr) {
14676       assert((NoexceptExpr->isTypeDependent() ||
14677               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14678               Context.BoolTy) &&
14679              "Parser should have made sure that the expression is boolean");
14680       if (IsTopLevel && NoexceptExpr &&
14681           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
14682         ESI.Type = EST_BasicNoexcept;
14683         return;
14684       }
14685 
14686       if (!NoexceptExpr->isValueDependent())
14687         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
14688                          diag::err_noexcept_needs_constant_expression,
14689                          /*AllowFold*/ false).get();
14690       ESI.NoexceptExpr = NoexceptExpr;
14691     }
14692     return;
14693   }
14694 }
14695 
14696 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14697              ExceptionSpecificationType EST,
14698              SourceRange SpecificationRange,
14699              ArrayRef<ParsedType> DynamicExceptions,
14700              ArrayRef<SourceRange> DynamicExceptionRanges,
14701              Expr *NoexceptExpr) {
14702   if (!MethodD)
14703     return;
14704 
14705   // Dig out the method we're referring to.
14706   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14707     MethodD = FunTmpl->getTemplatedDecl();
14708 
14709   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14710   if (!Method)
14711     return;
14712 
14713   // Check the exception specification.
14714   llvm::SmallVector<QualType, 4> Exceptions;
14715   FunctionProtoType::ExceptionSpecInfo ESI;
14716   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14717                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
14718                               ESI);
14719 
14720   // Update the exception specification on the function type.
14721   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14722 
14723   if (Method->isStatic())
14724     checkThisInStaticMemberFunctionExceptionSpec(Method);
14725 
14726   if (Method->isVirtual()) {
14727     // Check overrides, which we previously had to delay.
14728     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14729                                      OEnd = Method->end_overridden_methods();
14730          O != OEnd; ++O)
14731       CheckOverridingFunctionExceptionSpec(Method, *O);
14732   }
14733 }
14734 
14735 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14736 ///
14737 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14738                                        SourceLocation DeclStart,
14739                                        Declarator &D, Expr *BitWidth,
14740                                        InClassInitStyle InitStyle,
14741                                        AccessSpecifier AS,
14742                                        AttributeList *MSPropertyAttr) {
14743   IdentifierInfo *II = D.getIdentifier();
14744   if (!II) {
14745     Diag(DeclStart, diag::err_anonymous_property);
14746     return nullptr;
14747   }
14748   SourceLocation Loc = D.getIdentifierLoc();
14749 
14750   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14751   QualType T = TInfo->getType();
14752   if (getLangOpts().CPlusPlus) {
14753     CheckExtraCXXDefaultArguments(D);
14754 
14755     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14756                                         UPPC_DataMemberType)) {
14757       D.setInvalidType();
14758       T = Context.IntTy;
14759       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14760     }
14761   }
14762 
14763   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14764 
14765   if (D.getDeclSpec().isInlineSpecified())
14766     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14767         << getLangOpts().CPlusPlus1z;
14768   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14769     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14770          diag::err_invalid_thread)
14771       << DeclSpec::getSpecifierName(TSCS);
14772 
14773   // Check to see if this name was declared as a member previously
14774   NamedDecl *PrevDecl = nullptr;
14775   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14776   LookupName(Previous, S);
14777   switch (Previous.getResultKind()) {
14778   case LookupResult::Found:
14779   case LookupResult::FoundUnresolvedValue:
14780     PrevDecl = Previous.getAsSingle<NamedDecl>();
14781     break;
14782 
14783   case LookupResult::FoundOverloaded:
14784     PrevDecl = Previous.getRepresentativeDecl();
14785     break;
14786 
14787   case LookupResult::NotFound:
14788   case LookupResult::NotFoundInCurrentInstantiation:
14789   case LookupResult::Ambiguous:
14790     break;
14791   }
14792 
14793   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14794     // Maybe we will complain about the shadowed template parameter.
14795     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14796     // Just pretend that we didn't see the previous declaration.
14797     PrevDecl = nullptr;
14798   }
14799 
14800   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14801     PrevDecl = nullptr;
14802 
14803   SourceLocation TSSL = D.getLocStart();
14804   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
14805   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14806       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
14807   ProcessDeclAttributes(TUScope, NewPD, D);
14808   NewPD->setAccess(AS);
14809 
14810   if (NewPD->isInvalidDecl())
14811     Record->setInvalidDecl();
14812 
14813   if (D.getDeclSpec().isModulePrivateSpecified())
14814     NewPD->setModulePrivate();
14815 
14816   if (NewPD->isInvalidDecl() && PrevDecl) {
14817     // Don't introduce NewFD into scope; there's already something
14818     // with the same name in the same scope.
14819   } else if (II) {
14820     PushOnScopeChains(NewPD, S);
14821   } else
14822     Record->addDecl(NewPD);
14823 
14824   return NewPD;
14825 }
14826