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/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include <map>
43 #include <set>
44 
45 using namespace clang;
46 
47 //===----------------------------------------------------------------------===//
48 // CheckDefaultArgumentVisitor
49 //===----------------------------------------------------------------------===//
50 
51 namespace {
52   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53   /// the default argument of a parameter to determine whether it
54   /// contains any ill-formed subexpressions. For example, this will
55   /// diagnose the use of local variables or parameters within the
56   /// default argument expression.
57   class CheckDefaultArgumentVisitor
58     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
59     Expr *DefaultArg;
60     Sema *S;
61 
62   public:
63     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64       : DefaultArg(defarg), S(s) {}
65 
66     bool VisitExpr(Expr *Node);
67     bool VisitDeclRefExpr(DeclRefExpr *DRE);
68     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69     bool VisitLambdaExpr(LambdaExpr *Lambda);
70     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
71   };
72 
73   /// VisitExpr - Visit all of the children of this expression.
74   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75     bool IsInvalid = false;
76     for (Stmt *SubStmt : Node->children())
77       IsInvalid |= Visit(SubStmt);
78     return IsInvalid;
79   }
80 
81   /// VisitDeclRefExpr - Visit a reference to a declaration, to
82   /// determine whether this declaration can be used in the default
83   /// argument expression.
84   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85     NamedDecl *Decl = DRE->getDecl();
86     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87       // C++ [dcl.fct.default]p9
88       //   Default arguments are evaluated each time the function is
89       //   called. The order of evaluation of function arguments is
90       //   unspecified. Consequently, parameters of a function shall not
91       //   be used in default argument expressions, even if they are not
92       //   evaluated. Parameters of a function declared before a default
93       //   argument expression are in scope and can hide namespace and
94       //   class member names.
95       return S->Diag(DRE->getLocStart(),
96                      diag::err_param_default_argument_references_param)
97          << Param->getDeclName() << DefaultArg->getSourceRange();
98     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99       // C++ [dcl.fct.default]p7
100       //   Local variables shall not be used in default argument
101       //   expressions.
102       if (VDecl->isLocalVarDecl())
103         return S->Diag(DRE->getLocStart(),
104                        diag::err_param_default_argument_references_local)
105           << VDecl->getDeclName() << DefaultArg->getSourceRange();
106     }
107 
108     return false;
109   }
110 
111   /// VisitCXXThisExpr - Visit a C++ "this" expression.
112   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113     // C++ [dcl.fct.default]p8:
114     //   The keyword this shall not be used in a default argument of a
115     //   member function.
116     return S->Diag(ThisE->getLocStart(),
117                    diag::err_param_default_argument_references_this)
118                << ThisE->getSourceRange();
119   }
120 
121   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122     bool Invalid = false;
123     for (PseudoObjectExpr::semantics_iterator
124            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125       Expr *E = *i;
126 
127       // Look through bindings.
128       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129         E = OVE->getSourceExpr();
130         assert(E && "pseudo-object binding without source expression?");
131       }
132 
133       Invalid |= Visit(E);
134     }
135     return Invalid;
136   }
137 
138   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139     // C++11 [expr.lambda.prim]p13:
140     //   A lambda-expression appearing in a default argument shall not
141     //   implicitly or explicitly capture any entity.
142     if (Lambda->capture_begin() == Lambda->capture_end())
143       return false;
144 
145     return S->Diag(Lambda->getLocStart(),
146                    diag::err_lambda_capture_default_arg);
147   }
148 }
149 
150 void
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152                                                  const CXXMethodDecl *Method) {
153   // If we have an MSAny spec already, don't bother.
154   if (!Method || ComputedEST == EST_MSAny)
155     return;
156 
157   const FunctionProtoType *Proto
158     = Method->getType()->getAs<FunctionProtoType>();
159   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160   if (!Proto)
161     return;
162 
163   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164 
165   // If we have a throw-all spec at this point, ignore the function.
166   if (ComputedEST == EST_None)
167     return;
168 
169   switch(EST) {
170   // If this function can throw any exceptions, make a note of that.
171   case EST_MSAny:
172   case EST_None:
173     ClearExceptions();
174     ComputedEST = EST;
175     return;
176   // FIXME: If the call to this decl is using any of its default arguments, we
177   // need to search them for potentially-throwing calls.
178   // If this function has a basic noexcept, it doesn't affect the outcome.
179   case EST_BasicNoexcept:
180     return;
181   // If we're still at noexcept(true) and there's a nothrow() callee,
182   // change to that specification.
183   case EST_DynamicNone:
184     if (ComputedEST == EST_BasicNoexcept)
185       ComputedEST = EST_DynamicNone;
186     return;
187   // Check out noexcept specs.
188   case EST_ComputedNoexcept:
189   {
190     FunctionProtoType::NoexceptResult NR =
191         Proto->getNoexceptSpec(Self->Context);
192     assert(NR != FunctionProtoType::NR_NoNoexcept &&
193            "Must have noexcept result for EST_ComputedNoexcept.");
194     assert(NR != FunctionProtoType::NR_Dependent &&
195            "Should not generate implicit declarations for dependent cases, "
196            "and don't know how to handle them anyway.");
197     // noexcept(false) -> no spec on the new function
198     if (NR == FunctionProtoType::NR_Throw) {
199       ClearExceptions();
200       ComputedEST = EST_None;
201     }
202     // noexcept(true) won't change anything either.
203     return;
204   }
205   default:
206     break;
207   }
208   assert(EST == EST_Dynamic && "EST case not considered earlier.");
209   assert(ComputedEST != EST_None &&
210          "Shouldn't collect exceptions when throw-all is guaranteed.");
211   ComputedEST = EST_Dynamic;
212   // Record the exceptions in this function's exception specification.
213   for (const auto &E : Proto->exceptions())
214     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
215       Exceptions.push_back(E);
216 }
217 
218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
219   if (!E || ComputedEST == EST_MSAny)
220     return;
221 
222   // FIXME:
223   //
224   // C++0x [except.spec]p14:
225   //   [An] implicit exception-specification specifies the type-id T if and
226   // only if T is allowed by the exception-specification of a function directly
227   // invoked by f's implicit definition; f shall allow all exceptions if any
228   // function it directly invokes allows all exceptions, and f shall allow no
229   // exceptions if every function it directly invokes allows no exceptions.
230   //
231   // Note in particular that if an implicit exception-specification is generated
232   // for a function containing a throw-expression, that specification can still
233   // be noexcept(true).
234   //
235   // Note also that 'directly invoked' is not defined in the standard, and there
236   // is no indication that we should only consider potentially-evaluated calls.
237   //
238   // Ultimately we should implement the intent of the standard: the exception
239   // specification should be the set of exceptions which can be thrown by the
240   // implicit definition. For now, we assume that any non-nothrow expression can
241   // throw any exception.
242 
243   if (Self->canThrow(E))
244     ComputedEST = EST_None;
245 }
246 
247 bool
248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
249                               SourceLocation EqualLoc) {
250   if (RequireCompleteType(Param->getLocation(), Param->getType(),
251                           diag::err_typecheck_decl_incomplete_type)) {
252     Param->setInvalidDecl();
253     return true;
254   }
255 
256   // C++ [dcl.fct.default]p5
257   //   A default argument expression is implicitly converted (clause
258   //   4) to the parameter type. The default argument expression has
259   //   the same semantic constraints as the initializer expression in
260   //   a declaration of a variable of the parameter type, using the
261   //   copy-initialization semantics (8.5).
262   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
263                                                                     Param);
264   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
265                                                            EqualLoc);
266   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
267   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
268   if (Result.isInvalid())
269     return true;
270   Arg = Result.getAs<Expr>();
271 
272   CheckCompletedExpr(Arg, EqualLoc);
273   Arg = MaybeCreateExprWithCleanups(Arg);
274 
275   // Okay: add the default argument to the parameter
276   Param->setDefaultArg(Arg);
277 
278   // We have already instantiated this parameter; provide each of the
279   // instantiations with the uninstantiated default argument.
280   UnparsedDefaultArgInstantiationsMap::iterator InstPos
281     = UnparsedDefaultArgInstantiations.find(Param);
282   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
283     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
284       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
285 
286     // We're done tracking this parameter's instantiations.
287     UnparsedDefaultArgInstantiations.erase(InstPos);
288   }
289 
290   return false;
291 }
292 
293 /// ActOnParamDefaultArgument - Check whether the default argument
294 /// provided for a function parameter is well-formed. If so, attach it
295 /// to the parameter declaration.
296 void
297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
298                                 Expr *DefaultArg) {
299   if (!param || !DefaultArg)
300     return;
301 
302   ParmVarDecl *Param = cast<ParmVarDecl>(param);
303   UnparsedDefaultArgLocs.erase(Param);
304 
305   // Default arguments are only permitted in C++
306   if (!getLangOpts().CPlusPlus) {
307     Diag(EqualLoc, diag::err_param_default_argument)
308       << DefaultArg->getSourceRange();
309     Param->setInvalidDecl();
310     return;
311   }
312 
313   // Check for unexpanded parameter packs.
314   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
315     Param->setInvalidDecl();
316     return;
317   }
318 
319   // C++11 [dcl.fct.default]p3
320   //   A default argument expression [...] shall not be specified for a
321   //   parameter pack.
322   if (Param->isParameterPack()) {
323     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
324         << DefaultArg->getSourceRange();
325     return;
326   }
327 
328   // Check that the default argument is well-formed
329   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
330   if (DefaultArgChecker.Visit(DefaultArg)) {
331     Param->setInvalidDecl();
332     return;
333   }
334 
335   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
336 }
337 
338 /// ActOnParamUnparsedDefaultArgument - We've seen a default
339 /// argument for a function parameter, but we can't parse it yet
340 /// because we're inside a class definition. Note that this default
341 /// argument will be parsed later.
342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
343                                              SourceLocation EqualLoc,
344                                              SourceLocation ArgLoc) {
345   if (!param)
346     return;
347 
348   ParmVarDecl *Param = cast<ParmVarDecl>(param);
349   Param->setUnparsedDefaultArg();
350   UnparsedDefaultArgLocs[Param] = ArgLoc;
351 }
352 
353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
354 /// the default argument for the parameter param failed.
355 void Sema::ActOnParamDefaultArgumentError(Decl *param,
356                                           SourceLocation EqualLoc) {
357   if (!param)
358     return;
359 
360   ParmVarDecl *Param = cast<ParmVarDecl>(param);
361   Param->setInvalidDecl();
362   UnparsedDefaultArgLocs.erase(Param);
363   Param->setDefaultArg(new(Context)
364                        OpaqueValueExpr(EqualLoc,
365                                        Param->getType().getNonReferenceType(),
366                                        VK_RValue));
367 }
368 
369 /// CheckExtraCXXDefaultArguments - Check for any extra default
370 /// arguments in the declarator, which is not a function declaration
371 /// or definition and therefore is not permitted to have default
372 /// arguments. This routine should be invoked for every declarator
373 /// that is not a function declaration or definition.
374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
375   // C++ [dcl.fct.default]p3
376   //   A default argument expression shall be specified only in the
377   //   parameter-declaration-clause of a function declaration or in a
378   //   template-parameter (14.1). It shall not be specified for a
379   //   parameter pack. If it is specified in a
380   //   parameter-declaration-clause, it shall not occur within a
381   //   declarator or abstract-declarator of a parameter-declaration.
382   bool MightBeFunction = D.isFunctionDeclarationContext();
383   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
384     DeclaratorChunk &chunk = D.getTypeObject(i);
385     if (chunk.Kind == DeclaratorChunk::Function) {
386       if (MightBeFunction) {
387         // This is a function declaration. It can have default arguments, but
388         // keep looking in case its return type is a function type with default
389         // arguments.
390         MightBeFunction = false;
391         continue;
392       }
393       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
394            ++argIdx) {
395         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
396         if (Param->hasUnparsedDefaultArg()) {
397           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
398           SourceRange SR;
399           if (Toks->size() > 1)
400             SR = SourceRange((*Toks)[1].getLocation(),
401                              Toks->back().getLocation());
402           else
403             SR = UnparsedDefaultArgLocs[Param];
404           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
405             << SR;
406           delete Toks;
407           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
408         } else if (Param->getDefaultArg()) {
409           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410             << Param->getDefaultArg()->getSourceRange();
411           Param->setDefaultArg(nullptr);
412         }
413       }
414     } else if (chunk.Kind != DeclaratorChunk::Paren) {
415       MightBeFunction = false;
416     }
417   }
418 }
419 
420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423     if (!PVD->hasDefaultArg())
424       return false;
425     if (!PVD->hasInheritedDefaultArg())
426       return true;
427   }
428   return false;
429 }
430 
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436                                 Scope *S) {
437   bool Invalid = false;
438 
439   // The declaration context corresponding to the scope is the semantic
440   // parent, unless this is a local function declaration, in which case
441   // it is that surrounding function.
442   DeclContext *ScopeDC = New->isLocalExternDecl()
443                              ? New->getLexicalDeclContext()
444                              : New->getDeclContext();
445 
446   // Find the previous declaration for the purpose of default arguments.
447   FunctionDecl *PrevForDefaultArgs = Old;
448   for (/**/; PrevForDefaultArgs;
449        // Don't bother looking back past the latest decl if this is a local
450        // extern declaration; nothing else could work.
451        PrevForDefaultArgs = New->isLocalExternDecl()
452                                 ? nullptr
453                                 : PrevForDefaultArgs->getPreviousDecl()) {
454     // Ignore hidden declarations.
455     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456       continue;
457 
458     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459         !New->isCXXClassMember()) {
460       // Ignore default arguments of old decl if they are not in
461       // the same scope and this is not an out-of-line definition of
462       // a member function.
463       continue;
464     }
465 
466     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467       // If only one of these is a local function declaration, then they are
468       // declared in different scopes, even though isDeclInScope may think
469       // they're in the same scope. (If both are local, the scope check is
470       // sufficent, and if neither is local, then they are in the same scope.)
471       continue;
472     }
473 
474     // We found our guy.
475     break;
476   }
477 
478   // C++ [dcl.fct.default]p4:
479   //   For non-template functions, default arguments can be added in
480   //   later declarations of a function in the same
481   //   scope. Declarations in different scopes have completely
482   //   distinct sets of default arguments. That is, declarations in
483   //   inner scopes do not acquire default arguments from
484   //   declarations in outer scopes, and vice versa. In a given
485   //   function declaration, all parameters subsequent to a
486   //   parameter with a default argument shall have default
487   //   arguments supplied in this or previous declarations. A
488   //   default argument shall not be redefined by a later
489   //   declaration (not even to the same value).
490   //
491   // C++ [dcl.fct.default]p6:
492   //   Except for member functions of class templates, the default arguments
493   //   in a member function definition that appears outside of the class
494   //   definition are added to the set of default arguments provided by the
495   //   member function declaration in the class definition.
496   for (unsigned p = 0, NumParams = PrevForDefaultArgs
497                                        ? PrevForDefaultArgs->getNumParams()
498                                        : 0;
499        p < NumParams; ++p) {
500     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501     ParmVarDecl *NewParam = New->getParamDecl(p);
502 
503     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504     bool NewParamHasDfl = NewParam->hasDefaultArg();
505 
506     if (OldParamHasDfl && NewParamHasDfl) {
507       unsigned DiagDefaultParamID =
508         diag::err_param_default_argument_redefinition;
509 
510       // MSVC accepts that default parameters be redefined for member functions
511       // of template class. The new default parameter's value is ignored.
512       Invalid = true;
513       if (getLangOpts().MicrosoftExt) {
514         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515         if (MD && MD->getParent()->getDescribedClassTemplate()) {
516           // Merge the old default argument into the new parameter.
517           NewParam->setHasInheritedDefaultArg();
518           if (OldParam->hasUninstantiatedDefaultArg())
519             NewParam->setUninstantiatedDefaultArg(
520                                       OldParam->getUninstantiatedDefaultArg());
521           else
522             NewParam->setDefaultArg(OldParam->getInit());
523           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524           Invalid = false;
525         }
526       }
527 
528       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529       // hint here. Alternatively, we could walk the type-source information
530       // for NewParam to find the last source location in the type... but it
531       // isn't worth the effort right now. This is the kind of test case that
532       // is hard to get right:
533       //   int f(int);
534       //   void g(int (*fp)(int) = f);
535       //   void g(int (*fp)(int) = &f);
536       Diag(NewParam->getLocation(), DiagDefaultParamID)
537         << NewParam->getDefaultArgRange();
538 
539       // Look for the function declaration where the default argument was
540       // actually written, which may be a declaration prior to Old.
541       for (auto Older = PrevForDefaultArgs;
542            OldParam->hasInheritedDefaultArg(); /**/) {
543         Older = Older->getPreviousDecl();
544         OldParam = Older->getParamDecl(p);
545       }
546 
547       Diag(OldParam->getLocation(), diag::note_previous_definition)
548         << OldParam->getDefaultArgRange();
549     } else if (OldParamHasDfl) {
550       // Merge the old default argument into the new parameter.
551       // It's important to use getInit() here;  getDefaultArg()
552       // strips off any top-level ExprWithCleanups.
553       NewParam->setHasInheritedDefaultArg();
554       if (OldParam->hasUnparsedDefaultArg())
555         NewParam->setUnparsedDefaultArg();
556       else if (OldParam->hasUninstantiatedDefaultArg())
557         NewParam->setUninstantiatedDefaultArg(
558                                       OldParam->getUninstantiatedDefaultArg());
559       else
560         NewParam->setDefaultArg(OldParam->getInit());
561     } else if (NewParamHasDfl) {
562       if (New->getDescribedFunctionTemplate()) {
563         // Paragraph 4, quoted above, only applies to non-template functions.
564         Diag(NewParam->getLocation(),
565              diag::err_param_default_argument_template_redecl)
566           << NewParam->getDefaultArgRange();
567         Diag(PrevForDefaultArgs->getLocation(),
568              diag::note_template_prev_declaration)
569             << false;
570       } else if (New->getTemplateSpecializationKind()
571                    != TSK_ImplicitInstantiation &&
572                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
573         // C++ [temp.expr.spec]p21:
574         //   Default function arguments shall not be specified in a declaration
575         //   or a definition for one of the following explicit specializations:
576         //     - the explicit specialization of a function template;
577         //     - the explicit specialization of a member function template;
578         //     - the explicit specialization of a member function of a class
579         //       template where the class template specialization to which the
580         //       member function specialization belongs is implicitly
581         //       instantiated.
582         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584           << New->getDeclName()
585           << NewParam->getDefaultArgRange();
586       } else if (New->getDeclContext()->isDependentContext()) {
587         // C++ [dcl.fct.default]p6 (DR217):
588         //   Default arguments for a member function of a class template shall
589         //   be specified on the initial declaration of the member function
590         //   within the class template.
591         //
592         // Reading the tea leaves a bit in DR217 and its reference to DR205
593         // leads me to the conclusion that one cannot add default function
594         // arguments for an out-of-line definition of a member function of a
595         // dependent type.
596         int WhichKind = 2;
597         if (CXXRecordDecl *Record
598               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599           if (Record->getDescribedClassTemplate())
600             WhichKind = 0;
601           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602             WhichKind = 1;
603           else
604             WhichKind = 2;
605         }
606 
607         Diag(NewParam->getLocation(),
608              diag::err_param_default_argument_member_template_redecl)
609           << WhichKind
610           << NewParam->getDefaultArgRange();
611       }
612     }
613   }
614 
615   // DR1344: If a default argument is added outside a class definition and that
616   // default argument makes the function a special member function, the program
617   // is ill-formed. This can only happen for constructors.
618   if (isa<CXXConstructorDecl>(New) &&
619       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622     if (NewSM != OldSM) {
623       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624       assert(NewParam->hasDefaultArg());
625       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626         << NewParam->getDefaultArgRange() << NewSM;
627       Diag(Old->getLocation(), diag::note_previous_declaration);
628     }
629   }
630 
631   const FunctionDecl *Def;
632   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
633   // template has a constexpr specifier then all its declarations shall
634   // contain the constexpr specifier.
635   if (New->isConstexpr() != Old->isConstexpr()) {
636     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637       << New << New->isConstexpr();
638     Diag(Old->getLocation(), diag::note_previous_declaration);
639     Invalid = true;
640   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641              Old->isDefined(Def)) {
642     // C++11 [dcl.fcn.spec]p4:
643     //   If the definition of a function appears in a translation unit before its
644     //   first declaration as inline, the program is ill-formed.
645     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646     Diag(Def->getLocation(), diag::note_previous_definition);
647     Invalid = true;
648   }
649 
650   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
651   // argument expression, that declaration shall be a definition and shall be
652   // the only declaration of the function or function template in the
653   // translation unit.
654   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
655       functionDeclHasDefaultArgument(Old)) {
656     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
657     Diag(Old->getLocation(), diag::note_previous_declaration);
658     Invalid = true;
659   }
660 
661   if (CheckEquivalentExceptionSpec(Old, New))
662     Invalid = true;
663 
664   return Invalid;
665 }
666 
667 /// \brief Merge the exception specifications of two variable declarations.
668 ///
669 /// This is called when there's a redeclaration of a VarDecl. The function
670 /// checks if the redeclaration might have an exception specification and
671 /// validates compatibility and merges the specs if necessary.
672 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
673   // Shortcut if exceptions are disabled.
674   if (!getLangOpts().CXXExceptions)
675     return;
676 
677   assert(Context.hasSameType(New->getType(), Old->getType()) &&
678          "Should only be called if types are otherwise the same.");
679 
680   QualType NewType = New->getType();
681   QualType OldType = Old->getType();
682 
683   // We're only interested in pointers and references to functions, as well
684   // as pointers to member functions.
685   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
686     NewType = R->getPointeeType();
687     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
688   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
689     NewType = P->getPointeeType();
690     OldType = OldType->getAs<PointerType>()->getPointeeType();
691   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
692     NewType = M->getPointeeType();
693     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
694   }
695 
696   if (!NewType->isFunctionProtoType())
697     return;
698 
699   // There's lots of special cases for functions. For function pointers, system
700   // libraries are hopefully not as broken so that we don't need these
701   // workarounds.
702   if (CheckEquivalentExceptionSpec(
703         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
704         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
705     New->setInvalidDecl();
706   }
707 }
708 
709 /// CheckCXXDefaultArguments - Verify that the default arguments for a
710 /// function declaration are well-formed according to C++
711 /// [dcl.fct.default].
712 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
713   unsigned NumParams = FD->getNumParams();
714   unsigned p;
715 
716   // Find first parameter with a default argument
717   for (p = 0; p < NumParams; ++p) {
718     ParmVarDecl *Param = FD->getParamDecl(p);
719     if (Param->hasDefaultArg())
720       break;
721   }
722 
723   // C++11 [dcl.fct.default]p4:
724   //   In a given function declaration, each parameter subsequent to a parameter
725   //   with a default argument shall have a default argument supplied in this or
726   //   a previous declaration or shall be a function parameter pack. A default
727   //   argument shall not be redefined by a later declaration (not even to the
728   //   same value).
729   unsigned LastMissingDefaultArg = 0;
730   for (; p < NumParams; ++p) {
731     ParmVarDecl *Param = FD->getParamDecl(p);
732     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
733       if (Param->isInvalidDecl())
734         /* We already complained about this parameter. */;
735       else if (Param->getIdentifier())
736         Diag(Param->getLocation(),
737              diag::err_param_default_argument_missing_name)
738           << Param->getIdentifier();
739       else
740         Diag(Param->getLocation(),
741              diag::err_param_default_argument_missing);
742 
743       LastMissingDefaultArg = p;
744     }
745   }
746 
747   if (LastMissingDefaultArg > 0) {
748     // Some default arguments were missing. Clear out all of the
749     // default arguments up to (and including) the last missing
750     // default argument, so that we leave the function parameters
751     // in a semantically valid state.
752     for (p = 0; p <= LastMissingDefaultArg; ++p) {
753       ParmVarDecl *Param = FD->getParamDecl(p);
754       if (Param->hasDefaultArg()) {
755         Param->setDefaultArg(nullptr);
756       }
757     }
758   }
759 }
760 
761 // CheckConstexprParameterTypes - Check whether a function's parameter types
762 // are all literal types. If so, return true. If not, produce a suitable
763 // diagnostic and return false.
764 static bool CheckConstexprParameterTypes(Sema &SemaRef,
765                                          const FunctionDecl *FD) {
766   unsigned ArgIndex = 0;
767   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
768   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
769                                               e = FT->param_type_end();
770        i != e; ++i, ++ArgIndex) {
771     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
772     SourceLocation ParamLoc = PD->getLocation();
773     if (!(*i)->isDependentType() &&
774         SemaRef.RequireLiteralType(ParamLoc, *i,
775                                    diag::err_constexpr_non_literal_param,
776                                    ArgIndex+1, PD->getSourceRange(),
777                                    isa<CXXConstructorDecl>(FD)))
778       return false;
779   }
780   return true;
781 }
782 
783 /// \brief Get diagnostic %select index for tag kind for
784 /// record diagnostic message.
785 /// WARNING: Indexes apply to particular diagnostics only!
786 ///
787 /// \returns diagnostic %select index.
788 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
789   switch (Tag) {
790   case TTK_Struct: return 0;
791   case TTK_Interface: return 1;
792   case TTK_Class:  return 2;
793   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
794   }
795 }
796 
797 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
798 // the requirements of a constexpr function definition or a constexpr
799 // constructor definition. If so, return true. If not, produce appropriate
800 // diagnostics and return false.
801 //
802 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
803 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
804   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
805   if (MD && MD->isInstance()) {
806     // C++11 [dcl.constexpr]p4:
807     //  The definition of a constexpr constructor shall satisfy the following
808     //  constraints:
809     //  - the class shall not have any virtual base classes;
810     const CXXRecordDecl *RD = MD->getParent();
811     if (RD->getNumVBases()) {
812       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
813         << isa<CXXConstructorDecl>(NewFD)
814         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
815       for (const auto &I : RD->vbases())
816         Diag(I.getLocStart(),
817              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
818       return false;
819     }
820   }
821 
822   if (!isa<CXXConstructorDecl>(NewFD)) {
823     // C++11 [dcl.constexpr]p3:
824     //  The definition of a constexpr function shall satisfy the following
825     //  constraints:
826     // - it shall not be virtual;
827     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
828     if (Method && Method->isVirtual()) {
829       Method = Method->getCanonicalDecl();
830       Diag(Method->getLocation(), diag::err_constexpr_virtual);
831 
832       // If it's not obvious why this function is virtual, find an overridden
833       // function which uses the 'virtual' keyword.
834       const CXXMethodDecl *WrittenVirtual = Method;
835       while (!WrittenVirtual->isVirtualAsWritten())
836         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
837       if (WrittenVirtual != Method)
838         Diag(WrittenVirtual->getLocation(),
839              diag::note_overridden_virtual_function);
840       return false;
841     }
842 
843     // - its return type shall be a literal type;
844     QualType RT = NewFD->getReturnType();
845     if (!RT->isDependentType() &&
846         RequireLiteralType(NewFD->getLocation(), RT,
847                            diag::err_constexpr_non_literal_return))
848       return false;
849   }
850 
851   // - each of its parameter types shall be a literal type;
852   if (!CheckConstexprParameterTypes(*this, NewFD))
853     return false;
854 
855   return true;
856 }
857 
858 /// Check the given declaration statement is legal within a constexpr function
859 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
860 ///
861 /// \return true if the body is OK (maybe only as an extension), false if we
862 ///         have diagnosed a problem.
863 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
864                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
865   // C++11 [dcl.constexpr]p3 and p4:
866   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
867   //  contain only
868   for (const auto *DclIt : DS->decls()) {
869     switch (DclIt->getKind()) {
870     case Decl::StaticAssert:
871     case Decl::Using:
872     case Decl::UsingShadow:
873     case Decl::UsingDirective:
874     case Decl::UnresolvedUsingTypename:
875     case Decl::UnresolvedUsingValue:
876       //   - static_assert-declarations
877       //   - using-declarations,
878       //   - using-directives,
879       continue;
880 
881     case Decl::Typedef:
882     case Decl::TypeAlias: {
883       //   - typedef declarations and alias-declarations that do not define
884       //     classes or enumerations,
885       const auto *TN = cast<TypedefNameDecl>(DclIt);
886       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
887         // Don't allow variably-modified types in constexpr functions.
888         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
889         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
890           << TL.getSourceRange() << TL.getType()
891           << isa<CXXConstructorDecl>(Dcl);
892         return false;
893       }
894       continue;
895     }
896 
897     case Decl::Enum:
898     case Decl::CXXRecord:
899       // C++1y allows types to be defined, not just declared.
900       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
901         SemaRef.Diag(DS->getLocStart(),
902                      SemaRef.getLangOpts().CPlusPlus14
903                        ? diag::warn_cxx11_compat_constexpr_type_definition
904                        : diag::ext_constexpr_type_definition)
905           << isa<CXXConstructorDecl>(Dcl);
906       continue;
907 
908     case Decl::EnumConstant:
909     case Decl::IndirectField:
910     case Decl::ParmVar:
911       // These can only appear with other declarations which are banned in
912       // C++11 and permitted in C++1y, so ignore them.
913       continue;
914 
915     case Decl::Var: {
916       // C++1y [dcl.constexpr]p3 allows anything except:
917       //   a definition of a variable of non-literal type or of static or
918       //   thread storage duration or for which no initialization is performed.
919       const auto *VD = cast<VarDecl>(DclIt);
920       if (VD->isThisDeclarationADefinition()) {
921         if (VD->isStaticLocal()) {
922           SemaRef.Diag(VD->getLocation(),
923                        diag::err_constexpr_local_var_static)
924             << isa<CXXConstructorDecl>(Dcl)
925             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
926           return false;
927         }
928         if (!VD->getType()->isDependentType() &&
929             SemaRef.RequireLiteralType(
930               VD->getLocation(), VD->getType(),
931               diag::err_constexpr_local_var_non_literal_type,
932               isa<CXXConstructorDecl>(Dcl)))
933           return false;
934         if (!VD->getType()->isDependentType() &&
935             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
936           SemaRef.Diag(VD->getLocation(),
937                        diag::err_constexpr_local_var_no_init)
938             << isa<CXXConstructorDecl>(Dcl);
939           return false;
940         }
941       }
942       SemaRef.Diag(VD->getLocation(),
943                    SemaRef.getLangOpts().CPlusPlus14
944                     ? diag::warn_cxx11_compat_constexpr_local_var
945                     : diag::ext_constexpr_local_var)
946         << isa<CXXConstructorDecl>(Dcl);
947       continue;
948     }
949 
950     case Decl::NamespaceAlias:
951     case Decl::Function:
952       // These are disallowed in C++11 and permitted in C++1y. Allow them
953       // everywhere as an extension.
954       if (!Cxx1yLoc.isValid())
955         Cxx1yLoc = DS->getLocStart();
956       continue;
957 
958     default:
959       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
960         << isa<CXXConstructorDecl>(Dcl);
961       return false;
962     }
963   }
964 
965   return true;
966 }
967 
968 /// Check that the given field is initialized within a constexpr constructor.
969 ///
970 /// \param Dcl The constexpr constructor being checked.
971 /// \param Field The field being checked. This may be a member of an anonymous
972 ///        struct or union nested within the class being checked.
973 /// \param Inits All declarations, including anonymous struct/union members and
974 ///        indirect members, for which any initialization was provided.
975 /// \param Diagnosed Set to true if an error is produced.
976 static void CheckConstexprCtorInitializer(Sema &SemaRef,
977                                           const FunctionDecl *Dcl,
978                                           FieldDecl *Field,
979                                           llvm::SmallSet<Decl*, 16> &Inits,
980                                           bool &Diagnosed) {
981   if (Field->isInvalidDecl())
982     return;
983 
984   if (Field->isUnnamedBitfield())
985     return;
986 
987   // Anonymous unions with no variant members and empty anonymous structs do not
988   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
989   // indirect fields don't need initializing.
990   if (Field->isAnonymousStructOrUnion() &&
991       (Field->getType()->isUnionType()
992            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
993            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
994     return;
995 
996   if (!Inits.count(Field)) {
997     if (!Diagnosed) {
998       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
999       Diagnosed = true;
1000     }
1001     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1002   } else if (Field->isAnonymousStructOrUnion()) {
1003     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1004     for (auto *I : RD->fields())
1005       // If an anonymous union contains an anonymous struct of which any member
1006       // is initialized, all members must be initialized.
1007       if (!RD->isUnion() || Inits.count(I))
1008         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1009   }
1010 }
1011 
1012 /// Check the provided statement is allowed in a constexpr function
1013 /// definition.
1014 static bool
1015 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1016                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1017                            SourceLocation &Cxx1yLoc) {
1018   // - its function-body shall be [...] a compound-statement that contains only
1019   switch (S->getStmtClass()) {
1020   case Stmt::NullStmtClass:
1021     //   - null statements,
1022     return true;
1023 
1024   case Stmt::DeclStmtClass:
1025     //   - static_assert-declarations
1026     //   - using-declarations,
1027     //   - using-directives,
1028     //   - typedef declarations and alias-declarations that do not define
1029     //     classes or enumerations,
1030     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1031       return false;
1032     return true;
1033 
1034   case Stmt::ReturnStmtClass:
1035     //   - and exactly one return statement;
1036     if (isa<CXXConstructorDecl>(Dcl)) {
1037       // C++1y allows return statements in constexpr constructors.
1038       if (!Cxx1yLoc.isValid())
1039         Cxx1yLoc = S->getLocStart();
1040       return true;
1041     }
1042 
1043     ReturnStmts.push_back(S->getLocStart());
1044     return true;
1045 
1046   case Stmt::CompoundStmtClass: {
1047     // C++1y allows compound-statements.
1048     if (!Cxx1yLoc.isValid())
1049       Cxx1yLoc = S->getLocStart();
1050 
1051     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1052     for (auto *BodyIt : CompStmt->body()) {
1053       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1054                                       Cxx1yLoc))
1055         return false;
1056     }
1057     return true;
1058   }
1059 
1060   case Stmt::AttributedStmtClass:
1061     if (!Cxx1yLoc.isValid())
1062       Cxx1yLoc = S->getLocStart();
1063     return true;
1064 
1065   case Stmt::IfStmtClass: {
1066     // C++1y allows if-statements.
1067     if (!Cxx1yLoc.isValid())
1068       Cxx1yLoc = S->getLocStart();
1069 
1070     IfStmt *If = cast<IfStmt>(S);
1071     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1072                                     Cxx1yLoc))
1073       return false;
1074     if (If->getElse() &&
1075         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1076                                     Cxx1yLoc))
1077       return false;
1078     return true;
1079   }
1080 
1081   case Stmt::WhileStmtClass:
1082   case Stmt::DoStmtClass:
1083   case Stmt::ForStmtClass:
1084   case Stmt::CXXForRangeStmtClass:
1085   case Stmt::ContinueStmtClass:
1086     // C++1y allows all of these. We don't allow them as extensions in C++11,
1087     // because they don't make sense without variable mutation.
1088     if (!SemaRef.getLangOpts().CPlusPlus14)
1089       break;
1090     if (!Cxx1yLoc.isValid())
1091       Cxx1yLoc = S->getLocStart();
1092     for (Stmt *SubStmt : S->children())
1093       if (SubStmt &&
1094           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1095                                       Cxx1yLoc))
1096         return false;
1097     return true;
1098 
1099   case Stmt::SwitchStmtClass:
1100   case Stmt::CaseStmtClass:
1101   case Stmt::DefaultStmtClass:
1102   case Stmt::BreakStmtClass:
1103     // C++1y allows switch-statements, and since they don't need variable
1104     // mutation, we can reasonably allow them in C++11 as an extension.
1105     if (!Cxx1yLoc.isValid())
1106       Cxx1yLoc = S->getLocStart();
1107     for (Stmt *SubStmt : S->children())
1108       if (SubStmt &&
1109           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1110                                       Cxx1yLoc))
1111         return false;
1112     return true;
1113 
1114   default:
1115     if (!isa<Expr>(S))
1116       break;
1117 
1118     // C++1y allows expression-statements.
1119     if (!Cxx1yLoc.isValid())
1120       Cxx1yLoc = S->getLocStart();
1121     return true;
1122   }
1123 
1124   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1125     << isa<CXXConstructorDecl>(Dcl);
1126   return false;
1127 }
1128 
1129 /// Check the body for the given constexpr function declaration only contains
1130 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1131 ///
1132 /// \return true if the body is OK, false if we have diagnosed a problem.
1133 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1134   if (isa<CXXTryStmt>(Body)) {
1135     // C++11 [dcl.constexpr]p3:
1136     //  The definition of a constexpr function shall satisfy the following
1137     //  constraints: [...]
1138     // - its function-body shall be = delete, = default, or a
1139     //   compound-statement
1140     //
1141     // C++11 [dcl.constexpr]p4:
1142     //  In the definition of a constexpr constructor, [...]
1143     // - its function-body shall not be a function-try-block;
1144     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1145       << isa<CXXConstructorDecl>(Dcl);
1146     return false;
1147   }
1148 
1149   SmallVector<SourceLocation, 4> ReturnStmts;
1150 
1151   // - its function-body shall be [...] a compound-statement that contains only
1152   //   [... list of cases ...]
1153   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1154   SourceLocation Cxx1yLoc;
1155   for (auto *BodyIt : CompBody->body()) {
1156     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1157       return false;
1158   }
1159 
1160   if (Cxx1yLoc.isValid())
1161     Diag(Cxx1yLoc,
1162          getLangOpts().CPlusPlus14
1163            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1164            : diag::ext_constexpr_body_invalid_stmt)
1165       << isa<CXXConstructorDecl>(Dcl);
1166 
1167   if (const CXXConstructorDecl *Constructor
1168         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1169     const CXXRecordDecl *RD = Constructor->getParent();
1170     // DR1359:
1171     // - every non-variant non-static data member and base class sub-object
1172     //   shall be initialized;
1173     // DR1460:
1174     // - if the class is a union having variant members, exactly one of them
1175     //   shall be initialized;
1176     if (RD->isUnion()) {
1177       if (Constructor->getNumCtorInitializers() == 0 &&
1178           RD->hasVariantMembers()) {
1179         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1180         return false;
1181       }
1182     } else if (!Constructor->isDependentContext() &&
1183                !Constructor->isDelegatingConstructor()) {
1184       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1185 
1186       // Skip detailed checking if we have enough initializers, and we would
1187       // allow at most one initializer per member.
1188       bool AnyAnonStructUnionMembers = false;
1189       unsigned Fields = 0;
1190       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1191            E = RD->field_end(); I != E; ++I, ++Fields) {
1192         if (I->isAnonymousStructOrUnion()) {
1193           AnyAnonStructUnionMembers = true;
1194           break;
1195         }
1196       }
1197       // DR1460:
1198       // - if the class is a union-like class, but is not a union, for each of
1199       //   its anonymous union members having variant members, exactly one of
1200       //   them shall be initialized;
1201       if (AnyAnonStructUnionMembers ||
1202           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1203         // Check initialization of non-static data members. Base classes are
1204         // always initialized so do not need to be checked. Dependent bases
1205         // might not have initializers in the member initializer list.
1206         llvm::SmallSet<Decl*, 16> Inits;
1207         for (const auto *I: Constructor->inits()) {
1208           if (FieldDecl *FD = I->getMember())
1209             Inits.insert(FD);
1210           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1211             Inits.insert(ID->chain_begin(), ID->chain_end());
1212         }
1213 
1214         bool Diagnosed = false;
1215         for (auto *I : RD->fields())
1216           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1217         if (Diagnosed)
1218           return false;
1219       }
1220     }
1221   } else {
1222     if (ReturnStmts.empty()) {
1223       // C++1y doesn't require constexpr functions to contain a 'return'
1224       // statement. We still do, unless the return type might be void, because
1225       // otherwise if there's no return statement, the function cannot
1226       // be used in a core constant expression.
1227       bool OK = getLangOpts().CPlusPlus14 &&
1228                 (Dcl->getReturnType()->isVoidType() ||
1229                  Dcl->getReturnType()->isDependentType());
1230       Diag(Dcl->getLocation(),
1231            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1232               : diag::err_constexpr_body_no_return);
1233       if (!OK)
1234         return false;
1235     } else if (ReturnStmts.size() > 1) {
1236       Diag(ReturnStmts.back(),
1237            getLangOpts().CPlusPlus14
1238              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1239              : diag::ext_constexpr_body_multiple_return);
1240       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1241         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1242     }
1243   }
1244 
1245   // C++11 [dcl.constexpr]p5:
1246   //   if no function argument values exist such that the function invocation
1247   //   substitution would produce a constant expression, the program is
1248   //   ill-formed; no diagnostic required.
1249   // C++11 [dcl.constexpr]p3:
1250   //   - every constructor call and implicit conversion used in initializing the
1251   //     return value shall be one of those allowed in a constant expression.
1252   // C++11 [dcl.constexpr]p4:
1253   //   - every constructor involved in initializing non-static data members and
1254   //     base class sub-objects shall be a constexpr constructor.
1255   SmallVector<PartialDiagnosticAt, 8> Diags;
1256   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1257     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1258       << isa<CXXConstructorDecl>(Dcl);
1259     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1260       Diag(Diags[I].first, Diags[I].second);
1261     // Don't return false here: we allow this for compatibility in
1262     // system headers.
1263   }
1264 
1265   return true;
1266 }
1267 
1268 /// isCurrentClassName - Determine whether the identifier II is the
1269 /// name of the class type currently being defined. In the case of
1270 /// nested classes, this will only return true if II is the name of
1271 /// the innermost class.
1272 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1273                               const CXXScopeSpec *SS) {
1274   assert(getLangOpts().CPlusPlus && "No class names in C!");
1275 
1276   CXXRecordDecl *CurDecl;
1277   if (SS && SS->isSet() && !SS->isInvalid()) {
1278     DeclContext *DC = computeDeclContext(*SS, true);
1279     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1280   } else
1281     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1282 
1283   if (CurDecl && CurDecl->getIdentifier())
1284     return &II == CurDecl->getIdentifier();
1285   return false;
1286 }
1287 
1288 /// \brief Determine whether the identifier II is a typo for the name of
1289 /// the class type currently being defined. If so, update it to the identifier
1290 /// that should have been used.
1291 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1292   assert(getLangOpts().CPlusPlus && "No class names in C!");
1293 
1294   if (!getLangOpts().SpellChecking)
1295     return false;
1296 
1297   CXXRecordDecl *CurDecl;
1298   if (SS && SS->isSet() && !SS->isInvalid()) {
1299     DeclContext *DC = computeDeclContext(*SS, true);
1300     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1301   } else
1302     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1303 
1304   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1305       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1306           < II->getLength()) {
1307     II = CurDecl->getIdentifier();
1308     return true;
1309   }
1310 
1311   return false;
1312 }
1313 
1314 /// \brief Determine whether the given class is a base class of the given
1315 /// class, including looking at dependent bases.
1316 static bool findCircularInheritance(const CXXRecordDecl *Class,
1317                                     const CXXRecordDecl *Current) {
1318   SmallVector<const CXXRecordDecl*, 8> Queue;
1319 
1320   Class = Class->getCanonicalDecl();
1321   while (true) {
1322     for (const auto &I : Current->bases()) {
1323       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1324       if (!Base)
1325         continue;
1326 
1327       Base = Base->getDefinition();
1328       if (!Base)
1329         continue;
1330 
1331       if (Base->getCanonicalDecl() == Class)
1332         return true;
1333 
1334       Queue.push_back(Base);
1335     }
1336 
1337     if (Queue.empty())
1338       return false;
1339 
1340     Current = Queue.pop_back_val();
1341   }
1342 
1343   return false;
1344 }
1345 
1346 /// \brief Check the validity of a C++ base class specifier.
1347 ///
1348 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1349 /// and returns NULL otherwise.
1350 CXXBaseSpecifier *
1351 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1352                          SourceRange SpecifierRange,
1353                          bool Virtual, AccessSpecifier Access,
1354                          TypeSourceInfo *TInfo,
1355                          SourceLocation EllipsisLoc) {
1356   QualType BaseType = TInfo->getType();
1357 
1358   // C++ [class.union]p1:
1359   //   A union shall not have base classes.
1360   if (Class->isUnion()) {
1361     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1362       << SpecifierRange;
1363     return nullptr;
1364   }
1365 
1366   if (EllipsisLoc.isValid() &&
1367       !TInfo->getType()->containsUnexpandedParameterPack()) {
1368     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1369       << TInfo->getTypeLoc().getSourceRange();
1370     EllipsisLoc = SourceLocation();
1371   }
1372 
1373   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1374 
1375   if (BaseType->isDependentType()) {
1376     // Make sure that we don't have circular inheritance among our dependent
1377     // bases. For non-dependent bases, the check for completeness below handles
1378     // this.
1379     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1380       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1381           ((BaseDecl = BaseDecl->getDefinition()) &&
1382            findCircularInheritance(Class, BaseDecl))) {
1383         Diag(BaseLoc, diag::err_circular_inheritance)
1384           << BaseType << Context.getTypeDeclType(Class);
1385 
1386         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1387           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1388             << BaseType;
1389 
1390         return nullptr;
1391       }
1392     }
1393 
1394     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1395                                           Class->getTagKind() == TTK_Class,
1396                                           Access, TInfo, EllipsisLoc);
1397   }
1398 
1399   // Base specifiers must be record types.
1400   if (!BaseType->isRecordType()) {
1401     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1402     return nullptr;
1403   }
1404 
1405   // C++ [class.union]p1:
1406   //   A union shall not be used as a base class.
1407   if (BaseType->isUnionType()) {
1408     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1409     return nullptr;
1410   }
1411 
1412   // For the MS ABI, propagate DLL attributes to base class templates.
1413   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1414     if (Attr *ClassAttr = getDLLAttr(Class)) {
1415       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1416               BaseType->getAsCXXRecordDecl())) {
1417         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
1418                                             BaseLoc);
1419       }
1420     }
1421   }
1422 
1423   // C++ [class.derived]p2:
1424   //   The class-name in a base-specifier shall not be an incompletely
1425   //   defined class.
1426   if (RequireCompleteType(BaseLoc, BaseType,
1427                           diag::err_incomplete_base_class, SpecifierRange)) {
1428     Class->setInvalidDecl();
1429     return nullptr;
1430   }
1431 
1432   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1433   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1434   assert(BaseDecl && "Record type has no declaration");
1435   BaseDecl = BaseDecl->getDefinition();
1436   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1437   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1438   assert(CXXBaseDecl && "Base type is not a C++ type");
1439 
1440   // A class which contains a flexible array member is not suitable for use as a
1441   // base class:
1442   //   - If the layout determines that a base comes before another base,
1443   //     the flexible array member would index into the subsequent base.
1444   //   - If the layout determines that base comes before the derived class,
1445   //     the flexible array member would index into the derived class.
1446   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1447     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1448       << CXXBaseDecl->getDeclName();
1449     return nullptr;
1450   }
1451 
1452   // C++ [class]p3:
1453   //   If a class is marked final and it appears as a base-type-specifier in
1454   //   base-clause, the program is ill-formed.
1455   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1456     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1457       << CXXBaseDecl->getDeclName()
1458       << FA->isSpelledAsSealed();
1459     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1460         << CXXBaseDecl->getDeclName() << FA->getRange();
1461     return nullptr;
1462   }
1463 
1464   if (BaseDecl->isInvalidDecl())
1465     Class->setInvalidDecl();
1466 
1467   // Create the base specifier.
1468   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1469                                         Class->getTagKind() == TTK_Class,
1470                                         Access, TInfo, EllipsisLoc);
1471 }
1472 
1473 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1474 /// one entry in the base class list of a class specifier, for
1475 /// example:
1476 ///    class foo : public bar, virtual private baz {
1477 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1478 BaseResult
1479 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1480                          ParsedAttributes &Attributes,
1481                          bool Virtual, AccessSpecifier Access,
1482                          ParsedType basetype, SourceLocation BaseLoc,
1483                          SourceLocation EllipsisLoc) {
1484   if (!classdecl)
1485     return true;
1486 
1487   AdjustDeclIfTemplate(classdecl);
1488   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1489   if (!Class)
1490     return true;
1491 
1492   // We haven't yet attached the base specifiers.
1493   Class->setIsParsingBaseSpecifiers();
1494 
1495   // We do not support any C++11 attributes on base-specifiers yet.
1496   // Diagnose any attributes we see.
1497   if (!Attributes.empty()) {
1498     for (AttributeList *Attr = Attributes.getList(); Attr;
1499          Attr = Attr->getNext()) {
1500       if (Attr->isInvalid() ||
1501           Attr->getKind() == AttributeList::IgnoredAttribute)
1502         continue;
1503       Diag(Attr->getLoc(),
1504            Attr->getKind() == AttributeList::UnknownAttribute
1505              ? diag::warn_unknown_attribute_ignored
1506              : diag::err_base_specifier_attribute)
1507         << Attr->getName();
1508     }
1509   }
1510 
1511   TypeSourceInfo *TInfo = nullptr;
1512   GetTypeFromParser(basetype, &TInfo);
1513 
1514   if (EllipsisLoc.isInvalid() &&
1515       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1516                                       UPPC_BaseType))
1517     return true;
1518 
1519   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1520                                                       Virtual, Access, TInfo,
1521                                                       EllipsisLoc))
1522     return BaseSpec;
1523   else
1524     Class->setInvalidDecl();
1525 
1526   return true;
1527 }
1528 
1529 /// Use small set to collect indirect bases.  As this is only used
1530 /// locally, there's no need to abstract the small size parameter.
1531 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1532 
1533 /// \brief Recursively add the bases of Type.  Don't add Type itself.
1534 static void
1535 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1536                   const QualType &Type)
1537 {
1538   // Even though the incoming type is a base, it might not be
1539   // a class -- it could be a template parm, for instance.
1540   if (auto Rec = Type->getAs<RecordType>()) {
1541     auto Decl = Rec->getAsCXXRecordDecl();
1542 
1543     // Iterate over its bases.
1544     for (const auto &BaseSpec : Decl->bases()) {
1545       QualType Base = Context.getCanonicalType(BaseSpec.getType())
1546         .getUnqualifiedType();
1547       if (Set.insert(Base).second)
1548         // If we've not already seen it, recurse.
1549         NoteIndirectBases(Context, Set, Base);
1550     }
1551   }
1552 }
1553 
1554 /// \brief Performs the actual work of attaching the given base class
1555 /// specifiers to a C++ class.
1556 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
1557                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
1558  if (Bases.empty())
1559     return false;
1560 
1561   // Used to keep track of which base types we have already seen, so
1562   // that we can properly diagnose redundant direct base types. Note
1563   // that the key is always the unqualified canonical type of the base
1564   // class.
1565   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1566 
1567   // Used to track indirect bases so we can see if a direct base is
1568   // ambiguous.
1569   IndirectBaseSet IndirectBaseTypes;
1570 
1571   // Copy non-redundant base specifiers into permanent storage.
1572   unsigned NumGoodBases = 0;
1573   bool Invalid = false;
1574   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
1575     QualType NewBaseType
1576       = Context.getCanonicalType(Bases[idx]->getType());
1577     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1578 
1579     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1580     if (KnownBase) {
1581       // C++ [class.mi]p3:
1582       //   A class shall not be specified as a direct base class of a
1583       //   derived class more than once.
1584       Diag(Bases[idx]->getLocStart(),
1585            diag::err_duplicate_base_class)
1586         << KnownBase->getType()
1587         << Bases[idx]->getSourceRange();
1588 
1589       // Delete the duplicate base class specifier; we're going to
1590       // overwrite its pointer later.
1591       Context.Deallocate(Bases[idx]);
1592 
1593       Invalid = true;
1594     } else {
1595       // Okay, add this new base class.
1596       KnownBase = Bases[idx];
1597       Bases[NumGoodBases++] = Bases[idx];
1598 
1599       // Note this base's direct & indirect bases, if there could be ambiguity.
1600       if (Bases.size() > 1)
1601         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1602 
1603       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1604         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1605         if (Class->isInterface() &&
1606               (!RD->isInterface() ||
1607                KnownBase->getAccessSpecifier() != AS_public)) {
1608           // The Microsoft extension __interface does not permit bases that
1609           // are not themselves public interfaces.
1610           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1611             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1612             << RD->getSourceRange();
1613           Invalid = true;
1614         }
1615         if (RD->hasAttr<WeakAttr>())
1616           Class->addAttr(WeakAttr::CreateImplicit(Context));
1617       }
1618     }
1619   }
1620 
1621   // Attach the remaining base class specifiers to the derived class.
1622   Class->setBases(Bases.data(), NumGoodBases);
1623 
1624   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1625     // Check whether this direct base is inaccessible due to ambiguity.
1626     QualType BaseType = Bases[idx]->getType();
1627     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1628       .getUnqualifiedType();
1629 
1630     if (IndirectBaseTypes.count(CanonicalBase)) {
1631       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1632                          /*DetectVirtual=*/true);
1633       bool found
1634         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1635       assert(found);
1636       (void)found;
1637 
1638       if (Paths.isAmbiguous(CanonicalBase))
1639         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1640           << BaseType << getAmbiguousPathsDisplayString(Paths)
1641           << Bases[idx]->getSourceRange();
1642       else
1643         assert(Bases[idx]->isVirtual());
1644     }
1645 
1646     // Delete the base class specifier, since its data has been copied
1647     // into the CXXRecordDecl.
1648     Context.Deallocate(Bases[idx]);
1649   }
1650 
1651   return Invalid;
1652 }
1653 
1654 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1655 /// class, after checking whether there are any duplicate base
1656 /// classes.
1657 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
1658                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
1659   if (!ClassDecl || Bases.empty())
1660     return;
1661 
1662   AdjustDeclIfTemplate(ClassDecl);
1663   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
1664 }
1665 
1666 /// \brief Determine whether the type \p Derived is a C++ class that is
1667 /// derived from the type \p Base.
1668 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
1669   if (!getLangOpts().CPlusPlus)
1670     return false;
1671 
1672   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1673   if (!DerivedRD)
1674     return false;
1675 
1676   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1677   if (!BaseRD)
1678     return false;
1679 
1680   // If either the base or the derived type is invalid, don't try to
1681   // check whether one is derived from the other.
1682   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1683     return false;
1684 
1685   // FIXME: In a modules build, do we need the entire path to be visible for us
1686   // to be able to use the inheritance relationship?
1687   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
1688     return false;
1689 
1690   return DerivedRD->isDerivedFrom(BaseRD);
1691 }
1692 
1693 /// \brief Determine whether the type \p Derived is a C++ class that is
1694 /// derived from the type \p Base.
1695 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
1696                          CXXBasePaths &Paths) {
1697   if (!getLangOpts().CPlusPlus)
1698     return false;
1699 
1700   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1701   if (!DerivedRD)
1702     return false;
1703 
1704   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1705   if (!BaseRD)
1706     return false;
1707 
1708   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
1709     return false;
1710 
1711   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1712 }
1713 
1714 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1715                               CXXCastPath &BasePathArray) {
1716   assert(BasePathArray.empty() && "Base path array must be empty!");
1717   assert(Paths.isRecordingPaths() && "Must record paths!");
1718 
1719   const CXXBasePath &Path = Paths.front();
1720 
1721   // We first go backward and check if we have a virtual base.
1722   // FIXME: It would be better if CXXBasePath had the base specifier for
1723   // the nearest virtual base.
1724   unsigned Start = 0;
1725   for (unsigned I = Path.size(); I != 0; --I) {
1726     if (Path[I - 1].Base->isVirtual()) {
1727       Start = I - 1;
1728       break;
1729     }
1730   }
1731 
1732   // Now add all bases.
1733   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1734     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1735 }
1736 
1737 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1738 /// conversion (where Derived and Base are class types) is
1739 /// well-formed, meaning that the conversion is unambiguous (and
1740 /// that all of the base classes are accessible). Returns true
1741 /// and emits a diagnostic if the code is ill-formed, returns false
1742 /// otherwise. Loc is the location where this routine should point to
1743 /// if there is an error, and Range is the source range to highlight
1744 /// if there is an error.
1745 ///
1746 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
1747 /// diagnostic for the respective type of error will be suppressed, but the
1748 /// check for ill-formed code will still be performed.
1749 bool
1750 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1751                                    unsigned InaccessibleBaseID,
1752                                    unsigned AmbigiousBaseConvID,
1753                                    SourceLocation Loc, SourceRange Range,
1754                                    DeclarationName Name,
1755                                    CXXCastPath *BasePath,
1756                                    bool IgnoreAccess) {
1757   // First, determine whether the path from Derived to Base is
1758   // ambiguous. This is slightly more expensive than checking whether
1759   // the Derived to Base conversion exists, because here we need to
1760   // explore multiple paths to determine if there is an ambiguity.
1761   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1762                      /*DetectVirtual=*/false);
1763   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
1764   assert(DerivationOkay &&
1765          "Can only be used with a derived-to-base conversion");
1766   (void)DerivationOkay;
1767 
1768   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1769     if (!IgnoreAccess) {
1770       // Check that the base class can be accessed.
1771       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1772                                    InaccessibleBaseID)) {
1773         case AR_inaccessible:
1774           return true;
1775         case AR_accessible:
1776         case AR_dependent:
1777         case AR_delayed:
1778           break;
1779       }
1780     }
1781 
1782     // Build a base path if necessary.
1783     if (BasePath)
1784       BuildBasePathArray(Paths, *BasePath);
1785     return false;
1786   }
1787 
1788   if (AmbigiousBaseConvID) {
1789     // We know that the derived-to-base conversion is ambiguous, and
1790     // we're going to produce a diagnostic. Perform the derived-to-base
1791     // search just one more time to compute all of the possible paths so
1792     // that we can print them out. This is more expensive than any of
1793     // the previous derived-to-base checks we've done, but at this point
1794     // performance isn't as much of an issue.
1795     Paths.clear();
1796     Paths.setRecordingPaths(true);
1797     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
1798     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1799     (void)StillOkay;
1800 
1801     // Build up a textual representation of the ambiguous paths, e.g.,
1802     // D -> B -> A, that will be used to illustrate the ambiguous
1803     // conversions in the diagnostic. We only print one of the paths
1804     // to each base class subobject.
1805     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1806 
1807     Diag(Loc, AmbigiousBaseConvID)
1808     << Derived << Base << PathDisplayStr << Range << Name;
1809   }
1810   return true;
1811 }
1812 
1813 bool
1814 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1815                                    SourceLocation Loc, SourceRange Range,
1816                                    CXXCastPath *BasePath,
1817                                    bool IgnoreAccess) {
1818   return CheckDerivedToBaseConversion(
1819       Derived, Base, diag::err_upcast_to_inaccessible_base,
1820       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
1821       BasePath, IgnoreAccess);
1822 }
1823 
1824 
1825 /// @brief Builds a string representing ambiguous paths from a
1826 /// specific derived class to different subobjects of the same base
1827 /// class.
1828 ///
1829 /// This function builds a string that can be used in error messages
1830 /// to show the different paths that one can take through the
1831 /// inheritance hierarchy to go from the derived class to different
1832 /// subobjects of a base class. The result looks something like this:
1833 /// @code
1834 /// struct D -> struct B -> struct A
1835 /// struct D -> struct C -> struct A
1836 /// @endcode
1837 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1838   std::string PathDisplayStr;
1839   std::set<unsigned> DisplayedPaths;
1840   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1841        Path != Paths.end(); ++Path) {
1842     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1843       // We haven't displayed a path to this particular base
1844       // class subobject yet.
1845       PathDisplayStr += "\n    ";
1846       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1847       for (CXXBasePath::const_iterator Element = Path->begin();
1848            Element != Path->end(); ++Element)
1849         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1850     }
1851   }
1852 
1853   return PathDisplayStr;
1854 }
1855 
1856 //===----------------------------------------------------------------------===//
1857 // C++ class member Handling
1858 //===----------------------------------------------------------------------===//
1859 
1860 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1861 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1862                                 SourceLocation ASLoc,
1863                                 SourceLocation ColonLoc,
1864                                 AttributeList *Attrs) {
1865   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1866   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1867                                                   ASLoc, ColonLoc);
1868   CurContext->addHiddenDecl(ASDecl);
1869   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1870 }
1871 
1872 /// CheckOverrideControl - Check C++11 override control semantics.
1873 void Sema::CheckOverrideControl(NamedDecl *D) {
1874   if (D->isInvalidDecl())
1875     return;
1876 
1877   // We only care about "override" and "final" declarations.
1878   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1879     return;
1880 
1881   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1882 
1883   // We can't check dependent instance methods.
1884   if (MD && MD->isInstance() &&
1885       (MD->getParent()->hasAnyDependentBases() ||
1886        MD->getType()->isDependentType()))
1887     return;
1888 
1889   if (MD && !MD->isVirtual()) {
1890     // If we have a non-virtual method, check if if hides a virtual method.
1891     // (In that case, it's most likely the method has the wrong type.)
1892     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1893     FindHiddenVirtualMethods(MD, OverloadedMethods);
1894 
1895     if (!OverloadedMethods.empty()) {
1896       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1897         Diag(OA->getLocation(),
1898              diag::override_keyword_hides_virtual_member_function)
1899           << "override" << (OverloadedMethods.size() > 1);
1900       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1901         Diag(FA->getLocation(),
1902              diag::override_keyword_hides_virtual_member_function)
1903           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1904           << (OverloadedMethods.size() > 1);
1905       }
1906       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1907       MD->setInvalidDecl();
1908       return;
1909     }
1910     // Fall through into the general case diagnostic.
1911     // FIXME: We might want to attempt typo correction here.
1912   }
1913 
1914   if (!MD || !MD->isVirtual()) {
1915     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1916       Diag(OA->getLocation(),
1917            diag::override_keyword_only_allowed_on_virtual_member_functions)
1918         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1919       D->dropAttr<OverrideAttr>();
1920     }
1921     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1922       Diag(FA->getLocation(),
1923            diag::override_keyword_only_allowed_on_virtual_member_functions)
1924         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1925         << FixItHint::CreateRemoval(FA->getLocation());
1926       D->dropAttr<FinalAttr>();
1927     }
1928     return;
1929   }
1930 
1931   // C++11 [class.virtual]p5:
1932   //   If a function is marked with the virt-specifier override and
1933   //   does not override a member function of a base class, the program is
1934   //   ill-formed.
1935   bool HasOverriddenMethods =
1936     MD->begin_overridden_methods() != MD->end_overridden_methods();
1937   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1938     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1939       << MD->getDeclName();
1940 }
1941 
1942 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1943   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1944     return;
1945   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1946   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1947       isa<CXXDestructorDecl>(MD))
1948     return;
1949 
1950   SourceLocation Loc = MD->getLocation();
1951   SourceLocation SpellingLoc = Loc;
1952   if (getSourceManager().isMacroArgExpansion(Loc))
1953     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1954   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1955   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1956       return;
1957 
1958   if (MD->size_overridden_methods() > 0) {
1959     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1960       << MD->getDeclName();
1961     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1962     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1963   }
1964 }
1965 
1966 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1967 /// function overrides a virtual member function marked 'final', according to
1968 /// C++11 [class.virtual]p4.
1969 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1970                                                   const CXXMethodDecl *Old) {
1971   FinalAttr *FA = Old->getAttr<FinalAttr>();
1972   if (!FA)
1973     return false;
1974 
1975   Diag(New->getLocation(), diag::err_final_function_overridden)
1976     << New->getDeclName()
1977     << FA->isSpelledAsSealed();
1978   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1979   return true;
1980 }
1981 
1982 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1983   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1984   // FIXME: Destruction of ObjC lifetime types has side-effects.
1985   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1986     return !RD->isCompleteDefinition() ||
1987            !RD->hasTrivialDefaultConstructor() ||
1988            !RD->hasTrivialDestructor();
1989   return false;
1990 }
1991 
1992 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1993   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1994     if (it->isDeclspecPropertyAttribute())
1995       return it;
1996   return nullptr;
1997 }
1998 
1999 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2000 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2001 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2002 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2003 /// present (but parsing it has been deferred).
2004 NamedDecl *
2005 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2006                                MultiTemplateParamsArg TemplateParameterLists,
2007                                Expr *BW, const VirtSpecifiers &VS,
2008                                InClassInitStyle InitStyle) {
2009   const DeclSpec &DS = D.getDeclSpec();
2010   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2011   DeclarationName Name = NameInfo.getName();
2012   SourceLocation Loc = NameInfo.getLoc();
2013 
2014   // For anonymous bitfields, the location should point to the type.
2015   if (Loc.isInvalid())
2016     Loc = D.getLocStart();
2017 
2018   Expr *BitWidth = static_cast<Expr*>(BW);
2019 
2020   assert(isa<CXXRecordDecl>(CurContext));
2021   assert(!DS.isFriendSpecified());
2022 
2023   bool isFunc = D.isDeclarationOfFunction();
2024 
2025   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2026     // The Microsoft extension __interface only permits public member functions
2027     // and prohibits constructors, destructors, operators, non-public member
2028     // functions, static methods and data members.
2029     unsigned InvalidDecl;
2030     bool ShowDeclName = true;
2031     if (!isFunc)
2032       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2033     else if (AS != AS_public)
2034       InvalidDecl = 2;
2035     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2036       InvalidDecl = 3;
2037     else switch (Name.getNameKind()) {
2038       case DeclarationName::CXXConstructorName:
2039         InvalidDecl = 4;
2040         ShowDeclName = false;
2041         break;
2042 
2043       case DeclarationName::CXXDestructorName:
2044         InvalidDecl = 5;
2045         ShowDeclName = false;
2046         break;
2047 
2048       case DeclarationName::CXXOperatorName:
2049       case DeclarationName::CXXConversionFunctionName:
2050         InvalidDecl = 6;
2051         break;
2052 
2053       default:
2054         InvalidDecl = 0;
2055         break;
2056     }
2057 
2058     if (InvalidDecl) {
2059       if (ShowDeclName)
2060         Diag(Loc, diag::err_invalid_member_in_interface)
2061           << (InvalidDecl-1) << Name;
2062       else
2063         Diag(Loc, diag::err_invalid_member_in_interface)
2064           << (InvalidDecl-1) << "";
2065       return nullptr;
2066     }
2067   }
2068 
2069   // C++ 9.2p6: A member shall not be declared to have automatic storage
2070   // duration (auto, register) or with the extern storage-class-specifier.
2071   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2072   // data members and cannot be applied to names declared const or static,
2073   // and cannot be applied to reference members.
2074   switch (DS.getStorageClassSpec()) {
2075   case DeclSpec::SCS_unspecified:
2076   case DeclSpec::SCS_typedef:
2077   case DeclSpec::SCS_static:
2078     break;
2079   case DeclSpec::SCS_mutable:
2080     if (isFunc) {
2081       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2082 
2083       // FIXME: It would be nicer if the keyword was ignored only for this
2084       // declarator. Otherwise we could get follow-up errors.
2085       D.getMutableDeclSpec().ClearStorageClassSpecs();
2086     }
2087     break;
2088   default:
2089     Diag(DS.getStorageClassSpecLoc(),
2090          diag::err_storageclass_invalid_for_member);
2091     D.getMutableDeclSpec().ClearStorageClassSpecs();
2092     break;
2093   }
2094 
2095   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2096                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2097                       !isFunc);
2098 
2099   if (DS.isConstexprSpecified() && isInstField) {
2100     SemaDiagnosticBuilder B =
2101         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2102     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2103     if (InitStyle == ICIS_NoInit) {
2104       B << 0 << 0;
2105       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2106         B << FixItHint::CreateRemoval(ConstexprLoc);
2107       else {
2108         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2109         D.getMutableDeclSpec().ClearConstexprSpec();
2110         const char *PrevSpec;
2111         unsigned DiagID;
2112         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2113             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2114         (void)Failed;
2115         assert(!Failed && "Making a constexpr member const shouldn't fail");
2116       }
2117     } else {
2118       B << 1;
2119       const char *PrevSpec;
2120       unsigned DiagID;
2121       if (D.getMutableDeclSpec().SetStorageClassSpec(
2122           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2123           Context.getPrintingPolicy())) {
2124         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2125                "This is the only DeclSpec that should fail to be applied");
2126         B << 1;
2127       } else {
2128         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2129         isInstField = false;
2130       }
2131     }
2132   }
2133 
2134   NamedDecl *Member;
2135   if (isInstField) {
2136     CXXScopeSpec &SS = D.getCXXScopeSpec();
2137 
2138     // Data members must have identifiers for names.
2139     if (!Name.isIdentifier()) {
2140       Diag(Loc, diag::err_bad_variable_name)
2141         << Name;
2142       return nullptr;
2143     }
2144 
2145     IdentifierInfo *II = Name.getAsIdentifierInfo();
2146 
2147     // Member field could not be with "template" keyword.
2148     // So TemplateParameterLists should be empty in this case.
2149     if (TemplateParameterLists.size()) {
2150       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2151       if (TemplateParams->size()) {
2152         // There is no such thing as a member field template.
2153         Diag(D.getIdentifierLoc(), diag::err_template_member)
2154             << II
2155             << SourceRange(TemplateParams->getTemplateLoc(),
2156                 TemplateParams->getRAngleLoc());
2157       } else {
2158         // There is an extraneous 'template<>' for this member.
2159         Diag(TemplateParams->getTemplateLoc(),
2160             diag::err_template_member_noparams)
2161             << II
2162             << SourceRange(TemplateParams->getTemplateLoc(),
2163                 TemplateParams->getRAngleLoc());
2164       }
2165       return nullptr;
2166     }
2167 
2168     if (SS.isSet() && !SS.isInvalid()) {
2169       // The user provided a superfluous scope specifier inside a class
2170       // definition:
2171       //
2172       // class X {
2173       //   int X::member;
2174       // };
2175       if (DeclContext *DC = computeDeclContext(SS, false))
2176         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2177       else
2178         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2179           << Name << SS.getRange();
2180 
2181       SS.clear();
2182     }
2183 
2184     AttributeList *MSPropertyAttr =
2185       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2186     if (MSPropertyAttr) {
2187       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2188                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2189       if (!Member)
2190         return nullptr;
2191       isInstField = false;
2192     } else {
2193       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2194                                 BitWidth, InitStyle, AS);
2195       assert(Member && "HandleField never returns null");
2196     }
2197   } else {
2198     Member = HandleDeclarator(S, D, TemplateParameterLists);
2199     if (!Member)
2200       return nullptr;
2201 
2202     // Non-instance-fields can't have a bitfield.
2203     if (BitWidth) {
2204       if (Member->isInvalidDecl()) {
2205         // don't emit another diagnostic.
2206       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2207         // C++ 9.6p3: A bit-field shall not be a static member.
2208         // "static member 'A' cannot be a bit-field"
2209         Diag(Loc, diag::err_static_not_bitfield)
2210           << Name << BitWidth->getSourceRange();
2211       } else if (isa<TypedefDecl>(Member)) {
2212         // "typedef member 'x' cannot be a bit-field"
2213         Diag(Loc, diag::err_typedef_not_bitfield)
2214           << Name << BitWidth->getSourceRange();
2215       } else {
2216         // A function typedef ("typedef int f(); f a;").
2217         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2218         Diag(Loc, diag::err_not_integral_type_bitfield)
2219           << Name << cast<ValueDecl>(Member)->getType()
2220           << BitWidth->getSourceRange();
2221       }
2222 
2223       BitWidth = nullptr;
2224       Member->setInvalidDecl();
2225     }
2226 
2227     Member->setAccess(AS);
2228 
2229     // If we have declared a member function template or static data member
2230     // template, set the access of the templated declaration as well.
2231     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2232       FunTmpl->getTemplatedDecl()->setAccess(AS);
2233     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2234       VarTmpl->getTemplatedDecl()->setAccess(AS);
2235   }
2236 
2237   if (VS.isOverrideSpecified())
2238     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2239   if (VS.isFinalSpecified())
2240     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2241                                             VS.isFinalSpelledSealed()));
2242 
2243   if (VS.getLastLocation().isValid()) {
2244     // Update the end location of a method that has a virt-specifiers.
2245     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2246       MD->setRangeEnd(VS.getLastLocation());
2247   }
2248 
2249   CheckOverrideControl(Member);
2250 
2251   assert((Name || isInstField) && "No identifier for non-field ?");
2252 
2253   if (isInstField) {
2254     FieldDecl *FD = cast<FieldDecl>(Member);
2255     FieldCollector->Add(FD);
2256 
2257     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2258       // Remember all explicit private FieldDecls that have a name, no side
2259       // effects and are not part of a dependent type declaration.
2260       if (!FD->isImplicit() && FD->getDeclName() &&
2261           FD->getAccess() == AS_private &&
2262           !FD->hasAttr<UnusedAttr>() &&
2263           !FD->getParent()->isDependentContext() &&
2264           !InitializationHasSideEffects(*FD))
2265         UnusedPrivateFields.insert(FD);
2266     }
2267   }
2268 
2269   return Member;
2270 }
2271 
2272 namespace {
2273   class UninitializedFieldVisitor
2274       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2275     Sema &S;
2276     // List of Decls to generate a warning on.  Also remove Decls that become
2277     // initialized.
2278     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2279     // List of base classes of the record.  Classes are removed after their
2280     // initializers.
2281     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2282     // Vector of decls to be removed from the Decl set prior to visiting the
2283     // nodes.  These Decls may have been initialized in the prior initializer.
2284     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2285     // If non-null, add a note to the warning pointing back to the constructor.
2286     const CXXConstructorDecl *Constructor;
2287     // Variables to hold state when processing an initializer list.  When
2288     // InitList is true, special case initialization of FieldDecls matching
2289     // InitListFieldDecl.
2290     bool InitList;
2291     FieldDecl *InitListFieldDecl;
2292     llvm::SmallVector<unsigned, 4> InitFieldIndex;
2293 
2294   public:
2295     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2296     UninitializedFieldVisitor(Sema &S,
2297                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2298                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2299       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2300         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2301 
2302     // Returns true if the use of ME is not an uninitialized use.
2303     bool IsInitListMemberExprInitialized(MemberExpr *ME,
2304                                          bool CheckReferenceOnly) {
2305       llvm::SmallVector<FieldDecl*, 4> Fields;
2306       bool ReferenceField = false;
2307       while (ME) {
2308         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2309         if (!FD)
2310           return false;
2311         Fields.push_back(FD);
2312         if (FD->getType()->isReferenceType())
2313           ReferenceField = true;
2314         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2315       }
2316 
2317       // Binding a reference to an unintialized field is not an
2318       // uninitialized use.
2319       if (CheckReferenceOnly && !ReferenceField)
2320         return true;
2321 
2322       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2323       // Discard the first field since it is the field decl that is being
2324       // initialized.
2325       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2326         UsedFieldIndex.push_back((*I)->getFieldIndex());
2327       }
2328 
2329       for (auto UsedIter = UsedFieldIndex.begin(),
2330                 UsedEnd = UsedFieldIndex.end(),
2331                 OrigIter = InitFieldIndex.begin(),
2332                 OrigEnd = InitFieldIndex.end();
2333            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2334         if (*UsedIter < *OrigIter)
2335           return true;
2336         if (*UsedIter > *OrigIter)
2337           break;
2338       }
2339 
2340       return false;
2341     }
2342 
2343     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2344                           bool AddressOf) {
2345       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2346         return;
2347 
2348       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2349       // or union.
2350       MemberExpr *FieldME = ME;
2351 
2352       bool AllPODFields = FieldME->getType().isPODType(S.Context);
2353 
2354       Expr *Base = ME;
2355       while (MemberExpr *SubME =
2356                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2357 
2358         if (isa<VarDecl>(SubME->getMemberDecl()))
2359           return;
2360 
2361         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2362           if (!FD->isAnonymousStructOrUnion())
2363             FieldME = SubME;
2364 
2365         if (!FieldME->getType().isPODType(S.Context))
2366           AllPODFields = false;
2367 
2368         Base = SubME->getBase();
2369       }
2370 
2371       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2372         return;
2373 
2374       if (AddressOf && AllPODFields)
2375         return;
2376 
2377       ValueDecl* FoundVD = FieldME->getMemberDecl();
2378 
2379       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2380         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2381           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2382         }
2383 
2384         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2385           QualType T = BaseCast->getType();
2386           if (T->isPointerType() &&
2387               BaseClasses.count(T->getPointeeType())) {
2388             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2389                 << T->getPointeeType() << FoundVD;
2390           }
2391         }
2392       }
2393 
2394       if (!Decls.count(FoundVD))
2395         return;
2396 
2397       const bool IsReference = FoundVD->getType()->isReferenceType();
2398 
2399       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2400         // Special checking for initializer lists.
2401         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2402           return;
2403         }
2404       } else {
2405         // Prevent double warnings on use of unbounded references.
2406         if (CheckReferenceOnly && !IsReference)
2407           return;
2408       }
2409 
2410       unsigned diag = IsReference
2411           ? diag::warn_reference_field_is_uninit
2412           : diag::warn_field_is_uninit;
2413       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2414       if (Constructor)
2415         S.Diag(Constructor->getLocation(),
2416                diag::note_uninit_in_this_constructor)
2417           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2418 
2419     }
2420 
2421     void HandleValue(Expr *E, bool AddressOf) {
2422       E = E->IgnoreParens();
2423 
2424       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2425         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2426                          AddressOf /*AddressOf*/);
2427         return;
2428       }
2429 
2430       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2431         Visit(CO->getCond());
2432         HandleValue(CO->getTrueExpr(), AddressOf);
2433         HandleValue(CO->getFalseExpr(), AddressOf);
2434         return;
2435       }
2436 
2437       if (BinaryConditionalOperator *BCO =
2438               dyn_cast<BinaryConditionalOperator>(E)) {
2439         Visit(BCO->getCond());
2440         HandleValue(BCO->getFalseExpr(), AddressOf);
2441         return;
2442       }
2443 
2444       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2445         HandleValue(OVE->getSourceExpr(), AddressOf);
2446         return;
2447       }
2448 
2449       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2450         switch (BO->getOpcode()) {
2451         default:
2452           break;
2453         case(BO_PtrMemD):
2454         case(BO_PtrMemI):
2455           HandleValue(BO->getLHS(), AddressOf);
2456           Visit(BO->getRHS());
2457           return;
2458         case(BO_Comma):
2459           Visit(BO->getLHS());
2460           HandleValue(BO->getRHS(), AddressOf);
2461           return;
2462         }
2463       }
2464 
2465       Visit(E);
2466     }
2467 
2468     void CheckInitListExpr(InitListExpr *ILE) {
2469       InitFieldIndex.push_back(0);
2470       for (auto Child : ILE->children()) {
2471         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2472           CheckInitListExpr(SubList);
2473         } else {
2474           Visit(Child);
2475         }
2476         ++InitFieldIndex.back();
2477       }
2478       InitFieldIndex.pop_back();
2479     }
2480 
2481     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2482                           FieldDecl *Field, const Type *BaseClass) {
2483       // Remove Decls that may have been initialized in the previous
2484       // initializer.
2485       for (ValueDecl* VD : DeclsToRemove)
2486         Decls.erase(VD);
2487       DeclsToRemove.clear();
2488 
2489       Constructor = FieldConstructor;
2490       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2491 
2492       if (ILE && Field) {
2493         InitList = true;
2494         InitListFieldDecl = Field;
2495         InitFieldIndex.clear();
2496         CheckInitListExpr(ILE);
2497       } else {
2498         InitList = false;
2499         Visit(E);
2500       }
2501 
2502       if (Field)
2503         Decls.erase(Field);
2504       if (BaseClass)
2505         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2506     }
2507 
2508     void VisitMemberExpr(MemberExpr *ME) {
2509       // All uses of unbounded reference fields will warn.
2510       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2511     }
2512 
2513     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2514       if (E->getCastKind() == CK_LValueToRValue) {
2515         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2516         return;
2517       }
2518 
2519       Inherited::VisitImplicitCastExpr(E);
2520     }
2521 
2522     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2523       if (E->getConstructor()->isCopyConstructor()) {
2524         Expr *ArgExpr = E->getArg(0);
2525         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2526           if (ILE->getNumInits() == 1)
2527             ArgExpr = ILE->getInit(0);
2528         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2529           if (ICE->getCastKind() == CK_NoOp)
2530             ArgExpr = ICE->getSubExpr();
2531         HandleValue(ArgExpr, false /*AddressOf*/);
2532         return;
2533       }
2534       Inherited::VisitCXXConstructExpr(E);
2535     }
2536 
2537     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2538       Expr *Callee = E->getCallee();
2539       if (isa<MemberExpr>(Callee)) {
2540         HandleValue(Callee, false /*AddressOf*/);
2541         for (auto Arg : E->arguments())
2542           Visit(Arg);
2543         return;
2544       }
2545 
2546       Inherited::VisitCXXMemberCallExpr(E);
2547     }
2548 
2549     void VisitCallExpr(CallExpr *E) {
2550       // Treat std::move as a use.
2551       if (E->getNumArgs() == 1) {
2552         if (FunctionDecl *FD = E->getDirectCallee()) {
2553           if (FD->isInStdNamespace() && FD->getIdentifier() &&
2554               FD->getIdentifier()->isStr("move")) {
2555             HandleValue(E->getArg(0), false /*AddressOf*/);
2556             return;
2557           }
2558         }
2559       }
2560 
2561       Inherited::VisitCallExpr(E);
2562     }
2563 
2564     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2565       Expr *Callee = E->getCallee();
2566 
2567       if (isa<UnresolvedLookupExpr>(Callee))
2568         return Inherited::VisitCXXOperatorCallExpr(E);
2569 
2570       Visit(Callee);
2571       for (auto Arg : E->arguments())
2572         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2573     }
2574 
2575     void VisitBinaryOperator(BinaryOperator *E) {
2576       // If a field assignment is detected, remove the field from the
2577       // uninitiailized field set.
2578       if (E->getOpcode() == BO_Assign)
2579         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2580           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2581             if (!FD->getType()->isReferenceType())
2582               DeclsToRemove.push_back(FD);
2583 
2584       if (E->isCompoundAssignmentOp()) {
2585         HandleValue(E->getLHS(), false /*AddressOf*/);
2586         Visit(E->getRHS());
2587         return;
2588       }
2589 
2590       Inherited::VisitBinaryOperator(E);
2591     }
2592 
2593     void VisitUnaryOperator(UnaryOperator *E) {
2594       if (E->isIncrementDecrementOp()) {
2595         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2596         return;
2597       }
2598       if (E->getOpcode() == UO_AddrOf) {
2599         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2600           HandleValue(ME->getBase(), true /*AddressOf*/);
2601           return;
2602         }
2603       }
2604 
2605       Inherited::VisitUnaryOperator(E);
2606     }
2607   };
2608 
2609   // Diagnose value-uses of fields to initialize themselves, e.g.
2610   //   foo(foo)
2611   // where foo is not also a parameter to the constructor.
2612   // Also diagnose across field uninitialized use such as
2613   //   x(y), y(x)
2614   // TODO: implement -Wuninitialized and fold this into that framework.
2615   static void DiagnoseUninitializedFields(
2616       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2617 
2618     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2619                                            Constructor->getLocation())) {
2620       return;
2621     }
2622 
2623     if (Constructor->isInvalidDecl())
2624       return;
2625 
2626     const CXXRecordDecl *RD = Constructor->getParent();
2627 
2628     if (RD->getDescribedClassTemplate())
2629       return;
2630 
2631     // Holds fields that are uninitialized.
2632     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2633 
2634     // At the beginning, all fields are uninitialized.
2635     for (auto *I : RD->decls()) {
2636       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2637         UninitializedFields.insert(FD);
2638       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2639         UninitializedFields.insert(IFD->getAnonField());
2640       }
2641     }
2642 
2643     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2644     for (auto I : RD->bases())
2645       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2646 
2647     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2648       return;
2649 
2650     UninitializedFieldVisitor UninitializedChecker(SemaRef,
2651                                                    UninitializedFields,
2652                                                    UninitializedBaseClasses);
2653 
2654     for (const auto *FieldInit : Constructor->inits()) {
2655       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2656         break;
2657 
2658       Expr *InitExpr = FieldInit->getInit();
2659       if (!InitExpr)
2660         continue;
2661 
2662       if (CXXDefaultInitExpr *Default =
2663               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2664         InitExpr = Default->getExpr();
2665         if (!InitExpr)
2666           continue;
2667         // In class initializers will point to the constructor.
2668         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2669                                               FieldInit->getAnyMember(),
2670                                               FieldInit->getBaseClass());
2671       } else {
2672         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2673                                               FieldInit->getAnyMember(),
2674                                               FieldInit->getBaseClass());
2675       }
2676     }
2677   }
2678 } // namespace
2679 
2680 /// \brief Enter a new C++ default initializer scope. After calling this, the
2681 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2682 /// parsing or instantiating the initializer failed.
2683 void Sema::ActOnStartCXXInClassMemberInitializer() {
2684   // Create a synthetic function scope to represent the call to the constructor
2685   // that notionally surrounds a use of this initializer.
2686   PushFunctionScope();
2687 }
2688 
2689 /// \brief This is invoked after parsing an in-class initializer for a
2690 /// non-static C++ class member, and after instantiating an in-class initializer
2691 /// in a class template. Such actions are deferred until the class is complete.
2692 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2693                                                   SourceLocation InitLoc,
2694                                                   Expr *InitExpr) {
2695   // Pop the notional constructor scope we created earlier.
2696   PopFunctionScopeInfo(nullptr, D);
2697 
2698   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2699   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2700          "must set init style when field is created");
2701 
2702   if (!InitExpr) {
2703     D->setInvalidDecl();
2704     if (FD)
2705       FD->removeInClassInitializer();
2706     return;
2707   }
2708 
2709   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2710     FD->setInvalidDecl();
2711     FD->removeInClassInitializer();
2712     return;
2713   }
2714 
2715   ExprResult Init = InitExpr;
2716   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2717     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2718     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2719         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2720         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2721     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2722     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2723     if (Init.isInvalid()) {
2724       FD->setInvalidDecl();
2725       return;
2726     }
2727   }
2728 
2729   // C++11 [class.base.init]p7:
2730   //   The initialization of each base and member constitutes a
2731   //   full-expression.
2732   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2733   if (Init.isInvalid()) {
2734     FD->setInvalidDecl();
2735     return;
2736   }
2737 
2738   InitExpr = Init.get();
2739 
2740   FD->setInClassInitializer(InitExpr);
2741 }
2742 
2743 /// \brief Find the direct and/or virtual base specifiers that
2744 /// correspond to the given base type, for use in base initialization
2745 /// within a constructor.
2746 static bool FindBaseInitializer(Sema &SemaRef,
2747                                 CXXRecordDecl *ClassDecl,
2748                                 QualType BaseType,
2749                                 const CXXBaseSpecifier *&DirectBaseSpec,
2750                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2751   // First, check for a direct base class.
2752   DirectBaseSpec = nullptr;
2753   for (const auto &Base : ClassDecl->bases()) {
2754     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2755       // We found a direct base of this type. That's what we're
2756       // initializing.
2757       DirectBaseSpec = &Base;
2758       break;
2759     }
2760   }
2761 
2762   // Check for a virtual base class.
2763   // FIXME: We might be able to short-circuit this if we know in advance that
2764   // there are no virtual bases.
2765   VirtualBaseSpec = nullptr;
2766   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2767     // We haven't found a base yet; search the class hierarchy for a
2768     // virtual base class.
2769     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2770                        /*DetectVirtual=*/false);
2771     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
2772                               SemaRef.Context.getTypeDeclType(ClassDecl),
2773                               BaseType, Paths)) {
2774       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2775            Path != Paths.end(); ++Path) {
2776         if (Path->back().Base->isVirtual()) {
2777           VirtualBaseSpec = Path->back().Base;
2778           break;
2779         }
2780       }
2781     }
2782   }
2783 
2784   return DirectBaseSpec || VirtualBaseSpec;
2785 }
2786 
2787 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2788 MemInitResult
2789 Sema::ActOnMemInitializer(Decl *ConstructorD,
2790                           Scope *S,
2791                           CXXScopeSpec &SS,
2792                           IdentifierInfo *MemberOrBase,
2793                           ParsedType TemplateTypeTy,
2794                           const DeclSpec &DS,
2795                           SourceLocation IdLoc,
2796                           Expr *InitList,
2797                           SourceLocation EllipsisLoc) {
2798   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2799                              DS, IdLoc, InitList,
2800                              EllipsisLoc);
2801 }
2802 
2803 /// \brief Handle a C++ member initializer using parentheses syntax.
2804 MemInitResult
2805 Sema::ActOnMemInitializer(Decl *ConstructorD,
2806                           Scope *S,
2807                           CXXScopeSpec &SS,
2808                           IdentifierInfo *MemberOrBase,
2809                           ParsedType TemplateTypeTy,
2810                           const DeclSpec &DS,
2811                           SourceLocation IdLoc,
2812                           SourceLocation LParenLoc,
2813                           ArrayRef<Expr *> Args,
2814                           SourceLocation RParenLoc,
2815                           SourceLocation EllipsisLoc) {
2816   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2817                                            Args, RParenLoc);
2818   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2819                              DS, IdLoc, List, EllipsisLoc);
2820 }
2821 
2822 namespace {
2823 
2824 // Callback to only accept typo corrections that can be a valid C++ member
2825 // intializer: either a non-static field member or a base class.
2826 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2827 public:
2828   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2829       : ClassDecl(ClassDecl) {}
2830 
2831   bool ValidateCandidate(const TypoCorrection &candidate) override {
2832     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2833       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2834         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2835       return isa<TypeDecl>(ND);
2836     }
2837     return false;
2838   }
2839 
2840 private:
2841   CXXRecordDecl *ClassDecl;
2842 };
2843 
2844 }
2845 
2846 /// \brief Handle a C++ member initializer.
2847 MemInitResult
2848 Sema::BuildMemInitializer(Decl *ConstructorD,
2849                           Scope *S,
2850                           CXXScopeSpec &SS,
2851                           IdentifierInfo *MemberOrBase,
2852                           ParsedType TemplateTypeTy,
2853                           const DeclSpec &DS,
2854                           SourceLocation IdLoc,
2855                           Expr *Init,
2856                           SourceLocation EllipsisLoc) {
2857   ExprResult Res = CorrectDelayedTyposInExpr(Init);
2858   if (!Res.isUsable())
2859     return true;
2860   Init = Res.get();
2861 
2862   if (!ConstructorD)
2863     return true;
2864 
2865   AdjustDeclIfTemplate(ConstructorD);
2866 
2867   CXXConstructorDecl *Constructor
2868     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2869   if (!Constructor) {
2870     // The user wrote a constructor initializer on a function that is
2871     // not a C++ constructor. Ignore the error for now, because we may
2872     // have more member initializers coming; we'll diagnose it just
2873     // once in ActOnMemInitializers.
2874     return true;
2875   }
2876 
2877   CXXRecordDecl *ClassDecl = Constructor->getParent();
2878 
2879   // C++ [class.base.init]p2:
2880   //   Names in a mem-initializer-id are looked up in the scope of the
2881   //   constructor's class and, if not found in that scope, are looked
2882   //   up in the scope containing the constructor's definition.
2883   //   [Note: if the constructor's class contains a member with the
2884   //   same name as a direct or virtual base class of the class, a
2885   //   mem-initializer-id naming the member or base class and composed
2886   //   of a single identifier refers to the class member. A
2887   //   mem-initializer-id for the hidden base class may be specified
2888   //   using a qualified name. ]
2889   if (!SS.getScopeRep() && !TemplateTypeTy) {
2890     // Look for a member, first.
2891     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2892     if (!Result.empty()) {
2893       ValueDecl *Member;
2894       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2895           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2896         if (EllipsisLoc.isValid())
2897           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2898             << MemberOrBase
2899             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2900 
2901         return BuildMemberInitializer(Member, Init, IdLoc);
2902       }
2903     }
2904   }
2905   // It didn't name a member, so see if it names a class.
2906   QualType BaseType;
2907   TypeSourceInfo *TInfo = nullptr;
2908 
2909   if (TemplateTypeTy) {
2910     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2911   } else if (DS.getTypeSpecType() == TST_decltype) {
2912     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2913   } else {
2914     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2915     LookupParsedName(R, S, &SS);
2916 
2917     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2918     if (!TyD) {
2919       if (R.isAmbiguous()) return true;
2920 
2921       // We don't want access-control diagnostics here.
2922       R.suppressDiagnostics();
2923 
2924       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2925         bool NotUnknownSpecialization = false;
2926         DeclContext *DC = computeDeclContext(SS, false);
2927         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2928           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2929 
2930         if (!NotUnknownSpecialization) {
2931           // When the scope specifier can refer to a member of an unknown
2932           // specialization, we take it as a type name.
2933           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2934                                        SS.getWithLocInContext(Context),
2935                                        *MemberOrBase, IdLoc);
2936           if (BaseType.isNull())
2937             return true;
2938 
2939           R.clear();
2940           R.setLookupName(MemberOrBase);
2941         }
2942       }
2943 
2944       // If no results were found, try to correct typos.
2945       TypoCorrection Corr;
2946       if (R.empty() && BaseType.isNull() &&
2947           (Corr = CorrectTypo(
2948                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2949                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2950                CTK_ErrorRecovery, ClassDecl))) {
2951         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2952           // We have found a non-static data member with a similar
2953           // name to what was typed; complain and initialize that
2954           // member.
2955           diagnoseTypo(Corr,
2956                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2957                          << MemberOrBase << true);
2958           return BuildMemberInitializer(Member, Init, IdLoc);
2959         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2960           const CXXBaseSpecifier *DirectBaseSpec;
2961           const CXXBaseSpecifier *VirtualBaseSpec;
2962           if (FindBaseInitializer(*this, ClassDecl,
2963                                   Context.getTypeDeclType(Type),
2964                                   DirectBaseSpec, VirtualBaseSpec)) {
2965             // We have found a direct or virtual base class with a
2966             // similar name to what was typed; complain and initialize
2967             // that base class.
2968             diagnoseTypo(Corr,
2969                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2970                            << MemberOrBase << false,
2971                          PDiag() /*Suppress note, we provide our own.*/);
2972 
2973             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2974                                                               : VirtualBaseSpec;
2975             Diag(BaseSpec->getLocStart(),
2976                  diag::note_base_class_specified_here)
2977               << BaseSpec->getType()
2978               << BaseSpec->getSourceRange();
2979 
2980             TyD = Type;
2981           }
2982         }
2983       }
2984 
2985       if (!TyD && BaseType.isNull()) {
2986         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2987           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2988         return true;
2989       }
2990     }
2991 
2992     if (BaseType.isNull()) {
2993       BaseType = Context.getTypeDeclType(TyD);
2994       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
2995       if (SS.isSet()) {
2996         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2997                                              BaseType);
2998         TInfo = Context.CreateTypeSourceInfo(BaseType);
2999         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3000         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3001         TL.setElaboratedKeywordLoc(SourceLocation());
3002         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3003       }
3004     }
3005   }
3006 
3007   if (!TInfo)
3008     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3009 
3010   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3011 }
3012 
3013 /// Checks a member initializer expression for cases where reference (or
3014 /// pointer) members are bound to by-value parameters (or their addresses).
3015 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3016                                                Expr *Init,
3017                                                SourceLocation IdLoc) {
3018   QualType MemberTy = Member->getType();
3019 
3020   // We only handle pointers and references currently.
3021   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3022   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3023     return;
3024 
3025   const bool IsPointer = MemberTy->isPointerType();
3026   if (IsPointer) {
3027     if (const UnaryOperator *Op
3028           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3029       // The only case we're worried about with pointers requires taking the
3030       // address.
3031       if (Op->getOpcode() != UO_AddrOf)
3032         return;
3033 
3034       Init = Op->getSubExpr();
3035     } else {
3036       // We only handle address-of expression initializers for pointers.
3037       return;
3038     }
3039   }
3040 
3041   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3042     // We only warn when referring to a non-reference parameter declaration.
3043     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3044     if (!Parameter || Parameter->getType()->isReferenceType())
3045       return;
3046 
3047     S.Diag(Init->getExprLoc(),
3048            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3049                      : diag::warn_bind_ref_member_to_parameter)
3050       << Member << Parameter << Init->getSourceRange();
3051   } else {
3052     // Other initializers are fine.
3053     return;
3054   }
3055 
3056   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3057     << (unsigned)IsPointer;
3058 }
3059 
3060 MemInitResult
3061 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3062                              SourceLocation IdLoc) {
3063   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3064   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3065   assert((DirectMember || IndirectMember) &&
3066          "Member must be a FieldDecl or IndirectFieldDecl");
3067 
3068   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3069     return true;
3070 
3071   if (Member->isInvalidDecl())
3072     return true;
3073 
3074   MultiExprArg Args;
3075   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3076     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3077   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3078     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3079   } else {
3080     // Template instantiation doesn't reconstruct ParenListExprs for us.
3081     Args = Init;
3082   }
3083 
3084   SourceRange InitRange = Init->getSourceRange();
3085 
3086   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3087     // Can't check initialization for a member of dependent type or when
3088     // any of the arguments are type-dependent expressions.
3089     DiscardCleanupsInEvaluationContext();
3090   } else {
3091     bool InitList = false;
3092     if (isa<InitListExpr>(Init)) {
3093       InitList = true;
3094       Args = Init;
3095     }
3096 
3097     // Initialize the member.
3098     InitializedEntity MemberEntity =
3099       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3100                    : InitializedEntity::InitializeMember(IndirectMember,
3101                                                          nullptr);
3102     InitializationKind Kind =
3103       InitList ? InitializationKind::CreateDirectList(IdLoc)
3104                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3105                                                   InitRange.getEnd());
3106 
3107     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3108     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3109                                             nullptr);
3110     if (MemberInit.isInvalid())
3111       return true;
3112 
3113     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3114 
3115     // C++11 [class.base.init]p7:
3116     //   The initialization of each base and member constitutes a
3117     //   full-expression.
3118     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3119     if (MemberInit.isInvalid())
3120       return true;
3121 
3122     Init = MemberInit.get();
3123   }
3124 
3125   if (DirectMember) {
3126     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3127                                             InitRange.getBegin(), Init,
3128                                             InitRange.getEnd());
3129   } else {
3130     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3131                                             InitRange.getBegin(), Init,
3132                                             InitRange.getEnd());
3133   }
3134 }
3135 
3136 MemInitResult
3137 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3138                                  CXXRecordDecl *ClassDecl) {
3139   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3140   if (!LangOpts.CPlusPlus11)
3141     return Diag(NameLoc, diag::err_delegating_ctor)
3142       << TInfo->getTypeLoc().getLocalSourceRange();
3143   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3144 
3145   bool InitList = true;
3146   MultiExprArg Args = Init;
3147   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3148     InitList = false;
3149     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3150   }
3151 
3152   SourceRange InitRange = Init->getSourceRange();
3153   // Initialize the object.
3154   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3155                                      QualType(ClassDecl->getTypeForDecl(), 0));
3156   InitializationKind Kind =
3157     InitList ? InitializationKind::CreateDirectList(NameLoc)
3158              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3159                                                 InitRange.getEnd());
3160   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3161   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3162                                               Args, nullptr);
3163   if (DelegationInit.isInvalid())
3164     return true;
3165 
3166   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3167          "Delegating constructor with no target?");
3168 
3169   // C++11 [class.base.init]p7:
3170   //   The initialization of each base and member constitutes a
3171   //   full-expression.
3172   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3173                                        InitRange.getBegin());
3174   if (DelegationInit.isInvalid())
3175     return true;
3176 
3177   // If we are in a dependent context, template instantiation will
3178   // perform this type-checking again. Just save the arguments that we
3179   // received in a ParenListExpr.
3180   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3181   // of the information that we have about the base
3182   // initializer. However, deconstructing the ASTs is a dicey process,
3183   // and this approach is far more likely to get the corner cases right.
3184   if (CurContext->isDependentContext())
3185     DelegationInit = Init;
3186 
3187   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3188                                           DelegationInit.getAs<Expr>(),
3189                                           InitRange.getEnd());
3190 }
3191 
3192 MemInitResult
3193 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3194                            Expr *Init, CXXRecordDecl *ClassDecl,
3195                            SourceLocation EllipsisLoc) {
3196   SourceLocation BaseLoc
3197     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3198 
3199   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3200     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3201              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3202 
3203   // C++ [class.base.init]p2:
3204   //   [...] Unless the mem-initializer-id names a nonstatic data
3205   //   member of the constructor's class or a direct or virtual base
3206   //   of that class, the mem-initializer is ill-formed. A
3207   //   mem-initializer-list can initialize a base class using any
3208   //   name that denotes that base class type.
3209   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3210 
3211   SourceRange InitRange = Init->getSourceRange();
3212   if (EllipsisLoc.isValid()) {
3213     // This is a pack expansion.
3214     if (!BaseType->containsUnexpandedParameterPack())  {
3215       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3216         << SourceRange(BaseLoc, InitRange.getEnd());
3217 
3218       EllipsisLoc = SourceLocation();
3219     }
3220   } else {
3221     // Check for any unexpanded parameter packs.
3222     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3223       return true;
3224 
3225     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3226       return true;
3227   }
3228 
3229   // Check for direct and virtual base classes.
3230   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3231   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3232   if (!Dependent) {
3233     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3234                                        BaseType))
3235       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3236 
3237     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3238                         VirtualBaseSpec);
3239 
3240     // C++ [base.class.init]p2:
3241     // Unless the mem-initializer-id names a nonstatic data member of the
3242     // constructor's class or a direct or virtual base of that class, the
3243     // mem-initializer is ill-formed.
3244     if (!DirectBaseSpec && !VirtualBaseSpec) {
3245       // If the class has any dependent bases, then it's possible that
3246       // one of those types will resolve to the same type as
3247       // BaseType. Therefore, just treat this as a dependent base
3248       // class initialization.  FIXME: Should we try to check the
3249       // initialization anyway? It seems odd.
3250       if (ClassDecl->hasAnyDependentBases())
3251         Dependent = true;
3252       else
3253         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3254           << BaseType << Context.getTypeDeclType(ClassDecl)
3255           << BaseTInfo->getTypeLoc().getLocalSourceRange();
3256     }
3257   }
3258 
3259   if (Dependent) {
3260     DiscardCleanupsInEvaluationContext();
3261 
3262     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3263                                             /*IsVirtual=*/false,
3264                                             InitRange.getBegin(), Init,
3265                                             InitRange.getEnd(), EllipsisLoc);
3266   }
3267 
3268   // C++ [base.class.init]p2:
3269   //   If a mem-initializer-id is ambiguous because it designates both
3270   //   a direct non-virtual base class and an inherited virtual base
3271   //   class, the mem-initializer is ill-formed.
3272   if (DirectBaseSpec && VirtualBaseSpec)
3273     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3274       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3275 
3276   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3277   if (!BaseSpec)
3278     BaseSpec = VirtualBaseSpec;
3279 
3280   // Initialize the base.
3281   bool InitList = true;
3282   MultiExprArg Args = Init;
3283   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3284     InitList = false;
3285     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3286   }
3287 
3288   InitializedEntity BaseEntity =
3289     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3290   InitializationKind Kind =
3291     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3292              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3293                                                 InitRange.getEnd());
3294   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3295   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3296   if (BaseInit.isInvalid())
3297     return true;
3298 
3299   // C++11 [class.base.init]p7:
3300   //   The initialization of each base and member constitutes a
3301   //   full-expression.
3302   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3303   if (BaseInit.isInvalid())
3304     return true;
3305 
3306   // If we are in a dependent context, template instantiation will
3307   // perform this type-checking again. Just save the arguments that we
3308   // received in a ParenListExpr.
3309   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3310   // of the information that we have about the base
3311   // initializer. However, deconstructing the ASTs is a dicey process,
3312   // and this approach is far more likely to get the corner cases right.
3313   if (CurContext->isDependentContext())
3314     BaseInit = Init;
3315 
3316   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3317                                           BaseSpec->isVirtual(),
3318                                           InitRange.getBegin(),
3319                                           BaseInit.getAs<Expr>(),
3320                                           InitRange.getEnd(), EllipsisLoc);
3321 }
3322 
3323 // Create a static_cast\<T&&>(expr).
3324 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3325   if (T.isNull()) T = E->getType();
3326   QualType TargetType = SemaRef.BuildReferenceType(
3327       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3328   SourceLocation ExprLoc = E->getLocStart();
3329   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3330       TargetType, ExprLoc);
3331 
3332   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3333                                    SourceRange(ExprLoc, ExprLoc),
3334                                    E->getSourceRange()).get();
3335 }
3336 
3337 /// ImplicitInitializerKind - How an implicit base or member initializer should
3338 /// initialize its base or member.
3339 enum ImplicitInitializerKind {
3340   IIK_Default,
3341   IIK_Copy,
3342   IIK_Move,
3343   IIK_Inherit
3344 };
3345 
3346 static bool
3347 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3348                              ImplicitInitializerKind ImplicitInitKind,
3349                              CXXBaseSpecifier *BaseSpec,
3350                              bool IsInheritedVirtualBase,
3351                              CXXCtorInitializer *&CXXBaseInit) {
3352   InitializedEntity InitEntity
3353     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3354                                         IsInheritedVirtualBase);
3355 
3356   ExprResult BaseInit;
3357 
3358   switch (ImplicitInitKind) {
3359   case IIK_Inherit: {
3360     const CXXRecordDecl *Inherited =
3361         Constructor->getInheritedConstructor()->getParent();
3362     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3363     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3364       // C++11 [class.inhctor]p8:
3365       //   Each expression in the expression-list is of the form
3366       //   static_cast<T&&>(p), where p is the name of the corresponding
3367       //   constructor parameter and T is the declared type of p.
3368       SmallVector<Expr*, 16> Args;
3369       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3370         ParmVarDecl *PD = Constructor->getParamDecl(I);
3371         ExprResult ArgExpr =
3372             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3373                                      VK_LValue, SourceLocation());
3374         if (ArgExpr.isInvalid())
3375           return true;
3376         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3377       }
3378 
3379       InitializationKind InitKind = InitializationKind::CreateDirect(
3380           Constructor->getLocation(), SourceLocation(), SourceLocation());
3381       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3382       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3383       break;
3384     }
3385   }
3386   // Fall through.
3387   case IIK_Default: {
3388     InitializationKind InitKind
3389       = InitializationKind::CreateDefault(Constructor->getLocation());
3390     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3391     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3392     break;
3393   }
3394 
3395   case IIK_Move:
3396   case IIK_Copy: {
3397     bool Moving = ImplicitInitKind == IIK_Move;
3398     ParmVarDecl *Param = Constructor->getParamDecl(0);
3399     QualType ParamType = Param->getType().getNonReferenceType();
3400 
3401     Expr *CopyCtorArg =
3402       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3403                           SourceLocation(), Param, false,
3404                           Constructor->getLocation(), ParamType,
3405                           VK_LValue, nullptr);
3406 
3407     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3408 
3409     // Cast to the base class to avoid ambiguities.
3410     QualType ArgTy =
3411       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3412                                        ParamType.getQualifiers());
3413 
3414     if (Moving) {
3415       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3416     }
3417 
3418     CXXCastPath BasePath;
3419     BasePath.push_back(BaseSpec);
3420     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3421                                             CK_UncheckedDerivedToBase,
3422                                             Moving ? VK_XValue : VK_LValue,
3423                                             &BasePath).get();
3424 
3425     InitializationKind InitKind
3426       = InitializationKind::CreateDirect(Constructor->getLocation(),
3427                                          SourceLocation(), SourceLocation());
3428     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3429     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3430     break;
3431   }
3432   }
3433 
3434   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3435   if (BaseInit.isInvalid())
3436     return true;
3437 
3438   CXXBaseInit =
3439     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3440                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3441                                                         SourceLocation()),
3442                                              BaseSpec->isVirtual(),
3443                                              SourceLocation(),
3444                                              BaseInit.getAs<Expr>(),
3445                                              SourceLocation(),
3446                                              SourceLocation());
3447 
3448   return false;
3449 }
3450 
3451 static bool RefersToRValueRef(Expr *MemRef) {
3452   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3453   return Referenced->getType()->isRValueReferenceType();
3454 }
3455 
3456 static bool
3457 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3458                                ImplicitInitializerKind ImplicitInitKind,
3459                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3460                                CXXCtorInitializer *&CXXMemberInit) {
3461   if (Field->isInvalidDecl())
3462     return true;
3463 
3464   SourceLocation Loc = Constructor->getLocation();
3465 
3466   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3467     bool Moving = ImplicitInitKind == IIK_Move;
3468     ParmVarDecl *Param = Constructor->getParamDecl(0);
3469     QualType ParamType = Param->getType().getNonReferenceType();
3470 
3471     // Suppress copying zero-width bitfields.
3472     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3473       return false;
3474 
3475     Expr *MemberExprBase =
3476       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3477                           SourceLocation(), Param, false,
3478                           Loc, ParamType, VK_LValue, nullptr);
3479 
3480     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3481 
3482     if (Moving) {
3483       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3484     }
3485 
3486     // Build a reference to this field within the parameter.
3487     CXXScopeSpec SS;
3488     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3489                               Sema::LookupMemberName);
3490     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3491                                   : cast<ValueDecl>(Field), AS_public);
3492     MemberLookup.resolveKind();
3493     ExprResult CtorArg
3494       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3495                                          ParamType, Loc,
3496                                          /*IsArrow=*/false,
3497                                          SS,
3498                                          /*TemplateKWLoc=*/SourceLocation(),
3499                                          /*FirstQualifierInScope=*/nullptr,
3500                                          MemberLookup,
3501                                          /*TemplateArgs=*/nullptr,
3502                                          /*S*/nullptr);
3503     if (CtorArg.isInvalid())
3504       return true;
3505 
3506     // C++11 [class.copy]p15:
3507     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3508     //     with static_cast<T&&>(x.m);
3509     if (RefersToRValueRef(CtorArg.get())) {
3510       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3511     }
3512 
3513     // When the field we are copying is an array, create index variables for
3514     // each dimension of the array. We use these index variables to subscript
3515     // the source array, and other clients (e.g., CodeGen) will perform the
3516     // necessary iteration with these index variables.
3517     SmallVector<VarDecl *, 4> IndexVariables;
3518     QualType BaseType = Field->getType();
3519     QualType SizeType = SemaRef.Context.getSizeType();
3520     bool InitializingArray = false;
3521     while (const ConstantArrayType *Array
3522                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3523       InitializingArray = true;
3524       // Create the iteration variable for this array index.
3525       IdentifierInfo *IterationVarName = nullptr;
3526       {
3527         SmallString<8> Str;
3528         llvm::raw_svector_ostream OS(Str);
3529         OS << "__i" << IndexVariables.size();
3530         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3531       }
3532       VarDecl *IterationVar
3533         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3534                           IterationVarName, SizeType,
3535                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3536                           SC_None);
3537       IndexVariables.push_back(IterationVar);
3538 
3539       // Create a reference to the iteration variable.
3540       ExprResult IterationVarRef
3541         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3542       assert(!IterationVarRef.isInvalid() &&
3543              "Reference to invented variable cannot fail!");
3544       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3545       assert(!IterationVarRef.isInvalid() &&
3546              "Conversion of invented variable cannot fail!");
3547 
3548       // Subscript the array with this iteration variable.
3549       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3550                                                         IterationVarRef.get(),
3551                                                         Loc);
3552       if (CtorArg.isInvalid())
3553         return true;
3554 
3555       BaseType = Array->getElementType();
3556     }
3557 
3558     // The array subscript expression is an lvalue, which is wrong for moving.
3559     if (Moving && InitializingArray)
3560       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3561 
3562     // Construct the entity that we will be initializing. For an array, this
3563     // will be first element in the array, which may require several levels
3564     // of array-subscript entities.
3565     SmallVector<InitializedEntity, 4> Entities;
3566     Entities.reserve(1 + IndexVariables.size());
3567     if (Indirect)
3568       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3569     else
3570       Entities.push_back(InitializedEntity::InitializeMember(Field));
3571     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3572       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3573                                                               0,
3574                                                               Entities.back()));
3575 
3576     // Direct-initialize to use the copy constructor.
3577     InitializationKind InitKind =
3578       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3579 
3580     Expr *CtorArgE = CtorArg.getAs<Expr>();
3581     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3582                                    CtorArgE);
3583 
3584     ExprResult MemberInit
3585       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3586                         MultiExprArg(&CtorArgE, 1));
3587     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3588     if (MemberInit.isInvalid())
3589       return true;
3590 
3591     if (Indirect) {
3592       assert(IndexVariables.size() == 0 &&
3593              "Indirect field improperly initialized");
3594       CXXMemberInit
3595         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3596                                                    Loc, Loc,
3597                                                    MemberInit.getAs<Expr>(),
3598                                                    Loc);
3599     } else
3600       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3601                                                  Loc, MemberInit.getAs<Expr>(),
3602                                                  Loc,
3603                                                  IndexVariables.data(),
3604                                                  IndexVariables.size());
3605     return false;
3606   }
3607 
3608   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3609          "Unhandled implicit init kind!");
3610 
3611   QualType FieldBaseElementType =
3612     SemaRef.Context.getBaseElementType(Field->getType());
3613 
3614   if (FieldBaseElementType->isRecordType()) {
3615     InitializedEntity InitEntity
3616       = Indirect? InitializedEntity::InitializeMember(Indirect)
3617                 : InitializedEntity::InitializeMember(Field);
3618     InitializationKind InitKind =
3619       InitializationKind::CreateDefault(Loc);
3620 
3621     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3622     ExprResult MemberInit =
3623       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3624 
3625     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3626     if (MemberInit.isInvalid())
3627       return true;
3628 
3629     if (Indirect)
3630       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3631                                                                Indirect, Loc,
3632                                                                Loc,
3633                                                                MemberInit.get(),
3634                                                                Loc);
3635     else
3636       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3637                                                                Field, Loc, Loc,
3638                                                                MemberInit.get(),
3639                                                                Loc);
3640     return false;
3641   }
3642 
3643   if (!Field->getParent()->isUnion()) {
3644     if (FieldBaseElementType->isReferenceType()) {
3645       SemaRef.Diag(Constructor->getLocation(),
3646                    diag::err_uninitialized_member_in_ctor)
3647       << (int)Constructor->isImplicit()
3648       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3649       << 0 << Field->getDeclName();
3650       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3651       return true;
3652     }
3653 
3654     if (FieldBaseElementType.isConstQualified()) {
3655       SemaRef.Diag(Constructor->getLocation(),
3656                    diag::err_uninitialized_member_in_ctor)
3657       << (int)Constructor->isImplicit()
3658       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3659       << 1 << Field->getDeclName();
3660       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3661       return true;
3662     }
3663   }
3664 
3665   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3666       FieldBaseElementType->isObjCRetainableType() &&
3667       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3668       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3669     // ARC:
3670     //   Default-initialize Objective-C pointers to NULL.
3671     CXXMemberInit
3672       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3673                                                  Loc, Loc,
3674                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3675                                                  Loc);
3676     return false;
3677   }
3678 
3679   // Nothing to initialize.
3680   CXXMemberInit = nullptr;
3681   return false;
3682 }
3683 
3684 namespace {
3685 struct BaseAndFieldInfo {
3686   Sema &S;
3687   CXXConstructorDecl *Ctor;
3688   bool AnyErrorsInInits;
3689   ImplicitInitializerKind IIK;
3690   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3691   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3692   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3693 
3694   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3695     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3696     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3697     if (Generated && Ctor->isCopyConstructor())
3698       IIK = IIK_Copy;
3699     else if (Generated && Ctor->isMoveConstructor())
3700       IIK = IIK_Move;
3701     else if (Ctor->getInheritedConstructor())
3702       IIK = IIK_Inherit;
3703     else
3704       IIK = IIK_Default;
3705   }
3706 
3707   bool isImplicitCopyOrMove() const {
3708     switch (IIK) {
3709     case IIK_Copy:
3710     case IIK_Move:
3711       return true;
3712 
3713     case IIK_Default:
3714     case IIK_Inherit:
3715       return false;
3716     }
3717 
3718     llvm_unreachable("Invalid ImplicitInitializerKind!");
3719   }
3720 
3721   bool addFieldInitializer(CXXCtorInitializer *Init) {
3722     AllToInit.push_back(Init);
3723 
3724     // Check whether this initializer makes the field "used".
3725     if (Init->getInit()->HasSideEffects(S.Context))
3726       S.UnusedPrivateFields.remove(Init->getAnyMember());
3727 
3728     return false;
3729   }
3730 
3731   bool isInactiveUnionMember(FieldDecl *Field) {
3732     RecordDecl *Record = Field->getParent();
3733     if (!Record->isUnion())
3734       return false;
3735 
3736     if (FieldDecl *Active =
3737             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3738       return Active != Field->getCanonicalDecl();
3739 
3740     // In an implicit copy or move constructor, ignore any in-class initializer.
3741     if (isImplicitCopyOrMove())
3742       return true;
3743 
3744     // If there's no explicit initialization, the field is active only if it
3745     // has an in-class initializer...
3746     if (Field->hasInClassInitializer())
3747       return false;
3748     // ... or it's an anonymous struct or union whose class has an in-class
3749     // initializer.
3750     if (!Field->isAnonymousStructOrUnion())
3751       return true;
3752     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3753     return !FieldRD->hasInClassInitializer();
3754   }
3755 
3756   /// \brief Determine whether the given field is, or is within, a union member
3757   /// that is inactive (because there was an initializer given for a different
3758   /// member of the union, or because the union was not initialized at all).
3759   bool isWithinInactiveUnionMember(FieldDecl *Field,
3760                                    IndirectFieldDecl *Indirect) {
3761     if (!Indirect)
3762       return isInactiveUnionMember(Field);
3763 
3764     for (auto *C : Indirect->chain()) {
3765       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3766       if (Field && isInactiveUnionMember(Field))
3767         return true;
3768     }
3769     return false;
3770   }
3771 };
3772 }
3773 
3774 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3775 /// array type.
3776 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3777   if (T->isIncompleteArrayType())
3778     return true;
3779 
3780   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3781     if (!ArrayT->getSize())
3782       return true;
3783 
3784     T = ArrayT->getElementType();
3785   }
3786 
3787   return false;
3788 }
3789 
3790 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3791                                     FieldDecl *Field,
3792                                     IndirectFieldDecl *Indirect = nullptr) {
3793   if (Field->isInvalidDecl())
3794     return false;
3795 
3796   // Overwhelmingly common case: we have a direct initializer for this field.
3797   if (CXXCtorInitializer *Init =
3798           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3799     return Info.addFieldInitializer(Init);
3800 
3801   // C++11 [class.base.init]p8:
3802   //   if the entity is a non-static data member that has a
3803   //   brace-or-equal-initializer and either
3804   //   -- the constructor's class is a union and no other variant member of that
3805   //      union is designated by a mem-initializer-id or
3806   //   -- the constructor's class is not a union, and, if the entity is a member
3807   //      of an anonymous union, no other member of that union is designated by
3808   //      a mem-initializer-id,
3809   //   the entity is initialized as specified in [dcl.init].
3810   //
3811   // We also apply the same rules to handle anonymous structs within anonymous
3812   // unions.
3813   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3814     return false;
3815 
3816   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3817     ExprResult DIE =
3818         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3819     if (DIE.isInvalid())
3820       return true;
3821     CXXCtorInitializer *Init;
3822     if (Indirect)
3823       Init = new (SemaRef.Context)
3824           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3825                              SourceLocation(), DIE.get(), SourceLocation());
3826     else
3827       Init = new (SemaRef.Context)
3828           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3829                              SourceLocation(), DIE.get(), SourceLocation());
3830     return Info.addFieldInitializer(Init);
3831   }
3832 
3833   // Don't initialize incomplete or zero-length arrays.
3834   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3835     return false;
3836 
3837   // Don't try to build an implicit initializer if there were semantic
3838   // errors in any of the initializers (and therefore we might be
3839   // missing some that the user actually wrote).
3840   if (Info.AnyErrorsInInits)
3841     return false;
3842 
3843   CXXCtorInitializer *Init = nullptr;
3844   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3845                                      Indirect, Init))
3846     return true;
3847 
3848   if (!Init)
3849     return false;
3850 
3851   return Info.addFieldInitializer(Init);
3852 }
3853 
3854 bool
3855 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3856                                CXXCtorInitializer *Initializer) {
3857   assert(Initializer->isDelegatingInitializer());
3858   Constructor->setNumCtorInitializers(1);
3859   CXXCtorInitializer **initializer =
3860     new (Context) CXXCtorInitializer*[1];
3861   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3862   Constructor->setCtorInitializers(initializer);
3863 
3864   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3865     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3866     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3867   }
3868 
3869   DelegatingCtorDecls.push_back(Constructor);
3870 
3871   DiagnoseUninitializedFields(*this, Constructor);
3872 
3873   return false;
3874 }
3875 
3876 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3877                                ArrayRef<CXXCtorInitializer *> Initializers) {
3878   if (Constructor->isDependentContext()) {
3879     // Just store the initializers as written, they will be checked during
3880     // instantiation.
3881     if (!Initializers.empty()) {
3882       Constructor->setNumCtorInitializers(Initializers.size());
3883       CXXCtorInitializer **baseOrMemberInitializers =
3884         new (Context) CXXCtorInitializer*[Initializers.size()];
3885       memcpy(baseOrMemberInitializers, Initializers.data(),
3886              Initializers.size() * sizeof(CXXCtorInitializer*));
3887       Constructor->setCtorInitializers(baseOrMemberInitializers);
3888     }
3889 
3890     // Let template instantiation know whether we had errors.
3891     if (AnyErrors)
3892       Constructor->setInvalidDecl();
3893 
3894     return false;
3895   }
3896 
3897   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3898 
3899   // We need to build the initializer AST according to order of construction
3900   // and not what user specified in the Initializers list.
3901   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3902   if (!ClassDecl)
3903     return true;
3904 
3905   bool HadError = false;
3906 
3907   for (unsigned i = 0; i < Initializers.size(); i++) {
3908     CXXCtorInitializer *Member = Initializers[i];
3909 
3910     if (Member->isBaseInitializer())
3911       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3912     else {
3913       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3914 
3915       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3916         for (auto *C : F->chain()) {
3917           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3918           if (FD && FD->getParent()->isUnion())
3919             Info.ActiveUnionMember.insert(std::make_pair(
3920                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3921         }
3922       } else if (FieldDecl *FD = Member->getMember()) {
3923         if (FD->getParent()->isUnion())
3924           Info.ActiveUnionMember.insert(std::make_pair(
3925               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3926       }
3927     }
3928   }
3929 
3930   // Keep track of the direct virtual bases.
3931   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3932   for (auto &I : ClassDecl->bases()) {
3933     if (I.isVirtual())
3934       DirectVBases.insert(&I);
3935   }
3936 
3937   // Push virtual bases before others.
3938   for (auto &VBase : ClassDecl->vbases()) {
3939     if (CXXCtorInitializer *Value
3940         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3941       // [class.base.init]p7, per DR257:
3942       //   A mem-initializer where the mem-initializer-id names a virtual base
3943       //   class is ignored during execution of a constructor of any class that
3944       //   is not the most derived class.
3945       if (ClassDecl->isAbstract()) {
3946         // FIXME: Provide a fixit to remove the base specifier. This requires
3947         // tracking the location of the associated comma for a base specifier.
3948         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3949           << VBase.getType() << ClassDecl;
3950         DiagnoseAbstractType(ClassDecl);
3951       }
3952 
3953       Info.AllToInit.push_back(Value);
3954     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3955       // [class.base.init]p8, per DR257:
3956       //   If a given [...] base class is not named by a mem-initializer-id
3957       //   [...] and the entity is not a virtual base class of an abstract
3958       //   class, then [...] the entity is default-initialized.
3959       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3960       CXXCtorInitializer *CXXBaseInit;
3961       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3962                                        &VBase, IsInheritedVirtualBase,
3963                                        CXXBaseInit)) {
3964         HadError = true;
3965         continue;
3966       }
3967 
3968       Info.AllToInit.push_back(CXXBaseInit);
3969     }
3970   }
3971 
3972   // Non-virtual bases.
3973   for (auto &Base : ClassDecl->bases()) {
3974     // Virtuals are in the virtual base list and already constructed.
3975     if (Base.isVirtual())
3976       continue;
3977 
3978     if (CXXCtorInitializer *Value
3979           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3980       Info.AllToInit.push_back(Value);
3981     } else if (!AnyErrors) {
3982       CXXCtorInitializer *CXXBaseInit;
3983       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3984                                        &Base, /*IsInheritedVirtualBase=*/false,
3985                                        CXXBaseInit)) {
3986         HadError = true;
3987         continue;
3988       }
3989 
3990       Info.AllToInit.push_back(CXXBaseInit);
3991     }
3992   }
3993 
3994   // Fields.
3995   for (auto *Mem : ClassDecl->decls()) {
3996     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3997       // C++ [class.bit]p2:
3998       //   A declaration for a bit-field that omits the identifier declares an
3999       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4000       //   initialized.
4001       if (F->isUnnamedBitfield())
4002         continue;
4003 
4004       // If we're not generating the implicit copy/move constructor, then we'll
4005       // handle anonymous struct/union fields based on their individual
4006       // indirect fields.
4007       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4008         continue;
4009 
4010       if (CollectFieldInitializer(*this, Info, F))
4011         HadError = true;
4012       continue;
4013     }
4014 
4015     // Beyond this point, we only consider default initialization.
4016     if (Info.isImplicitCopyOrMove())
4017       continue;
4018 
4019     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4020       if (F->getType()->isIncompleteArrayType()) {
4021         assert(ClassDecl->hasFlexibleArrayMember() &&
4022                "Incomplete array type is not valid");
4023         continue;
4024       }
4025 
4026       // Initialize each field of an anonymous struct individually.
4027       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4028         HadError = true;
4029 
4030       continue;
4031     }
4032   }
4033 
4034   unsigned NumInitializers = Info.AllToInit.size();
4035   if (NumInitializers > 0) {
4036     Constructor->setNumCtorInitializers(NumInitializers);
4037     CXXCtorInitializer **baseOrMemberInitializers =
4038       new (Context) CXXCtorInitializer*[NumInitializers];
4039     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4040            NumInitializers * sizeof(CXXCtorInitializer*));
4041     Constructor->setCtorInitializers(baseOrMemberInitializers);
4042 
4043     // Constructors implicitly reference the base and member
4044     // destructors.
4045     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4046                                            Constructor->getParent());
4047   }
4048 
4049   return HadError;
4050 }
4051 
4052 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4053   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4054     const RecordDecl *RD = RT->getDecl();
4055     if (RD->isAnonymousStructOrUnion()) {
4056       for (auto *Field : RD->fields())
4057         PopulateKeysForFields(Field, IdealInits);
4058       return;
4059     }
4060   }
4061   IdealInits.push_back(Field->getCanonicalDecl());
4062 }
4063 
4064 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4065   return Context.getCanonicalType(BaseType).getTypePtr();
4066 }
4067 
4068 static const void *GetKeyForMember(ASTContext &Context,
4069                                    CXXCtorInitializer *Member) {
4070   if (!Member->isAnyMemberInitializer())
4071     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4072 
4073   return Member->getAnyMember()->getCanonicalDecl();
4074 }
4075 
4076 static void DiagnoseBaseOrMemInitializerOrder(
4077     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4078     ArrayRef<CXXCtorInitializer *> Inits) {
4079   if (Constructor->getDeclContext()->isDependentContext())
4080     return;
4081 
4082   // Don't check initializers order unless the warning is enabled at the
4083   // location of at least one initializer.
4084   bool ShouldCheckOrder = false;
4085   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4086     CXXCtorInitializer *Init = Inits[InitIndex];
4087     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4088                                  Init->getSourceLocation())) {
4089       ShouldCheckOrder = true;
4090       break;
4091     }
4092   }
4093   if (!ShouldCheckOrder)
4094     return;
4095 
4096   // Build the list of bases and members in the order that they'll
4097   // actually be initialized.  The explicit initializers should be in
4098   // this same order but may be missing things.
4099   SmallVector<const void*, 32> IdealInitKeys;
4100 
4101   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4102 
4103   // 1. Virtual bases.
4104   for (const auto &VBase : ClassDecl->vbases())
4105     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4106 
4107   // 2. Non-virtual bases.
4108   for (const auto &Base : ClassDecl->bases()) {
4109     if (Base.isVirtual())
4110       continue;
4111     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4112   }
4113 
4114   // 3. Direct fields.
4115   for (auto *Field : ClassDecl->fields()) {
4116     if (Field->isUnnamedBitfield())
4117       continue;
4118 
4119     PopulateKeysForFields(Field, IdealInitKeys);
4120   }
4121 
4122   unsigned NumIdealInits = IdealInitKeys.size();
4123   unsigned IdealIndex = 0;
4124 
4125   CXXCtorInitializer *PrevInit = nullptr;
4126   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4127     CXXCtorInitializer *Init = Inits[InitIndex];
4128     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4129 
4130     // Scan forward to try to find this initializer in the idealized
4131     // initializers list.
4132     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4133       if (InitKey == IdealInitKeys[IdealIndex])
4134         break;
4135 
4136     // If we didn't find this initializer, it must be because we
4137     // scanned past it on a previous iteration.  That can only
4138     // happen if we're out of order;  emit a warning.
4139     if (IdealIndex == NumIdealInits && PrevInit) {
4140       Sema::SemaDiagnosticBuilder D =
4141         SemaRef.Diag(PrevInit->getSourceLocation(),
4142                      diag::warn_initializer_out_of_order);
4143 
4144       if (PrevInit->isAnyMemberInitializer())
4145         D << 0 << PrevInit->getAnyMember()->getDeclName();
4146       else
4147         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4148 
4149       if (Init->isAnyMemberInitializer())
4150         D << 0 << Init->getAnyMember()->getDeclName();
4151       else
4152         D << 1 << Init->getTypeSourceInfo()->getType();
4153 
4154       // Move back to the initializer's location in the ideal list.
4155       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4156         if (InitKey == IdealInitKeys[IdealIndex])
4157           break;
4158 
4159       assert(IdealIndex < NumIdealInits &&
4160              "initializer not found in initializer list");
4161     }
4162 
4163     PrevInit = Init;
4164   }
4165 }
4166 
4167 namespace {
4168 bool CheckRedundantInit(Sema &S,
4169                         CXXCtorInitializer *Init,
4170                         CXXCtorInitializer *&PrevInit) {
4171   if (!PrevInit) {
4172     PrevInit = Init;
4173     return false;
4174   }
4175 
4176   if (FieldDecl *Field = Init->getAnyMember())
4177     S.Diag(Init->getSourceLocation(),
4178            diag::err_multiple_mem_initialization)
4179       << Field->getDeclName()
4180       << Init->getSourceRange();
4181   else {
4182     const Type *BaseClass = Init->getBaseClass();
4183     assert(BaseClass && "neither field nor base");
4184     S.Diag(Init->getSourceLocation(),
4185            diag::err_multiple_base_initialization)
4186       << QualType(BaseClass, 0)
4187       << Init->getSourceRange();
4188   }
4189   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4190     << 0 << PrevInit->getSourceRange();
4191 
4192   return true;
4193 }
4194 
4195 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4196 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4197 
4198 bool CheckRedundantUnionInit(Sema &S,
4199                              CXXCtorInitializer *Init,
4200                              RedundantUnionMap &Unions) {
4201   FieldDecl *Field = Init->getAnyMember();
4202   RecordDecl *Parent = Field->getParent();
4203   NamedDecl *Child = Field;
4204 
4205   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4206     if (Parent->isUnion()) {
4207       UnionEntry &En = Unions[Parent];
4208       if (En.first && En.first != Child) {
4209         S.Diag(Init->getSourceLocation(),
4210                diag::err_multiple_mem_union_initialization)
4211           << Field->getDeclName()
4212           << Init->getSourceRange();
4213         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4214           << 0 << En.second->getSourceRange();
4215         return true;
4216       }
4217       if (!En.first) {
4218         En.first = Child;
4219         En.second = Init;
4220       }
4221       if (!Parent->isAnonymousStructOrUnion())
4222         return false;
4223     }
4224 
4225     Child = Parent;
4226     Parent = cast<RecordDecl>(Parent->getDeclContext());
4227   }
4228 
4229   return false;
4230 }
4231 }
4232 
4233 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4234 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4235                                 SourceLocation ColonLoc,
4236                                 ArrayRef<CXXCtorInitializer*> MemInits,
4237                                 bool AnyErrors) {
4238   if (!ConstructorDecl)
4239     return;
4240 
4241   AdjustDeclIfTemplate(ConstructorDecl);
4242 
4243   CXXConstructorDecl *Constructor
4244     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4245 
4246   if (!Constructor) {
4247     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4248     return;
4249   }
4250 
4251   // Mapping for the duplicate initializers check.
4252   // For member initializers, this is keyed with a FieldDecl*.
4253   // For base initializers, this is keyed with a Type*.
4254   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4255 
4256   // Mapping for the inconsistent anonymous-union initializers check.
4257   RedundantUnionMap MemberUnions;
4258 
4259   bool HadError = false;
4260   for (unsigned i = 0; i < MemInits.size(); i++) {
4261     CXXCtorInitializer *Init = MemInits[i];
4262 
4263     // Set the source order index.
4264     Init->setSourceOrder(i);
4265 
4266     if (Init->isAnyMemberInitializer()) {
4267       const void *Key = GetKeyForMember(Context, Init);
4268       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4269           CheckRedundantUnionInit(*this, Init, MemberUnions))
4270         HadError = true;
4271     } else if (Init->isBaseInitializer()) {
4272       const void *Key = GetKeyForMember(Context, Init);
4273       if (CheckRedundantInit(*this, Init, Members[Key]))
4274         HadError = true;
4275     } else {
4276       assert(Init->isDelegatingInitializer());
4277       // This must be the only initializer
4278       if (MemInits.size() != 1) {
4279         Diag(Init->getSourceLocation(),
4280              diag::err_delegating_initializer_alone)
4281           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4282         // We will treat this as being the only initializer.
4283       }
4284       SetDelegatingInitializer(Constructor, MemInits[i]);
4285       // Return immediately as the initializer is set.
4286       return;
4287     }
4288   }
4289 
4290   if (HadError)
4291     return;
4292 
4293   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4294 
4295   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4296 
4297   DiagnoseUninitializedFields(*this, Constructor);
4298 }
4299 
4300 void
4301 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4302                                              CXXRecordDecl *ClassDecl) {
4303   // Ignore dependent contexts. Also ignore unions, since their members never
4304   // have destructors implicitly called.
4305   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4306     return;
4307 
4308   // FIXME: all the access-control diagnostics are positioned on the
4309   // field/base declaration.  That's probably good; that said, the
4310   // user might reasonably want to know why the destructor is being
4311   // emitted, and we currently don't say.
4312 
4313   // Non-static data members.
4314   for (auto *Field : ClassDecl->fields()) {
4315     if (Field->isInvalidDecl())
4316       continue;
4317 
4318     // Don't destroy incomplete or zero-length arrays.
4319     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4320       continue;
4321 
4322     QualType FieldType = Context.getBaseElementType(Field->getType());
4323 
4324     const RecordType* RT = FieldType->getAs<RecordType>();
4325     if (!RT)
4326       continue;
4327 
4328     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4329     if (FieldClassDecl->isInvalidDecl())
4330       continue;
4331     if (FieldClassDecl->hasIrrelevantDestructor())
4332       continue;
4333     // The destructor for an implicit anonymous union member is never invoked.
4334     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4335       continue;
4336 
4337     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4338     assert(Dtor && "No dtor found for FieldClassDecl!");
4339     CheckDestructorAccess(Field->getLocation(), Dtor,
4340                           PDiag(diag::err_access_dtor_field)
4341                             << Field->getDeclName()
4342                             << FieldType);
4343 
4344     MarkFunctionReferenced(Location, Dtor);
4345     DiagnoseUseOfDecl(Dtor, Location);
4346   }
4347 
4348   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4349 
4350   // Bases.
4351   for (const auto &Base : ClassDecl->bases()) {
4352     // Bases are always records in a well-formed non-dependent class.
4353     const RecordType *RT = Base.getType()->getAs<RecordType>();
4354 
4355     // Remember direct virtual bases.
4356     if (Base.isVirtual())
4357       DirectVirtualBases.insert(RT);
4358 
4359     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4360     // If our base class is invalid, we probably can't get its dtor anyway.
4361     if (BaseClassDecl->isInvalidDecl())
4362       continue;
4363     if (BaseClassDecl->hasIrrelevantDestructor())
4364       continue;
4365 
4366     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4367     assert(Dtor && "No dtor found for BaseClassDecl!");
4368 
4369     // FIXME: caret should be on the start of the class name
4370     CheckDestructorAccess(Base.getLocStart(), Dtor,
4371                           PDiag(diag::err_access_dtor_base)
4372                             << Base.getType()
4373                             << Base.getSourceRange(),
4374                           Context.getTypeDeclType(ClassDecl));
4375 
4376     MarkFunctionReferenced(Location, Dtor);
4377     DiagnoseUseOfDecl(Dtor, Location);
4378   }
4379 
4380   // Virtual bases.
4381   for (const auto &VBase : ClassDecl->vbases()) {
4382     // Bases are always records in a well-formed non-dependent class.
4383     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4384 
4385     // Ignore direct virtual bases.
4386     if (DirectVirtualBases.count(RT))
4387       continue;
4388 
4389     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4390     // If our base class is invalid, we probably can't get its dtor anyway.
4391     if (BaseClassDecl->isInvalidDecl())
4392       continue;
4393     if (BaseClassDecl->hasIrrelevantDestructor())
4394       continue;
4395 
4396     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4397     assert(Dtor && "No dtor found for BaseClassDecl!");
4398     if (CheckDestructorAccess(
4399             ClassDecl->getLocation(), Dtor,
4400             PDiag(diag::err_access_dtor_vbase)
4401                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4402             Context.getTypeDeclType(ClassDecl)) ==
4403         AR_accessible) {
4404       CheckDerivedToBaseConversion(
4405           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4406           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4407           SourceRange(), DeclarationName(), nullptr);
4408     }
4409 
4410     MarkFunctionReferenced(Location, Dtor);
4411     DiagnoseUseOfDecl(Dtor, Location);
4412   }
4413 }
4414 
4415 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4416   if (!CDtorDecl)
4417     return;
4418 
4419   if (CXXConstructorDecl *Constructor
4420       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4421     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4422     DiagnoseUninitializedFields(*this, Constructor);
4423   }
4424 }
4425 
4426 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
4427   if (!getLangOpts().CPlusPlus)
4428     return false;
4429 
4430   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
4431   if (!RD)
4432     return false;
4433 
4434   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
4435   // class template specialization here, but doing so breaks a lot of code.
4436 
4437   // We can't answer whether something is abstract until it has a
4438   // definition. If it's currently being defined, we'll walk back
4439   // over all the declarations when we have a full definition.
4440   const CXXRecordDecl *Def = RD->getDefinition();
4441   if (!Def || Def->isBeingDefined())
4442     return false;
4443 
4444   return RD->isAbstract();
4445 }
4446 
4447 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4448                                   TypeDiagnoser &Diagnoser) {
4449   if (!isAbstractType(Loc, T))
4450     return false;
4451 
4452   T = Context.getBaseElementType(T);
4453   Diagnoser.diagnose(*this, Loc, T);
4454   DiagnoseAbstractType(T->getAsCXXRecordDecl());
4455   return true;
4456 }
4457 
4458 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4459   // Check if we've already emitted the list of pure virtual functions
4460   // for this class.
4461   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4462     return;
4463 
4464   // If the diagnostic is suppressed, don't emit the notes. We're only
4465   // going to emit them once, so try to attach them to a diagnostic we're
4466   // actually going to show.
4467   if (Diags.isLastDiagnosticIgnored())
4468     return;
4469 
4470   CXXFinalOverriderMap FinalOverriders;
4471   RD->getFinalOverriders(FinalOverriders);
4472 
4473   // Keep a set of seen pure methods so we won't diagnose the same method
4474   // more than once.
4475   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4476 
4477   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4478                                    MEnd = FinalOverriders.end();
4479        M != MEnd;
4480        ++M) {
4481     for (OverridingMethods::iterator SO = M->second.begin(),
4482                                   SOEnd = M->second.end();
4483          SO != SOEnd; ++SO) {
4484       // C++ [class.abstract]p4:
4485       //   A class is abstract if it contains or inherits at least one
4486       //   pure virtual function for which the final overrider is pure
4487       //   virtual.
4488 
4489       //
4490       if (SO->second.size() != 1)
4491         continue;
4492 
4493       if (!SO->second.front().Method->isPure())
4494         continue;
4495 
4496       if (!SeenPureMethods.insert(SO->second.front().Method).second)
4497         continue;
4498 
4499       Diag(SO->second.front().Method->getLocation(),
4500            diag::note_pure_virtual_function)
4501         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4502     }
4503   }
4504 
4505   if (!PureVirtualClassDiagSet)
4506     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4507   PureVirtualClassDiagSet->insert(RD);
4508 }
4509 
4510 namespace {
4511 struct AbstractUsageInfo {
4512   Sema &S;
4513   CXXRecordDecl *Record;
4514   CanQualType AbstractType;
4515   bool Invalid;
4516 
4517   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4518     : S(S), Record(Record),
4519       AbstractType(S.Context.getCanonicalType(
4520                    S.Context.getTypeDeclType(Record))),
4521       Invalid(false) {}
4522 
4523   void DiagnoseAbstractType() {
4524     if (Invalid) return;
4525     S.DiagnoseAbstractType(Record);
4526     Invalid = true;
4527   }
4528 
4529   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4530 };
4531 
4532 struct CheckAbstractUsage {
4533   AbstractUsageInfo &Info;
4534   const NamedDecl *Ctx;
4535 
4536   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4537     : Info(Info), Ctx(Ctx) {}
4538 
4539   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4540     switch (TL.getTypeLocClass()) {
4541 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4542 #define TYPELOC(CLASS, PARENT) \
4543     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4544 #include "clang/AST/TypeLocNodes.def"
4545     }
4546   }
4547 
4548   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4549     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4550     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4551       if (!TL.getParam(I))
4552         continue;
4553 
4554       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4555       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4556     }
4557   }
4558 
4559   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4560     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4561   }
4562 
4563   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4564     // Visit the type parameters from a permissive context.
4565     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4566       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4567       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4568         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4569           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4570       // TODO: other template argument types?
4571     }
4572   }
4573 
4574   // Visit pointee types from a permissive context.
4575 #define CheckPolymorphic(Type) \
4576   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4577     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4578   }
4579   CheckPolymorphic(PointerTypeLoc)
4580   CheckPolymorphic(ReferenceTypeLoc)
4581   CheckPolymorphic(MemberPointerTypeLoc)
4582   CheckPolymorphic(BlockPointerTypeLoc)
4583   CheckPolymorphic(AtomicTypeLoc)
4584 
4585   /// Handle all the types we haven't given a more specific
4586   /// implementation for above.
4587   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4588     // Every other kind of type that we haven't called out already
4589     // that has an inner type is either (1) sugar or (2) contains that
4590     // inner type in some way as a subobject.
4591     if (TypeLoc Next = TL.getNextTypeLoc())
4592       return Visit(Next, Sel);
4593 
4594     // If there's no inner type and we're in a permissive context,
4595     // don't diagnose.
4596     if (Sel == Sema::AbstractNone) return;
4597 
4598     // Check whether the type matches the abstract type.
4599     QualType T = TL.getType();
4600     if (T->isArrayType()) {
4601       Sel = Sema::AbstractArrayType;
4602       T = Info.S.Context.getBaseElementType(T);
4603     }
4604     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4605     if (CT != Info.AbstractType) return;
4606 
4607     // It matched; do some magic.
4608     if (Sel == Sema::AbstractArrayType) {
4609       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4610         << T << TL.getSourceRange();
4611     } else {
4612       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4613         << Sel << T << TL.getSourceRange();
4614     }
4615     Info.DiagnoseAbstractType();
4616   }
4617 };
4618 
4619 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4620                                   Sema::AbstractDiagSelID Sel) {
4621   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4622 }
4623 
4624 }
4625 
4626 /// Check for invalid uses of an abstract type in a method declaration.
4627 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4628                                     CXXMethodDecl *MD) {
4629   // No need to do the check on definitions, which require that
4630   // the return/param types be complete.
4631   if (MD->doesThisDeclarationHaveABody())
4632     return;
4633 
4634   // For safety's sake, just ignore it if we don't have type source
4635   // information.  This should never happen for non-implicit methods,
4636   // but...
4637   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4638     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4639 }
4640 
4641 /// Check for invalid uses of an abstract type within a class definition.
4642 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4643                                     CXXRecordDecl *RD) {
4644   for (auto *D : RD->decls()) {
4645     if (D->isImplicit()) continue;
4646 
4647     // Methods and method templates.
4648     if (isa<CXXMethodDecl>(D)) {
4649       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4650     } else if (isa<FunctionTemplateDecl>(D)) {
4651       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4652       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4653 
4654     // Fields and static variables.
4655     } else if (isa<FieldDecl>(D)) {
4656       FieldDecl *FD = cast<FieldDecl>(D);
4657       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4658         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4659     } else if (isa<VarDecl>(D)) {
4660       VarDecl *VD = cast<VarDecl>(D);
4661       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4662         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4663 
4664     // Nested classes and class templates.
4665     } else if (isa<CXXRecordDecl>(D)) {
4666       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4667     } else if (isa<ClassTemplateDecl>(D)) {
4668       CheckAbstractClassUsage(Info,
4669                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4670     }
4671   }
4672 }
4673 
4674 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
4675   Attr *ClassAttr = getDLLAttr(Class);
4676   if (!ClassAttr)
4677     return;
4678 
4679   assert(ClassAttr->getKind() == attr::DLLExport);
4680 
4681   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4682 
4683   if (TSK == TSK_ExplicitInstantiationDeclaration)
4684     // Don't go any further if this is just an explicit instantiation
4685     // declaration.
4686     return;
4687 
4688   for (Decl *Member : Class->decls()) {
4689     auto *MD = dyn_cast<CXXMethodDecl>(Member);
4690     if (!MD)
4691       continue;
4692 
4693     if (Member->getAttr<DLLExportAttr>()) {
4694       if (MD->isUserProvided()) {
4695         // Instantiate non-default class member functions ...
4696 
4697         // .. except for certain kinds of template specializations.
4698         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4699           continue;
4700 
4701         S.MarkFunctionReferenced(Class->getLocation(), MD);
4702 
4703         // The function will be passed to the consumer when its definition is
4704         // encountered.
4705       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4706                  MD->isCopyAssignmentOperator() ||
4707                  MD->isMoveAssignmentOperator()) {
4708         // Synthesize and instantiate non-trivial implicit methods, explicitly
4709         // defaulted methods, and the copy and move assignment operators. The
4710         // latter are exported even if they are trivial, because the address of
4711         // an operator can be taken and should compare equal accross libraries.
4712         DiagnosticErrorTrap Trap(S.Diags);
4713         S.MarkFunctionReferenced(Class->getLocation(), MD);
4714         if (Trap.hasErrorOccurred()) {
4715           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4716               << Class->getName() << !S.getLangOpts().CPlusPlus11;
4717           break;
4718         }
4719 
4720         // There is no later point when we will see the definition of this
4721         // function, so pass it to the consumer now.
4722         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4723       }
4724     }
4725   }
4726 }
4727 
4728 /// \brief Check class-level dllimport/dllexport attribute.
4729 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
4730   Attr *ClassAttr = getDLLAttr(Class);
4731 
4732   // MSVC inherits DLL attributes to partial class template specializations.
4733   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4734     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4735       if (Attr *TemplateAttr =
4736               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4737         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
4738         A->setInherited(true);
4739         ClassAttr = A;
4740       }
4741     }
4742   }
4743 
4744   if (!ClassAttr)
4745     return;
4746 
4747   if (!Class->isExternallyVisible()) {
4748     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4749         << Class << ClassAttr;
4750     return;
4751   }
4752 
4753   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4754       !ClassAttr->isInherited()) {
4755     // Diagnose dll attributes on members of class with dll attribute.
4756     for (Decl *Member : Class->decls()) {
4757       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4758         continue;
4759       InheritableAttr *MemberAttr = getDLLAttr(Member);
4760       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4761         continue;
4762 
4763       Diag(MemberAttr->getLocation(),
4764              diag::err_attribute_dll_member_of_dll_class)
4765           << MemberAttr << ClassAttr;
4766       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4767       Member->setInvalidDecl();
4768     }
4769   }
4770 
4771   if (Class->getDescribedClassTemplate())
4772     // Don't inherit dll attribute until the template is instantiated.
4773     return;
4774 
4775   // The class is either imported or exported.
4776   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4777 
4778   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4779 
4780   // Ignore explicit dllexport on explicit class template instantiation declarations.
4781   if (ClassExported && !ClassAttr->isInherited() &&
4782       TSK == TSK_ExplicitInstantiationDeclaration) {
4783     Class->dropAttr<DLLExportAttr>();
4784     return;
4785   }
4786 
4787   // Force declaration of implicit members so they can inherit the attribute.
4788   ForceDeclarationOfImplicitMembers(Class);
4789 
4790   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4791   // seem to be true in practice?
4792 
4793   for (Decl *Member : Class->decls()) {
4794     VarDecl *VD = dyn_cast<VarDecl>(Member);
4795     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4796 
4797     // Only methods and static fields inherit the attributes.
4798     if (!VD && !MD)
4799       continue;
4800 
4801     if (MD) {
4802       // Don't process deleted methods.
4803       if (MD->isDeleted())
4804         continue;
4805 
4806       if (MD->isInlined()) {
4807         // MinGW does not import or export inline methods.
4808         if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
4809           continue;
4810 
4811         // MSVC versions before 2015 don't export the move assignment operators
4812         // and move constructor, so don't attempt to import/export them if
4813         // we have a definition.
4814         auto *CXXC = dyn_cast<CXXConstructorDecl>(MD);
4815         if ((MD->isMoveAssignmentOperator() ||
4816              (CXXC && CXXC->isMoveConstructor())) &&
4817             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
4818           continue;
4819       }
4820     }
4821 
4822     if (!cast<NamedDecl>(Member)->isExternallyVisible())
4823       continue;
4824 
4825     if (!getDLLAttr(Member)) {
4826       auto *NewAttr =
4827           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4828       NewAttr->setInherited(true);
4829       Member->addAttr(NewAttr);
4830     }
4831   }
4832 
4833   if (ClassExported)
4834     DelayedDllExportClasses.push_back(Class);
4835 }
4836 
4837 /// \brief Perform propagation of DLL attributes from a derived class to a
4838 /// templated base class for MS compatibility.
4839 void Sema::propagateDLLAttrToBaseClassTemplate(
4840     CXXRecordDecl *Class, Attr *ClassAttr,
4841     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4842   if (getDLLAttr(
4843           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4844     // If the base class template has a DLL attribute, don't try to change it.
4845     return;
4846   }
4847 
4848   auto TSK = BaseTemplateSpec->getSpecializationKind();
4849   if (!getDLLAttr(BaseTemplateSpec) &&
4850       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4851        TSK == TSK_ImplicitInstantiation)) {
4852     // The template hasn't been instantiated yet (or it has, but only as an
4853     // explicit instantiation declaration or implicit instantiation, which means
4854     // we haven't codegenned any members yet), so propagate the attribute.
4855     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4856     NewAttr->setInherited(true);
4857     BaseTemplateSpec->addAttr(NewAttr);
4858 
4859     // If the template is already instantiated, checkDLLAttributeRedeclaration()
4860     // needs to be run again to work see the new attribute. Otherwise this will
4861     // get run whenever the template is instantiated.
4862     if (TSK != TSK_Undeclared)
4863       checkClassLevelDLLAttribute(BaseTemplateSpec);
4864 
4865     return;
4866   }
4867 
4868   if (getDLLAttr(BaseTemplateSpec)) {
4869     // The template has already been specialized or instantiated with an
4870     // attribute, explicitly or through propagation. We should not try to change
4871     // it.
4872     return;
4873   }
4874 
4875   // The template was previously instantiated or explicitly specialized without
4876   // a dll attribute, It's too late for us to add an attribute, so warn that
4877   // this is unsupported.
4878   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4879       << BaseTemplateSpec->isExplicitSpecialization();
4880   Diag(ClassAttr->getLocation(), diag::note_attribute);
4881   if (BaseTemplateSpec->isExplicitSpecialization()) {
4882     Diag(BaseTemplateSpec->getLocation(),
4883            diag::note_template_class_explicit_specialization_was_here)
4884         << BaseTemplateSpec;
4885   } else {
4886     Diag(BaseTemplateSpec->getPointOfInstantiation(),
4887            diag::note_template_class_instantiation_was_here)
4888         << BaseTemplateSpec;
4889   }
4890 }
4891 
4892 /// \brief Perform semantic checks on a class definition that has been
4893 /// completing, introducing implicitly-declared members, checking for
4894 /// abstract types, etc.
4895 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4896   if (!Record)
4897     return;
4898 
4899   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4900     AbstractUsageInfo Info(*this, Record);
4901     CheckAbstractClassUsage(Info, Record);
4902   }
4903 
4904   // If this is not an aggregate type and has no user-declared constructor,
4905   // complain about any non-static data members of reference or const scalar
4906   // type, since they will never get initializers.
4907   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4908       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4909       !Record->isLambda()) {
4910     bool Complained = false;
4911     for (const auto *F : Record->fields()) {
4912       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4913         continue;
4914 
4915       if (F->getType()->isReferenceType() ||
4916           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4917         if (!Complained) {
4918           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4919             << Record->getTagKind() << Record;
4920           Complained = true;
4921         }
4922 
4923         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4924           << F->getType()->isReferenceType()
4925           << F->getDeclName();
4926       }
4927     }
4928   }
4929 
4930   if (Record->getIdentifier()) {
4931     // C++ [class.mem]p13:
4932     //   If T is the name of a class, then each of the following shall have a
4933     //   name different from T:
4934     //     - every member of every anonymous union that is a member of class T.
4935     //
4936     // C++ [class.mem]p14:
4937     //   In addition, if class T has a user-declared constructor (12.1), every
4938     //   non-static data member of class T shall have a name different from T.
4939     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4940     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4941          ++I) {
4942       NamedDecl *D = *I;
4943       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4944           isa<IndirectFieldDecl>(D)) {
4945         Diag(D->getLocation(), diag::err_member_name_of_class)
4946           << D->getDeclName();
4947         break;
4948       }
4949     }
4950   }
4951 
4952   // Warn if the class has virtual methods but non-virtual public destructor.
4953   if (Record->isPolymorphic() && !Record->isDependentType()) {
4954     CXXDestructorDecl *dtor = Record->getDestructor();
4955     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4956         !Record->hasAttr<FinalAttr>())
4957       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4958            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4959   }
4960 
4961   if (Record->isAbstract()) {
4962     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4963       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4964         << FA->isSpelledAsSealed();
4965       DiagnoseAbstractType(Record);
4966     }
4967   }
4968 
4969   bool HasMethodWithOverrideControl = false,
4970        HasOverridingMethodWithoutOverrideControl = false;
4971   if (!Record->isDependentType()) {
4972     for (auto *M : Record->methods()) {
4973       // See if a method overloads virtual methods in a base
4974       // class without overriding any.
4975       if (!M->isStatic())
4976         DiagnoseHiddenVirtualMethods(M);
4977       if (M->hasAttr<OverrideAttr>())
4978         HasMethodWithOverrideControl = true;
4979       else if (M->size_overridden_methods() > 0)
4980         HasOverridingMethodWithoutOverrideControl = true;
4981       // Check whether the explicitly-defaulted special members are valid.
4982       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4983         CheckExplicitlyDefaultedSpecialMember(M);
4984 
4985       // For an explicitly defaulted or deleted special member, we defer
4986       // determining triviality until the class is complete. That time is now!
4987       if (!M->isImplicit() && !M->isUserProvided()) {
4988         CXXSpecialMember CSM = getSpecialMember(M);
4989         if (CSM != CXXInvalid) {
4990           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4991 
4992           // Inform the class that we've finished declaring this member.
4993           Record->finishedDefaultedOrDeletedMember(M);
4994         }
4995       }
4996     }
4997   }
4998 
4999   if (HasMethodWithOverrideControl &&
5000       HasOverridingMethodWithoutOverrideControl) {
5001     // At least one method has the 'override' control declared.
5002     // Diagnose all other overridden methods which do not have 'override' specified on them.
5003     for (auto *M : Record->methods())
5004       DiagnoseAbsenceOfOverrideControl(M);
5005   }
5006 
5007   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5008   // whether this class uses any C++ features that are implemented
5009   // completely differently in MSVC, and if so, emit a diagnostic.
5010   // That diagnostic defaults to an error, but we allow projects to
5011   // map it down to a warning (or ignore it).  It's a fairly common
5012   // practice among users of the ms_struct pragma to mass-annotate
5013   // headers, sweeping up a bunch of types that the project doesn't
5014   // really rely on MSVC-compatible layout for.  We must therefore
5015   // support "ms_struct except for C++ stuff" as a secondary ABI.
5016   if (Record->isMsStruct(Context) &&
5017       (Record->isPolymorphic() || Record->getNumBases())) {
5018     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5019   }
5020 
5021   // Declare inheriting constructors. We do this eagerly here because:
5022   // - The standard requires an eager diagnostic for conflicting inheriting
5023   //   constructors from different classes.
5024   // - The lazy declaration of the other implicit constructors is so as to not
5025   //   waste space and performance on classes that are not meant to be
5026   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
5027   //   have inheriting constructors.
5028   DeclareInheritingConstructors(Record);
5029 
5030   checkClassLevelDLLAttribute(Record);
5031 }
5032 
5033 /// Look up the special member function that would be called by a special
5034 /// member function for a subobject of class type.
5035 ///
5036 /// \param Class The class type of the subobject.
5037 /// \param CSM The kind of special member function.
5038 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5039 /// \param ConstRHS True if this is a copy operation with a const object
5040 ///        on its RHS, that is, if the argument to the outer special member
5041 ///        function is 'const' and this is not a field marked 'mutable'.
5042 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5043     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5044     unsigned FieldQuals, bool ConstRHS) {
5045   unsigned LHSQuals = 0;
5046   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5047     LHSQuals = FieldQuals;
5048 
5049   unsigned RHSQuals = FieldQuals;
5050   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5051     RHSQuals = 0;
5052   else if (ConstRHS)
5053     RHSQuals |= Qualifiers::Const;
5054 
5055   return S.LookupSpecialMember(Class, CSM,
5056                                RHSQuals & Qualifiers::Const,
5057                                RHSQuals & Qualifiers::Volatile,
5058                                false,
5059                                LHSQuals & Qualifiers::Const,
5060                                LHSQuals & Qualifiers::Volatile);
5061 }
5062 
5063 /// Is the special member function which would be selected to perform the
5064 /// specified operation on the specified class type a constexpr constructor?
5065 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5066                                      Sema::CXXSpecialMember CSM,
5067                                      unsigned Quals, bool ConstRHS) {
5068   Sema::SpecialMemberOverloadResult *SMOR =
5069       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5070   if (!SMOR || !SMOR->getMethod())
5071     // A constructor we wouldn't select can't be "involved in initializing"
5072     // anything.
5073     return true;
5074   return SMOR->getMethod()->isConstexpr();
5075 }
5076 
5077 /// Determine whether the specified special member function would be constexpr
5078 /// if it were implicitly defined.
5079 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5080                                               Sema::CXXSpecialMember CSM,
5081                                               bool ConstArg) {
5082   if (!S.getLangOpts().CPlusPlus11)
5083     return false;
5084 
5085   // C++11 [dcl.constexpr]p4:
5086   // In the definition of a constexpr constructor [...]
5087   bool Ctor = true;
5088   switch (CSM) {
5089   case Sema::CXXDefaultConstructor:
5090     // Since default constructor lookup is essentially trivial (and cannot
5091     // involve, for instance, template instantiation), we compute whether a
5092     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5093     //
5094     // This is important for performance; we need to know whether the default
5095     // constructor is constexpr to determine whether the type is a literal type.
5096     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5097 
5098   case Sema::CXXCopyConstructor:
5099   case Sema::CXXMoveConstructor:
5100     // For copy or move constructors, we need to perform overload resolution.
5101     break;
5102 
5103   case Sema::CXXCopyAssignment:
5104   case Sema::CXXMoveAssignment:
5105     if (!S.getLangOpts().CPlusPlus14)
5106       return false;
5107     // In C++1y, we need to perform overload resolution.
5108     Ctor = false;
5109     break;
5110 
5111   case Sema::CXXDestructor:
5112   case Sema::CXXInvalid:
5113     return false;
5114   }
5115 
5116   //   -- if the class is a non-empty union, or for each non-empty anonymous
5117   //      union member of a non-union class, exactly one non-static data member
5118   //      shall be initialized; [DR1359]
5119   //
5120   // If we squint, this is guaranteed, since exactly one non-static data member
5121   // will be initialized (if the constructor isn't deleted), we just don't know
5122   // which one.
5123   if (Ctor && ClassDecl->isUnion())
5124     return true;
5125 
5126   //   -- the class shall not have any virtual base classes;
5127   if (Ctor && ClassDecl->getNumVBases())
5128     return false;
5129 
5130   // C++1y [class.copy]p26:
5131   //   -- [the class] is a literal type, and
5132   if (!Ctor && !ClassDecl->isLiteral())
5133     return false;
5134 
5135   //   -- every constructor involved in initializing [...] base class
5136   //      sub-objects shall be a constexpr constructor;
5137   //   -- the assignment operator selected to copy/move each direct base
5138   //      class is a constexpr function, and
5139   for (const auto &B : ClassDecl->bases()) {
5140     const RecordType *BaseType = B.getType()->getAs<RecordType>();
5141     if (!BaseType) continue;
5142 
5143     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5144     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
5145       return false;
5146   }
5147 
5148   //   -- every constructor involved in initializing non-static data members
5149   //      [...] shall be a constexpr constructor;
5150   //   -- every non-static data member and base class sub-object shall be
5151   //      initialized
5152   //   -- for each non-static data member of X that is of class type (or array
5153   //      thereof), the assignment operator selected to copy/move that member is
5154   //      a constexpr function
5155   for (const auto *F : ClassDecl->fields()) {
5156     if (F->isInvalidDecl())
5157       continue;
5158     QualType BaseType = S.Context.getBaseElementType(F->getType());
5159     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5160       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5161       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5162                                     BaseType.getCVRQualifiers(),
5163                                     ConstArg && !F->isMutable()))
5164         return false;
5165     }
5166   }
5167 
5168   // All OK, it's constexpr!
5169   return true;
5170 }
5171 
5172 static Sema::ImplicitExceptionSpecification
5173 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5174   switch (S.getSpecialMember(MD)) {
5175   case Sema::CXXDefaultConstructor:
5176     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5177   case Sema::CXXCopyConstructor:
5178     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5179   case Sema::CXXCopyAssignment:
5180     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5181   case Sema::CXXMoveConstructor:
5182     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5183   case Sema::CXXMoveAssignment:
5184     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5185   case Sema::CXXDestructor:
5186     return S.ComputeDefaultedDtorExceptionSpec(MD);
5187   case Sema::CXXInvalid:
5188     break;
5189   }
5190   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5191          "only special members have implicit exception specs");
5192   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5193 }
5194 
5195 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5196                                                             CXXMethodDecl *MD) {
5197   FunctionProtoType::ExtProtoInfo EPI;
5198 
5199   // Build an exception specification pointing back at this member.
5200   EPI.ExceptionSpec.Type = EST_Unevaluated;
5201   EPI.ExceptionSpec.SourceDecl = MD;
5202 
5203   // Set the calling convention to the default for C++ instance methods.
5204   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5205       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5206                                             /*IsCXXMethod=*/true));
5207   return EPI;
5208 }
5209 
5210 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5211   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5212   if (FPT->getExceptionSpecType() != EST_Unevaluated)
5213     return;
5214 
5215   // Evaluate the exception specification.
5216   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5217 
5218   // Update the type of the special member to use it.
5219   UpdateExceptionSpec(MD, ESI);
5220 
5221   // A user-provided destructor can be defined outside the class. When that
5222   // happens, be sure to update the exception specification on both
5223   // declarations.
5224   const FunctionProtoType *CanonicalFPT =
5225     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5226   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5227     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5228 }
5229 
5230 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5231   CXXRecordDecl *RD = MD->getParent();
5232   CXXSpecialMember CSM = getSpecialMember(MD);
5233 
5234   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5235          "not an explicitly-defaulted special member");
5236 
5237   // Whether this was the first-declared instance of the constructor.
5238   // This affects whether we implicitly add an exception spec and constexpr.
5239   bool First = MD == MD->getCanonicalDecl();
5240 
5241   bool HadError = false;
5242 
5243   // C++11 [dcl.fct.def.default]p1:
5244   //   A function that is explicitly defaulted shall
5245   //     -- be a special member function (checked elsewhere),
5246   //     -- have the same type (except for ref-qualifiers, and except that a
5247   //        copy operation can take a non-const reference) as an implicit
5248   //        declaration, and
5249   //     -- not have default arguments.
5250   unsigned ExpectedParams = 1;
5251   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5252     ExpectedParams = 0;
5253   if (MD->getNumParams() != ExpectedParams) {
5254     // This also checks for default arguments: a copy or move constructor with a
5255     // default argument is classified as a default constructor, and assignment
5256     // operations and destructors can't have default arguments.
5257     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5258       << CSM << MD->getSourceRange();
5259     HadError = true;
5260   } else if (MD->isVariadic()) {
5261     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5262       << CSM << MD->getSourceRange();
5263     HadError = true;
5264   }
5265 
5266   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5267 
5268   bool CanHaveConstParam = false;
5269   if (CSM == CXXCopyConstructor)
5270     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5271   else if (CSM == CXXCopyAssignment)
5272     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5273 
5274   QualType ReturnType = Context.VoidTy;
5275   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5276     // Check for return type matching.
5277     ReturnType = Type->getReturnType();
5278     QualType ExpectedReturnType =
5279         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5280     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5281       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5282         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5283       HadError = true;
5284     }
5285 
5286     // A defaulted special member cannot have cv-qualifiers.
5287     if (Type->getTypeQuals()) {
5288       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5289         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5290       HadError = true;
5291     }
5292   }
5293 
5294   // Check for parameter type matching.
5295   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5296   bool HasConstParam = false;
5297   if (ExpectedParams && ArgType->isReferenceType()) {
5298     // Argument must be reference to possibly-const T.
5299     QualType ReferentType = ArgType->getPointeeType();
5300     HasConstParam = ReferentType.isConstQualified();
5301 
5302     if (ReferentType.isVolatileQualified()) {
5303       Diag(MD->getLocation(),
5304            diag::err_defaulted_special_member_volatile_param) << CSM;
5305       HadError = true;
5306     }
5307 
5308     if (HasConstParam && !CanHaveConstParam) {
5309       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5310         Diag(MD->getLocation(),
5311              diag::err_defaulted_special_member_copy_const_param)
5312           << (CSM == CXXCopyAssignment);
5313         // FIXME: Explain why this special member can't be const.
5314       } else {
5315         Diag(MD->getLocation(),
5316              diag::err_defaulted_special_member_move_const_param)
5317           << (CSM == CXXMoveAssignment);
5318       }
5319       HadError = true;
5320     }
5321   } else if (ExpectedParams) {
5322     // A copy assignment operator can take its argument by value, but a
5323     // defaulted one cannot.
5324     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5325     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5326     HadError = true;
5327   }
5328 
5329   // C++11 [dcl.fct.def.default]p2:
5330   //   An explicitly-defaulted function may be declared constexpr only if it
5331   //   would have been implicitly declared as constexpr,
5332   // Do not apply this rule to members of class templates, since core issue 1358
5333   // makes such functions always instantiate to constexpr functions. For
5334   // functions which cannot be constexpr (for non-constructors in C++11 and for
5335   // destructors in C++1y), this is checked elsewhere.
5336   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5337                                                      HasConstParam);
5338   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5339                                  : isa<CXXConstructorDecl>(MD)) &&
5340       MD->isConstexpr() && !Constexpr &&
5341       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5342     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5343     // FIXME: Explain why the special member can't be constexpr.
5344     HadError = true;
5345   }
5346 
5347   //   and may have an explicit exception-specification only if it is compatible
5348   //   with the exception-specification on the implicit declaration.
5349   if (Type->hasExceptionSpec()) {
5350     // Delay the check if this is the first declaration of the special member,
5351     // since we may not have parsed some necessary in-class initializers yet.
5352     if (First) {
5353       // If the exception specification needs to be instantiated, do so now,
5354       // before we clobber it with an EST_Unevaluated specification below.
5355       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5356         InstantiateExceptionSpec(MD->getLocStart(), MD);
5357         Type = MD->getType()->getAs<FunctionProtoType>();
5358       }
5359       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5360     } else
5361       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5362   }
5363 
5364   //   If a function is explicitly defaulted on its first declaration,
5365   if (First) {
5366     //  -- it is implicitly considered to be constexpr if the implicit
5367     //     definition would be,
5368     MD->setConstexpr(Constexpr);
5369 
5370     //  -- it is implicitly considered to have the same exception-specification
5371     //     as if it had been implicitly declared,
5372     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5373     EPI.ExceptionSpec.Type = EST_Unevaluated;
5374     EPI.ExceptionSpec.SourceDecl = MD;
5375     MD->setType(Context.getFunctionType(ReturnType,
5376                                         llvm::makeArrayRef(&ArgType,
5377                                                            ExpectedParams),
5378                                         EPI));
5379   }
5380 
5381   if (ShouldDeleteSpecialMember(MD, CSM)) {
5382     if (First) {
5383       SetDeclDeleted(MD, MD->getLocation());
5384     } else {
5385       // C++11 [dcl.fct.def.default]p4:
5386       //   [For a] user-provided explicitly-defaulted function [...] if such a
5387       //   function is implicitly defined as deleted, the program is ill-formed.
5388       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5389       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5390       HadError = true;
5391     }
5392   }
5393 
5394   if (HadError)
5395     MD->setInvalidDecl();
5396 }
5397 
5398 /// Check whether the exception specification provided for an
5399 /// explicitly-defaulted special member matches the exception specification
5400 /// that would have been generated for an implicit special member, per
5401 /// C++11 [dcl.fct.def.default]p2.
5402 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5403     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5404   // If the exception specification was explicitly specified but hadn't been
5405   // parsed when the method was defaulted, grab it now.
5406   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5407     SpecifiedType =
5408         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5409 
5410   // Compute the implicit exception specification.
5411   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5412                                                        /*IsCXXMethod=*/true);
5413   FunctionProtoType::ExtProtoInfo EPI(CC);
5414   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5415                           .getExceptionSpec();
5416   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5417     Context.getFunctionType(Context.VoidTy, None, EPI));
5418 
5419   // Ensure that it matches.
5420   CheckEquivalentExceptionSpec(
5421     PDiag(diag::err_incorrect_defaulted_exception_spec)
5422       << getSpecialMember(MD), PDiag(),
5423     ImplicitType, SourceLocation(),
5424     SpecifiedType, MD->getLocation());
5425 }
5426 
5427 void Sema::CheckDelayedMemberExceptionSpecs() {
5428   decltype(DelayedExceptionSpecChecks) Checks;
5429   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5430 
5431   std::swap(Checks, DelayedExceptionSpecChecks);
5432   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5433 
5434   // Perform any deferred checking of exception specifications for virtual
5435   // destructors.
5436   for (auto &Check : Checks)
5437     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5438 
5439   // Check that any explicitly-defaulted methods have exception specifications
5440   // compatible with their implicit exception specifications.
5441   for (auto &Spec : Specs)
5442     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5443 }
5444 
5445 namespace {
5446 struct SpecialMemberDeletionInfo {
5447   Sema &S;
5448   CXXMethodDecl *MD;
5449   Sema::CXXSpecialMember CSM;
5450   bool Diagnose;
5451 
5452   // Properties of the special member, computed for convenience.
5453   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5454   SourceLocation Loc;
5455 
5456   bool AllFieldsAreConst;
5457 
5458   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5459                             Sema::CXXSpecialMember CSM, bool Diagnose)
5460     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5461       IsConstructor(false), IsAssignment(false), IsMove(false),
5462       ConstArg(false), Loc(MD->getLocation()),
5463       AllFieldsAreConst(true) {
5464     switch (CSM) {
5465       case Sema::CXXDefaultConstructor:
5466       case Sema::CXXCopyConstructor:
5467         IsConstructor = true;
5468         break;
5469       case Sema::CXXMoveConstructor:
5470         IsConstructor = true;
5471         IsMove = true;
5472         break;
5473       case Sema::CXXCopyAssignment:
5474         IsAssignment = true;
5475         break;
5476       case Sema::CXXMoveAssignment:
5477         IsAssignment = true;
5478         IsMove = true;
5479         break;
5480       case Sema::CXXDestructor:
5481         break;
5482       case Sema::CXXInvalid:
5483         llvm_unreachable("invalid special member kind");
5484     }
5485 
5486     if (MD->getNumParams()) {
5487       if (const ReferenceType *RT =
5488               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5489         ConstArg = RT->getPointeeType().isConstQualified();
5490     }
5491   }
5492 
5493   bool inUnion() const { return MD->getParent()->isUnion(); }
5494 
5495   /// Look up the corresponding special member in the given class.
5496   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5497                                               unsigned Quals, bool IsMutable) {
5498     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5499                                        ConstArg && !IsMutable);
5500   }
5501 
5502   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5503 
5504   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5505   bool shouldDeleteForField(FieldDecl *FD);
5506   bool shouldDeleteForAllConstMembers();
5507 
5508   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5509                                      unsigned Quals);
5510   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5511                                     Sema::SpecialMemberOverloadResult *SMOR,
5512                                     bool IsDtorCallInCtor);
5513 
5514   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5515 };
5516 }
5517 
5518 /// Is the given special member inaccessible when used on the given
5519 /// sub-object.
5520 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5521                                              CXXMethodDecl *target) {
5522   /// If we're operating on a base class, the object type is the
5523   /// type of this special member.
5524   QualType objectTy;
5525   AccessSpecifier access = target->getAccess();
5526   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5527     objectTy = S.Context.getTypeDeclType(MD->getParent());
5528     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5529 
5530   // If we're operating on a field, the object type is the type of the field.
5531   } else {
5532     objectTy = S.Context.getTypeDeclType(target->getParent());
5533   }
5534 
5535   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5536 }
5537 
5538 /// Check whether we should delete a special member due to the implicit
5539 /// definition containing a call to a special member of a subobject.
5540 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5541     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5542     bool IsDtorCallInCtor) {
5543   CXXMethodDecl *Decl = SMOR->getMethod();
5544   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5545 
5546   int DiagKind = -1;
5547 
5548   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5549     DiagKind = !Decl ? 0 : 1;
5550   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5551     DiagKind = 2;
5552   else if (!isAccessible(Subobj, Decl))
5553     DiagKind = 3;
5554   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5555            !Decl->isTrivial()) {
5556     // A member of a union must have a trivial corresponding special member.
5557     // As a weird special case, a destructor call from a union's constructor
5558     // must be accessible and non-deleted, but need not be trivial. Such a
5559     // destructor is never actually called, but is semantically checked as
5560     // if it were.
5561     DiagKind = 4;
5562   }
5563 
5564   if (DiagKind == -1)
5565     return false;
5566 
5567   if (Diagnose) {
5568     if (Field) {
5569       S.Diag(Field->getLocation(),
5570              diag::note_deleted_special_member_class_subobject)
5571         << CSM << MD->getParent() << /*IsField*/true
5572         << Field << DiagKind << IsDtorCallInCtor;
5573     } else {
5574       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5575       S.Diag(Base->getLocStart(),
5576              diag::note_deleted_special_member_class_subobject)
5577         << CSM << MD->getParent() << /*IsField*/false
5578         << Base->getType() << DiagKind << IsDtorCallInCtor;
5579     }
5580 
5581     if (DiagKind == 1)
5582       S.NoteDeletedFunction(Decl);
5583     // FIXME: Explain inaccessibility if DiagKind == 3.
5584   }
5585 
5586   return true;
5587 }
5588 
5589 /// Check whether we should delete a special member function due to having a
5590 /// direct or virtual base class or non-static data member of class type M.
5591 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5592     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5593   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5594   bool IsMutable = Field && Field->isMutable();
5595 
5596   // C++11 [class.ctor]p5:
5597   // -- any direct or virtual base class, or non-static data member with no
5598   //    brace-or-equal-initializer, has class type M (or array thereof) and
5599   //    either M has no default constructor or overload resolution as applied
5600   //    to M's default constructor results in an ambiguity or in a function
5601   //    that is deleted or inaccessible
5602   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5603   // -- a direct or virtual base class B that cannot be copied/moved because
5604   //    overload resolution, as applied to B's corresponding special member,
5605   //    results in an ambiguity or a function that is deleted or inaccessible
5606   //    from the defaulted special member
5607   // C++11 [class.dtor]p5:
5608   // -- any direct or virtual base class [...] has a type with a destructor
5609   //    that is deleted or inaccessible
5610   if (!(CSM == Sema::CXXDefaultConstructor &&
5611         Field && Field->hasInClassInitializer()) &&
5612       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5613                                    false))
5614     return true;
5615 
5616   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5617   // -- any direct or virtual base class or non-static data member has a
5618   //    type with a destructor that is deleted or inaccessible
5619   if (IsConstructor) {
5620     Sema::SpecialMemberOverloadResult *SMOR =
5621         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5622                               false, false, false, false, false);
5623     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5624       return true;
5625   }
5626 
5627   return false;
5628 }
5629 
5630 /// Check whether we should delete a special member function due to the class
5631 /// having a particular direct or virtual base class.
5632 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5633   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5634   // If program is correct, BaseClass cannot be null, but if it is, the error
5635   // must be reported elsewhere.
5636   return BaseClass && shouldDeleteForClassSubobject(BaseClass, Base, 0);
5637 }
5638 
5639 /// Check whether we should delete a special member function due to the class
5640 /// having a particular non-static data member.
5641 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5642   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5643   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5644 
5645   if (CSM == Sema::CXXDefaultConstructor) {
5646     // For a default constructor, all references must be initialized in-class
5647     // and, if a union, it must have a non-const member.
5648     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5649       if (Diagnose)
5650         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5651           << MD->getParent() << FD << FieldType << /*Reference*/0;
5652       return true;
5653     }
5654     // C++11 [class.ctor]p5: any non-variant non-static data member of
5655     // const-qualified type (or array thereof) with no
5656     // brace-or-equal-initializer does not have a user-provided default
5657     // constructor.
5658     if (!inUnion() && FieldType.isConstQualified() &&
5659         !FD->hasInClassInitializer() &&
5660         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5661       if (Diagnose)
5662         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5663           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5664       return true;
5665     }
5666 
5667     if (inUnion() && !FieldType.isConstQualified())
5668       AllFieldsAreConst = false;
5669   } else if (CSM == Sema::CXXCopyConstructor) {
5670     // For a copy constructor, data members must not be of rvalue reference
5671     // type.
5672     if (FieldType->isRValueReferenceType()) {
5673       if (Diagnose)
5674         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5675           << MD->getParent() << FD << FieldType;
5676       return true;
5677     }
5678   } else if (IsAssignment) {
5679     // For an assignment operator, data members must not be of reference type.
5680     if (FieldType->isReferenceType()) {
5681       if (Diagnose)
5682         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5683           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5684       return true;
5685     }
5686     if (!FieldRecord && FieldType.isConstQualified()) {
5687       // C++11 [class.copy]p23:
5688       // -- a non-static data member of const non-class type (or array thereof)
5689       if (Diagnose)
5690         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5691           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5692       return true;
5693     }
5694   }
5695 
5696   if (FieldRecord) {
5697     // Some additional restrictions exist on the variant members.
5698     if (!inUnion() && FieldRecord->isUnion() &&
5699         FieldRecord->isAnonymousStructOrUnion()) {
5700       bool AllVariantFieldsAreConst = true;
5701 
5702       // FIXME: Handle anonymous unions declared within anonymous unions.
5703       for (auto *UI : FieldRecord->fields()) {
5704         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5705 
5706         if (!UnionFieldType.isConstQualified())
5707           AllVariantFieldsAreConst = false;
5708 
5709         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5710         if (UnionFieldRecord &&
5711             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5712                                           UnionFieldType.getCVRQualifiers()))
5713           return true;
5714       }
5715 
5716       // At least one member in each anonymous union must be non-const
5717       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5718           !FieldRecord->field_empty()) {
5719         if (Diagnose)
5720           S.Diag(FieldRecord->getLocation(),
5721                  diag::note_deleted_default_ctor_all_const)
5722             << MD->getParent() << /*anonymous union*/1;
5723         return true;
5724       }
5725 
5726       // Don't check the implicit member of the anonymous union type.
5727       // This is technically non-conformant, but sanity demands it.
5728       return false;
5729     }
5730 
5731     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5732                                       FieldType.getCVRQualifiers()))
5733       return true;
5734   }
5735 
5736   return false;
5737 }
5738 
5739 /// C++11 [class.ctor] p5:
5740 ///   A defaulted default constructor for a class X is defined as deleted if
5741 /// X is a union and all of its variant members are of const-qualified type.
5742 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5743   // This is a silly definition, because it gives an empty union a deleted
5744   // default constructor. Don't do that.
5745   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5746       !MD->getParent()->field_empty()) {
5747     if (Diagnose)
5748       S.Diag(MD->getParent()->getLocation(),
5749              diag::note_deleted_default_ctor_all_const)
5750         << MD->getParent() << /*not anonymous union*/0;
5751     return true;
5752   }
5753   return false;
5754 }
5755 
5756 /// Determine whether a defaulted special member function should be defined as
5757 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5758 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5759 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5760                                      bool Diagnose) {
5761   if (MD->isInvalidDecl())
5762     return false;
5763   CXXRecordDecl *RD = MD->getParent();
5764   assert(!RD->isDependentType() && "do deletion after instantiation");
5765   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5766     return false;
5767 
5768   // C++11 [expr.lambda.prim]p19:
5769   //   The closure type associated with a lambda-expression has a
5770   //   deleted (8.4.3) default constructor and a deleted copy
5771   //   assignment operator.
5772   if (RD->isLambda() &&
5773       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5774     if (Diagnose)
5775       Diag(RD->getLocation(), diag::note_lambda_decl);
5776     return true;
5777   }
5778 
5779   // For an anonymous struct or union, the copy and assignment special members
5780   // will never be used, so skip the check. For an anonymous union declared at
5781   // namespace scope, the constructor and destructor are used.
5782   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5783       RD->isAnonymousStructOrUnion())
5784     return false;
5785 
5786   // C++11 [class.copy]p7, p18:
5787   //   If the class definition declares a move constructor or move assignment
5788   //   operator, an implicitly declared copy constructor or copy assignment
5789   //   operator is defined as deleted.
5790   if (MD->isImplicit() &&
5791       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5792     CXXMethodDecl *UserDeclaredMove = nullptr;
5793 
5794     // In Microsoft mode, a user-declared move only causes the deletion of the
5795     // corresponding copy operation, not both copy operations.
5796     if (RD->hasUserDeclaredMoveConstructor() &&
5797         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5798       if (!Diagnose) return true;
5799 
5800       // Find any user-declared move constructor.
5801       for (auto *I : RD->ctors()) {
5802         if (I->isMoveConstructor()) {
5803           UserDeclaredMove = I;
5804           break;
5805         }
5806       }
5807       assert(UserDeclaredMove);
5808     } else if (RD->hasUserDeclaredMoveAssignment() &&
5809                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5810       if (!Diagnose) return true;
5811 
5812       // Find any user-declared move assignment operator.
5813       for (auto *I : RD->methods()) {
5814         if (I->isMoveAssignmentOperator()) {
5815           UserDeclaredMove = I;
5816           break;
5817         }
5818       }
5819       assert(UserDeclaredMove);
5820     }
5821 
5822     if (UserDeclaredMove) {
5823       Diag(UserDeclaredMove->getLocation(),
5824            diag::note_deleted_copy_user_declared_move)
5825         << (CSM == CXXCopyAssignment) << RD
5826         << UserDeclaredMove->isMoveAssignmentOperator();
5827       return true;
5828     }
5829   }
5830 
5831   // Do access control from the special member function
5832   ContextRAII MethodContext(*this, MD);
5833 
5834   // C++11 [class.dtor]p5:
5835   // -- for a virtual destructor, lookup of the non-array deallocation function
5836   //    results in an ambiguity or in a function that is deleted or inaccessible
5837   if (CSM == CXXDestructor && MD->isVirtual()) {
5838     FunctionDecl *OperatorDelete = nullptr;
5839     DeclarationName Name =
5840       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5841     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5842                                  OperatorDelete, false)) {
5843       if (Diagnose)
5844         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5845       return true;
5846     }
5847   }
5848 
5849   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5850 
5851   for (auto &BI : RD->bases())
5852     if (!BI.isVirtual() &&
5853         SMI.shouldDeleteForBase(&BI))
5854       return true;
5855 
5856   // Per DR1611, do not consider virtual bases of constructors of abstract
5857   // classes, since we are not going to construct them.
5858   if (!RD->isAbstract() || !SMI.IsConstructor) {
5859     for (auto &BI : RD->vbases())
5860       if (SMI.shouldDeleteForBase(&BI))
5861         return true;
5862   }
5863 
5864   for (auto *FI : RD->fields())
5865     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5866         SMI.shouldDeleteForField(FI))
5867       return true;
5868 
5869   if (SMI.shouldDeleteForAllConstMembers())
5870     return true;
5871 
5872   if (getLangOpts().CUDA) {
5873     // We should delete the special member in CUDA mode if target inference
5874     // failed.
5875     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5876                                                    Diagnose);
5877   }
5878 
5879   return false;
5880 }
5881 
5882 /// Perform lookup for a special member of the specified kind, and determine
5883 /// whether it is trivial. If the triviality can be determined without the
5884 /// lookup, skip it. This is intended for use when determining whether a
5885 /// special member of a containing object is trivial, and thus does not ever
5886 /// perform overload resolution for default constructors.
5887 ///
5888 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5889 /// member that was most likely to be intended to be trivial, if any.
5890 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5891                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5892                                      bool ConstRHS, CXXMethodDecl **Selected) {
5893   if (Selected)
5894     *Selected = nullptr;
5895 
5896   switch (CSM) {
5897   case Sema::CXXInvalid:
5898     llvm_unreachable("not a special member");
5899 
5900   case Sema::CXXDefaultConstructor:
5901     // C++11 [class.ctor]p5:
5902     //   A default constructor is trivial if:
5903     //    - all the [direct subobjects] have trivial default constructors
5904     //
5905     // Note, no overload resolution is performed in this case.
5906     if (RD->hasTrivialDefaultConstructor())
5907       return true;
5908 
5909     if (Selected) {
5910       // If there's a default constructor which could have been trivial, dig it
5911       // out. Otherwise, if there's any user-provided default constructor, point
5912       // to that as an example of why there's not a trivial one.
5913       CXXConstructorDecl *DefCtor = nullptr;
5914       if (RD->needsImplicitDefaultConstructor())
5915         S.DeclareImplicitDefaultConstructor(RD);
5916       for (auto *CI : RD->ctors()) {
5917         if (!CI->isDefaultConstructor())
5918           continue;
5919         DefCtor = CI;
5920         if (!DefCtor->isUserProvided())
5921           break;
5922       }
5923 
5924       *Selected = DefCtor;
5925     }
5926 
5927     return false;
5928 
5929   case Sema::CXXDestructor:
5930     // C++11 [class.dtor]p5:
5931     //   A destructor is trivial if:
5932     //    - all the direct [subobjects] have trivial destructors
5933     if (RD->hasTrivialDestructor())
5934       return true;
5935 
5936     if (Selected) {
5937       if (RD->needsImplicitDestructor())
5938         S.DeclareImplicitDestructor(RD);
5939       *Selected = RD->getDestructor();
5940     }
5941 
5942     return false;
5943 
5944   case Sema::CXXCopyConstructor:
5945     // C++11 [class.copy]p12:
5946     //   A copy constructor is trivial if:
5947     //    - the constructor selected to copy each direct [subobject] is trivial
5948     if (RD->hasTrivialCopyConstructor()) {
5949       if (Quals == Qualifiers::Const)
5950         // We must either select the trivial copy constructor or reach an
5951         // ambiguity; no need to actually perform overload resolution.
5952         return true;
5953     } else if (!Selected) {
5954       return false;
5955     }
5956     // In C++98, we are not supposed to perform overload resolution here, but we
5957     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5958     // cases like B as having a non-trivial copy constructor:
5959     //   struct A { template<typename T> A(T&); };
5960     //   struct B { mutable A a; };
5961     goto NeedOverloadResolution;
5962 
5963   case Sema::CXXCopyAssignment:
5964     // C++11 [class.copy]p25:
5965     //   A copy assignment operator is trivial if:
5966     //    - the assignment operator selected to copy each direct [subobject] is
5967     //      trivial
5968     if (RD->hasTrivialCopyAssignment()) {
5969       if (Quals == Qualifiers::Const)
5970         return true;
5971     } else if (!Selected) {
5972       return false;
5973     }
5974     // In C++98, we are not supposed to perform overload resolution here, but we
5975     // treat that as a language defect.
5976     goto NeedOverloadResolution;
5977 
5978   case Sema::CXXMoveConstructor:
5979   case Sema::CXXMoveAssignment:
5980   NeedOverloadResolution:
5981     Sema::SpecialMemberOverloadResult *SMOR =
5982         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5983 
5984     // The standard doesn't describe how to behave if the lookup is ambiguous.
5985     // We treat it as not making the member non-trivial, just like the standard
5986     // mandates for the default constructor. This should rarely matter, because
5987     // the member will also be deleted.
5988     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5989       return true;
5990 
5991     if (!SMOR->getMethod()) {
5992       assert(SMOR->getKind() ==
5993              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5994       return false;
5995     }
5996 
5997     // We deliberately don't check if we found a deleted special member. We're
5998     // not supposed to!
5999     if (Selected)
6000       *Selected = SMOR->getMethod();
6001     return SMOR->getMethod()->isTrivial();
6002   }
6003 
6004   llvm_unreachable("unknown special method kind");
6005 }
6006 
6007 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6008   for (auto *CI : RD->ctors())
6009     if (!CI->isImplicit())
6010       return CI;
6011 
6012   // Look for constructor templates.
6013   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6014   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6015     if (CXXConstructorDecl *CD =
6016           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6017       return CD;
6018   }
6019 
6020   return nullptr;
6021 }
6022 
6023 /// The kind of subobject we are checking for triviality. The values of this
6024 /// enumeration are used in diagnostics.
6025 enum TrivialSubobjectKind {
6026   /// The subobject is a base class.
6027   TSK_BaseClass,
6028   /// The subobject is a non-static data member.
6029   TSK_Field,
6030   /// The object is actually the complete object.
6031   TSK_CompleteObject
6032 };
6033 
6034 /// Check whether the special member selected for a given type would be trivial.
6035 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6036                                       QualType SubType, bool ConstRHS,
6037                                       Sema::CXXSpecialMember CSM,
6038                                       TrivialSubobjectKind Kind,
6039                                       bool Diagnose) {
6040   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6041   if (!SubRD)
6042     return true;
6043 
6044   CXXMethodDecl *Selected;
6045   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6046                                ConstRHS, Diagnose ? &Selected : nullptr))
6047     return true;
6048 
6049   if (Diagnose) {
6050     if (ConstRHS)
6051       SubType.addConst();
6052 
6053     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6054       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6055         << Kind << SubType.getUnqualifiedType();
6056       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6057         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6058     } else if (!Selected)
6059       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6060         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6061     else if (Selected->isUserProvided()) {
6062       if (Kind == TSK_CompleteObject)
6063         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6064           << Kind << SubType.getUnqualifiedType() << CSM;
6065       else {
6066         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6067           << Kind << SubType.getUnqualifiedType() << CSM;
6068         S.Diag(Selected->getLocation(), diag::note_declared_at);
6069       }
6070     } else {
6071       if (Kind != TSK_CompleteObject)
6072         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6073           << Kind << SubType.getUnqualifiedType() << CSM;
6074 
6075       // Explain why the defaulted or deleted special member isn't trivial.
6076       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6077     }
6078   }
6079 
6080   return false;
6081 }
6082 
6083 /// Check whether the members of a class type allow a special member to be
6084 /// trivial.
6085 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6086                                      Sema::CXXSpecialMember CSM,
6087                                      bool ConstArg, bool Diagnose) {
6088   for (const auto *FI : RD->fields()) {
6089     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6090       continue;
6091 
6092     QualType FieldType = S.Context.getBaseElementType(FI->getType());
6093 
6094     // Pretend anonymous struct or union members are members of this class.
6095     if (FI->isAnonymousStructOrUnion()) {
6096       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6097                                     CSM, ConstArg, Diagnose))
6098         return false;
6099       continue;
6100     }
6101 
6102     // C++11 [class.ctor]p5:
6103     //   A default constructor is trivial if [...]
6104     //    -- no non-static data member of its class has a
6105     //       brace-or-equal-initializer
6106     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6107       if (Diagnose)
6108         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6109       return false;
6110     }
6111 
6112     // Objective C ARC 4.3.5:
6113     //   [...] nontrivally ownership-qualified types are [...] not trivially
6114     //   default constructible, copy constructible, move constructible, copy
6115     //   assignable, move assignable, or destructible [...]
6116     if (S.getLangOpts().ObjCAutoRefCount &&
6117         FieldType.hasNonTrivialObjCLifetime()) {
6118       if (Diagnose)
6119         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6120           << RD << FieldType.getObjCLifetime();
6121       return false;
6122     }
6123 
6124     bool ConstRHS = ConstArg && !FI->isMutable();
6125     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6126                                    CSM, TSK_Field, Diagnose))
6127       return false;
6128   }
6129 
6130   return true;
6131 }
6132 
6133 /// Diagnose why the specified class does not have a trivial special member of
6134 /// the given kind.
6135 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6136   QualType Ty = Context.getRecordType(RD);
6137 
6138   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6139   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6140                             TSK_CompleteObject, /*Diagnose*/true);
6141 }
6142 
6143 /// Determine whether a defaulted or deleted special member function is trivial,
6144 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6145 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6146 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6147                                   bool Diagnose) {
6148   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6149 
6150   CXXRecordDecl *RD = MD->getParent();
6151 
6152   bool ConstArg = false;
6153 
6154   // C++11 [class.copy]p12, p25: [DR1593]
6155   //   A [special member] is trivial if [...] its parameter-type-list is
6156   //   equivalent to the parameter-type-list of an implicit declaration [...]
6157   switch (CSM) {
6158   case CXXDefaultConstructor:
6159   case CXXDestructor:
6160     // Trivial default constructors and destructors cannot have parameters.
6161     break;
6162 
6163   case CXXCopyConstructor:
6164   case CXXCopyAssignment: {
6165     // Trivial copy operations always have const, non-volatile parameter types.
6166     ConstArg = true;
6167     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6168     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6169     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6170       if (Diagnose)
6171         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6172           << Param0->getSourceRange() << Param0->getType()
6173           << Context.getLValueReferenceType(
6174                Context.getRecordType(RD).withConst());
6175       return false;
6176     }
6177     break;
6178   }
6179 
6180   case CXXMoveConstructor:
6181   case CXXMoveAssignment: {
6182     // Trivial move operations always have non-cv-qualified parameters.
6183     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6184     const RValueReferenceType *RT =
6185       Param0->getType()->getAs<RValueReferenceType>();
6186     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6187       if (Diagnose)
6188         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6189           << Param0->getSourceRange() << Param0->getType()
6190           << Context.getRValueReferenceType(Context.getRecordType(RD));
6191       return false;
6192     }
6193     break;
6194   }
6195 
6196   case CXXInvalid:
6197     llvm_unreachable("not a special member");
6198   }
6199 
6200   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6201     if (Diagnose)
6202       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6203            diag::note_nontrivial_default_arg)
6204         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6205     return false;
6206   }
6207   if (MD->isVariadic()) {
6208     if (Diagnose)
6209       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6210     return false;
6211   }
6212 
6213   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6214   //   A copy/move [constructor or assignment operator] is trivial if
6215   //    -- the [member] selected to copy/move each direct base class subobject
6216   //       is trivial
6217   //
6218   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6219   //   A [default constructor or destructor] is trivial if
6220   //    -- all the direct base classes have trivial [default constructors or
6221   //       destructors]
6222   for (const auto &BI : RD->bases())
6223     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6224                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
6225       return false;
6226 
6227   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6228   //   A copy/move [constructor or assignment operator] for a class X is
6229   //   trivial if
6230   //    -- for each non-static data member of X that is of class type (or array
6231   //       thereof), the constructor selected to copy/move that member is
6232   //       trivial
6233   //
6234   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6235   //   A [default constructor or destructor] is trivial if
6236   //    -- for all of the non-static data members of its class that are of class
6237   //       type (or array thereof), each such class has a trivial [default
6238   //       constructor or destructor]
6239   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6240     return false;
6241 
6242   // C++11 [class.dtor]p5:
6243   //   A destructor is trivial if [...]
6244   //    -- the destructor is not virtual
6245   if (CSM == CXXDestructor && MD->isVirtual()) {
6246     if (Diagnose)
6247       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6248     return false;
6249   }
6250 
6251   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6252   //   A [special member] for class X is trivial if [...]
6253   //    -- class X has no virtual functions and no virtual base classes
6254   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6255     if (!Diagnose)
6256       return false;
6257 
6258     if (RD->getNumVBases()) {
6259       // Check for virtual bases. We already know that the corresponding
6260       // member in all bases is trivial, so vbases must all be direct.
6261       CXXBaseSpecifier &BS = *RD->vbases_begin();
6262       assert(BS.isVirtual());
6263       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6264       return false;
6265     }
6266 
6267     // Must have a virtual method.
6268     for (const auto *MI : RD->methods()) {
6269       if (MI->isVirtual()) {
6270         SourceLocation MLoc = MI->getLocStart();
6271         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6272         return false;
6273       }
6274     }
6275 
6276     llvm_unreachable("dynamic class with no vbases and no virtual functions");
6277   }
6278 
6279   // Looks like it's trivial!
6280   return true;
6281 }
6282 
6283 namespace {
6284 struct FindHiddenVirtualMethod {
6285   Sema *S;
6286   CXXMethodDecl *Method;
6287   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6288   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6289 
6290 private:
6291   /// Check whether any most overriden method from MD in Methods
6292   static bool CheckMostOverridenMethods(
6293       const CXXMethodDecl *MD,
6294       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
6295     if (MD->size_overridden_methods() == 0)
6296       return Methods.count(MD->getCanonicalDecl());
6297     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6298                                         E = MD->end_overridden_methods();
6299          I != E; ++I)
6300       if (CheckMostOverridenMethods(*I, Methods))
6301         return true;
6302     return false;
6303   }
6304 
6305 public:
6306   /// Member lookup function that determines whether a given C++
6307   /// method overloads virtual methods in a base class without overriding any,
6308   /// to be used with CXXRecordDecl::lookupInBases().
6309   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6310     RecordDecl *BaseRecord =
6311         Specifier->getType()->getAs<RecordType>()->getDecl();
6312 
6313     DeclarationName Name = Method->getDeclName();
6314     assert(Name.getNameKind() == DeclarationName::Identifier);
6315 
6316     bool foundSameNameMethod = false;
6317     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6318     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6319          Path.Decls = Path.Decls.slice(1)) {
6320       NamedDecl *D = Path.Decls.front();
6321       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6322         MD = MD->getCanonicalDecl();
6323         foundSameNameMethod = true;
6324         // Interested only in hidden virtual methods.
6325         if (!MD->isVirtual())
6326           continue;
6327         // If the method we are checking overrides a method from its base
6328         // don't warn about the other overloaded methods. Clang deviates from
6329         // GCC by only diagnosing overloads of inherited virtual functions that
6330         // do not override any other virtual functions in the base. GCC's
6331         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6332         // function from a base class. These cases may be better served by a
6333         // warning (not specific to virtual functions) on call sites when the
6334         // call would select a different function from the base class, were it
6335         // visible.
6336         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6337         if (!S->IsOverload(Method, MD, false))
6338           return true;
6339         // Collect the overload only if its hidden.
6340         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
6341           overloadedMethods.push_back(MD);
6342       }
6343     }
6344 
6345     if (foundSameNameMethod)
6346       OverloadedMethods.append(overloadedMethods.begin(),
6347                                overloadedMethods.end());
6348     return foundSameNameMethod;
6349   }
6350 };
6351 } // end anonymous namespace
6352 
6353 /// \brief Add the most overriden methods from MD to Methods
6354 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6355                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6356   if (MD->size_overridden_methods() == 0)
6357     Methods.insert(MD->getCanonicalDecl());
6358   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6359                                       E = MD->end_overridden_methods();
6360        I != E; ++I)
6361     AddMostOverridenMethods(*I, Methods);
6362 }
6363 
6364 /// \brief Check if a method overloads virtual methods in a base class without
6365 /// overriding any.
6366 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6367                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6368   if (!MD->getDeclName().isIdentifier())
6369     return;
6370 
6371   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6372                      /*bool RecordPaths=*/false,
6373                      /*bool DetectVirtual=*/false);
6374   FindHiddenVirtualMethod FHVM;
6375   FHVM.Method = MD;
6376   FHVM.S = this;
6377 
6378   // Keep the base methods that were overriden or introduced in the subclass
6379   // by 'using' in a set. A base method not in this set is hidden.
6380   CXXRecordDecl *DC = MD->getParent();
6381   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6382   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6383     NamedDecl *ND = *I;
6384     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6385       ND = shad->getTargetDecl();
6386     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6387       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
6388   }
6389 
6390   if (DC->lookupInBases(FHVM, Paths))
6391     OverloadedMethods = FHVM.OverloadedMethods;
6392 }
6393 
6394 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6395                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6396   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6397     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6398     PartialDiagnostic PD = PDiag(
6399          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6400     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6401     Diag(overloadedMD->getLocation(), PD);
6402   }
6403 }
6404 
6405 /// \brief Diagnose methods which overload virtual methods in a base class
6406 /// without overriding any.
6407 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6408   if (MD->isInvalidDecl())
6409     return;
6410 
6411   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6412     return;
6413 
6414   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6415   FindHiddenVirtualMethods(MD, OverloadedMethods);
6416   if (!OverloadedMethods.empty()) {
6417     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6418       << MD << (OverloadedMethods.size() > 1);
6419 
6420     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6421   }
6422 }
6423 
6424 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6425                                              Decl *TagDecl,
6426                                              SourceLocation LBrac,
6427                                              SourceLocation RBrac,
6428                                              AttributeList *AttrList) {
6429   if (!TagDecl)
6430     return;
6431 
6432   AdjustDeclIfTemplate(TagDecl);
6433 
6434   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6435     if (l->getKind() != AttributeList::AT_Visibility)
6436       continue;
6437     l->setInvalid();
6438     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6439       l->getName();
6440   }
6441 
6442   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6443               // strict aliasing violation!
6444               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6445               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6446 
6447   CheckCompletedCXXClass(
6448                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6449 }
6450 
6451 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6452 /// special functions, such as the default constructor, copy
6453 /// constructor, or destructor, to the given C++ class (C++
6454 /// [special]p1).  This routine can only be executed just before the
6455 /// definition of the class is complete.
6456 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6457   if (!ClassDecl->hasUserDeclaredConstructor())
6458     ++ASTContext::NumImplicitDefaultConstructors;
6459 
6460   // If this class inherited any constructors, declare the default constructor
6461   // now in case it displaces one from a base class.
6462   if (ClassDecl->needsImplicitDefaultConstructor() &&
6463       ClassDecl->hasInheritedConstructor())
6464     DeclareImplicitDefaultConstructor(ClassDecl);
6465 
6466   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6467     ++ASTContext::NumImplicitCopyConstructors;
6468 
6469     // If the properties or semantics of the copy constructor couldn't be
6470     // determined while the class was being declared, force a declaration
6471     // of it now.
6472     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
6473         ClassDecl->hasInheritedConstructor())
6474       DeclareImplicitCopyConstructor(ClassDecl);
6475   }
6476 
6477   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6478     ++ASTContext::NumImplicitMoveConstructors;
6479 
6480     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
6481         ClassDecl->hasInheritedConstructor())
6482       DeclareImplicitMoveConstructor(ClassDecl);
6483   }
6484 
6485   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6486     ++ASTContext::NumImplicitCopyAssignmentOperators;
6487 
6488     // If we have a dynamic class, then the copy assignment operator may be
6489     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6490     // it shows up in the right place in the vtable and that we diagnose
6491     // problems with the implicit exception specification.
6492     if (ClassDecl->isDynamicClass() ||
6493         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
6494         ClassDecl->hasInheritedAssignment())
6495       DeclareImplicitCopyAssignment(ClassDecl);
6496   }
6497 
6498   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6499     ++ASTContext::NumImplicitMoveAssignmentOperators;
6500 
6501     // Likewise for the move assignment operator.
6502     if (ClassDecl->isDynamicClass() ||
6503         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
6504         ClassDecl->hasInheritedAssignment())
6505       DeclareImplicitMoveAssignment(ClassDecl);
6506   }
6507 
6508   if (!ClassDecl->hasUserDeclaredDestructor()) {
6509     ++ASTContext::NumImplicitDestructors;
6510 
6511     // If we have a dynamic class, then the destructor may be virtual, so we
6512     // have to declare the destructor immediately. This ensures that, e.g., it
6513     // shows up in the right place in the vtable and that we diagnose problems
6514     // with the implicit exception specification.
6515     if (ClassDecl->isDynamicClass() ||
6516         ClassDecl->needsOverloadResolutionForDestructor())
6517       DeclareImplicitDestructor(ClassDecl);
6518   }
6519 }
6520 
6521 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6522   if (!D)
6523     return 0;
6524 
6525   // The order of template parameters is not important here. All names
6526   // get added to the same scope.
6527   SmallVector<TemplateParameterList *, 4> ParameterLists;
6528 
6529   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6530     D = TD->getTemplatedDecl();
6531 
6532   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6533     ParameterLists.push_back(PSD->getTemplateParameters());
6534 
6535   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6536     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6537       ParameterLists.push_back(DD->getTemplateParameterList(i));
6538 
6539     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6540       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6541         ParameterLists.push_back(FTD->getTemplateParameters());
6542     }
6543   }
6544 
6545   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6546     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6547       ParameterLists.push_back(TD->getTemplateParameterList(i));
6548 
6549     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6550       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6551         ParameterLists.push_back(CTD->getTemplateParameters());
6552     }
6553   }
6554 
6555   unsigned Count = 0;
6556   for (TemplateParameterList *Params : ParameterLists) {
6557     if (Params->size() > 0)
6558       // Ignore explicit specializations; they don't contribute to the template
6559       // depth.
6560       ++Count;
6561     for (NamedDecl *Param : *Params) {
6562       if (Param->getDeclName()) {
6563         S->AddDecl(Param);
6564         IdResolver.AddDecl(Param);
6565       }
6566     }
6567   }
6568 
6569   return Count;
6570 }
6571 
6572 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6573   if (!RecordD) return;
6574   AdjustDeclIfTemplate(RecordD);
6575   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6576   PushDeclContext(S, Record);
6577 }
6578 
6579 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6580   if (!RecordD) return;
6581   PopDeclContext();
6582 }
6583 
6584 /// This is used to implement the constant expression evaluation part of the
6585 /// attribute enable_if extension. There is nothing in standard C++ which would
6586 /// require reentering parameters.
6587 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6588   if (!Param)
6589     return;
6590 
6591   S->AddDecl(Param);
6592   if (Param->getDeclName())
6593     IdResolver.AddDecl(Param);
6594 }
6595 
6596 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6597 /// parsing a top-level (non-nested) C++ class, and we are now
6598 /// parsing those parts of the given Method declaration that could
6599 /// not be parsed earlier (C++ [class.mem]p2), such as default
6600 /// arguments. This action should enter the scope of the given
6601 /// Method declaration as if we had just parsed the qualified method
6602 /// name. However, it should not bring the parameters into scope;
6603 /// that will be performed by ActOnDelayedCXXMethodParameter.
6604 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6605 }
6606 
6607 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6608 /// C++ method declaration. We're (re-)introducing the given
6609 /// function parameter into scope for use in parsing later parts of
6610 /// the method declaration. For example, we could see an
6611 /// ActOnParamDefaultArgument event for this parameter.
6612 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6613   if (!ParamD)
6614     return;
6615 
6616   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6617 
6618   // If this parameter has an unparsed default argument, clear it out
6619   // to make way for the parsed default argument.
6620   if (Param->hasUnparsedDefaultArg())
6621     Param->setDefaultArg(nullptr);
6622 
6623   S->AddDecl(Param);
6624   if (Param->getDeclName())
6625     IdResolver.AddDecl(Param);
6626 }
6627 
6628 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6629 /// processing the delayed method declaration for Method. The method
6630 /// declaration is now considered finished. There may be a separate
6631 /// ActOnStartOfFunctionDef action later (not necessarily
6632 /// immediately!) for this method, if it was also defined inside the
6633 /// class body.
6634 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6635   if (!MethodD)
6636     return;
6637 
6638   AdjustDeclIfTemplate(MethodD);
6639 
6640   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6641 
6642   // Now that we have our default arguments, check the constructor
6643   // again. It could produce additional diagnostics or affect whether
6644   // the class has implicitly-declared destructors, among other
6645   // things.
6646   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6647     CheckConstructor(Constructor);
6648 
6649   // Check the default arguments, which we may have added.
6650   if (!Method->isInvalidDecl())
6651     CheckCXXDefaultArguments(Method);
6652 }
6653 
6654 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6655 /// the well-formedness of the constructor declarator @p D with type @p
6656 /// R. If there are any errors in the declarator, this routine will
6657 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6658 /// will be updated to reflect a well-formed type for the constructor and
6659 /// returned.
6660 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6661                                           StorageClass &SC) {
6662   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6663 
6664   // C++ [class.ctor]p3:
6665   //   A constructor shall not be virtual (10.3) or static (9.4). A
6666   //   constructor can be invoked for a const, volatile or const
6667   //   volatile object. A constructor shall not be declared const,
6668   //   volatile, or const volatile (9.3.2).
6669   if (isVirtual) {
6670     if (!D.isInvalidType())
6671       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6672         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6673         << SourceRange(D.getIdentifierLoc());
6674     D.setInvalidType();
6675   }
6676   if (SC == SC_Static) {
6677     if (!D.isInvalidType())
6678       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6679         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6680         << SourceRange(D.getIdentifierLoc());
6681     D.setInvalidType();
6682     SC = SC_None;
6683   }
6684 
6685   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6686     diagnoseIgnoredQualifiers(
6687         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6688         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6689         D.getDeclSpec().getRestrictSpecLoc(),
6690         D.getDeclSpec().getAtomicSpecLoc());
6691     D.setInvalidType();
6692   }
6693 
6694   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6695   if (FTI.TypeQuals != 0) {
6696     if (FTI.TypeQuals & Qualifiers::Const)
6697       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6698         << "const" << SourceRange(D.getIdentifierLoc());
6699     if (FTI.TypeQuals & Qualifiers::Volatile)
6700       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6701         << "volatile" << SourceRange(D.getIdentifierLoc());
6702     if (FTI.TypeQuals & Qualifiers::Restrict)
6703       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6704         << "restrict" << SourceRange(D.getIdentifierLoc());
6705     D.setInvalidType();
6706   }
6707 
6708   // C++0x [class.ctor]p4:
6709   //   A constructor shall not be declared with a ref-qualifier.
6710   if (FTI.hasRefQualifier()) {
6711     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6712       << FTI.RefQualifierIsLValueRef
6713       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6714     D.setInvalidType();
6715   }
6716 
6717   // Rebuild the function type "R" without any type qualifiers (in
6718   // case any of the errors above fired) and with "void" as the
6719   // return type, since constructors don't have return types.
6720   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6721   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6722     return R;
6723 
6724   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6725   EPI.TypeQuals = 0;
6726   EPI.RefQualifier = RQ_None;
6727 
6728   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6729 }
6730 
6731 /// CheckConstructor - Checks a fully-formed constructor for
6732 /// well-formedness, issuing any diagnostics required. Returns true if
6733 /// the constructor declarator is invalid.
6734 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6735   CXXRecordDecl *ClassDecl
6736     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6737   if (!ClassDecl)
6738     return Constructor->setInvalidDecl();
6739 
6740   // C++ [class.copy]p3:
6741   //   A declaration of a constructor for a class X is ill-formed if
6742   //   its first parameter is of type (optionally cv-qualified) X and
6743   //   either there are no other parameters or else all other
6744   //   parameters have default arguments.
6745   if (!Constructor->isInvalidDecl() &&
6746       ((Constructor->getNumParams() == 1) ||
6747        (Constructor->getNumParams() > 1 &&
6748         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6749       Constructor->getTemplateSpecializationKind()
6750                                               != TSK_ImplicitInstantiation) {
6751     QualType ParamType = Constructor->getParamDecl(0)->getType();
6752     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6753     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6754       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6755       const char *ConstRef
6756         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6757                                                         : " const &";
6758       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6759         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6760 
6761       // FIXME: Rather that making the constructor invalid, we should endeavor
6762       // to fix the type.
6763       Constructor->setInvalidDecl();
6764     }
6765   }
6766 }
6767 
6768 /// CheckDestructor - Checks a fully-formed destructor definition for
6769 /// well-formedness, issuing any diagnostics required.  Returns true
6770 /// on error.
6771 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6772   CXXRecordDecl *RD = Destructor->getParent();
6773 
6774   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6775     SourceLocation Loc;
6776 
6777     if (!Destructor->isImplicit())
6778       Loc = Destructor->getLocation();
6779     else
6780       Loc = RD->getLocation();
6781 
6782     // If we have a virtual destructor, look up the deallocation function
6783     FunctionDecl *OperatorDelete = nullptr;
6784     DeclarationName Name =
6785     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6786     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6787       return true;
6788     // If there's no class-specific operator delete, look up the global
6789     // non-array delete.
6790     if (!OperatorDelete)
6791       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6792 
6793     MarkFunctionReferenced(Loc, OperatorDelete);
6794 
6795     Destructor->setOperatorDelete(OperatorDelete);
6796   }
6797 
6798   return false;
6799 }
6800 
6801 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6802 /// the well-formednes of the destructor declarator @p D with type @p
6803 /// R. If there are any errors in the declarator, this routine will
6804 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6805 /// will be updated to reflect a well-formed type for the destructor and
6806 /// returned.
6807 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6808                                          StorageClass& SC) {
6809   // C++ [class.dtor]p1:
6810   //   [...] A typedef-name that names a class is a class-name
6811   //   (7.1.3); however, a typedef-name that names a class shall not
6812   //   be used as the identifier in the declarator for a destructor
6813   //   declaration.
6814   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6815   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6816     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6817       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6818   else if (const TemplateSpecializationType *TST =
6819              DeclaratorType->getAs<TemplateSpecializationType>())
6820     if (TST->isTypeAlias())
6821       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6822         << DeclaratorType << 1;
6823 
6824   // C++ [class.dtor]p2:
6825   //   A destructor is used to destroy objects of its class type. A
6826   //   destructor takes no parameters, and no return type can be
6827   //   specified for it (not even void). The address of a destructor
6828   //   shall not be taken. A destructor shall not be static. A
6829   //   destructor can be invoked for a const, volatile or const
6830   //   volatile object. A destructor shall not be declared const,
6831   //   volatile or const volatile (9.3.2).
6832   if (SC == SC_Static) {
6833     if (!D.isInvalidType())
6834       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6835         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6836         << SourceRange(D.getIdentifierLoc())
6837         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6838 
6839     SC = SC_None;
6840   }
6841   if (!D.isInvalidType()) {
6842     // Destructors don't have return types, but the parser will
6843     // happily parse something like:
6844     //
6845     //   class X {
6846     //     float ~X();
6847     //   };
6848     //
6849     // The return type will be eliminated later.
6850     if (D.getDeclSpec().hasTypeSpecifier())
6851       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6852         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6853         << SourceRange(D.getIdentifierLoc());
6854     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6855       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6856                                 SourceLocation(),
6857                                 D.getDeclSpec().getConstSpecLoc(),
6858                                 D.getDeclSpec().getVolatileSpecLoc(),
6859                                 D.getDeclSpec().getRestrictSpecLoc(),
6860                                 D.getDeclSpec().getAtomicSpecLoc());
6861       D.setInvalidType();
6862     }
6863   }
6864 
6865   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6866   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6867     if (FTI.TypeQuals & Qualifiers::Const)
6868       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6869         << "const" << SourceRange(D.getIdentifierLoc());
6870     if (FTI.TypeQuals & Qualifiers::Volatile)
6871       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6872         << "volatile" << SourceRange(D.getIdentifierLoc());
6873     if (FTI.TypeQuals & Qualifiers::Restrict)
6874       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6875         << "restrict" << SourceRange(D.getIdentifierLoc());
6876     D.setInvalidType();
6877   }
6878 
6879   // C++0x [class.dtor]p2:
6880   //   A destructor shall not be declared with a ref-qualifier.
6881   if (FTI.hasRefQualifier()) {
6882     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6883       << FTI.RefQualifierIsLValueRef
6884       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6885     D.setInvalidType();
6886   }
6887 
6888   // Make sure we don't have any parameters.
6889   if (FTIHasNonVoidParameters(FTI)) {
6890     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6891 
6892     // Delete the parameters.
6893     FTI.freeParams();
6894     D.setInvalidType();
6895   }
6896 
6897   // Make sure the destructor isn't variadic.
6898   if (FTI.isVariadic) {
6899     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6900     D.setInvalidType();
6901   }
6902 
6903   // Rebuild the function type "R" without any type qualifiers or
6904   // parameters (in case any of the errors above fired) and with
6905   // "void" as the return type, since destructors don't have return
6906   // types.
6907   if (!D.isInvalidType())
6908     return R;
6909 
6910   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6911   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6912   EPI.Variadic = false;
6913   EPI.TypeQuals = 0;
6914   EPI.RefQualifier = RQ_None;
6915   return Context.getFunctionType(Context.VoidTy, None, EPI);
6916 }
6917 
6918 static void extendLeft(SourceRange &R, SourceRange Before) {
6919   if (Before.isInvalid())
6920     return;
6921   R.setBegin(Before.getBegin());
6922   if (R.getEnd().isInvalid())
6923     R.setEnd(Before.getEnd());
6924 }
6925 
6926 static void extendRight(SourceRange &R, SourceRange After) {
6927   if (After.isInvalid())
6928     return;
6929   if (R.getBegin().isInvalid())
6930     R.setBegin(After.getBegin());
6931   R.setEnd(After.getEnd());
6932 }
6933 
6934 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6935 /// well-formednes of the conversion function declarator @p D with
6936 /// type @p R. If there are any errors in the declarator, this routine
6937 /// will emit diagnostics and return true. Otherwise, it will return
6938 /// false. Either way, the type @p R will be updated to reflect a
6939 /// well-formed type for the conversion operator.
6940 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6941                                      StorageClass& SC) {
6942   // C++ [class.conv.fct]p1:
6943   //   Neither parameter types nor return type can be specified. The
6944   //   type of a conversion function (8.3.5) is "function taking no
6945   //   parameter returning conversion-type-id."
6946   if (SC == SC_Static) {
6947     if (!D.isInvalidType())
6948       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6949         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6950         << D.getName().getSourceRange();
6951     D.setInvalidType();
6952     SC = SC_None;
6953   }
6954 
6955   TypeSourceInfo *ConvTSI = nullptr;
6956   QualType ConvType =
6957       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
6958 
6959   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6960     // Conversion functions don't have return types, but the parser will
6961     // happily parse something like:
6962     //
6963     //   class X {
6964     //     float operator bool();
6965     //   };
6966     //
6967     // The return type will be changed later anyway.
6968     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6969       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6970       << SourceRange(D.getIdentifierLoc());
6971     D.setInvalidType();
6972   }
6973 
6974   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6975 
6976   // Make sure we don't have any parameters.
6977   if (Proto->getNumParams() > 0) {
6978     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6979 
6980     // Delete the parameters.
6981     D.getFunctionTypeInfo().freeParams();
6982     D.setInvalidType();
6983   } else if (Proto->isVariadic()) {
6984     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6985     D.setInvalidType();
6986   }
6987 
6988   // Diagnose "&operator bool()" and other such nonsense.  This
6989   // is actually a gcc extension which we don't support.
6990   if (Proto->getReturnType() != ConvType) {
6991     bool NeedsTypedef = false;
6992     SourceRange Before, After;
6993 
6994     // Walk the chunks and extract information on them for our diagnostic.
6995     bool PastFunctionChunk = false;
6996     for (auto &Chunk : D.type_objects()) {
6997       switch (Chunk.Kind) {
6998       case DeclaratorChunk::Function:
6999         if (!PastFunctionChunk) {
7000           if (Chunk.Fun.HasTrailingReturnType) {
7001             TypeSourceInfo *TRT = nullptr;
7002             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7003             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7004           }
7005           PastFunctionChunk = true;
7006           break;
7007         }
7008         // Fall through.
7009       case DeclaratorChunk::Array:
7010         NeedsTypedef = true;
7011         extendRight(After, Chunk.getSourceRange());
7012         break;
7013 
7014       case DeclaratorChunk::Pointer:
7015       case DeclaratorChunk::BlockPointer:
7016       case DeclaratorChunk::Reference:
7017       case DeclaratorChunk::MemberPointer:
7018       case DeclaratorChunk::Pipe:
7019         extendLeft(Before, Chunk.getSourceRange());
7020         break;
7021 
7022       case DeclaratorChunk::Paren:
7023         extendLeft(Before, Chunk.Loc);
7024         extendRight(After, Chunk.EndLoc);
7025         break;
7026       }
7027     }
7028 
7029     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7030                          After.isValid()  ? After.getBegin() :
7031                                             D.getIdentifierLoc();
7032     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7033     DB << Before << After;
7034 
7035     if (!NeedsTypedef) {
7036       DB << /*don't need a typedef*/0;
7037 
7038       // If we can provide a correct fix-it hint, do so.
7039       if (After.isInvalid() && ConvTSI) {
7040         SourceLocation InsertLoc =
7041             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7042         DB << FixItHint::CreateInsertion(InsertLoc, " ")
7043            << FixItHint::CreateInsertionFromRange(
7044                   InsertLoc, CharSourceRange::getTokenRange(Before))
7045            << FixItHint::CreateRemoval(Before);
7046       }
7047     } else if (!Proto->getReturnType()->isDependentType()) {
7048       DB << /*typedef*/1 << Proto->getReturnType();
7049     } else if (getLangOpts().CPlusPlus11) {
7050       DB << /*alias template*/2 << Proto->getReturnType();
7051     } else {
7052       DB << /*might not be fixable*/3;
7053     }
7054 
7055     // Recover by incorporating the other type chunks into the result type.
7056     // Note, this does *not* change the name of the function. This is compatible
7057     // with the GCC extension:
7058     //   struct S { &operator int(); } s;
7059     //   int &r = s.operator int(); // ok in GCC
7060     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
7061     ConvType = Proto->getReturnType();
7062   }
7063 
7064   // C++ [class.conv.fct]p4:
7065   //   The conversion-type-id shall not represent a function type nor
7066   //   an array type.
7067   if (ConvType->isArrayType()) {
7068     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7069     ConvType = Context.getPointerType(ConvType);
7070     D.setInvalidType();
7071   } else if (ConvType->isFunctionType()) {
7072     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7073     ConvType = Context.getPointerType(ConvType);
7074     D.setInvalidType();
7075   }
7076 
7077   // Rebuild the function type "R" without any parameters (in case any
7078   // of the errors above fired) and with the conversion type as the
7079   // return type.
7080   if (D.isInvalidType())
7081     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7082 
7083   // C++0x explicit conversion operators.
7084   if (D.getDeclSpec().isExplicitSpecified())
7085     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7086          getLangOpts().CPlusPlus11 ?
7087            diag::warn_cxx98_compat_explicit_conversion_functions :
7088            diag::ext_explicit_conversion_functions)
7089       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7090 }
7091 
7092 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7093 /// the declaration of the given C++ conversion function. This routine
7094 /// is responsible for recording the conversion function in the C++
7095 /// class, if possible.
7096 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7097   assert(Conversion && "Expected to receive a conversion function declaration");
7098 
7099   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7100 
7101   // Make sure we aren't redeclaring the conversion function.
7102   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7103 
7104   // C++ [class.conv.fct]p1:
7105   //   [...] A conversion function is never used to convert a
7106   //   (possibly cv-qualified) object to the (possibly cv-qualified)
7107   //   same object type (or a reference to it), to a (possibly
7108   //   cv-qualified) base class of that type (or a reference to it),
7109   //   or to (possibly cv-qualified) void.
7110   // FIXME: Suppress this warning if the conversion function ends up being a
7111   // virtual function that overrides a virtual function in a base class.
7112   QualType ClassType
7113     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7114   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7115     ConvType = ConvTypeRef->getPointeeType();
7116   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7117       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7118     /* Suppress diagnostics for instantiations. */;
7119   else if (ConvType->isRecordType()) {
7120     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7121     if (ConvType == ClassType)
7122       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7123         << ClassType;
7124     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
7125       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7126         <<  ClassType << ConvType;
7127   } else if (ConvType->isVoidType()) {
7128     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7129       << ClassType << ConvType;
7130   }
7131 
7132   if (FunctionTemplateDecl *ConversionTemplate
7133                                 = Conversion->getDescribedFunctionTemplate())
7134     return ConversionTemplate;
7135 
7136   return Conversion;
7137 }
7138 
7139 //===----------------------------------------------------------------------===//
7140 // Namespace Handling
7141 //===----------------------------------------------------------------------===//
7142 
7143 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7144 /// reopened.
7145 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7146                                             SourceLocation Loc,
7147                                             IdentifierInfo *II, bool *IsInline,
7148                                             NamespaceDecl *PrevNS) {
7149   assert(*IsInline != PrevNS->isInline());
7150 
7151   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7152   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7153   // inline namespaces, with the intention of bringing names into namespace std.
7154   //
7155   // We support this just well enough to get that case working; this is not
7156   // sufficient to support reopening namespaces as inline in general.
7157   if (*IsInline && II && II->getName().startswith("__atomic") &&
7158       S.getSourceManager().isInSystemHeader(Loc)) {
7159     // Mark all prior declarations of the namespace as inline.
7160     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7161          NS = NS->getPreviousDecl())
7162       NS->setInline(*IsInline);
7163     // Patch up the lookup table for the containing namespace. This isn't really
7164     // correct, but it's good enough for this particular case.
7165     for (auto *I : PrevNS->decls())
7166       if (auto *ND = dyn_cast<NamedDecl>(I))
7167         PrevNS->getParent()->makeDeclVisibleInContext(ND);
7168     return;
7169   }
7170 
7171   if (PrevNS->isInline())
7172     // The user probably just forgot the 'inline', so suggest that it
7173     // be added back.
7174     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7175       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7176   else
7177     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7178 
7179   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7180   *IsInline = PrevNS->isInline();
7181 }
7182 
7183 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7184 /// definition.
7185 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7186                                    SourceLocation InlineLoc,
7187                                    SourceLocation NamespaceLoc,
7188                                    SourceLocation IdentLoc,
7189                                    IdentifierInfo *II,
7190                                    SourceLocation LBrace,
7191                                    AttributeList *AttrList,
7192                                    UsingDirectiveDecl *&UD) {
7193   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7194   // For anonymous namespace, take the location of the left brace.
7195   SourceLocation Loc = II ? IdentLoc : LBrace;
7196   bool IsInline = InlineLoc.isValid();
7197   bool IsInvalid = false;
7198   bool IsStd = false;
7199   bool AddToKnown = false;
7200   Scope *DeclRegionScope = NamespcScope->getParent();
7201 
7202   NamespaceDecl *PrevNS = nullptr;
7203   if (II) {
7204     // C++ [namespace.def]p2:
7205     //   The identifier in an original-namespace-definition shall not
7206     //   have been previously defined in the declarative region in
7207     //   which the original-namespace-definition appears. The
7208     //   identifier in an original-namespace-definition is the name of
7209     //   the namespace. Subsequently in that declarative region, it is
7210     //   treated as an original-namespace-name.
7211     //
7212     // Since namespace names are unique in their scope, and we don't
7213     // look through using directives, just look for any ordinary names
7214     // as if by qualified name lookup.
7215     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
7216     LookupQualifiedName(R, CurContext->getRedeclContext());
7217     NamedDecl *PrevDecl =
7218         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
7219     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7220 
7221     if (PrevNS) {
7222       // This is an extended namespace definition.
7223       if (IsInline != PrevNS->isInline())
7224         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7225                                         &IsInline, PrevNS);
7226     } else if (PrevDecl) {
7227       // This is an invalid name redefinition.
7228       Diag(Loc, diag::err_redefinition_different_kind)
7229         << II;
7230       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7231       IsInvalid = true;
7232       // Continue on to push Namespc as current DeclContext and return it.
7233     } else if (II->isStr("std") &&
7234                CurContext->getRedeclContext()->isTranslationUnit()) {
7235       // This is the first "real" definition of the namespace "std", so update
7236       // our cache of the "std" namespace to point at this definition.
7237       PrevNS = getStdNamespace();
7238       IsStd = true;
7239       AddToKnown = !IsInline;
7240     } else {
7241       // We've seen this namespace for the first time.
7242       AddToKnown = !IsInline;
7243     }
7244   } else {
7245     // Anonymous namespaces.
7246 
7247     // Determine whether the parent already has an anonymous namespace.
7248     DeclContext *Parent = CurContext->getRedeclContext();
7249     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7250       PrevNS = TU->getAnonymousNamespace();
7251     } else {
7252       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7253       PrevNS = ND->getAnonymousNamespace();
7254     }
7255 
7256     if (PrevNS && IsInline != PrevNS->isInline())
7257       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7258                                       &IsInline, PrevNS);
7259   }
7260 
7261   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7262                                                  StartLoc, Loc, II, PrevNS);
7263   if (IsInvalid)
7264     Namespc->setInvalidDecl();
7265 
7266   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7267 
7268   // FIXME: Should we be merging attributes?
7269   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7270     PushNamespaceVisibilityAttr(Attr, Loc);
7271 
7272   if (IsStd)
7273     StdNamespace = Namespc;
7274   if (AddToKnown)
7275     KnownNamespaces[Namespc] = false;
7276 
7277   if (II) {
7278     PushOnScopeChains(Namespc, DeclRegionScope);
7279   } else {
7280     // Link the anonymous namespace into its parent.
7281     DeclContext *Parent = CurContext->getRedeclContext();
7282     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7283       TU->setAnonymousNamespace(Namespc);
7284     } else {
7285       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7286     }
7287 
7288     CurContext->addDecl(Namespc);
7289 
7290     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
7291     //   behaves as if it were replaced by
7292     //     namespace unique { /* empty body */ }
7293     //     using namespace unique;
7294     //     namespace unique { namespace-body }
7295     //   where all occurrences of 'unique' in a translation unit are
7296     //   replaced by the same identifier and this identifier differs
7297     //   from all other identifiers in the entire program.
7298 
7299     // We just create the namespace with an empty name and then add an
7300     // implicit using declaration, just like the standard suggests.
7301     //
7302     // CodeGen enforces the "universally unique" aspect by giving all
7303     // declarations semantically contained within an anonymous
7304     // namespace internal linkage.
7305 
7306     if (!PrevNS) {
7307       UD = UsingDirectiveDecl::Create(Context, Parent,
7308                                       /* 'using' */ LBrace,
7309                                       /* 'namespace' */ SourceLocation(),
7310                                       /* qualifier */ NestedNameSpecifierLoc(),
7311                                       /* identifier */ SourceLocation(),
7312                                       Namespc,
7313                                       /* Ancestor */ Parent);
7314       UD->setImplicit();
7315       Parent->addDecl(UD);
7316     }
7317   }
7318 
7319   ActOnDocumentableDecl(Namespc);
7320 
7321   // Although we could have an invalid decl (i.e. the namespace name is a
7322   // redefinition), push it as current DeclContext and try to continue parsing.
7323   // FIXME: We should be able to push Namespc here, so that the each DeclContext
7324   // for the namespace has the declarations that showed up in that particular
7325   // namespace definition.
7326   PushDeclContext(NamespcScope, Namespc);
7327   return Namespc;
7328 }
7329 
7330 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7331 /// is a namespace alias, returns the namespace it points to.
7332 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7333   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7334     return AD->getNamespace();
7335   return dyn_cast_or_null<NamespaceDecl>(D);
7336 }
7337 
7338 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7339 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7340 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7341   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7342   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7343   Namespc->setRBraceLoc(RBrace);
7344   PopDeclContext();
7345   if (Namespc->hasAttr<VisibilityAttr>())
7346     PopPragmaVisibility(true, RBrace);
7347 }
7348 
7349 CXXRecordDecl *Sema::getStdBadAlloc() const {
7350   return cast_or_null<CXXRecordDecl>(
7351                                   StdBadAlloc.get(Context.getExternalSource()));
7352 }
7353 
7354 NamespaceDecl *Sema::getStdNamespace() const {
7355   return cast_or_null<NamespaceDecl>(
7356                                  StdNamespace.get(Context.getExternalSource()));
7357 }
7358 
7359 /// \brief Retrieve the special "std" namespace, which may require us to
7360 /// implicitly define the namespace.
7361 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7362   if (!StdNamespace) {
7363     // The "std" namespace has not yet been defined, so build one implicitly.
7364     StdNamespace = NamespaceDecl::Create(Context,
7365                                          Context.getTranslationUnitDecl(),
7366                                          /*Inline=*/false,
7367                                          SourceLocation(), SourceLocation(),
7368                                          &PP.getIdentifierTable().get("std"),
7369                                          /*PrevDecl=*/nullptr);
7370     getStdNamespace()->setImplicit(true);
7371   }
7372 
7373   return getStdNamespace();
7374 }
7375 
7376 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7377   assert(getLangOpts().CPlusPlus &&
7378          "Looking for std::initializer_list outside of C++.");
7379 
7380   // We're looking for implicit instantiations of
7381   // template <typename E> class std::initializer_list.
7382 
7383   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7384     return false;
7385 
7386   ClassTemplateDecl *Template = nullptr;
7387   const TemplateArgument *Arguments = nullptr;
7388 
7389   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7390 
7391     ClassTemplateSpecializationDecl *Specialization =
7392         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7393     if (!Specialization)
7394       return false;
7395 
7396     Template = Specialization->getSpecializedTemplate();
7397     Arguments = Specialization->getTemplateArgs().data();
7398   } else if (const TemplateSpecializationType *TST =
7399                  Ty->getAs<TemplateSpecializationType>()) {
7400     Template = dyn_cast_or_null<ClassTemplateDecl>(
7401         TST->getTemplateName().getAsTemplateDecl());
7402     Arguments = TST->getArgs();
7403   }
7404   if (!Template)
7405     return false;
7406 
7407   if (!StdInitializerList) {
7408     // Haven't recognized std::initializer_list yet, maybe this is it.
7409     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7410     if (TemplateClass->getIdentifier() !=
7411             &PP.getIdentifierTable().get("initializer_list") ||
7412         !getStdNamespace()->InEnclosingNamespaceSetOf(
7413             TemplateClass->getDeclContext()))
7414       return false;
7415     // This is a template called std::initializer_list, but is it the right
7416     // template?
7417     TemplateParameterList *Params = Template->getTemplateParameters();
7418     if (Params->getMinRequiredArguments() != 1)
7419       return false;
7420     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7421       return false;
7422 
7423     // It's the right template.
7424     StdInitializerList = Template;
7425   }
7426 
7427   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
7428     return false;
7429 
7430   // This is an instance of std::initializer_list. Find the argument type.
7431   if (Element)
7432     *Element = Arguments[0].getAsType();
7433   return true;
7434 }
7435 
7436 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7437   NamespaceDecl *Std = S.getStdNamespace();
7438   if (!Std) {
7439     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7440     return nullptr;
7441   }
7442 
7443   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7444                       Loc, Sema::LookupOrdinaryName);
7445   if (!S.LookupQualifiedName(Result, Std)) {
7446     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7447     return nullptr;
7448   }
7449   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7450   if (!Template) {
7451     Result.suppressDiagnostics();
7452     // We found something weird. Complain about the first thing we found.
7453     NamedDecl *Found = *Result.begin();
7454     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7455     return nullptr;
7456   }
7457 
7458   // We found some template called std::initializer_list. Now verify that it's
7459   // correct.
7460   TemplateParameterList *Params = Template->getTemplateParameters();
7461   if (Params->getMinRequiredArguments() != 1 ||
7462       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7463     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7464     return nullptr;
7465   }
7466 
7467   return Template;
7468 }
7469 
7470 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7471   if (!StdInitializerList) {
7472     StdInitializerList = LookupStdInitializerList(*this, Loc);
7473     if (!StdInitializerList)
7474       return QualType();
7475   }
7476 
7477   TemplateArgumentListInfo Args(Loc, Loc);
7478   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7479                                        Context.getTrivialTypeSourceInfo(Element,
7480                                                                         Loc)));
7481   return Context.getCanonicalType(
7482       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7483 }
7484 
7485 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7486   // C++ [dcl.init.list]p2:
7487   //   A constructor is an initializer-list constructor if its first parameter
7488   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7489   //   std::initializer_list<E> for some type E, and either there are no other
7490   //   parameters or else all other parameters have default arguments.
7491   if (Ctor->getNumParams() < 1 ||
7492       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7493     return false;
7494 
7495   QualType ArgType = Ctor->getParamDecl(0)->getType();
7496   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7497     ArgType = RT->getPointeeType().getUnqualifiedType();
7498 
7499   return isStdInitializerList(ArgType, nullptr);
7500 }
7501 
7502 /// \brief Determine whether a using statement is in a context where it will be
7503 /// apply in all contexts.
7504 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7505   switch (CurContext->getDeclKind()) {
7506     case Decl::TranslationUnit:
7507       return true;
7508     case Decl::LinkageSpec:
7509       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7510     default:
7511       return false;
7512   }
7513 }
7514 
7515 namespace {
7516 
7517 // Callback to only accept typo corrections that are namespaces.
7518 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7519 public:
7520   bool ValidateCandidate(const TypoCorrection &candidate) override {
7521     if (NamedDecl *ND = candidate.getCorrectionDecl())
7522       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7523     return false;
7524   }
7525 };
7526 
7527 }
7528 
7529 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7530                                        CXXScopeSpec &SS,
7531                                        SourceLocation IdentLoc,
7532                                        IdentifierInfo *Ident) {
7533   R.clear();
7534   if (TypoCorrection Corrected =
7535           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7536                         llvm::make_unique<NamespaceValidatorCCC>(),
7537                         Sema::CTK_ErrorRecovery)) {
7538     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7539       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7540       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7541                               Ident->getName().equals(CorrectedStr);
7542       S.diagnoseTypo(Corrected,
7543                      S.PDiag(diag::err_using_directive_member_suggest)
7544                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7545                      S.PDiag(diag::note_namespace_defined_here));
7546     } else {
7547       S.diagnoseTypo(Corrected,
7548                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7549                      S.PDiag(diag::note_namespace_defined_here));
7550     }
7551     R.addDecl(Corrected.getFoundDecl());
7552     return true;
7553   }
7554   return false;
7555 }
7556 
7557 Decl *Sema::ActOnUsingDirective(Scope *S,
7558                                           SourceLocation UsingLoc,
7559                                           SourceLocation NamespcLoc,
7560                                           CXXScopeSpec &SS,
7561                                           SourceLocation IdentLoc,
7562                                           IdentifierInfo *NamespcName,
7563                                           AttributeList *AttrList) {
7564   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7565   assert(NamespcName && "Invalid NamespcName.");
7566   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7567 
7568   // This can only happen along a recovery path.
7569   while (S->isTemplateParamScope())
7570     S = S->getParent();
7571   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7572 
7573   UsingDirectiveDecl *UDir = nullptr;
7574   NestedNameSpecifier *Qualifier = nullptr;
7575   if (SS.isSet())
7576     Qualifier = SS.getScopeRep();
7577 
7578   // Lookup namespace name.
7579   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7580   LookupParsedName(R, S, &SS);
7581   if (R.isAmbiguous())
7582     return nullptr;
7583 
7584   if (R.empty()) {
7585     R.clear();
7586     // Allow "using namespace std;" or "using namespace ::std;" even if
7587     // "std" hasn't been defined yet, for GCC compatibility.
7588     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7589         NamespcName->isStr("std")) {
7590       Diag(IdentLoc, diag::ext_using_undefined_std);
7591       R.addDecl(getOrCreateStdNamespace());
7592       R.resolveKind();
7593     }
7594     // Otherwise, attempt typo correction.
7595     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7596   }
7597 
7598   if (!R.empty()) {
7599     NamedDecl *Named = R.getRepresentativeDecl();
7600     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
7601     assert(NS && "expected namespace decl");
7602 
7603     // The use of a nested name specifier may trigger deprecation warnings.
7604     DiagnoseUseOfDecl(Named, IdentLoc);
7605 
7606     // C++ [namespace.udir]p1:
7607     //   A using-directive specifies that the names in the nominated
7608     //   namespace can be used in the scope in which the
7609     //   using-directive appears after the using-directive. During
7610     //   unqualified name lookup (3.4.1), the names appear as if they
7611     //   were declared in the nearest enclosing namespace which
7612     //   contains both the using-directive and the nominated
7613     //   namespace. [Note: in this context, "contains" means "contains
7614     //   directly or indirectly". ]
7615 
7616     // Find enclosing context containing both using-directive and
7617     // nominated namespace.
7618     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7619     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7620       CommonAncestor = CommonAncestor->getParent();
7621 
7622     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7623                                       SS.getWithLocInContext(Context),
7624                                       IdentLoc, Named, CommonAncestor);
7625 
7626     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7627         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7628       Diag(IdentLoc, diag::warn_using_directive_in_header);
7629     }
7630 
7631     PushUsingDirective(S, UDir);
7632   } else {
7633     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7634   }
7635 
7636   if (UDir)
7637     ProcessDeclAttributeList(S, UDir, AttrList);
7638 
7639   return UDir;
7640 }
7641 
7642 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7643   // If the scope has an associated entity and the using directive is at
7644   // namespace or translation unit scope, add the UsingDirectiveDecl into
7645   // its lookup structure so qualified name lookup can find it.
7646   DeclContext *Ctx = S->getEntity();
7647   if (Ctx && !Ctx->isFunctionOrMethod())
7648     Ctx->addDecl(UDir);
7649   else
7650     // Otherwise, it is at block scope. The using-directives will affect lookup
7651     // only to the end of the scope.
7652     S->PushUsingDirective(UDir);
7653 }
7654 
7655 
7656 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7657                                   AccessSpecifier AS,
7658                                   bool HasUsingKeyword,
7659                                   SourceLocation UsingLoc,
7660                                   CXXScopeSpec &SS,
7661                                   UnqualifiedId &Name,
7662                                   AttributeList *AttrList,
7663                                   bool HasTypenameKeyword,
7664                                   SourceLocation TypenameLoc) {
7665   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7666 
7667   switch (Name.getKind()) {
7668   case UnqualifiedId::IK_ImplicitSelfParam:
7669   case UnqualifiedId::IK_Identifier:
7670   case UnqualifiedId::IK_OperatorFunctionId:
7671   case UnqualifiedId::IK_LiteralOperatorId:
7672   case UnqualifiedId::IK_ConversionFunctionId:
7673     break;
7674 
7675   case UnqualifiedId::IK_ConstructorName:
7676   case UnqualifiedId::IK_ConstructorTemplateId:
7677     // C++11 inheriting constructors.
7678     Diag(Name.getLocStart(),
7679          getLangOpts().CPlusPlus11 ?
7680            diag::warn_cxx98_compat_using_decl_constructor :
7681            diag::err_using_decl_constructor)
7682       << SS.getRange();
7683 
7684     if (getLangOpts().CPlusPlus11) break;
7685 
7686     return nullptr;
7687 
7688   case UnqualifiedId::IK_DestructorName:
7689     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7690       << SS.getRange();
7691     return nullptr;
7692 
7693   case UnqualifiedId::IK_TemplateId:
7694     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7695       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7696     return nullptr;
7697   }
7698 
7699   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7700   DeclarationName TargetName = TargetNameInfo.getName();
7701   if (!TargetName)
7702     return nullptr;
7703 
7704   // Warn about access declarations.
7705   if (!HasUsingKeyword) {
7706     Diag(Name.getLocStart(),
7707          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7708                                    : diag::warn_access_decl_deprecated)
7709       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7710   }
7711 
7712   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7713       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7714     return nullptr;
7715 
7716   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7717                                         TargetNameInfo, AttrList,
7718                                         /* IsInstantiation */ false,
7719                                         HasTypenameKeyword, TypenameLoc);
7720   if (UD)
7721     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7722 
7723   return UD;
7724 }
7725 
7726 /// \brief Determine whether a using declaration considers the given
7727 /// declarations as "equivalent", e.g., if they are redeclarations of
7728 /// the same entity or are both typedefs of the same type.
7729 static bool
7730 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7731   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7732     return true;
7733 
7734   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7735     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7736       return Context.hasSameType(TD1->getUnderlyingType(),
7737                                  TD2->getUnderlyingType());
7738 
7739   return false;
7740 }
7741 
7742 
7743 /// Determines whether to create a using shadow decl for a particular
7744 /// decl, given the set of decls existing prior to this using lookup.
7745 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7746                                 const LookupResult &Previous,
7747                                 UsingShadowDecl *&PrevShadow) {
7748   // Diagnose finding a decl which is not from a base class of the
7749   // current class.  We do this now because there are cases where this
7750   // function will silently decide not to build a shadow decl, which
7751   // will pre-empt further diagnostics.
7752   //
7753   // We don't need to do this in C++11 because we do the check once on
7754   // the qualifier.
7755   //
7756   // FIXME: diagnose the following if we care enough:
7757   //   struct A { int foo; };
7758   //   struct B : A { using A::foo; };
7759   //   template <class T> struct C : A {};
7760   //   template <class T> struct D : C<T> { using B::foo; } // <---
7761   // This is invalid (during instantiation) in C++03 because B::foo
7762   // resolves to the using decl in B, which is not a base class of D<T>.
7763   // We can't diagnose it immediately because C<T> is an unknown
7764   // specialization.  The UsingShadowDecl in D<T> then points directly
7765   // to A::foo, which will look well-formed when we instantiate.
7766   // The right solution is to not collapse the shadow-decl chain.
7767   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7768     DeclContext *OrigDC = Orig->getDeclContext();
7769 
7770     // Handle enums and anonymous structs.
7771     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7772     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7773     while (OrigRec->isAnonymousStructOrUnion())
7774       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7775 
7776     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7777       if (OrigDC == CurContext) {
7778         Diag(Using->getLocation(),
7779              diag::err_using_decl_nested_name_specifier_is_current_class)
7780           << Using->getQualifierLoc().getSourceRange();
7781         Diag(Orig->getLocation(), diag::note_using_decl_target);
7782         return true;
7783       }
7784 
7785       Diag(Using->getQualifierLoc().getBeginLoc(),
7786            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7787         << Using->getQualifier()
7788         << cast<CXXRecordDecl>(CurContext)
7789         << Using->getQualifierLoc().getSourceRange();
7790       Diag(Orig->getLocation(), diag::note_using_decl_target);
7791       return true;
7792     }
7793   }
7794 
7795   if (Previous.empty()) return false;
7796 
7797   NamedDecl *Target = Orig;
7798   if (isa<UsingShadowDecl>(Target))
7799     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7800 
7801   // If the target happens to be one of the previous declarations, we
7802   // don't have a conflict.
7803   //
7804   // FIXME: but we might be increasing its access, in which case we
7805   // should redeclare it.
7806   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7807   bool FoundEquivalentDecl = false;
7808   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7809          I != E; ++I) {
7810     NamedDecl *D = (*I)->getUnderlyingDecl();
7811     // We can have UsingDecls in our Previous results because we use the same
7812     // LookupResult for checking whether the UsingDecl itself is a valid
7813     // redeclaration.
7814     if (isa<UsingDecl>(D))
7815       continue;
7816 
7817     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7818       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7819         PrevShadow = Shadow;
7820       FoundEquivalentDecl = true;
7821     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
7822       // We don't conflict with an existing using shadow decl of an equivalent
7823       // declaration, but we're not a redeclaration of it.
7824       FoundEquivalentDecl = true;
7825     }
7826 
7827     if (isVisible(D))
7828       (isa<TagDecl>(D) ? Tag : NonTag) = D;
7829   }
7830 
7831   if (FoundEquivalentDecl)
7832     return false;
7833 
7834   if (FunctionDecl *FD = Target->getAsFunction()) {
7835     NamedDecl *OldDecl = nullptr;
7836     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7837                           /*IsForUsingDecl*/ true)) {
7838     case Ovl_Overload:
7839       return false;
7840 
7841     case Ovl_NonFunction:
7842       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7843       break;
7844 
7845     // We found a decl with the exact signature.
7846     case Ovl_Match:
7847       // If we're in a record, we want to hide the target, so we
7848       // return true (without a diagnostic) to tell the caller not to
7849       // build a shadow decl.
7850       if (CurContext->isRecord())
7851         return true;
7852 
7853       // If we're not in a record, this is an error.
7854       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7855       break;
7856     }
7857 
7858     Diag(Target->getLocation(), diag::note_using_decl_target);
7859     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7860     return true;
7861   }
7862 
7863   // Target is not a function.
7864 
7865   if (isa<TagDecl>(Target)) {
7866     // No conflict between a tag and a non-tag.
7867     if (!Tag) return false;
7868 
7869     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7870     Diag(Target->getLocation(), diag::note_using_decl_target);
7871     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7872     return true;
7873   }
7874 
7875   // No conflict between a tag and a non-tag.
7876   if (!NonTag) return false;
7877 
7878   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7879   Diag(Target->getLocation(), diag::note_using_decl_target);
7880   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7881   return true;
7882 }
7883 
7884 /// Builds a shadow declaration corresponding to a 'using' declaration.
7885 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7886                                             UsingDecl *UD,
7887                                             NamedDecl *Orig,
7888                                             UsingShadowDecl *PrevDecl) {
7889 
7890   // If we resolved to another shadow declaration, just coalesce them.
7891   NamedDecl *Target = Orig;
7892   if (isa<UsingShadowDecl>(Target)) {
7893     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7894     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7895   }
7896 
7897   UsingShadowDecl *Shadow
7898     = UsingShadowDecl::Create(Context, CurContext,
7899                               UD->getLocation(), UD, Target);
7900   UD->addShadowDecl(Shadow);
7901 
7902   Shadow->setAccess(UD->getAccess());
7903   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7904     Shadow->setInvalidDecl();
7905 
7906   Shadow->setPreviousDecl(PrevDecl);
7907 
7908   if (S)
7909     PushOnScopeChains(Shadow, S);
7910   else
7911     CurContext->addDecl(Shadow);
7912 
7913 
7914   return Shadow;
7915 }
7916 
7917 /// Hides a using shadow declaration.  This is required by the current
7918 /// using-decl implementation when a resolvable using declaration in a
7919 /// class is followed by a declaration which would hide or override
7920 /// one or more of the using decl's targets; for example:
7921 ///
7922 ///   struct Base { void foo(int); };
7923 ///   struct Derived : Base {
7924 ///     using Base::foo;
7925 ///     void foo(int);
7926 ///   };
7927 ///
7928 /// The governing language is C++03 [namespace.udecl]p12:
7929 ///
7930 ///   When a using-declaration brings names from a base class into a
7931 ///   derived class scope, member functions in the derived class
7932 ///   override and/or hide member functions with the same name and
7933 ///   parameter types in a base class (rather than conflicting).
7934 ///
7935 /// There are two ways to implement this:
7936 ///   (1) optimistically create shadow decls when they're not hidden
7937 ///       by existing declarations, or
7938 ///   (2) don't create any shadow decls (or at least don't make them
7939 ///       visible) until we've fully parsed/instantiated the class.
7940 /// The problem with (1) is that we might have to retroactively remove
7941 /// a shadow decl, which requires several O(n) operations because the
7942 /// decl structures are (very reasonably) not designed for removal.
7943 /// (2) avoids this but is very fiddly and phase-dependent.
7944 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7945   if (Shadow->getDeclName().getNameKind() ==
7946         DeclarationName::CXXConversionFunctionName)
7947     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7948 
7949   // Remove it from the DeclContext...
7950   Shadow->getDeclContext()->removeDecl(Shadow);
7951 
7952   // ...and the scope, if applicable...
7953   if (S) {
7954     S->RemoveDecl(Shadow);
7955     IdResolver.RemoveDecl(Shadow);
7956   }
7957 
7958   // ...and the using decl.
7959   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7960 
7961   // TODO: complain somehow if Shadow was used.  It shouldn't
7962   // be possible for this to happen, because...?
7963 }
7964 
7965 /// Find the base specifier for a base class with the given type.
7966 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7967                                                 QualType DesiredBase,
7968                                                 bool &AnyDependentBases) {
7969   // Check whether the named type is a direct base class.
7970   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7971   for (auto &Base : Derived->bases()) {
7972     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7973     if (CanonicalDesiredBase == BaseType)
7974       return &Base;
7975     if (BaseType->isDependentType())
7976       AnyDependentBases = true;
7977   }
7978   return nullptr;
7979 }
7980 
7981 namespace {
7982 class UsingValidatorCCC : public CorrectionCandidateCallback {
7983 public:
7984   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7985                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7986       : HasTypenameKeyword(HasTypenameKeyword),
7987         IsInstantiation(IsInstantiation), OldNNS(NNS),
7988         RequireMemberOf(RequireMemberOf) {}
7989 
7990   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7991     NamedDecl *ND = Candidate.getCorrectionDecl();
7992 
7993     // Keywords are not valid here.
7994     if (!ND || isa<NamespaceDecl>(ND))
7995       return false;
7996 
7997     // Completely unqualified names are invalid for a 'using' declaration.
7998     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7999       return false;
8000 
8001     if (RequireMemberOf) {
8002       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8003       if (FoundRecord && FoundRecord->isInjectedClassName()) {
8004         // No-one ever wants a using-declaration to name an injected-class-name
8005         // of a base class, unless they're declaring an inheriting constructor.
8006         ASTContext &Ctx = ND->getASTContext();
8007         if (!Ctx.getLangOpts().CPlusPlus11)
8008           return false;
8009         QualType FoundType = Ctx.getRecordType(FoundRecord);
8010 
8011         // Check that the injected-class-name is named as a member of its own
8012         // type; we don't want to suggest 'using Derived::Base;', since that
8013         // means something else.
8014         NestedNameSpecifier *Specifier =
8015             Candidate.WillReplaceSpecifier()
8016                 ? Candidate.getCorrectionSpecifier()
8017                 : OldNNS;
8018         if (!Specifier->getAsType() ||
8019             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8020           return false;
8021 
8022         // Check that this inheriting constructor declaration actually names a
8023         // direct base class of the current class.
8024         bool AnyDependentBases = false;
8025         if (!findDirectBaseWithType(RequireMemberOf,
8026                                     Ctx.getRecordType(FoundRecord),
8027                                     AnyDependentBases) &&
8028             !AnyDependentBases)
8029           return false;
8030       } else {
8031         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8032         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8033           return false;
8034 
8035         // FIXME: Check that the base class member is accessible?
8036       }
8037     } else {
8038       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8039       if (FoundRecord && FoundRecord->isInjectedClassName())
8040         return false;
8041     }
8042 
8043     if (isa<TypeDecl>(ND))
8044       return HasTypenameKeyword || !IsInstantiation;
8045 
8046     return !HasTypenameKeyword;
8047   }
8048 
8049 private:
8050   bool HasTypenameKeyword;
8051   bool IsInstantiation;
8052   NestedNameSpecifier *OldNNS;
8053   CXXRecordDecl *RequireMemberOf;
8054 };
8055 } // end anonymous namespace
8056 
8057 /// Builds a using declaration.
8058 ///
8059 /// \param IsInstantiation - Whether this call arises from an
8060 ///   instantiation of an unresolved using declaration.  We treat
8061 ///   the lookup differently for these declarations.
8062 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8063                                        SourceLocation UsingLoc,
8064                                        CXXScopeSpec &SS,
8065                                        DeclarationNameInfo NameInfo,
8066                                        AttributeList *AttrList,
8067                                        bool IsInstantiation,
8068                                        bool HasTypenameKeyword,
8069                                        SourceLocation TypenameLoc) {
8070   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8071   SourceLocation IdentLoc = NameInfo.getLoc();
8072   assert(IdentLoc.isValid() && "Invalid TargetName location.");
8073 
8074   // FIXME: We ignore attributes for now.
8075 
8076   if (SS.isEmpty()) {
8077     Diag(IdentLoc, diag::err_using_requires_qualname);
8078     return nullptr;
8079   }
8080 
8081   // Do the redeclaration lookup in the current scope.
8082   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
8083                         ForRedeclaration);
8084   Previous.setHideTags(false);
8085   if (S) {
8086     LookupName(Previous, S);
8087 
8088     // It is really dumb that we have to do this.
8089     LookupResult::Filter F = Previous.makeFilter();
8090     while (F.hasNext()) {
8091       NamedDecl *D = F.next();
8092       if (!isDeclInScope(D, CurContext, S))
8093         F.erase();
8094       // If we found a local extern declaration that's not ordinarily visible,
8095       // and this declaration is being added to a non-block scope, ignore it.
8096       // We're only checking for scope conflicts here, not also for violations
8097       // of the linkage rules.
8098       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8099                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8100         F.erase();
8101     }
8102     F.done();
8103   } else {
8104     assert(IsInstantiation && "no scope in non-instantiation");
8105     assert(CurContext->isRecord() && "scope not record in instantiation");
8106     LookupQualifiedName(Previous, CurContext);
8107   }
8108 
8109   // Check for invalid redeclarations.
8110   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8111                                   SS, IdentLoc, Previous))
8112     return nullptr;
8113 
8114   // Check for bad qualifiers.
8115   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8116     return nullptr;
8117 
8118   DeclContext *LookupContext = computeDeclContext(SS);
8119   NamedDecl *D;
8120   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8121   if (!LookupContext) {
8122     if (HasTypenameKeyword) {
8123       // FIXME: not all declaration name kinds are legal here
8124       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8125                                               UsingLoc, TypenameLoc,
8126                                               QualifierLoc,
8127                                               IdentLoc, NameInfo.getName());
8128     } else {
8129       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8130                                            QualifierLoc, NameInfo);
8131     }
8132     D->setAccess(AS);
8133     CurContext->addDecl(D);
8134     return D;
8135   }
8136 
8137   auto Build = [&](bool Invalid) {
8138     UsingDecl *UD =
8139         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8140                           HasTypenameKeyword);
8141     UD->setAccess(AS);
8142     CurContext->addDecl(UD);
8143     UD->setInvalidDecl(Invalid);
8144     return UD;
8145   };
8146   auto BuildInvalid = [&]{ return Build(true); };
8147   auto BuildValid = [&]{ return Build(false); };
8148 
8149   if (RequireCompleteDeclContext(SS, LookupContext))
8150     return BuildInvalid();
8151 
8152   // Look up the target name.
8153   LookupResult R(*this, NameInfo, LookupOrdinaryName);
8154 
8155   // Unlike most lookups, we don't always want to hide tag
8156   // declarations: tag names are visible through the using declaration
8157   // even if hidden by ordinary names, *except* in a dependent context
8158   // where it's important for the sanity of two-phase lookup.
8159   if (!IsInstantiation)
8160     R.setHideTags(false);
8161 
8162   // For the purposes of this lookup, we have a base object type
8163   // equal to that of the current context.
8164   if (CurContext->isRecord()) {
8165     R.setBaseObjectType(
8166                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8167   }
8168 
8169   LookupQualifiedName(R, LookupContext);
8170 
8171   // Try to correct typos if possible. If constructor name lookup finds no
8172   // results, that means the named class has no explicit constructors, and we
8173   // suppressed declaring implicit ones (probably because it's dependent or
8174   // invalid).
8175   if (R.empty() &&
8176       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
8177     if (TypoCorrection Corrected = CorrectTypo(
8178             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8179             llvm::make_unique<UsingValidatorCCC>(
8180                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8181                 dyn_cast<CXXRecordDecl>(CurContext)),
8182             CTK_ErrorRecovery)) {
8183       // We reject any correction for which ND would be NULL.
8184       NamedDecl *ND = Corrected.getCorrectionDecl();
8185 
8186       // We reject candidates where DroppedSpecifier == true, hence the
8187       // literal '0' below.
8188       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8189                                 << NameInfo.getName() << LookupContext << 0
8190                                 << SS.getRange());
8191 
8192       // If we corrected to an inheriting constructor, handle it as one.
8193       auto *RD = dyn_cast<CXXRecordDecl>(ND);
8194       if (RD && RD->isInjectedClassName()) {
8195         // Fix up the information we'll use to build the using declaration.
8196         if (Corrected.WillReplaceSpecifier()) {
8197           NestedNameSpecifierLocBuilder Builder;
8198           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8199                               QualifierLoc.getSourceRange());
8200           QualifierLoc = Builder.getWithLocInContext(Context);
8201         }
8202 
8203         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8204             Context.getCanonicalType(Context.getRecordType(RD))));
8205         NameInfo.setNamedTypeInfo(nullptr);
8206         for (auto *Ctor : LookupConstructors(RD))
8207           R.addDecl(Ctor);
8208       } else {
8209         // FIXME: Pick up all the declarations if we found an overloaded function.
8210         R.addDecl(ND);
8211       }
8212     } else {
8213       Diag(IdentLoc, diag::err_no_member)
8214         << NameInfo.getName() << LookupContext << SS.getRange();
8215       return BuildInvalid();
8216     }
8217   }
8218 
8219   if (R.isAmbiguous())
8220     return BuildInvalid();
8221 
8222   if (HasTypenameKeyword) {
8223     // If we asked for a typename and got a non-type decl, error out.
8224     if (!R.getAsSingle<TypeDecl>()) {
8225       Diag(IdentLoc, diag::err_using_typename_non_type);
8226       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8227         Diag((*I)->getUnderlyingDecl()->getLocation(),
8228              diag::note_using_decl_target);
8229       return BuildInvalid();
8230     }
8231   } else {
8232     // If we asked for a non-typename and we got a type, error out,
8233     // but only if this is an instantiation of an unresolved using
8234     // decl.  Otherwise just silently find the type name.
8235     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8236       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8237       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8238       return BuildInvalid();
8239     }
8240   }
8241 
8242   // C++14 [namespace.udecl]p6:
8243   // A using-declaration shall not name a namespace.
8244   if (R.getAsSingle<NamespaceDecl>()) {
8245     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8246       << SS.getRange();
8247     return BuildInvalid();
8248   }
8249 
8250   // C++14 [namespace.udecl]p7:
8251   // A using-declaration shall not name a scoped enumerator.
8252   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
8253     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
8254       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
8255         << SS.getRange();
8256       return BuildInvalid();
8257     }
8258   }
8259 
8260   UsingDecl *UD = BuildValid();
8261 
8262   // The normal rules do not apply to inheriting constructor declarations.
8263   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8264     // Suppress access diagnostics; the access check is instead performed at the
8265     // point of use for an inheriting constructor.
8266     R.suppressDiagnostics();
8267     CheckInheritingConstructorUsingDecl(UD);
8268     return UD;
8269   }
8270 
8271   // Otherwise, look up the target name.
8272 
8273   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8274     UsingShadowDecl *PrevDecl = nullptr;
8275     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8276       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8277   }
8278 
8279   return UD;
8280 }
8281 
8282 /// Additional checks for a using declaration referring to a constructor name.
8283 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8284   assert(!UD->hasTypename() && "expecting a constructor name");
8285 
8286   const Type *SourceType = UD->getQualifier()->getAsType();
8287   assert(SourceType &&
8288          "Using decl naming constructor doesn't have type in scope spec.");
8289   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8290 
8291   // Check whether the named type is a direct base class.
8292   bool AnyDependentBases = false;
8293   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8294                                       AnyDependentBases);
8295   if (!Base && !AnyDependentBases) {
8296     Diag(UD->getUsingLoc(),
8297          diag::err_using_decl_constructor_not_in_direct_base)
8298       << UD->getNameInfo().getSourceRange()
8299       << QualType(SourceType, 0) << TargetClass;
8300     UD->setInvalidDecl();
8301     return true;
8302   }
8303 
8304   if (Base)
8305     Base->setInheritConstructors();
8306 
8307   return false;
8308 }
8309 
8310 /// Checks that the given using declaration is not an invalid
8311 /// redeclaration.  Note that this is checking only for the using decl
8312 /// itself, not for any ill-formedness among the UsingShadowDecls.
8313 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8314                                        bool HasTypenameKeyword,
8315                                        const CXXScopeSpec &SS,
8316                                        SourceLocation NameLoc,
8317                                        const LookupResult &Prev) {
8318   // C++03 [namespace.udecl]p8:
8319   // C++0x [namespace.udecl]p10:
8320   //   A using-declaration is a declaration and can therefore be used
8321   //   repeatedly where (and only where) multiple declarations are
8322   //   allowed.
8323   //
8324   // That's in non-member contexts.
8325   if (!CurContext->getRedeclContext()->isRecord())
8326     return false;
8327 
8328   NestedNameSpecifier *Qual = SS.getScopeRep();
8329 
8330   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8331     NamedDecl *D = *I;
8332 
8333     bool DTypename;
8334     NestedNameSpecifier *DQual;
8335     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8336       DTypename = UD->hasTypename();
8337       DQual = UD->getQualifier();
8338     } else if (UnresolvedUsingValueDecl *UD
8339                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8340       DTypename = false;
8341       DQual = UD->getQualifier();
8342     } else if (UnresolvedUsingTypenameDecl *UD
8343                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8344       DTypename = true;
8345       DQual = UD->getQualifier();
8346     } else continue;
8347 
8348     // using decls differ if one says 'typename' and the other doesn't.
8349     // FIXME: non-dependent using decls?
8350     if (HasTypenameKeyword != DTypename) continue;
8351 
8352     // using decls differ if they name different scopes (but note that
8353     // template instantiation can cause this check to trigger when it
8354     // didn't before instantiation).
8355     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8356         Context.getCanonicalNestedNameSpecifier(DQual))
8357       continue;
8358 
8359     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8360     Diag(D->getLocation(), diag::note_using_decl) << 1;
8361     return true;
8362   }
8363 
8364   return false;
8365 }
8366 
8367 
8368 /// Checks that the given nested-name qualifier used in a using decl
8369 /// in the current context is appropriately related to the current
8370 /// scope.  If an error is found, diagnoses it and returns true.
8371 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8372                                    const CXXScopeSpec &SS,
8373                                    const DeclarationNameInfo &NameInfo,
8374                                    SourceLocation NameLoc) {
8375   DeclContext *NamedContext = computeDeclContext(SS);
8376 
8377   if (!CurContext->isRecord()) {
8378     // C++03 [namespace.udecl]p3:
8379     // C++0x [namespace.udecl]p8:
8380     //   A using-declaration for a class member shall be a member-declaration.
8381 
8382     // If we weren't able to compute a valid scope, it must be a
8383     // dependent class scope.
8384     if (!NamedContext || NamedContext->getRedeclContext()->isRecord()) {
8385       auto *RD = NamedContext
8386                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
8387                      : nullptr;
8388       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8389         RD = nullptr;
8390 
8391       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8392         << SS.getRange();
8393 
8394       // If we have a complete, non-dependent source type, try to suggest a
8395       // way to get the same effect.
8396       if (!RD)
8397         return true;
8398 
8399       // Find what this using-declaration was referring to.
8400       LookupResult R(*this, NameInfo, LookupOrdinaryName);
8401       R.setHideTags(false);
8402       R.suppressDiagnostics();
8403       LookupQualifiedName(R, RD);
8404 
8405       if (R.getAsSingle<TypeDecl>()) {
8406         if (getLangOpts().CPlusPlus11) {
8407           // Convert 'using X::Y;' to 'using Y = X::Y;'.
8408           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8409             << 0 // alias declaration
8410             << FixItHint::CreateInsertion(SS.getBeginLoc(),
8411                                           NameInfo.getName().getAsString() +
8412                                               " = ");
8413         } else {
8414           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8415           SourceLocation InsertLoc =
8416               getLocForEndOfToken(NameInfo.getLocEnd());
8417           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8418             << 1 // typedef declaration
8419             << FixItHint::CreateReplacement(UsingLoc, "typedef")
8420             << FixItHint::CreateInsertion(
8421                    InsertLoc, " " + NameInfo.getName().getAsString());
8422         }
8423       } else if (R.getAsSingle<VarDecl>()) {
8424         // Don't provide a fixit outside C++11 mode; we don't want to suggest
8425         // repeating the type of the static data member here.
8426         FixItHint FixIt;
8427         if (getLangOpts().CPlusPlus11) {
8428           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8429           FixIt = FixItHint::CreateReplacement(
8430               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8431         }
8432 
8433         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8434           << 2 // reference declaration
8435           << FixIt;
8436       } else if (R.getAsSingle<EnumConstantDecl>()) {
8437         // Don't provide a fixit outside C++11 mode; we don't want to suggest
8438         // repeating the type of the enumeration here, and we can't do so if
8439         // the type is anonymous.
8440         FixItHint FixIt;
8441         if (getLangOpts().CPlusPlus11) {
8442           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8443           FixIt = FixItHint::CreateReplacement(
8444               UsingLoc, "constexpr auto " + NameInfo.getName().getAsString() + " = ");
8445         }
8446 
8447         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8448           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
8449           << FixIt;
8450       }
8451       return true;
8452     }
8453 
8454     // Otherwise, everything is known to be fine.
8455     return false;
8456   }
8457 
8458   // The current scope is a record.
8459 
8460   // If the named context is dependent, we can't decide much.
8461   if (!NamedContext) {
8462     // FIXME: in C++0x, we can diagnose if we can prove that the
8463     // nested-name-specifier does not refer to a base class, which is
8464     // still possible in some cases.
8465 
8466     // Otherwise we have to conservatively report that things might be
8467     // okay.
8468     return false;
8469   }
8470 
8471   if (!NamedContext->isRecord()) {
8472     // Ideally this would point at the last name in the specifier,
8473     // but we don't have that level of source info.
8474     Diag(SS.getRange().getBegin(),
8475          diag::err_using_decl_nested_name_specifier_is_not_class)
8476       << SS.getScopeRep() << SS.getRange();
8477     return true;
8478   }
8479 
8480   if (!NamedContext->isDependentContext() &&
8481       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8482     return true;
8483 
8484   if (getLangOpts().CPlusPlus11) {
8485     // C++11 [namespace.udecl]p3:
8486     //   In a using-declaration used as a member-declaration, the
8487     //   nested-name-specifier shall name a base class of the class
8488     //   being defined.
8489 
8490     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8491                                  cast<CXXRecordDecl>(NamedContext))) {
8492       if (CurContext == NamedContext) {
8493         Diag(NameLoc,
8494              diag::err_using_decl_nested_name_specifier_is_current_class)
8495           << SS.getRange();
8496         return true;
8497       }
8498 
8499       Diag(SS.getRange().getBegin(),
8500            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8501         << SS.getScopeRep()
8502         << cast<CXXRecordDecl>(CurContext)
8503         << SS.getRange();
8504       return true;
8505     }
8506 
8507     return false;
8508   }
8509 
8510   // C++03 [namespace.udecl]p4:
8511   //   A using-declaration used as a member-declaration shall refer
8512   //   to a member of a base class of the class being defined [etc.].
8513 
8514   // Salient point: SS doesn't have to name a base class as long as
8515   // lookup only finds members from base classes.  Therefore we can
8516   // diagnose here only if we can prove that that can't happen,
8517   // i.e. if the class hierarchies provably don't intersect.
8518 
8519   // TODO: it would be nice if "definitely valid" results were cached
8520   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8521   // need to be repeated.
8522 
8523   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
8524   auto Collect = [&Bases](const CXXRecordDecl *Base) {
8525     Bases.insert(Base);
8526     return true;
8527   };
8528 
8529   // Collect all bases. Return false if we find a dependent base.
8530   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
8531     return false;
8532 
8533   // Returns true if the base is dependent or is one of the accumulated base
8534   // classes.
8535   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
8536     return !Bases.count(Base);
8537   };
8538 
8539   // Return false if the class has a dependent base or if it or one
8540   // of its bases is present in the base set of the current context.
8541   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
8542       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
8543     return false;
8544 
8545   Diag(SS.getRange().getBegin(),
8546        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8547     << SS.getScopeRep()
8548     << cast<CXXRecordDecl>(CurContext)
8549     << SS.getRange();
8550 
8551   return true;
8552 }
8553 
8554 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8555                                   AccessSpecifier AS,
8556                                   MultiTemplateParamsArg TemplateParamLists,
8557                                   SourceLocation UsingLoc,
8558                                   UnqualifiedId &Name,
8559                                   AttributeList *AttrList,
8560                                   TypeResult Type,
8561                                   Decl *DeclFromDeclSpec) {
8562   // Skip up to the relevant declaration scope.
8563   while (S->isTemplateParamScope())
8564     S = S->getParent();
8565   assert((S->getFlags() & Scope::DeclScope) &&
8566          "got alias-declaration outside of declaration scope");
8567 
8568   if (Type.isInvalid())
8569     return nullptr;
8570 
8571   bool Invalid = false;
8572   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8573   TypeSourceInfo *TInfo = nullptr;
8574   GetTypeFromParser(Type.get(), &TInfo);
8575 
8576   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8577     return nullptr;
8578 
8579   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8580                                       UPPC_DeclarationType)) {
8581     Invalid = true;
8582     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8583                                              TInfo->getTypeLoc().getBeginLoc());
8584   }
8585 
8586   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8587   LookupName(Previous, S);
8588 
8589   // Warn about shadowing the name of a template parameter.
8590   if (Previous.isSingleResult() &&
8591       Previous.getFoundDecl()->isTemplateParameter()) {
8592     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8593     Previous.clear();
8594   }
8595 
8596   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8597          "name in alias declaration must be an identifier");
8598   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8599                                                Name.StartLocation,
8600                                                Name.Identifier, TInfo);
8601 
8602   NewTD->setAccess(AS);
8603 
8604   if (Invalid)
8605     NewTD->setInvalidDecl();
8606 
8607   ProcessDeclAttributeList(S, NewTD, AttrList);
8608 
8609   CheckTypedefForVariablyModifiedType(S, NewTD);
8610   Invalid |= NewTD->isInvalidDecl();
8611 
8612   bool Redeclaration = false;
8613 
8614   NamedDecl *NewND;
8615   if (TemplateParamLists.size()) {
8616     TypeAliasTemplateDecl *OldDecl = nullptr;
8617     TemplateParameterList *OldTemplateParams = nullptr;
8618 
8619     if (TemplateParamLists.size() != 1) {
8620       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8621         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8622          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8623     }
8624     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8625 
8626     // Check that we can declare a template here.
8627     if (CheckTemplateDeclScope(S, TemplateParams))
8628       return nullptr;
8629 
8630     // Only consider previous declarations in the same scope.
8631     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8632                          /*ExplicitInstantiationOrSpecialization*/false);
8633     if (!Previous.empty()) {
8634       Redeclaration = true;
8635 
8636       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8637       if (!OldDecl && !Invalid) {
8638         Diag(UsingLoc, diag::err_redefinition_different_kind)
8639           << Name.Identifier;
8640 
8641         NamedDecl *OldD = Previous.getRepresentativeDecl();
8642         if (OldD->getLocation().isValid())
8643           Diag(OldD->getLocation(), diag::note_previous_definition);
8644 
8645         Invalid = true;
8646       }
8647 
8648       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8649         if (TemplateParameterListsAreEqual(TemplateParams,
8650                                            OldDecl->getTemplateParameters(),
8651                                            /*Complain=*/true,
8652                                            TPL_TemplateMatch))
8653           OldTemplateParams = OldDecl->getTemplateParameters();
8654         else
8655           Invalid = true;
8656 
8657         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8658         if (!Invalid &&
8659             !Context.hasSameType(OldTD->getUnderlyingType(),
8660                                  NewTD->getUnderlyingType())) {
8661           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8662           // but we can't reasonably accept it.
8663           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8664             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8665           if (OldTD->getLocation().isValid())
8666             Diag(OldTD->getLocation(), diag::note_previous_definition);
8667           Invalid = true;
8668         }
8669       }
8670     }
8671 
8672     // Merge any previous default template arguments into our parameters,
8673     // and check the parameter list.
8674     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8675                                    TPC_TypeAliasTemplate))
8676       return nullptr;
8677 
8678     TypeAliasTemplateDecl *NewDecl =
8679       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8680                                     Name.Identifier, TemplateParams,
8681                                     NewTD);
8682     NewTD->setDescribedAliasTemplate(NewDecl);
8683 
8684     NewDecl->setAccess(AS);
8685 
8686     if (Invalid)
8687       NewDecl->setInvalidDecl();
8688     else if (OldDecl)
8689       NewDecl->setPreviousDecl(OldDecl);
8690 
8691     NewND = NewDecl;
8692   } else {
8693     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8694       setTagNameForLinkagePurposes(TD, NewTD);
8695       handleTagNumbering(TD, S);
8696     }
8697     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8698     NewND = NewTD;
8699   }
8700 
8701   if (!Redeclaration)
8702     PushOnScopeChains(NewND, S);
8703 
8704   ActOnDocumentableDecl(NewND);
8705   return NewND;
8706 }
8707 
8708 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8709                                    SourceLocation AliasLoc,
8710                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
8711                                    SourceLocation IdentLoc,
8712                                    IdentifierInfo *Ident) {
8713 
8714   // Lookup the namespace name.
8715   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8716   LookupParsedName(R, S, &SS);
8717 
8718   if (R.isAmbiguous())
8719     return nullptr;
8720 
8721   if (R.empty()) {
8722     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8723       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8724       return nullptr;
8725     }
8726   }
8727   assert(!R.isAmbiguous() && !R.empty());
8728   NamedDecl *ND = R.getRepresentativeDecl();
8729 
8730   // Check if we have a previous declaration with the same name.
8731   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
8732                      ForRedeclaration);
8733   LookupName(PrevR, S);
8734 
8735   // Check we're not shadowing a template parameter.
8736   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
8737     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
8738     PrevR.clear();
8739   }
8740 
8741   // Filter out any other lookup result from an enclosing scope.
8742   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
8743                        /*AllowInlineNamespace*/false);
8744 
8745   // Find the previous declaration and check that we can redeclare it.
8746   NamespaceAliasDecl *Prev = nullptr;
8747   if (PrevR.isSingleResult()) {
8748     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
8749     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8750       // We already have an alias with the same name that points to the same
8751       // namespace; check that it matches.
8752       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8753         Prev = AD;
8754       } else if (isVisible(PrevDecl)) {
8755         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8756           << Alias;
8757         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
8758           << AD->getNamespace();
8759         return nullptr;
8760       }
8761     } else if (isVisible(PrevDecl)) {
8762       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
8763                             ? diag::err_redefinition
8764                             : diag::err_redefinition_different_kind;
8765       Diag(AliasLoc, DiagID) << Alias;
8766       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8767       return nullptr;
8768     }
8769   }
8770 
8771   // The use of a nested name specifier may trigger deprecation warnings.
8772   DiagnoseUseOfDecl(ND, IdentLoc);
8773 
8774   NamespaceAliasDecl *AliasDecl =
8775     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8776                                Alias, SS.getWithLocInContext(Context),
8777                                IdentLoc, ND);
8778   if (Prev)
8779     AliasDecl->setPreviousDecl(Prev);
8780 
8781   PushOnScopeChains(AliasDecl, S);
8782   return AliasDecl;
8783 }
8784 
8785 Sema::ImplicitExceptionSpecification
8786 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8787                                                CXXMethodDecl *MD) {
8788   CXXRecordDecl *ClassDecl = MD->getParent();
8789 
8790   // C++ [except.spec]p14:
8791   //   An implicitly declared special member function (Clause 12) shall have an
8792   //   exception-specification. [...]
8793   ImplicitExceptionSpecification ExceptSpec(*this);
8794   if (ClassDecl->isInvalidDecl())
8795     return ExceptSpec;
8796 
8797   // Direct base-class constructors.
8798   for (const auto &B : ClassDecl->bases()) {
8799     if (B.isVirtual()) // Handled below.
8800       continue;
8801 
8802     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8803       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8804       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8805       // If this is a deleted function, add it anyway. This might be conformant
8806       // with the standard. This might not. I'm not sure. It might not matter.
8807       if (Constructor)
8808         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8809     }
8810   }
8811 
8812   // Virtual base-class constructors.
8813   for (const auto &B : ClassDecl->vbases()) {
8814     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8815       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8816       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8817       // If this is a deleted function, add it anyway. This might be conformant
8818       // with the standard. This might not. I'm not sure. It might not matter.
8819       if (Constructor)
8820         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8821     }
8822   }
8823 
8824   // Field constructors.
8825   for (const auto *F : ClassDecl->fields()) {
8826     if (F->hasInClassInitializer()) {
8827       if (Expr *E = F->getInClassInitializer())
8828         ExceptSpec.CalledExpr(E);
8829     } else if (const RecordType *RecordTy
8830               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8831       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8832       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8833       // If this is a deleted function, add it anyway. This might be conformant
8834       // with the standard. This might not. I'm not sure. It might not matter.
8835       // In particular, the problem is that this function never gets called. It
8836       // might just be ill-formed because this function attempts to refer to
8837       // a deleted function here.
8838       if (Constructor)
8839         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8840     }
8841   }
8842 
8843   return ExceptSpec;
8844 }
8845 
8846 Sema::ImplicitExceptionSpecification
8847 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8848   CXXRecordDecl *ClassDecl = CD->getParent();
8849 
8850   // C++ [except.spec]p14:
8851   //   An inheriting constructor [...] shall have an exception-specification. [...]
8852   ImplicitExceptionSpecification ExceptSpec(*this);
8853   if (ClassDecl->isInvalidDecl())
8854     return ExceptSpec;
8855 
8856   // Inherited constructor.
8857   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8858   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8859   // FIXME: Copying or moving the parameters could add extra exceptions to the
8860   // set, as could the default arguments for the inherited constructor. This
8861   // will be addressed when we implement the resolution of core issue 1351.
8862   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8863 
8864   // Direct base-class constructors.
8865   for (const auto &B : ClassDecl->bases()) {
8866     if (B.isVirtual()) // Handled below.
8867       continue;
8868 
8869     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8870       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8871       if (BaseClassDecl == InheritedDecl)
8872         continue;
8873       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8874       if (Constructor)
8875         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8876     }
8877   }
8878 
8879   // Virtual base-class constructors.
8880   for (const auto &B : ClassDecl->vbases()) {
8881     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8882       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8883       if (BaseClassDecl == InheritedDecl)
8884         continue;
8885       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8886       if (Constructor)
8887         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8888     }
8889   }
8890 
8891   // Field constructors.
8892   for (const auto *F : ClassDecl->fields()) {
8893     if (F->hasInClassInitializer()) {
8894       if (Expr *E = F->getInClassInitializer())
8895         ExceptSpec.CalledExpr(E);
8896     } else if (const RecordType *RecordTy
8897               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8898       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8899       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8900       if (Constructor)
8901         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8902     }
8903   }
8904 
8905   return ExceptSpec;
8906 }
8907 
8908 namespace {
8909 /// RAII object to register a special member as being currently declared.
8910 struct DeclaringSpecialMember {
8911   Sema &S;
8912   Sema::SpecialMemberDecl D;
8913   Sema::ContextRAII SavedContext;
8914   bool WasAlreadyBeingDeclared;
8915 
8916   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8917     : S(S), D(RD, CSM), SavedContext(S, RD) {
8918     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
8919     if (WasAlreadyBeingDeclared)
8920       // This almost never happens, but if it does, ensure that our cache
8921       // doesn't contain a stale result.
8922       S.SpecialMemberCache.clear();
8923 
8924     // FIXME: Register a note to be produced if we encounter an error while
8925     // declaring the special member.
8926   }
8927   ~DeclaringSpecialMember() {
8928     if (!WasAlreadyBeingDeclared)
8929       S.SpecialMembersBeingDeclared.erase(D);
8930   }
8931 
8932   /// \brief Are we already trying to declare this special member?
8933   bool isAlreadyBeingDeclared() const {
8934     return WasAlreadyBeingDeclared;
8935   }
8936 };
8937 }
8938 
8939 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
8940   // Look up any existing declarations, but don't trigger declaration of all
8941   // implicit special members with this name.
8942   DeclarationName Name = FD->getDeclName();
8943   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
8944                  ForRedeclaration);
8945   for (auto *D : FD->getParent()->lookup(Name))
8946     if (auto *Acceptable = R.getAcceptableDecl(D))
8947       R.addDecl(Acceptable);
8948   R.resolveKind();
8949 
8950   CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
8951 }
8952 
8953 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8954                                                      CXXRecordDecl *ClassDecl) {
8955   // C++ [class.ctor]p5:
8956   //   A default constructor for a class X is a constructor of class X
8957   //   that can be called without an argument. If there is no
8958   //   user-declared constructor for class X, a default constructor is
8959   //   implicitly declared. An implicitly-declared default constructor
8960   //   is an inline public member of its class.
8961   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8962          "Should not build implicit default constructor!");
8963 
8964   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8965   if (DSM.isAlreadyBeingDeclared())
8966     return nullptr;
8967 
8968   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8969                                                      CXXDefaultConstructor,
8970                                                      false);
8971 
8972   // Create the actual constructor declaration.
8973   CanQualType ClassType
8974     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8975   SourceLocation ClassLoc = ClassDecl->getLocation();
8976   DeclarationName Name
8977     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8978   DeclarationNameInfo NameInfo(Name, ClassLoc);
8979   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8980       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8981       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8982       /*isImplicitlyDeclared=*/true, Constexpr);
8983   DefaultCon->setAccess(AS_public);
8984   DefaultCon->setDefaulted();
8985 
8986   if (getLangOpts().CUDA) {
8987     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8988                                             DefaultCon,
8989                                             /* ConstRHS */ false,
8990                                             /* Diagnose */ false);
8991   }
8992 
8993   // Build an exception specification pointing back at this constructor.
8994   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8995   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8996 
8997   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8998   // constructors is easy to compute.
8999   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
9000 
9001   // Note that we have declared this constructor.
9002   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
9003 
9004   Scope *S = getScopeForContext(ClassDecl);
9005   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
9006 
9007   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
9008     SetDeclDeleted(DefaultCon, ClassLoc);
9009 
9010   if (S)
9011     PushOnScopeChains(DefaultCon, S, false);
9012   ClassDecl->addDecl(DefaultCon);
9013 
9014   return DefaultCon;
9015 }
9016 
9017 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
9018                                             CXXConstructorDecl *Constructor) {
9019   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
9020           !Constructor->doesThisDeclarationHaveABody() &&
9021           !Constructor->isDeleted()) &&
9022     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
9023 
9024   CXXRecordDecl *ClassDecl = Constructor->getParent();
9025   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
9026 
9027   SynthesizedFunctionScope Scope(*this, Constructor);
9028   DiagnosticErrorTrap Trap(Diags);
9029   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9030       Trap.hasErrorOccurred()) {
9031     Diag(CurrentLocation, diag::note_member_synthesized_at)
9032       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
9033     Constructor->setInvalidDecl();
9034     return;
9035   }
9036 
9037   // The exception specification is needed because we are defining the
9038   // function.
9039   ResolveExceptionSpec(CurrentLocation,
9040                        Constructor->getType()->castAs<FunctionProtoType>());
9041 
9042   SourceLocation Loc = Constructor->getLocEnd().isValid()
9043                            ? Constructor->getLocEnd()
9044                            : Constructor->getLocation();
9045   Constructor->setBody(new (Context) CompoundStmt(Loc));
9046 
9047   Constructor->markUsed(Context);
9048   MarkVTableUsed(CurrentLocation, ClassDecl);
9049 
9050   if (ASTMutationListener *L = getASTMutationListener()) {
9051     L->CompletedImplicitDefinition(Constructor);
9052   }
9053 
9054   DiagnoseUninitializedFields(*this, Constructor);
9055 }
9056 
9057 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
9058   // Perform any delayed checks on exception specifications.
9059   CheckDelayedMemberExceptionSpecs();
9060 }
9061 
9062 namespace {
9063 /// Information on inheriting constructors to declare.
9064 class InheritingConstructorInfo {
9065 public:
9066   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
9067       : SemaRef(SemaRef), Derived(Derived) {
9068     // Mark the constructors that we already have in the derived class.
9069     //
9070     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
9071     //   unless there is a user-declared constructor with the same signature in
9072     //   the class where the using-declaration appears.
9073     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9074   }
9075 
9076   void inheritAll(CXXRecordDecl *RD) {
9077     visitAll(RD, &InheritingConstructorInfo::inherit);
9078   }
9079 
9080 private:
9081   /// Information about an inheriting constructor.
9082   struct InheritingConstructor {
9083     InheritingConstructor()
9084       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
9085 
9086     /// If \c true, a constructor with this signature is already declared
9087     /// in the derived class.
9088     bool DeclaredInDerived;
9089 
9090     /// The constructor which is inherited.
9091     const CXXConstructorDecl *BaseCtor;
9092 
9093     /// The derived constructor we declared.
9094     CXXConstructorDecl *DerivedCtor;
9095   };
9096 
9097   /// Inheriting constructors with a given canonical type. There can be at
9098   /// most one such non-template constructor, and any number of templated
9099   /// constructors.
9100   struct InheritingConstructorsForType {
9101     InheritingConstructor NonTemplate;
9102     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9103         Templates;
9104 
9105     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9106       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9107         TemplateParameterList *ParamList = FTD->getTemplateParameters();
9108         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9109           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9110                                                false, S.TPL_TemplateMatch))
9111             return Templates[I].second;
9112         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9113         return Templates.back().second;
9114       }
9115 
9116       return NonTemplate;
9117     }
9118   };
9119 
9120   /// Get or create the inheriting constructor record for a constructor.
9121   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9122                                   QualType CtorType) {
9123     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9124         .getEntry(SemaRef, Ctor);
9125   }
9126 
9127   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9128 
9129   /// Process all constructors for a class.
9130   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
9131     for (const auto *Ctor : RD->ctors())
9132       (this->*Callback)(Ctor);
9133     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9134              I(RD->decls_begin()), E(RD->decls_end());
9135          I != E; ++I) {
9136       const FunctionDecl *FD = (*I)->getTemplatedDecl();
9137       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9138         (this->*Callback)(CD);
9139     }
9140   }
9141 
9142   /// Note that a constructor (or constructor template) was declared in Derived.
9143   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9144     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9145   }
9146 
9147   /// Inherit a single constructor.
9148   void inherit(const CXXConstructorDecl *Ctor) {
9149     const FunctionProtoType *CtorType =
9150         Ctor->getType()->castAs<FunctionProtoType>();
9151     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
9152     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9153 
9154     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9155 
9156     // Core issue (no number yet): the ellipsis is always discarded.
9157     if (EPI.Variadic) {
9158       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9159       SemaRef.Diag(Ctor->getLocation(),
9160                    diag::note_using_decl_constructor_ellipsis);
9161       EPI.Variadic = false;
9162     }
9163 
9164     // Declare a constructor for each number of parameters.
9165     //
9166     // C++11 [class.inhctor]p1:
9167     //   The candidate set of inherited constructors from the class X named in
9168     //   the using-declaration consists of [... modulo defects ...] for each
9169     //   constructor or constructor template of X, the set of constructors or
9170     //   constructor templates that results from omitting any ellipsis parameter
9171     //   specification and successively omitting parameters with a default
9172     //   argument from the end of the parameter-type-list
9173     unsigned MinParams = minParamsToInherit(Ctor);
9174     unsigned Params = Ctor->getNumParams();
9175     if (Params >= MinParams) {
9176       do
9177         declareCtor(UsingLoc, Ctor,
9178                     SemaRef.Context.getFunctionType(
9179                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
9180       while (Params > MinParams &&
9181              Ctor->getParamDecl(--Params)->hasDefaultArg());
9182     }
9183   }
9184 
9185   /// Find the using-declaration which specified that we should inherit the
9186   /// constructors of \p Base.
9187   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9188     // No fancy lookup required; just look for the base constructor name
9189     // directly within the derived class.
9190     ASTContext &Context = SemaRef.Context;
9191     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9192         Context.getCanonicalType(Context.getRecordType(Base)));
9193     DeclContext::lookup_result Decls = Derived->lookup(Name);
9194     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9195   }
9196 
9197   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9198     // C++11 [class.inhctor]p3:
9199     //   [F]or each constructor template in the candidate set of inherited
9200     //   constructors, a constructor template is implicitly declared
9201     if (Ctor->getDescribedFunctionTemplate())
9202       return 0;
9203 
9204     //   For each non-template constructor in the candidate set of inherited
9205     //   constructors other than a constructor having no parameters or a
9206     //   copy/move constructor having a single parameter, a constructor is
9207     //   implicitly declared [...]
9208     if (Ctor->getNumParams() == 0)
9209       return 1;
9210     if (Ctor->isCopyOrMoveConstructor())
9211       return 2;
9212 
9213     // Per discussion on core reflector, never inherit a constructor which
9214     // would become a default, copy, or move constructor of Derived either.
9215     const ParmVarDecl *PD = Ctor->getParamDecl(0);
9216     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9217     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9218   }
9219 
9220   /// Declare a single inheriting constructor, inheriting the specified
9221   /// constructor, with the given type.
9222   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9223                    QualType DerivedType) {
9224     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9225 
9226     // C++11 [class.inhctor]p3:
9227     //   ... a constructor is implicitly declared with the same constructor
9228     //   characteristics unless there is a user-declared constructor with
9229     //   the same signature in the class where the using-declaration appears
9230     if (Entry.DeclaredInDerived)
9231       return;
9232 
9233     // C++11 [class.inhctor]p7:
9234     //   If two using-declarations declare inheriting constructors with the
9235     //   same signature, the program is ill-formed
9236     if (Entry.DerivedCtor) {
9237       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9238         // Only diagnose this once per constructor.
9239         if (Entry.DerivedCtor->isInvalidDecl())
9240           return;
9241         Entry.DerivedCtor->setInvalidDecl();
9242 
9243         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9244         SemaRef.Diag(BaseCtor->getLocation(),
9245                      diag::note_using_decl_constructor_conflict_current_ctor);
9246         SemaRef.Diag(Entry.BaseCtor->getLocation(),
9247                      diag::note_using_decl_constructor_conflict_previous_ctor);
9248         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9249                      diag::note_using_decl_constructor_conflict_previous_using);
9250       } else {
9251         // Core issue (no number): if the same inheriting constructor is
9252         // produced by multiple base class constructors from the same base
9253         // class, the inheriting constructor is defined as deleted.
9254         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9255       }
9256 
9257       return;
9258     }
9259 
9260     ASTContext &Context = SemaRef.Context;
9261     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9262         Context.getCanonicalType(Context.getRecordType(Derived)));
9263     DeclarationNameInfo NameInfo(Name, UsingLoc);
9264 
9265     TemplateParameterList *TemplateParams = nullptr;
9266     if (const FunctionTemplateDecl *FTD =
9267             BaseCtor->getDescribedFunctionTemplate()) {
9268       TemplateParams = FTD->getTemplateParameters();
9269       // We're reusing template parameters from a different DeclContext. This
9270       // is questionable at best, but works out because the template depth in
9271       // both places is guaranteed to be 0.
9272       // FIXME: Rebuild the template parameters in the new context, and
9273       // transform the function type to refer to them.
9274     }
9275 
9276     // Build type source info pointing at the using-declaration. This is
9277     // required by template instantiation.
9278     TypeSourceInfo *TInfo =
9279         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9280     FunctionProtoTypeLoc ProtoLoc =
9281         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9282 
9283     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9284         Context, Derived, UsingLoc, NameInfo, DerivedType,
9285         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9286         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9287 
9288     // Build an unevaluated exception specification for this constructor.
9289     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9290     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9291     EPI.ExceptionSpec.Type = EST_Unevaluated;
9292     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9293     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9294                                                  FPT->getParamTypes(), EPI));
9295 
9296     // Build the parameter declarations.
9297     SmallVector<ParmVarDecl *, 16> ParamDecls;
9298     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9299       TypeSourceInfo *TInfo =
9300           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9301       ParmVarDecl *PD = ParmVarDecl::Create(
9302           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9303           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9304       PD->setScopeInfo(0, I);
9305       PD->setImplicit();
9306       ParamDecls.push_back(PD);
9307       ProtoLoc.setParam(I, PD);
9308     }
9309 
9310     // Set up the new constructor.
9311     DerivedCtor->setAccess(BaseCtor->getAccess());
9312     DerivedCtor->setParams(ParamDecls);
9313     DerivedCtor->setInheritedConstructor(BaseCtor);
9314     if (BaseCtor->isDeleted())
9315       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9316 
9317     // If this is a constructor template, build the template declaration.
9318     if (TemplateParams) {
9319       FunctionTemplateDecl *DerivedTemplate =
9320           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9321                                        TemplateParams, DerivedCtor);
9322       DerivedTemplate->setAccess(BaseCtor->getAccess());
9323       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9324       Derived->addDecl(DerivedTemplate);
9325     } else {
9326       Derived->addDecl(DerivedCtor);
9327     }
9328 
9329     Entry.BaseCtor = BaseCtor;
9330     Entry.DerivedCtor = DerivedCtor;
9331   }
9332 
9333   Sema &SemaRef;
9334   CXXRecordDecl *Derived;
9335   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9336   MapType Map;
9337 };
9338 }
9339 
9340 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9341   // Defer declaring the inheriting constructors until the class is
9342   // instantiated.
9343   if (ClassDecl->isDependentContext())
9344     return;
9345 
9346   // Find base classes from which we might inherit constructors.
9347   SmallVector<CXXRecordDecl*, 4> InheritedBases;
9348   for (const auto &BaseIt : ClassDecl->bases())
9349     if (BaseIt.getInheritConstructors())
9350       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9351 
9352   // Go no further if we're not inheriting any constructors.
9353   if (InheritedBases.empty())
9354     return;
9355 
9356   // Declare the inherited constructors.
9357   InheritingConstructorInfo ICI(*this, ClassDecl);
9358   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9359     ICI.inheritAll(InheritedBases[I]);
9360 }
9361 
9362 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9363                                        CXXConstructorDecl *Constructor) {
9364   CXXRecordDecl *ClassDecl = Constructor->getParent();
9365   assert(Constructor->getInheritedConstructor() &&
9366          !Constructor->doesThisDeclarationHaveABody() &&
9367          !Constructor->isDeleted());
9368 
9369   SynthesizedFunctionScope Scope(*this, Constructor);
9370   DiagnosticErrorTrap Trap(Diags);
9371   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9372       Trap.hasErrorOccurred()) {
9373     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9374       << Context.getTagDeclType(ClassDecl);
9375     Constructor->setInvalidDecl();
9376     return;
9377   }
9378 
9379   SourceLocation Loc = Constructor->getLocation();
9380   Constructor->setBody(new (Context) CompoundStmt(Loc));
9381 
9382   Constructor->markUsed(Context);
9383   MarkVTableUsed(CurrentLocation, ClassDecl);
9384 
9385   if (ASTMutationListener *L = getASTMutationListener()) {
9386     L->CompletedImplicitDefinition(Constructor);
9387   }
9388 }
9389 
9390 
9391 Sema::ImplicitExceptionSpecification
9392 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9393   CXXRecordDecl *ClassDecl = MD->getParent();
9394 
9395   // C++ [except.spec]p14:
9396   //   An implicitly declared special member function (Clause 12) shall have
9397   //   an exception-specification.
9398   ImplicitExceptionSpecification ExceptSpec(*this);
9399   if (ClassDecl->isInvalidDecl())
9400     return ExceptSpec;
9401 
9402   // Direct base-class destructors.
9403   for (const auto &B : ClassDecl->bases()) {
9404     if (B.isVirtual()) // Handled below.
9405       continue;
9406 
9407     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9408       ExceptSpec.CalledDecl(B.getLocStart(),
9409                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9410   }
9411 
9412   // Virtual base-class destructors.
9413   for (const auto &B : ClassDecl->vbases()) {
9414     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9415       ExceptSpec.CalledDecl(B.getLocStart(),
9416                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9417   }
9418 
9419   // Field destructors.
9420   for (const auto *F : ClassDecl->fields()) {
9421     if (const RecordType *RecordTy
9422         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9423       ExceptSpec.CalledDecl(F->getLocation(),
9424                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9425   }
9426 
9427   return ExceptSpec;
9428 }
9429 
9430 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9431   // C++ [class.dtor]p2:
9432   //   If a class has no user-declared destructor, a destructor is
9433   //   declared implicitly. An implicitly-declared destructor is an
9434   //   inline public member of its class.
9435   assert(ClassDecl->needsImplicitDestructor());
9436 
9437   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9438   if (DSM.isAlreadyBeingDeclared())
9439     return nullptr;
9440 
9441   // Create the actual destructor declaration.
9442   CanQualType ClassType
9443     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9444   SourceLocation ClassLoc = ClassDecl->getLocation();
9445   DeclarationName Name
9446     = Context.DeclarationNames.getCXXDestructorName(ClassType);
9447   DeclarationNameInfo NameInfo(Name, ClassLoc);
9448   CXXDestructorDecl *Destructor
9449       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9450                                   QualType(), nullptr, /*isInline=*/true,
9451                                   /*isImplicitlyDeclared=*/true);
9452   Destructor->setAccess(AS_public);
9453   Destructor->setDefaulted();
9454 
9455   if (getLangOpts().CUDA) {
9456     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9457                                             Destructor,
9458                                             /* ConstRHS */ false,
9459                                             /* Diagnose */ false);
9460   }
9461 
9462   // Build an exception specification pointing back at this destructor.
9463   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9464   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9465 
9466   // We don't need to use SpecialMemberIsTrivial here; triviality for
9467   // destructors is easy to compute.
9468   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9469 
9470   // Note that we have declared this destructor.
9471   ++ASTContext::NumImplicitDestructorsDeclared;
9472 
9473   Scope *S = getScopeForContext(ClassDecl);
9474   CheckImplicitSpecialMemberDeclaration(S, Destructor);
9475 
9476   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9477     SetDeclDeleted(Destructor, ClassLoc);
9478 
9479   // Introduce this destructor into its scope.
9480   if (S)
9481     PushOnScopeChains(Destructor, S, false);
9482   ClassDecl->addDecl(Destructor);
9483 
9484   return Destructor;
9485 }
9486 
9487 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9488                                     CXXDestructorDecl *Destructor) {
9489   assert((Destructor->isDefaulted() &&
9490           !Destructor->doesThisDeclarationHaveABody() &&
9491           !Destructor->isDeleted()) &&
9492          "DefineImplicitDestructor - call it for implicit default dtor");
9493   CXXRecordDecl *ClassDecl = Destructor->getParent();
9494   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9495 
9496   if (Destructor->isInvalidDecl())
9497     return;
9498 
9499   SynthesizedFunctionScope Scope(*this, Destructor);
9500 
9501   DiagnosticErrorTrap Trap(Diags);
9502   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9503                                          Destructor->getParent());
9504 
9505   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9506     Diag(CurrentLocation, diag::note_member_synthesized_at)
9507       << CXXDestructor << Context.getTagDeclType(ClassDecl);
9508 
9509     Destructor->setInvalidDecl();
9510     return;
9511   }
9512 
9513   // The exception specification is needed because we are defining the
9514   // function.
9515   ResolveExceptionSpec(CurrentLocation,
9516                        Destructor->getType()->castAs<FunctionProtoType>());
9517 
9518   SourceLocation Loc = Destructor->getLocEnd().isValid()
9519                            ? Destructor->getLocEnd()
9520                            : Destructor->getLocation();
9521   Destructor->setBody(new (Context) CompoundStmt(Loc));
9522   Destructor->markUsed(Context);
9523   MarkVTableUsed(CurrentLocation, ClassDecl);
9524 
9525   if (ASTMutationListener *L = getASTMutationListener()) {
9526     L->CompletedImplicitDefinition(Destructor);
9527   }
9528 }
9529 
9530 /// \brief Perform any semantic analysis which needs to be delayed until all
9531 /// pending class member declarations have been parsed.
9532 void Sema::ActOnFinishCXXMemberDecls() {
9533   // If the context is an invalid C++ class, just suppress these checks.
9534   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9535     if (Record->isInvalidDecl()) {
9536       DelayedDefaultedMemberExceptionSpecs.clear();
9537       DelayedExceptionSpecChecks.clear();
9538       return;
9539     }
9540   }
9541 }
9542 
9543 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9544   // Don't do anything for template patterns.
9545   if (Class->getDescribedClassTemplate())
9546     return;
9547 
9548   CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
9549       /*IsVariadic=*/false, /*IsCXXMethod=*/true);
9550 
9551   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
9552   for (Decl *Member : Class->decls()) {
9553     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9554     if (!CD) {
9555       // Recurse on nested classes.
9556       if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9557         getDefaultArgExprsForConstructors(S, NestedRD);
9558       continue;
9559     } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9560       continue;
9561     }
9562 
9563     CallingConv ActualCallingConv =
9564         CD->getType()->getAs<FunctionProtoType>()->getCallConv();
9565 
9566     // Skip default constructors with typical calling conventions and no default
9567     // arguments.
9568     unsigned NumParams = CD->getNumParams();
9569     if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
9570       continue;
9571 
9572     if (LastExportedDefaultCtor) {
9573       S.Diag(LastExportedDefaultCtor->getLocation(),
9574              diag::err_attribute_dll_ambiguous_default_ctor) << Class;
9575       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
9576           << CD->getDeclName();
9577       return;
9578     }
9579     LastExportedDefaultCtor = CD;
9580 
9581     for (unsigned I = 0; I != NumParams; ++I) {
9582       // Skip any default arguments that we've already instantiated.
9583       if (S.Context.getDefaultArgExprForConstructor(CD, I))
9584         continue;
9585 
9586       Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9587                                                   CD->getParamDecl(I)).get();
9588       S.DiscardCleanupsInEvaluationContext();
9589       S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9590     }
9591   }
9592 }
9593 
9594 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
9595   auto *RD = dyn_cast<CXXRecordDecl>(D);
9596 
9597   // Default constructors that are annotated with __declspec(dllexport) which
9598   // have default arguments or don't use the standard calling convention are
9599   // wrapped with a thunk called the default constructor closure.
9600   if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9601     getDefaultArgExprsForConstructors(*this, RD);
9602 
9603   referenceDLLExportedClassMethods();
9604 }
9605 
9606 void Sema::referenceDLLExportedClassMethods() {
9607   if (!DelayedDllExportClasses.empty()) {
9608     // Calling ReferenceDllExportedMethods might cause the current function to
9609     // be called again, so use a local copy of DelayedDllExportClasses.
9610     SmallVector<CXXRecordDecl *, 4> WorkList;
9611     std::swap(DelayedDllExportClasses, WorkList);
9612     for (CXXRecordDecl *Class : WorkList)
9613       ReferenceDllExportedMethods(*this, Class);
9614   }
9615 }
9616 
9617 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9618                                          CXXDestructorDecl *Destructor) {
9619   assert(getLangOpts().CPlusPlus11 &&
9620          "adjusting dtor exception specs was introduced in c++11");
9621 
9622   // C++11 [class.dtor]p3:
9623   //   A declaration of a destructor that does not have an exception-
9624   //   specification is implicitly considered to have the same exception-
9625   //   specification as an implicit declaration.
9626   const FunctionProtoType *DtorType = Destructor->getType()->
9627                                         getAs<FunctionProtoType>();
9628   if (DtorType->hasExceptionSpec())
9629     return;
9630 
9631   // Replace the destructor's type, building off the existing one. Fortunately,
9632   // the only thing of interest in the destructor type is its extended info.
9633   // The return and arguments are fixed.
9634   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9635   EPI.ExceptionSpec.Type = EST_Unevaluated;
9636   EPI.ExceptionSpec.SourceDecl = Destructor;
9637   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9638 
9639   // FIXME: If the destructor has a body that could throw, and the newly created
9640   // spec doesn't allow exceptions, we should emit a warning, because this
9641   // change in behavior can break conforming C++03 programs at runtime.
9642   // However, we don't have a body or an exception specification yet, so it
9643   // needs to be done somewhere else.
9644 }
9645 
9646 namespace {
9647 /// \brief An abstract base class for all helper classes used in building the
9648 //  copy/move operators. These classes serve as factory functions and help us
9649 //  avoid using the same Expr* in the AST twice.
9650 class ExprBuilder {
9651   ExprBuilder(const ExprBuilder&) = delete;
9652   ExprBuilder &operator=(const ExprBuilder&) = delete;
9653 
9654 protected:
9655   static Expr *assertNotNull(Expr *E) {
9656     assert(E && "Expression construction must not fail.");
9657     return E;
9658   }
9659 
9660 public:
9661   ExprBuilder() {}
9662   virtual ~ExprBuilder() {}
9663 
9664   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9665 };
9666 
9667 class RefBuilder: public ExprBuilder {
9668   VarDecl *Var;
9669   QualType VarType;
9670 
9671 public:
9672   Expr *build(Sema &S, SourceLocation Loc) const override {
9673     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9674   }
9675 
9676   RefBuilder(VarDecl *Var, QualType VarType)
9677       : Var(Var), VarType(VarType) {}
9678 };
9679 
9680 class ThisBuilder: public ExprBuilder {
9681 public:
9682   Expr *build(Sema &S, SourceLocation Loc) const override {
9683     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9684   }
9685 };
9686 
9687 class CastBuilder: public ExprBuilder {
9688   const ExprBuilder &Builder;
9689   QualType Type;
9690   ExprValueKind Kind;
9691   const CXXCastPath &Path;
9692 
9693 public:
9694   Expr *build(Sema &S, SourceLocation Loc) const override {
9695     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9696                                              CK_UncheckedDerivedToBase, Kind,
9697                                              &Path).get());
9698   }
9699 
9700   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9701               const CXXCastPath &Path)
9702       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9703 };
9704 
9705 class DerefBuilder: public ExprBuilder {
9706   const ExprBuilder &Builder;
9707 
9708 public:
9709   Expr *build(Sema &S, SourceLocation Loc) const override {
9710     return assertNotNull(
9711         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9712   }
9713 
9714   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9715 };
9716 
9717 class MemberBuilder: public ExprBuilder {
9718   const ExprBuilder &Builder;
9719   QualType Type;
9720   CXXScopeSpec SS;
9721   bool IsArrow;
9722   LookupResult &MemberLookup;
9723 
9724 public:
9725   Expr *build(Sema &S, SourceLocation Loc) const override {
9726     return assertNotNull(S.BuildMemberReferenceExpr(
9727         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9728         nullptr, MemberLookup, nullptr, nullptr).get());
9729   }
9730 
9731   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9732                 LookupResult &MemberLookup)
9733       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9734         MemberLookup(MemberLookup) {}
9735 };
9736 
9737 class MoveCastBuilder: public ExprBuilder {
9738   const ExprBuilder &Builder;
9739 
9740 public:
9741   Expr *build(Sema &S, SourceLocation Loc) const override {
9742     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9743   }
9744 
9745   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9746 };
9747 
9748 class LvalueConvBuilder: public ExprBuilder {
9749   const ExprBuilder &Builder;
9750 
9751 public:
9752   Expr *build(Sema &S, SourceLocation Loc) const override {
9753     return assertNotNull(
9754         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9755   }
9756 
9757   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9758 };
9759 
9760 class SubscriptBuilder: public ExprBuilder {
9761   const ExprBuilder &Base;
9762   const ExprBuilder &Index;
9763 
9764 public:
9765   Expr *build(Sema &S, SourceLocation Loc) const override {
9766     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9767         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9768   }
9769 
9770   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9771       : Base(Base), Index(Index) {}
9772 };
9773 
9774 } // end anonymous namespace
9775 
9776 /// When generating a defaulted copy or move assignment operator, if a field
9777 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9778 /// do so. This optimization only applies for arrays of scalars, and for arrays
9779 /// of class type where the selected copy/move-assignment operator is trivial.
9780 static StmtResult
9781 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9782                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9783   // Compute the size of the memory buffer to be copied.
9784   QualType SizeType = S.Context.getSizeType();
9785   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9786                    S.Context.getTypeSizeInChars(T).getQuantity());
9787 
9788   // Take the address of the field references for "from" and "to". We
9789   // directly construct UnaryOperators here because semantic analysis
9790   // does not permit us to take the address of an xvalue.
9791   Expr *From = FromB.build(S, Loc);
9792   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9793                          S.Context.getPointerType(From->getType()),
9794                          VK_RValue, OK_Ordinary, Loc);
9795   Expr *To = ToB.build(S, Loc);
9796   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9797                        S.Context.getPointerType(To->getType()),
9798                        VK_RValue, OK_Ordinary, Loc);
9799 
9800   const Type *E = T->getBaseElementTypeUnsafe();
9801   bool NeedsCollectableMemCpy =
9802     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9803 
9804   // Create a reference to the __builtin_objc_memmove_collectable function
9805   StringRef MemCpyName = NeedsCollectableMemCpy ?
9806     "__builtin_objc_memmove_collectable" :
9807     "__builtin_memcpy";
9808   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9809                  Sema::LookupOrdinaryName);
9810   S.LookupName(R, S.TUScope, true);
9811 
9812   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9813   if (!MemCpy)
9814     // Something went horribly wrong earlier, and we will have complained
9815     // about it.
9816     return StmtError();
9817 
9818   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9819                                             VK_RValue, Loc, nullptr);
9820   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9821 
9822   Expr *CallArgs[] = {
9823     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9824   };
9825   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9826                                     Loc, CallArgs, Loc);
9827 
9828   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9829   return Call.getAs<Stmt>();
9830 }
9831 
9832 /// \brief Builds a statement that copies/moves the given entity from \p From to
9833 /// \c To.
9834 ///
9835 /// This routine is used to copy/move the members of a class with an
9836 /// implicitly-declared copy/move assignment operator. When the entities being
9837 /// copied are arrays, this routine builds for loops to copy them.
9838 ///
9839 /// \param S The Sema object used for type-checking.
9840 ///
9841 /// \param Loc The location where the implicit copy/move is being generated.
9842 ///
9843 /// \param T The type of the expressions being copied/moved. Both expressions
9844 /// must have this type.
9845 ///
9846 /// \param To The expression we are copying/moving to.
9847 ///
9848 /// \param From The expression we are copying/moving from.
9849 ///
9850 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9851 /// Otherwise, it's a non-static member subobject.
9852 ///
9853 /// \param Copying Whether we're copying or moving.
9854 ///
9855 /// \param Depth Internal parameter recording the depth of the recursion.
9856 ///
9857 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9858 /// if a memcpy should be used instead.
9859 static StmtResult
9860 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9861                                  const ExprBuilder &To, const ExprBuilder &From,
9862                                  bool CopyingBaseSubobject, bool Copying,
9863                                  unsigned Depth = 0) {
9864   // C++11 [class.copy]p28:
9865   //   Each subobject is assigned in the manner appropriate to its type:
9866   //
9867   //     - if the subobject is of class type, as if by a call to operator= with
9868   //       the subobject as the object expression and the corresponding
9869   //       subobject of x as a single function argument (as if by explicit
9870   //       qualification; that is, ignoring any possible virtual overriding
9871   //       functions in more derived classes);
9872   //
9873   // C++03 [class.copy]p13:
9874   //     - if the subobject is of class type, the copy assignment operator for
9875   //       the class is used (as if by explicit qualification; that is,
9876   //       ignoring any possible virtual overriding functions in more derived
9877   //       classes);
9878   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9879     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9880 
9881     // Look for operator=.
9882     DeclarationName Name
9883       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9884     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9885     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9886 
9887     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9888     // operator.
9889     if (!S.getLangOpts().CPlusPlus11) {
9890       LookupResult::Filter F = OpLookup.makeFilter();
9891       while (F.hasNext()) {
9892         NamedDecl *D = F.next();
9893         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9894           if (Method->isCopyAssignmentOperator() ||
9895               (!Copying && Method->isMoveAssignmentOperator()))
9896             continue;
9897 
9898         F.erase();
9899       }
9900       F.done();
9901     }
9902 
9903     // Suppress the protected check (C++ [class.protected]) for each of the
9904     // assignment operators we found. This strange dance is required when
9905     // we're assigning via a base classes's copy-assignment operator. To
9906     // ensure that we're getting the right base class subobject (without
9907     // ambiguities), we need to cast "this" to that subobject type; to
9908     // ensure that we don't go through the virtual call mechanism, we need
9909     // to qualify the operator= name with the base class (see below). However,
9910     // this means that if the base class has a protected copy assignment
9911     // operator, the protected member access check will fail. So, we
9912     // rewrite "protected" access to "public" access in this case, since we
9913     // know by construction that we're calling from a derived class.
9914     if (CopyingBaseSubobject) {
9915       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9916            L != LEnd; ++L) {
9917         if (L.getAccess() == AS_protected)
9918           L.setAccess(AS_public);
9919       }
9920     }
9921 
9922     // Create the nested-name-specifier that will be used to qualify the
9923     // reference to operator=; this is required to suppress the virtual
9924     // call mechanism.
9925     CXXScopeSpec SS;
9926     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9927     SS.MakeTrivial(S.Context,
9928                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9929                                                CanonicalT),
9930                    Loc);
9931 
9932     // Create the reference to operator=.
9933     ExprResult OpEqualRef
9934       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9935                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9936                                    /*FirstQualifierInScope=*/nullptr,
9937                                    OpLookup,
9938                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
9939                                    /*SuppressQualifierCheck=*/true);
9940     if (OpEqualRef.isInvalid())
9941       return StmtError();
9942 
9943     // Build the call to the assignment operator.
9944 
9945     Expr *FromInst = From.build(S, Loc);
9946     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9947                                                   OpEqualRef.getAs<Expr>(),
9948                                                   Loc, FromInst, Loc);
9949     if (Call.isInvalid())
9950       return StmtError();
9951 
9952     // If we built a call to a trivial 'operator=' while copying an array,
9953     // bail out. We'll replace the whole shebang with a memcpy.
9954     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9955     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9956       return StmtResult((Stmt*)nullptr);
9957 
9958     // Convert to an expression-statement, and clean up any produced
9959     // temporaries.
9960     return S.ActOnExprStmt(Call);
9961   }
9962 
9963   //     - if the subobject is of scalar type, the built-in assignment
9964   //       operator is used.
9965   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9966   if (!ArrayTy) {
9967     ExprResult Assignment = S.CreateBuiltinBinOp(
9968         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9969     if (Assignment.isInvalid())
9970       return StmtError();
9971     return S.ActOnExprStmt(Assignment);
9972   }
9973 
9974   //     - if the subobject is an array, each element is assigned, in the
9975   //       manner appropriate to the element type;
9976 
9977   // Construct a loop over the array bounds, e.g.,
9978   //
9979   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9980   //
9981   // that will copy each of the array elements.
9982   QualType SizeType = S.Context.getSizeType();
9983 
9984   // Create the iteration variable.
9985   IdentifierInfo *IterationVarName = nullptr;
9986   {
9987     SmallString<8> Str;
9988     llvm::raw_svector_ostream OS(Str);
9989     OS << "__i" << Depth;
9990     IterationVarName = &S.Context.Idents.get(OS.str());
9991   }
9992   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9993                                           IterationVarName, SizeType,
9994                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9995                                           SC_None);
9996 
9997   // Initialize the iteration variable to zero.
9998   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9999   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
10000 
10001   // Creates a reference to the iteration variable.
10002   RefBuilder IterationVarRef(IterationVar, SizeType);
10003   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
10004 
10005   // Create the DeclStmt that holds the iteration variable.
10006   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
10007 
10008   // Subscript the "from" and "to" expressions with the iteration variable.
10009   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10010   MoveCastBuilder FromIndexMove(FromIndexCopy);
10011   const ExprBuilder *FromIndex;
10012   if (Copying)
10013     FromIndex = &FromIndexCopy;
10014   else
10015     FromIndex = &FromIndexMove;
10016 
10017   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
10018 
10019   // Build the copy/move for an individual element of the array.
10020   StmtResult Copy =
10021     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
10022                                      ToIndex, *FromIndex, CopyingBaseSubobject,
10023                                      Copying, Depth + 1);
10024   // Bail out if copying fails or if we determined that we should use memcpy.
10025   if (Copy.isInvalid() || !Copy.get())
10026     return Copy;
10027 
10028   // Create the comparison against the array bound.
10029   llvm::APInt Upper
10030     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10031   Expr *Comparison
10032     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
10033                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10034                                      BO_NE, S.Context.BoolTy,
10035                                      VK_RValue, OK_Ordinary, Loc, false);
10036 
10037   // Create the pre-increment of the iteration variable.
10038   Expr *Increment
10039     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10040                                     SizeType, VK_LValue, OK_Ordinary, Loc);
10041 
10042   // Construct the loop that copies all elements of this array.
10043   return S.ActOnForStmt(Loc, Loc, InitStmt,
10044                         S.MakeFullExpr(Comparison),
10045                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
10046                         Loc, Copy.get());
10047 }
10048 
10049 static StmtResult
10050 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
10051                       const ExprBuilder &To, const ExprBuilder &From,
10052                       bool CopyingBaseSubobject, bool Copying) {
10053   // Maybe we should use a memcpy?
10054   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10055       T.isTriviallyCopyableType(S.Context))
10056     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10057 
10058   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10059                                                      CopyingBaseSubobject,
10060                                                      Copying, 0));
10061 
10062   // If we ended up picking a trivial assignment operator for an array of a
10063   // non-trivially-copyable class type, just emit a memcpy.
10064   if (!Result.isInvalid() && !Result.get())
10065     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10066 
10067   return Result;
10068 }
10069 
10070 Sema::ImplicitExceptionSpecification
10071 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10072   CXXRecordDecl *ClassDecl = MD->getParent();
10073 
10074   ImplicitExceptionSpecification ExceptSpec(*this);
10075   if (ClassDecl->isInvalidDecl())
10076     return ExceptSpec;
10077 
10078   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10079   assert(T->getNumParams() == 1 && "not a copy assignment op");
10080   unsigned ArgQuals =
10081       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10082 
10083   // C++ [except.spec]p14:
10084   //   An implicitly declared special member function (Clause 12) shall have an
10085   //   exception-specification. [...]
10086 
10087   // It is unspecified whether or not an implicit copy assignment operator
10088   // attempts to deduplicate calls to assignment operators of virtual bases are
10089   // made. As such, this exception specification is effectively unspecified.
10090   // Based on a similar decision made for constness in C++0x, we're erring on
10091   // the side of assuming such calls to be made regardless of whether they
10092   // actually happen.
10093   for (const auto &Base : ClassDecl->bases()) {
10094     if (Base.isVirtual())
10095       continue;
10096 
10097     CXXRecordDecl *BaseClassDecl
10098       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10099     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10100                                                             ArgQuals, false, 0))
10101       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10102   }
10103 
10104   for (const auto &Base : ClassDecl->vbases()) {
10105     CXXRecordDecl *BaseClassDecl
10106       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10107     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10108                                                             ArgQuals, false, 0))
10109       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10110   }
10111 
10112   for (const auto *Field : ClassDecl->fields()) {
10113     QualType FieldType = Context.getBaseElementType(Field->getType());
10114     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10115       if (CXXMethodDecl *CopyAssign =
10116           LookupCopyingAssignment(FieldClassDecl,
10117                                   ArgQuals | FieldType.getCVRQualifiers(),
10118                                   false, 0))
10119         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10120     }
10121   }
10122 
10123   return ExceptSpec;
10124 }
10125 
10126 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10127   // Note: The following rules are largely analoguous to the copy
10128   // constructor rules. Note that virtual bases are not taken into account
10129   // for determining the argument type of the operator. Note also that
10130   // operators taking an object instead of a reference are allowed.
10131   assert(ClassDecl->needsImplicitCopyAssignment());
10132 
10133   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10134   if (DSM.isAlreadyBeingDeclared())
10135     return nullptr;
10136 
10137   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10138   QualType RetType = Context.getLValueReferenceType(ArgType);
10139   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10140   if (Const)
10141     ArgType = ArgType.withConst();
10142   ArgType = Context.getLValueReferenceType(ArgType);
10143 
10144   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10145                                                      CXXCopyAssignment,
10146                                                      Const);
10147 
10148   //   An implicitly-declared copy assignment operator is an inline public
10149   //   member of its class.
10150   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10151   SourceLocation ClassLoc = ClassDecl->getLocation();
10152   DeclarationNameInfo NameInfo(Name, ClassLoc);
10153   CXXMethodDecl *CopyAssignment =
10154       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10155                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10156                             /*isInline=*/true, Constexpr, SourceLocation());
10157   CopyAssignment->setAccess(AS_public);
10158   CopyAssignment->setDefaulted();
10159   CopyAssignment->setImplicit();
10160 
10161   if (getLangOpts().CUDA) {
10162     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10163                                             CopyAssignment,
10164                                             /* ConstRHS */ Const,
10165                                             /* Diagnose */ false);
10166   }
10167 
10168   // Build an exception specification pointing back at this member.
10169   FunctionProtoType::ExtProtoInfo EPI =
10170       getImplicitMethodEPI(*this, CopyAssignment);
10171   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10172 
10173   // Add the parameter to the operator.
10174   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10175                                                ClassLoc, ClassLoc,
10176                                                /*Id=*/nullptr, ArgType,
10177                                                /*TInfo=*/nullptr, SC_None,
10178                                                nullptr);
10179   CopyAssignment->setParams(FromParam);
10180 
10181   CopyAssignment->setTrivial(
10182     ClassDecl->needsOverloadResolutionForCopyAssignment()
10183       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10184       : ClassDecl->hasTrivialCopyAssignment());
10185 
10186   // Note that we have added this copy-assignment operator.
10187   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10188 
10189   Scope *S = getScopeForContext(ClassDecl);
10190   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
10191 
10192   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10193     SetDeclDeleted(CopyAssignment, ClassLoc);
10194 
10195   if (S)
10196     PushOnScopeChains(CopyAssignment, S, false);
10197   ClassDecl->addDecl(CopyAssignment);
10198 
10199   return CopyAssignment;
10200 }
10201 
10202 /// Diagnose an implicit copy operation for a class which is odr-used, but
10203 /// which is deprecated because the class has a user-declared copy constructor,
10204 /// copy assignment operator, or destructor.
10205 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10206                                             SourceLocation UseLoc) {
10207   assert(CopyOp->isImplicit());
10208 
10209   CXXRecordDecl *RD = CopyOp->getParent();
10210   CXXMethodDecl *UserDeclaredOperation = nullptr;
10211 
10212   // In Microsoft mode, assignment operations don't affect constructors and
10213   // vice versa.
10214   if (RD->hasUserDeclaredDestructor()) {
10215     UserDeclaredOperation = RD->getDestructor();
10216   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10217              RD->hasUserDeclaredCopyConstructor() &&
10218              !S.getLangOpts().MSVCCompat) {
10219     // Find any user-declared copy constructor.
10220     for (auto *I : RD->ctors()) {
10221       if (I->isCopyConstructor()) {
10222         UserDeclaredOperation = I;
10223         break;
10224       }
10225     }
10226     assert(UserDeclaredOperation);
10227   } else if (isa<CXXConstructorDecl>(CopyOp) &&
10228              RD->hasUserDeclaredCopyAssignment() &&
10229              !S.getLangOpts().MSVCCompat) {
10230     // Find any user-declared move assignment operator.
10231     for (auto *I : RD->methods()) {
10232       if (I->isCopyAssignmentOperator()) {
10233         UserDeclaredOperation = I;
10234         break;
10235       }
10236     }
10237     assert(UserDeclaredOperation);
10238   }
10239 
10240   if (UserDeclaredOperation) {
10241     S.Diag(UserDeclaredOperation->getLocation(),
10242          diag::warn_deprecated_copy_operation)
10243       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10244       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10245     S.Diag(UseLoc, diag::note_member_synthesized_at)
10246       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10247                                           : Sema::CXXCopyAssignment)
10248       << RD;
10249   }
10250 }
10251 
10252 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10253                                         CXXMethodDecl *CopyAssignOperator) {
10254   assert((CopyAssignOperator->isDefaulted() &&
10255           CopyAssignOperator->isOverloadedOperator() &&
10256           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10257           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10258           !CopyAssignOperator->isDeleted()) &&
10259          "DefineImplicitCopyAssignment called for wrong function");
10260 
10261   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10262 
10263   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10264     CopyAssignOperator->setInvalidDecl();
10265     return;
10266   }
10267 
10268   // C++11 [class.copy]p18:
10269   //   The [definition of an implicitly declared copy assignment operator] is
10270   //   deprecated if the class has a user-declared copy constructor or a
10271   //   user-declared destructor.
10272   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10273     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10274 
10275   CopyAssignOperator->markUsed(Context);
10276 
10277   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10278   DiagnosticErrorTrap Trap(Diags);
10279 
10280   // C++0x [class.copy]p30:
10281   //   The implicitly-defined or explicitly-defaulted copy assignment operator
10282   //   for a non-union class X performs memberwise copy assignment of its
10283   //   subobjects. The direct base classes of X are assigned first, in the
10284   //   order of their declaration in the base-specifier-list, and then the
10285   //   immediate non-static data members of X are assigned, in the order in
10286   //   which they were declared in the class definition.
10287 
10288   // The statements that form the synthesized function body.
10289   SmallVector<Stmt*, 8> Statements;
10290 
10291   // The parameter for the "other" object, which we are copying from.
10292   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10293   Qualifiers OtherQuals = Other->getType().getQualifiers();
10294   QualType OtherRefType = Other->getType();
10295   if (const LValueReferenceType *OtherRef
10296                                 = OtherRefType->getAs<LValueReferenceType>()) {
10297     OtherRefType = OtherRef->getPointeeType();
10298     OtherQuals = OtherRefType.getQualifiers();
10299   }
10300 
10301   // Our location for everything implicitly-generated.
10302   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10303                            ? CopyAssignOperator->getLocEnd()
10304                            : CopyAssignOperator->getLocation();
10305 
10306   // Builds a DeclRefExpr for the "other" object.
10307   RefBuilder OtherRef(Other, OtherRefType);
10308 
10309   // Builds the "this" pointer.
10310   ThisBuilder This;
10311 
10312   // Assign base classes.
10313   bool Invalid = false;
10314   for (auto &Base : ClassDecl->bases()) {
10315     // Form the assignment:
10316     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10317     QualType BaseType = Base.getType().getUnqualifiedType();
10318     if (!BaseType->isRecordType()) {
10319       Invalid = true;
10320       continue;
10321     }
10322 
10323     CXXCastPath BasePath;
10324     BasePath.push_back(&Base);
10325 
10326     // Construct the "from" expression, which is an implicit cast to the
10327     // appropriately-qualified base type.
10328     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10329                      VK_LValue, BasePath);
10330 
10331     // Dereference "this".
10332     DerefBuilder DerefThis(This);
10333     CastBuilder To(DerefThis,
10334                    Context.getCVRQualifiedType(
10335                        BaseType, CopyAssignOperator->getTypeQualifiers()),
10336                    VK_LValue, BasePath);
10337 
10338     // Build the copy.
10339     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10340                                             To, From,
10341                                             /*CopyingBaseSubobject=*/true,
10342                                             /*Copying=*/true);
10343     if (Copy.isInvalid()) {
10344       Diag(CurrentLocation, diag::note_member_synthesized_at)
10345         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10346       CopyAssignOperator->setInvalidDecl();
10347       return;
10348     }
10349 
10350     // Success! Record the copy.
10351     Statements.push_back(Copy.getAs<Expr>());
10352   }
10353 
10354   // Assign non-static members.
10355   for (auto *Field : ClassDecl->fields()) {
10356     // FIXME: We should form some kind of AST representation for the implied
10357     // memcpy in a union copy operation.
10358     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10359       continue;
10360 
10361     if (Field->isInvalidDecl()) {
10362       Invalid = true;
10363       continue;
10364     }
10365 
10366     // Check for members of reference type; we can't copy those.
10367     if (Field->getType()->isReferenceType()) {
10368       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10369         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10370       Diag(Field->getLocation(), diag::note_declared_at);
10371       Diag(CurrentLocation, diag::note_member_synthesized_at)
10372         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10373       Invalid = true;
10374       continue;
10375     }
10376 
10377     // Check for members of const-qualified, non-class type.
10378     QualType BaseType = Context.getBaseElementType(Field->getType());
10379     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10380       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10381         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10382       Diag(Field->getLocation(), diag::note_declared_at);
10383       Diag(CurrentLocation, diag::note_member_synthesized_at)
10384         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10385       Invalid = true;
10386       continue;
10387     }
10388 
10389     // Suppress assigning zero-width bitfields.
10390     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10391       continue;
10392 
10393     QualType FieldType = Field->getType().getNonReferenceType();
10394     if (FieldType->isIncompleteArrayType()) {
10395       assert(ClassDecl->hasFlexibleArrayMember() &&
10396              "Incomplete array type is not valid");
10397       continue;
10398     }
10399 
10400     // Build references to the field in the object we're copying from and to.
10401     CXXScopeSpec SS; // Intentionally empty
10402     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10403                               LookupMemberName);
10404     MemberLookup.addDecl(Field);
10405     MemberLookup.resolveKind();
10406 
10407     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10408 
10409     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10410 
10411     // Build the copy of this field.
10412     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10413                                             To, From,
10414                                             /*CopyingBaseSubobject=*/false,
10415                                             /*Copying=*/true);
10416     if (Copy.isInvalid()) {
10417       Diag(CurrentLocation, diag::note_member_synthesized_at)
10418         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10419       CopyAssignOperator->setInvalidDecl();
10420       return;
10421     }
10422 
10423     // Success! Record the copy.
10424     Statements.push_back(Copy.getAs<Stmt>());
10425   }
10426 
10427   if (!Invalid) {
10428     // Add a "return *this;"
10429     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10430 
10431     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10432     if (Return.isInvalid())
10433       Invalid = true;
10434     else {
10435       Statements.push_back(Return.getAs<Stmt>());
10436 
10437       if (Trap.hasErrorOccurred()) {
10438         Diag(CurrentLocation, diag::note_member_synthesized_at)
10439           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10440         Invalid = true;
10441       }
10442     }
10443   }
10444 
10445   // The exception specification is needed because we are defining the
10446   // function.
10447   ResolveExceptionSpec(CurrentLocation,
10448                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10449 
10450   if (Invalid) {
10451     CopyAssignOperator->setInvalidDecl();
10452     return;
10453   }
10454 
10455   StmtResult Body;
10456   {
10457     CompoundScopeRAII CompoundScope(*this);
10458     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10459                              /*isStmtExpr=*/false);
10460     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10461   }
10462   CopyAssignOperator->setBody(Body.getAs<Stmt>());
10463 
10464   if (ASTMutationListener *L = getASTMutationListener()) {
10465     L->CompletedImplicitDefinition(CopyAssignOperator);
10466   }
10467 }
10468 
10469 Sema::ImplicitExceptionSpecification
10470 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10471   CXXRecordDecl *ClassDecl = MD->getParent();
10472 
10473   ImplicitExceptionSpecification ExceptSpec(*this);
10474   if (ClassDecl->isInvalidDecl())
10475     return ExceptSpec;
10476 
10477   // C++0x [except.spec]p14:
10478   //   An implicitly declared special member function (Clause 12) shall have an
10479   //   exception-specification. [...]
10480 
10481   // It is unspecified whether or not an implicit move assignment operator
10482   // attempts to deduplicate calls to assignment operators of virtual bases are
10483   // made. As such, this exception specification is effectively unspecified.
10484   // Based on a similar decision made for constness in C++0x, we're erring on
10485   // the side of assuming such calls to be made regardless of whether they
10486   // actually happen.
10487   // Note that a move constructor is not implicitly declared when there are
10488   // virtual bases, but it can still be user-declared and explicitly defaulted.
10489   for (const auto &Base : ClassDecl->bases()) {
10490     if (Base.isVirtual())
10491       continue;
10492 
10493     CXXRecordDecl *BaseClassDecl
10494       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10495     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10496                                                            0, false, 0))
10497       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10498   }
10499 
10500   for (const auto &Base : ClassDecl->vbases()) {
10501     CXXRecordDecl *BaseClassDecl
10502       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10503     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10504                                                            0, false, 0))
10505       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10506   }
10507 
10508   for (const auto *Field : ClassDecl->fields()) {
10509     QualType FieldType = Context.getBaseElementType(Field->getType());
10510     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10511       if (CXXMethodDecl *MoveAssign =
10512               LookupMovingAssignment(FieldClassDecl,
10513                                      FieldType.getCVRQualifiers(),
10514                                      false, 0))
10515         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10516     }
10517   }
10518 
10519   return ExceptSpec;
10520 }
10521 
10522 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10523   assert(ClassDecl->needsImplicitMoveAssignment());
10524 
10525   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10526   if (DSM.isAlreadyBeingDeclared())
10527     return nullptr;
10528 
10529   // Note: The following rules are largely analoguous to the move
10530   // constructor rules.
10531 
10532   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10533   QualType RetType = Context.getLValueReferenceType(ArgType);
10534   ArgType = Context.getRValueReferenceType(ArgType);
10535 
10536   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10537                                                      CXXMoveAssignment,
10538                                                      false);
10539 
10540   //   An implicitly-declared move assignment operator is an inline public
10541   //   member of its class.
10542   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10543   SourceLocation ClassLoc = ClassDecl->getLocation();
10544   DeclarationNameInfo NameInfo(Name, ClassLoc);
10545   CXXMethodDecl *MoveAssignment =
10546       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10547                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10548                             /*isInline=*/true, Constexpr, SourceLocation());
10549   MoveAssignment->setAccess(AS_public);
10550   MoveAssignment->setDefaulted();
10551   MoveAssignment->setImplicit();
10552 
10553   if (getLangOpts().CUDA) {
10554     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10555                                             MoveAssignment,
10556                                             /* ConstRHS */ false,
10557                                             /* Diagnose */ false);
10558   }
10559 
10560   // Build an exception specification pointing back at this member.
10561   FunctionProtoType::ExtProtoInfo EPI =
10562       getImplicitMethodEPI(*this, MoveAssignment);
10563   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10564 
10565   // Add the parameter to the operator.
10566   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10567                                                ClassLoc, ClassLoc,
10568                                                /*Id=*/nullptr, ArgType,
10569                                                /*TInfo=*/nullptr, SC_None,
10570                                                nullptr);
10571   MoveAssignment->setParams(FromParam);
10572 
10573   MoveAssignment->setTrivial(
10574     ClassDecl->needsOverloadResolutionForMoveAssignment()
10575       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10576       : ClassDecl->hasTrivialMoveAssignment());
10577 
10578   // Note that we have added this copy-assignment operator.
10579   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10580 
10581   Scope *S = getScopeForContext(ClassDecl);
10582   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
10583 
10584   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10585     ClassDecl->setImplicitMoveAssignmentIsDeleted();
10586     SetDeclDeleted(MoveAssignment, ClassLoc);
10587   }
10588 
10589   if (S)
10590     PushOnScopeChains(MoveAssignment, S, false);
10591   ClassDecl->addDecl(MoveAssignment);
10592 
10593   return MoveAssignment;
10594 }
10595 
10596 /// Check if we're implicitly defining a move assignment operator for a class
10597 /// with virtual bases. Such a move assignment might move-assign the virtual
10598 /// base multiple times.
10599 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10600                                                SourceLocation CurrentLocation) {
10601   assert(!Class->isDependentContext() && "should not define dependent move");
10602 
10603   // Only a virtual base could get implicitly move-assigned multiple times.
10604   // Only a non-trivial move assignment can observe this. We only want to
10605   // diagnose if we implicitly define an assignment operator that assigns
10606   // two base classes, both of which move-assign the same virtual base.
10607   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10608       Class->getNumBases() < 2)
10609     return;
10610 
10611   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10612   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10613   VBaseMap VBases;
10614 
10615   for (auto &BI : Class->bases()) {
10616     Worklist.push_back(&BI);
10617     while (!Worklist.empty()) {
10618       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10619       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10620 
10621       // If the base has no non-trivial move assignment operators,
10622       // we don't care about moves from it.
10623       if (!Base->hasNonTrivialMoveAssignment())
10624         continue;
10625 
10626       // If there's nothing virtual here, skip it.
10627       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10628         continue;
10629 
10630       // If we're not actually going to call a move assignment for this base,
10631       // or the selected move assignment is trivial, skip it.
10632       Sema::SpecialMemberOverloadResult *SMOR =
10633         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10634                               /*ConstArg*/false, /*VolatileArg*/false,
10635                               /*RValueThis*/true, /*ConstThis*/false,
10636                               /*VolatileThis*/false);
10637       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10638           !SMOR->getMethod()->isMoveAssignmentOperator())
10639         continue;
10640 
10641       if (BaseSpec->isVirtual()) {
10642         // We're going to move-assign this virtual base, and its move
10643         // assignment operator is not trivial. If this can happen for
10644         // multiple distinct direct bases of Class, diagnose it. (If it
10645         // only happens in one base, we'll diagnose it when synthesizing
10646         // that base class's move assignment operator.)
10647         CXXBaseSpecifier *&Existing =
10648             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10649                 .first->second;
10650         if (Existing && Existing != &BI) {
10651           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10652             << Class << Base;
10653           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10654             << (Base->getCanonicalDecl() ==
10655                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10656             << Base << Existing->getType() << Existing->getSourceRange();
10657           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10658             << (Base->getCanonicalDecl() ==
10659                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10660             << Base << BI.getType() << BaseSpec->getSourceRange();
10661 
10662           // Only diagnose each vbase once.
10663           Existing = nullptr;
10664         }
10665       } else {
10666         // Only walk over bases that have defaulted move assignment operators.
10667         // We assume that any user-provided move assignment operator handles
10668         // the multiple-moves-of-vbase case itself somehow.
10669         if (!SMOR->getMethod()->isDefaulted())
10670           continue;
10671 
10672         // We're going to move the base classes of Base. Add them to the list.
10673         for (auto &BI : Base->bases())
10674           Worklist.push_back(&BI);
10675       }
10676     }
10677   }
10678 }
10679 
10680 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10681                                         CXXMethodDecl *MoveAssignOperator) {
10682   assert((MoveAssignOperator->isDefaulted() &&
10683           MoveAssignOperator->isOverloadedOperator() &&
10684           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10685           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10686           !MoveAssignOperator->isDeleted()) &&
10687          "DefineImplicitMoveAssignment called for wrong function");
10688 
10689   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10690 
10691   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10692     MoveAssignOperator->setInvalidDecl();
10693     return;
10694   }
10695 
10696   MoveAssignOperator->markUsed(Context);
10697 
10698   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10699   DiagnosticErrorTrap Trap(Diags);
10700 
10701   // C++0x [class.copy]p28:
10702   //   The implicitly-defined or move assignment operator for a non-union class
10703   //   X performs memberwise move assignment of its subobjects. The direct base
10704   //   classes of X are assigned first, in the order of their declaration in the
10705   //   base-specifier-list, and then the immediate non-static data members of X
10706   //   are assigned, in the order in which they were declared in the class
10707   //   definition.
10708 
10709   // Issue a warning if our implicit move assignment operator will move
10710   // from a virtual base more than once.
10711   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10712 
10713   // The statements that form the synthesized function body.
10714   SmallVector<Stmt*, 8> Statements;
10715 
10716   // The parameter for the "other" object, which we are move from.
10717   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10718   QualType OtherRefType = Other->getType()->
10719       getAs<RValueReferenceType>()->getPointeeType();
10720   assert(!OtherRefType.getQualifiers() &&
10721          "Bad argument type of defaulted move assignment");
10722 
10723   // Our location for everything implicitly-generated.
10724   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10725                            ? MoveAssignOperator->getLocEnd()
10726                            : MoveAssignOperator->getLocation();
10727 
10728   // Builds a reference to the "other" object.
10729   RefBuilder OtherRef(Other, OtherRefType);
10730   // Cast to rvalue.
10731   MoveCastBuilder MoveOther(OtherRef);
10732 
10733   // Builds the "this" pointer.
10734   ThisBuilder This;
10735 
10736   // Assign base classes.
10737   bool Invalid = false;
10738   for (auto &Base : ClassDecl->bases()) {
10739     // C++11 [class.copy]p28:
10740     //   It is unspecified whether subobjects representing virtual base classes
10741     //   are assigned more than once by the implicitly-defined copy assignment
10742     //   operator.
10743     // FIXME: Do not assign to a vbase that will be assigned by some other base
10744     // class. For a move-assignment, this can result in the vbase being moved
10745     // multiple times.
10746 
10747     // Form the assignment:
10748     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10749     QualType BaseType = Base.getType().getUnqualifiedType();
10750     if (!BaseType->isRecordType()) {
10751       Invalid = true;
10752       continue;
10753     }
10754 
10755     CXXCastPath BasePath;
10756     BasePath.push_back(&Base);
10757 
10758     // Construct the "from" expression, which is an implicit cast to the
10759     // appropriately-qualified base type.
10760     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10761 
10762     // Dereference "this".
10763     DerefBuilder DerefThis(This);
10764 
10765     // Implicitly cast "this" to the appropriately-qualified base type.
10766     CastBuilder To(DerefThis,
10767                    Context.getCVRQualifiedType(
10768                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10769                    VK_LValue, BasePath);
10770 
10771     // Build the move.
10772     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10773                                             To, From,
10774                                             /*CopyingBaseSubobject=*/true,
10775                                             /*Copying=*/false);
10776     if (Move.isInvalid()) {
10777       Diag(CurrentLocation, diag::note_member_synthesized_at)
10778         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10779       MoveAssignOperator->setInvalidDecl();
10780       return;
10781     }
10782 
10783     // Success! Record the move.
10784     Statements.push_back(Move.getAs<Expr>());
10785   }
10786 
10787   // Assign non-static members.
10788   for (auto *Field : ClassDecl->fields()) {
10789     // FIXME: We should form some kind of AST representation for the implied
10790     // memcpy in a union copy operation.
10791     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10792       continue;
10793 
10794     if (Field->isInvalidDecl()) {
10795       Invalid = true;
10796       continue;
10797     }
10798 
10799     // Check for members of reference type; we can't move those.
10800     if (Field->getType()->isReferenceType()) {
10801       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10802         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10803       Diag(Field->getLocation(), diag::note_declared_at);
10804       Diag(CurrentLocation, diag::note_member_synthesized_at)
10805         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10806       Invalid = true;
10807       continue;
10808     }
10809 
10810     // Check for members of const-qualified, non-class type.
10811     QualType BaseType = Context.getBaseElementType(Field->getType());
10812     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10813       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10814         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10815       Diag(Field->getLocation(), diag::note_declared_at);
10816       Diag(CurrentLocation, diag::note_member_synthesized_at)
10817         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10818       Invalid = true;
10819       continue;
10820     }
10821 
10822     // Suppress assigning zero-width bitfields.
10823     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10824       continue;
10825 
10826     QualType FieldType = Field->getType().getNonReferenceType();
10827     if (FieldType->isIncompleteArrayType()) {
10828       assert(ClassDecl->hasFlexibleArrayMember() &&
10829              "Incomplete array type is not valid");
10830       continue;
10831     }
10832 
10833     // Build references to the field in the object we're copying from and to.
10834     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10835                               LookupMemberName);
10836     MemberLookup.addDecl(Field);
10837     MemberLookup.resolveKind();
10838     MemberBuilder From(MoveOther, OtherRefType,
10839                        /*IsArrow=*/false, MemberLookup);
10840     MemberBuilder To(This, getCurrentThisType(),
10841                      /*IsArrow=*/true, MemberLookup);
10842 
10843     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10844         "Member reference with rvalue base must be rvalue except for reference "
10845         "members, which aren't allowed for move assignment.");
10846 
10847     // Build the move of this field.
10848     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10849                                             To, From,
10850                                             /*CopyingBaseSubobject=*/false,
10851                                             /*Copying=*/false);
10852     if (Move.isInvalid()) {
10853       Diag(CurrentLocation, diag::note_member_synthesized_at)
10854         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10855       MoveAssignOperator->setInvalidDecl();
10856       return;
10857     }
10858 
10859     // Success! Record the copy.
10860     Statements.push_back(Move.getAs<Stmt>());
10861   }
10862 
10863   if (!Invalid) {
10864     // Add a "return *this;"
10865     ExprResult ThisObj =
10866         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10867 
10868     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10869     if (Return.isInvalid())
10870       Invalid = true;
10871     else {
10872       Statements.push_back(Return.getAs<Stmt>());
10873 
10874       if (Trap.hasErrorOccurred()) {
10875         Diag(CurrentLocation, diag::note_member_synthesized_at)
10876           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10877         Invalid = true;
10878       }
10879     }
10880   }
10881 
10882   // The exception specification is needed because we are defining the
10883   // function.
10884   ResolveExceptionSpec(CurrentLocation,
10885                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10886 
10887   if (Invalid) {
10888     MoveAssignOperator->setInvalidDecl();
10889     return;
10890   }
10891 
10892   StmtResult Body;
10893   {
10894     CompoundScopeRAII CompoundScope(*this);
10895     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10896                              /*isStmtExpr=*/false);
10897     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10898   }
10899   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10900 
10901   if (ASTMutationListener *L = getASTMutationListener()) {
10902     L->CompletedImplicitDefinition(MoveAssignOperator);
10903   }
10904 }
10905 
10906 Sema::ImplicitExceptionSpecification
10907 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10908   CXXRecordDecl *ClassDecl = MD->getParent();
10909 
10910   ImplicitExceptionSpecification ExceptSpec(*this);
10911   if (ClassDecl->isInvalidDecl())
10912     return ExceptSpec;
10913 
10914   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10915   assert(T->getNumParams() >= 1 && "not a copy ctor");
10916   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10917 
10918   // C++ [except.spec]p14:
10919   //   An implicitly declared special member function (Clause 12) shall have an
10920   //   exception-specification. [...]
10921   for (const auto &Base : ClassDecl->bases()) {
10922     // Virtual bases are handled below.
10923     if (Base.isVirtual())
10924       continue;
10925 
10926     CXXRecordDecl *BaseClassDecl
10927       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10928     if (CXXConstructorDecl *CopyConstructor =
10929           LookupCopyingConstructor(BaseClassDecl, Quals))
10930       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10931   }
10932   for (const auto &Base : ClassDecl->vbases()) {
10933     CXXRecordDecl *BaseClassDecl
10934       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10935     if (CXXConstructorDecl *CopyConstructor =
10936           LookupCopyingConstructor(BaseClassDecl, Quals))
10937       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10938   }
10939   for (const auto *Field : ClassDecl->fields()) {
10940     QualType FieldType = Context.getBaseElementType(Field->getType());
10941     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10942       if (CXXConstructorDecl *CopyConstructor =
10943               LookupCopyingConstructor(FieldClassDecl,
10944                                        Quals | FieldType.getCVRQualifiers()))
10945       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10946     }
10947   }
10948 
10949   return ExceptSpec;
10950 }
10951 
10952 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10953                                                     CXXRecordDecl *ClassDecl) {
10954   // C++ [class.copy]p4:
10955   //   If the class definition does not explicitly declare a copy
10956   //   constructor, one is declared implicitly.
10957   assert(ClassDecl->needsImplicitCopyConstructor());
10958 
10959   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10960   if (DSM.isAlreadyBeingDeclared())
10961     return nullptr;
10962 
10963   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10964   QualType ArgType = ClassType;
10965   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10966   if (Const)
10967     ArgType = ArgType.withConst();
10968   ArgType = Context.getLValueReferenceType(ArgType);
10969 
10970   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10971                                                      CXXCopyConstructor,
10972                                                      Const);
10973 
10974   DeclarationName Name
10975     = Context.DeclarationNames.getCXXConstructorName(
10976                                            Context.getCanonicalType(ClassType));
10977   SourceLocation ClassLoc = ClassDecl->getLocation();
10978   DeclarationNameInfo NameInfo(Name, ClassLoc);
10979 
10980   //   An implicitly-declared copy constructor is an inline public
10981   //   member of its class.
10982   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10983       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10984       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10985       Constexpr);
10986   CopyConstructor->setAccess(AS_public);
10987   CopyConstructor->setDefaulted();
10988 
10989   if (getLangOpts().CUDA) {
10990     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10991                                             CopyConstructor,
10992                                             /* ConstRHS */ Const,
10993                                             /* Diagnose */ false);
10994   }
10995 
10996   // Build an exception specification pointing back at this member.
10997   FunctionProtoType::ExtProtoInfo EPI =
10998       getImplicitMethodEPI(*this, CopyConstructor);
10999   CopyConstructor->setType(
11000       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11001 
11002   // Add the parameter to the constructor.
11003   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
11004                                                ClassLoc, ClassLoc,
11005                                                /*IdentifierInfo=*/nullptr,
11006                                                ArgType, /*TInfo=*/nullptr,
11007                                                SC_None, nullptr);
11008   CopyConstructor->setParams(FromParam);
11009 
11010   CopyConstructor->setTrivial(
11011     ClassDecl->needsOverloadResolutionForCopyConstructor()
11012       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11013       : ClassDecl->hasTrivialCopyConstructor());
11014 
11015   // Note that we have declared this constructor.
11016   ++ASTContext::NumImplicitCopyConstructorsDeclared;
11017 
11018   Scope *S = getScopeForContext(ClassDecl);
11019   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11020 
11021   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11022     SetDeclDeleted(CopyConstructor, ClassLoc);
11023 
11024   if (S)
11025     PushOnScopeChains(CopyConstructor, S, false);
11026   ClassDecl->addDecl(CopyConstructor);
11027 
11028   return CopyConstructor;
11029 }
11030 
11031 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
11032                                    CXXConstructorDecl *CopyConstructor) {
11033   assert((CopyConstructor->isDefaulted() &&
11034           CopyConstructor->isCopyConstructor() &&
11035           !CopyConstructor->doesThisDeclarationHaveABody() &&
11036           !CopyConstructor->isDeleted()) &&
11037          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
11038 
11039   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
11040   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
11041 
11042   // C++11 [class.copy]p7:
11043   //   The [definition of an implicitly declared copy constructor] is
11044   //   deprecated if the class has a user-declared copy assignment operator
11045   //   or a user-declared destructor.
11046   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11047     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11048 
11049   SynthesizedFunctionScope Scope(*this, CopyConstructor);
11050   DiagnosticErrorTrap Trap(Diags);
11051 
11052   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
11053       Trap.hasErrorOccurred()) {
11054     Diag(CurrentLocation, diag::note_member_synthesized_at)
11055       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
11056     CopyConstructor->setInvalidDecl();
11057   }  else {
11058     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11059                              ? CopyConstructor->getLocEnd()
11060                              : CopyConstructor->getLocation();
11061     Sema::CompoundScopeRAII CompoundScope(*this);
11062     CopyConstructor->setBody(
11063         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
11064   }
11065 
11066   // The exception specification is needed because we are defining the
11067   // function.
11068   ResolveExceptionSpec(CurrentLocation,
11069                        CopyConstructor->getType()->castAs<FunctionProtoType>());
11070 
11071   CopyConstructor->markUsed(Context);
11072   MarkVTableUsed(CurrentLocation, ClassDecl);
11073 
11074   if (ASTMutationListener *L = getASTMutationListener()) {
11075     L->CompletedImplicitDefinition(CopyConstructor);
11076   }
11077 }
11078 
11079 Sema::ImplicitExceptionSpecification
11080 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11081   CXXRecordDecl *ClassDecl = MD->getParent();
11082 
11083   // C++ [except.spec]p14:
11084   //   An implicitly declared special member function (Clause 12) shall have an
11085   //   exception-specification. [...]
11086   ImplicitExceptionSpecification ExceptSpec(*this);
11087   if (ClassDecl->isInvalidDecl())
11088     return ExceptSpec;
11089 
11090   // Direct base-class constructors.
11091   for (const auto &B : ClassDecl->bases()) {
11092     if (B.isVirtual()) // Handled below.
11093       continue;
11094 
11095     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11096       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11097       CXXConstructorDecl *Constructor =
11098           LookupMovingConstructor(BaseClassDecl, 0);
11099       // If this is a deleted function, add it anyway. This might be conformant
11100       // with the standard. This might not. I'm not sure. It might not matter.
11101       if (Constructor)
11102         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11103     }
11104   }
11105 
11106   // Virtual base-class constructors.
11107   for (const auto &B : ClassDecl->vbases()) {
11108     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11109       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11110       CXXConstructorDecl *Constructor =
11111           LookupMovingConstructor(BaseClassDecl, 0);
11112       // If this is a deleted function, add it anyway. This might be conformant
11113       // with the standard. This might not. I'm not sure. It might not matter.
11114       if (Constructor)
11115         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11116     }
11117   }
11118 
11119   // Field constructors.
11120   for (const auto *F : ClassDecl->fields()) {
11121     QualType FieldType = Context.getBaseElementType(F->getType());
11122     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11123       CXXConstructorDecl *Constructor =
11124           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11125       // If this is a deleted function, add it anyway. This might be conformant
11126       // with the standard. This might not. I'm not sure. It might not matter.
11127       // In particular, the problem is that this function never gets called. It
11128       // might just be ill-formed because this function attempts to refer to
11129       // a deleted function here.
11130       if (Constructor)
11131         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11132     }
11133   }
11134 
11135   return ExceptSpec;
11136 }
11137 
11138 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11139                                                     CXXRecordDecl *ClassDecl) {
11140   assert(ClassDecl->needsImplicitMoveConstructor());
11141 
11142   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11143   if (DSM.isAlreadyBeingDeclared())
11144     return nullptr;
11145 
11146   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11147   QualType ArgType = Context.getRValueReferenceType(ClassType);
11148 
11149   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11150                                                      CXXMoveConstructor,
11151                                                      false);
11152 
11153   DeclarationName Name
11154     = Context.DeclarationNames.getCXXConstructorName(
11155                                            Context.getCanonicalType(ClassType));
11156   SourceLocation ClassLoc = ClassDecl->getLocation();
11157   DeclarationNameInfo NameInfo(Name, ClassLoc);
11158 
11159   // C++11 [class.copy]p11:
11160   //   An implicitly-declared copy/move constructor is an inline public
11161   //   member of its class.
11162   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11163       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11164       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11165       Constexpr);
11166   MoveConstructor->setAccess(AS_public);
11167   MoveConstructor->setDefaulted();
11168 
11169   if (getLangOpts().CUDA) {
11170     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11171                                             MoveConstructor,
11172                                             /* ConstRHS */ false,
11173                                             /* Diagnose */ false);
11174   }
11175 
11176   // Build an exception specification pointing back at this member.
11177   FunctionProtoType::ExtProtoInfo EPI =
11178       getImplicitMethodEPI(*this, MoveConstructor);
11179   MoveConstructor->setType(
11180       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11181 
11182   // Add the parameter to the constructor.
11183   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11184                                                ClassLoc, ClassLoc,
11185                                                /*IdentifierInfo=*/nullptr,
11186                                                ArgType, /*TInfo=*/nullptr,
11187                                                SC_None, nullptr);
11188   MoveConstructor->setParams(FromParam);
11189 
11190   MoveConstructor->setTrivial(
11191     ClassDecl->needsOverloadResolutionForMoveConstructor()
11192       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11193       : ClassDecl->hasTrivialMoveConstructor());
11194 
11195   // Note that we have declared this constructor.
11196   ++ASTContext::NumImplicitMoveConstructorsDeclared;
11197 
11198   Scope *S = getScopeForContext(ClassDecl);
11199   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
11200 
11201   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11202     ClassDecl->setImplicitMoveConstructorIsDeleted();
11203     SetDeclDeleted(MoveConstructor, ClassLoc);
11204   }
11205 
11206   if (S)
11207     PushOnScopeChains(MoveConstructor, S, false);
11208   ClassDecl->addDecl(MoveConstructor);
11209 
11210   return MoveConstructor;
11211 }
11212 
11213 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11214                                    CXXConstructorDecl *MoveConstructor) {
11215   assert((MoveConstructor->isDefaulted() &&
11216           MoveConstructor->isMoveConstructor() &&
11217           !MoveConstructor->doesThisDeclarationHaveABody() &&
11218           !MoveConstructor->isDeleted()) &&
11219          "DefineImplicitMoveConstructor - call it for implicit move ctor");
11220 
11221   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11222   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11223 
11224   SynthesizedFunctionScope Scope(*this, MoveConstructor);
11225   DiagnosticErrorTrap Trap(Diags);
11226 
11227   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11228       Trap.hasErrorOccurred()) {
11229     Diag(CurrentLocation, diag::note_member_synthesized_at)
11230       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11231     MoveConstructor->setInvalidDecl();
11232   }  else {
11233     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11234                              ? MoveConstructor->getLocEnd()
11235                              : MoveConstructor->getLocation();
11236     Sema::CompoundScopeRAII CompoundScope(*this);
11237     MoveConstructor->setBody(ActOnCompoundStmt(
11238         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11239   }
11240 
11241   // The exception specification is needed because we are defining the
11242   // function.
11243   ResolveExceptionSpec(CurrentLocation,
11244                        MoveConstructor->getType()->castAs<FunctionProtoType>());
11245 
11246   MoveConstructor->markUsed(Context);
11247   MarkVTableUsed(CurrentLocation, ClassDecl);
11248 
11249   if (ASTMutationListener *L = getASTMutationListener()) {
11250     L->CompletedImplicitDefinition(MoveConstructor);
11251   }
11252 }
11253 
11254 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
11255   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11256 }
11257 
11258 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
11259                             SourceLocation CurrentLocation,
11260                             CXXConversionDecl *Conv) {
11261   CXXRecordDecl *Lambda = Conv->getParent();
11262   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11263   // If we are defining a specialization of a conversion to function-ptr
11264   // cache the deduced template arguments for this specialization
11265   // so that we can use them to retrieve the corresponding call-operator
11266   // and static-invoker.
11267   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11268 
11269   // Retrieve the corresponding call-operator specialization.
11270   if (Lambda->isGenericLambda()) {
11271     assert(Conv->isFunctionTemplateSpecialization());
11272     FunctionTemplateDecl *CallOpTemplate =
11273         CallOp->getDescribedFunctionTemplate();
11274     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11275     void *InsertPos = nullptr;
11276     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11277                                                 DeducedTemplateArgs->asArray(),
11278                                                 InsertPos);
11279     assert(CallOpSpec &&
11280           "Conversion operator must have a corresponding call operator");
11281     CallOp = cast<CXXMethodDecl>(CallOpSpec);
11282   }
11283   // Mark the call operator referenced (and add to pending instantiations
11284   // if necessary).
11285   // For both the conversion and static-invoker template specializations
11286   // we construct their body's in this function, so no need to add them
11287   // to the PendingInstantiations.
11288   MarkFunctionReferenced(CurrentLocation, CallOp);
11289 
11290   SynthesizedFunctionScope Scope(*this, Conv);
11291   DiagnosticErrorTrap Trap(Diags);
11292 
11293   // Retrieve the static invoker...
11294   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11295   // ... and get the corresponding specialization for a generic lambda.
11296   if (Lambda->isGenericLambda()) {
11297     assert(DeducedTemplateArgs &&
11298       "Must have deduced template arguments from Conversion Operator");
11299     FunctionTemplateDecl *InvokeTemplate =
11300                           Invoker->getDescribedFunctionTemplate();
11301     void *InsertPos = nullptr;
11302     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11303                                                 DeducedTemplateArgs->asArray(),
11304                                                 InsertPos);
11305     assert(InvokeSpec &&
11306       "Must have a corresponding static invoker specialization");
11307     Invoker = cast<CXXMethodDecl>(InvokeSpec);
11308   }
11309   // Construct the body of the conversion function { return __invoke; }.
11310   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11311                                         VK_LValue, Conv->getLocation()).get();
11312    assert(FunctionRef && "Can't refer to __invoke function?");
11313    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11314    Conv->setBody(new (Context) CompoundStmt(Context, Return,
11315                                             Conv->getLocation(),
11316                                             Conv->getLocation()));
11317 
11318   Conv->markUsed(Context);
11319   Conv->setReferenced();
11320 
11321   // Fill in the __invoke function with a dummy implementation. IR generation
11322   // will fill in the actual details.
11323   Invoker->markUsed(Context);
11324   Invoker->setReferenced();
11325   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11326 
11327   if (ASTMutationListener *L = getASTMutationListener()) {
11328     L->CompletedImplicitDefinition(Conv);
11329     L->CompletedImplicitDefinition(Invoker);
11330    }
11331 }
11332 
11333 
11334 
11335 void Sema::DefineImplicitLambdaToBlockPointerConversion(
11336        SourceLocation CurrentLocation,
11337        CXXConversionDecl *Conv)
11338 {
11339   assert(!Conv->getParent()->isGenericLambda());
11340 
11341   Conv->markUsed(Context);
11342 
11343   SynthesizedFunctionScope Scope(*this, Conv);
11344   DiagnosticErrorTrap Trap(Diags);
11345 
11346   // Copy-initialize the lambda object as needed to capture it.
11347   Expr *This = ActOnCXXThis(CurrentLocation).get();
11348   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11349 
11350   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11351                                                         Conv->getLocation(),
11352                                                         Conv, DerefThis);
11353 
11354   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11355   // behavior.  Note that only the general conversion function does this
11356   // (since it's unusable otherwise); in the case where we inline the
11357   // block literal, it has block literal lifetime semantics.
11358   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11359     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11360                                           CK_CopyAndAutoreleaseBlockObject,
11361                                           BuildBlock.get(), nullptr, VK_RValue);
11362 
11363   if (BuildBlock.isInvalid()) {
11364     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11365     Conv->setInvalidDecl();
11366     return;
11367   }
11368 
11369   // Create the return statement that returns the block from the conversion
11370   // function.
11371   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11372   if (Return.isInvalid()) {
11373     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11374     Conv->setInvalidDecl();
11375     return;
11376   }
11377 
11378   // Set the body of the conversion function.
11379   Stmt *ReturnS = Return.get();
11380   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11381                                            Conv->getLocation(),
11382                                            Conv->getLocation()));
11383 
11384   // We're done; notify the mutation listener, if any.
11385   if (ASTMutationListener *L = getASTMutationListener()) {
11386     L->CompletedImplicitDefinition(Conv);
11387   }
11388 }
11389 
11390 /// \brief Determine whether the given list arguments contains exactly one
11391 /// "real" (non-default) argument.
11392 static bool hasOneRealArgument(MultiExprArg Args) {
11393   switch (Args.size()) {
11394   case 0:
11395     return false;
11396 
11397   default:
11398     if (!Args[1]->isDefaultArgument())
11399       return false;
11400 
11401     // fall through
11402   case 1:
11403     return !Args[0]->isDefaultArgument();
11404   }
11405 
11406   return false;
11407 }
11408 
11409 ExprResult
11410 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11411                             NamedDecl *FoundDecl,
11412                             CXXConstructorDecl *Constructor,
11413                             MultiExprArg ExprArgs,
11414                             bool HadMultipleCandidates,
11415                             bool IsListInitialization,
11416                             bool IsStdInitListInitialization,
11417                             bool RequiresZeroInit,
11418                             unsigned ConstructKind,
11419                             SourceRange ParenRange) {
11420   bool Elidable = false;
11421 
11422   // C++0x [class.copy]p34:
11423   //   When certain criteria are met, an implementation is allowed to
11424   //   omit the copy/move construction of a class object, even if the
11425   //   copy/move constructor and/or destructor for the object have
11426   //   side effects. [...]
11427   //     - when a temporary class object that has not been bound to a
11428   //       reference (12.2) would be copied/moved to a class object
11429   //       with the same cv-unqualified type, the copy/move operation
11430   //       can be omitted by constructing the temporary object
11431   //       directly into the target of the omitted copy/move
11432   if (ConstructKind == CXXConstructExpr::CK_Complete &&
11433       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11434     Expr *SubExpr = ExprArgs[0];
11435     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11436   }
11437 
11438   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
11439                                FoundDecl, Constructor,
11440                                Elidable, ExprArgs, HadMultipleCandidates,
11441                                IsListInitialization,
11442                                IsStdInitListInitialization, RequiresZeroInit,
11443                                ConstructKind, ParenRange);
11444 }
11445 
11446 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11447 /// including handling of its default argument expressions.
11448 ExprResult
11449 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11450                             NamedDecl *FoundDecl,
11451                             CXXConstructorDecl *Constructor,
11452                             bool Elidable,
11453                             MultiExprArg ExprArgs,
11454                             bool HadMultipleCandidates,
11455                             bool IsListInitialization,
11456                             bool IsStdInitListInitialization,
11457                             bool RequiresZeroInit,
11458                             unsigned ConstructKind,
11459                             SourceRange ParenRange) {
11460   MarkFunctionReferenced(ConstructLoc, Constructor);
11461   return CXXConstructExpr::Create(
11462       Context, DeclInitType, ConstructLoc, FoundDecl, Constructor, Elidable,
11463       ExprArgs, HadMultipleCandidates, IsListInitialization,
11464       IsStdInitListInitialization, RequiresZeroInit,
11465       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11466       ParenRange);
11467 }
11468 
11469 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11470   assert(Field->hasInClassInitializer());
11471 
11472   // If we already have the in-class initializer nothing needs to be done.
11473   if (Field->getInClassInitializer())
11474     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11475 
11476   // Maybe we haven't instantiated the in-class initializer. Go check the
11477   // pattern FieldDecl to see if it has one.
11478   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11479 
11480   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11481     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11482     DeclContext::lookup_result Lookup =
11483         ClassPattern->lookup(Field->getDeclName());
11484 
11485     // Lookup can return at most two results: the pattern for the field, or the
11486     // injected class name of the parent record. No other member can have the
11487     // same name as the field.
11488     assert(!Lookup.empty() && Lookup.size() <= 2 &&
11489            "more than two lookup results for field name");
11490     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
11491     if (!Pattern) {
11492       assert(isa<CXXRecordDecl>(Lookup[0]) &&
11493              "cannot have other non-field member with same name");
11494       Pattern = cast<FieldDecl>(Lookup[1]);
11495     }
11496 
11497     if (InstantiateInClassInitializer(Loc, Field, Pattern,
11498                                       getTemplateInstantiationArgs(Field)))
11499       return ExprError();
11500     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11501   }
11502 
11503   // DR1351:
11504   //   If the brace-or-equal-initializer of a non-static data member
11505   //   invokes a defaulted default constructor of its class or of an
11506   //   enclosing class in a potentially evaluated subexpression, the
11507   //   program is ill-formed.
11508   //
11509   // This resolution is unworkable: the exception specification of the
11510   // default constructor can be needed in an unevaluated context, in
11511   // particular, in the operand of a noexcept-expression, and we can be
11512   // unable to compute an exception specification for an enclosed class.
11513   //
11514   // Any attempt to resolve the exception specification of a defaulted default
11515   // constructor before the initializer is lexically complete will ultimately
11516   // come here at which point we can diagnose it.
11517   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11518   if (OutermostClass == ParentRD) {
11519     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11520         << ParentRD << Field;
11521   } else {
11522     Diag(Field->getLocEnd(),
11523          diag::err_in_class_initializer_not_yet_parsed_outer_class)
11524         << ParentRD << OutermostClass << Field;
11525   }
11526 
11527   return ExprError();
11528 }
11529 
11530 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11531   if (VD->isInvalidDecl()) return;
11532 
11533   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11534   if (ClassDecl->isInvalidDecl()) return;
11535   if (ClassDecl->hasIrrelevantDestructor()) return;
11536   if (ClassDecl->isDependentContext()) return;
11537 
11538   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11539   MarkFunctionReferenced(VD->getLocation(), Destructor);
11540   CheckDestructorAccess(VD->getLocation(), Destructor,
11541                         PDiag(diag::err_access_dtor_var)
11542                         << VD->getDeclName()
11543                         << VD->getType());
11544   DiagnoseUseOfDecl(Destructor, VD->getLocation());
11545 
11546   if (Destructor->isTrivial()) return;
11547   if (!VD->hasGlobalStorage()) return;
11548 
11549   // Emit warning for non-trivial dtor in global scope (a real global,
11550   // class-static, function-static).
11551   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11552 
11553   // TODO: this should be re-enabled for static locals by !CXAAtExit
11554   if (!VD->isStaticLocal())
11555     Diag(VD->getLocation(), diag::warn_global_destructor);
11556 }
11557 
11558 /// \brief Given a constructor and the set of arguments provided for the
11559 /// constructor, convert the arguments and add any required default arguments
11560 /// to form a proper call to this constructor.
11561 ///
11562 /// \returns true if an error occurred, false otherwise.
11563 bool
11564 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11565                               MultiExprArg ArgsPtr,
11566                               SourceLocation Loc,
11567                               SmallVectorImpl<Expr*> &ConvertedArgs,
11568                               bool AllowExplicit,
11569                               bool IsListInitialization) {
11570   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11571   unsigned NumArgs = ArgsPtr.size();
11572   Expr **Args = ArgsPtr.data();
11573 
11574   const FunctionProtoType *Proto
11575     = Constructor->getType()->getAs<FunctionProtoType>();
11576   assert(Proto && "Constructor without a prototype?");
11577   unsigned NumParams = Proto->getNumParams();
11578 
11579   // If too few arguments are available, we'll fill in the rest with defaults.
11580   if (NumArgs < NumParams)
11581     ConvertedArgs.reserve(NumParams);
11582   else
11583     ConvertedArgs.reserve(NumArgs);
11584 
11585   VariadicCallType CallType =
11586     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11587   SmallVector<Expr *, 8> AllArgs;
11588   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11589                                         Proto, 0,
11590                                         llvm::makeArrayRef(Args, NumArgs),
11591                                         AllArgs,
11592                                         CallType, AllowExplicit,
11593                                         IsListInitialization);
11594   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11595 
11596   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11597 
11598   CheckConstructorCall(Constructor,
11599                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11600                        Proto, Loc);
11601 
11602   return Invalid;
11603 }
11604 
11605 static inline bool
11606 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11607                                        const FunctionDecl *FnDecl) {
11608   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11609   if (isa<NamespaceDecl>(DC)) {
11610     return SemaRef.Diag(FnDecl->getLocation(),
11611                         diag::err_operator_new_delete_declared_in_namespace)
11612       << FnDecl->getDeclName();
11613   }
11614 
11615   if (isa<TranslationUnitDecl>(DC) &&
11616       FnDecl->getStorageClass() == SC_Static) {
11617     return SemaRef.Diag(FnDecl->getLocation(),
11618                         diag::err_operator_new_delete_declared_static)
11619       << FnDecl->getDeclName();
11620   }
11621 
11622   return false;
11623 }
11624 
11625 static inline bool
11626 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11627                             CanQualType ExpectedResultType,
11628                             CanQualType ExpectedFirstParamType,
11629                             unsigned DependentParamTypeDiag,
11630                             unsigned InvalidParamTypeDiag) {
11631   QualType ResultType =
11632       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11633 
11634   // Check that the result type is not dependent.
11635   if (ResultType->isDependentType())
11636     return SemaRef.Diag(FnDecl->getLocation(),
11637                         diag::err_operator_new_delete_dependent_result_type)
11638     << FnDecl->getDeclName() << ExpectedResultType;
11639 
11640   // Check that the result type is what we expect.
11641   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11642     return SemaRef.Diag(FnDecl->getLocation(),
11643                         diag::err_operator_new_delete_invalid_result_type)
11644     << FnDecl->getDeclName() << ExpectedResultType;
11645 
11646   // A function template must have at least 2 parameters.
11647   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11648     return SemaRef.Diag(FnDecl->getLocation(),
11649                       diag::err_operator_new_delete_template_too_few_parameters)
11650         << FnDecl->getDeclName();
11651 
11652   // The function decl must have at least 1 parameter.
11653   if (FnDecl->getNumParams() == 0)
11654     return SemaRef.Diag(FnDecl->getLocation(),
11655                         diag::err_operator_new_delete_too_few_parameters)
11656       << FnDecl->getDeclName();
11657 
11658   // Check the first parameter type is not dependent.
11659   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11660   if (FirstParamType->isDependentType())
11661     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11662       << FnDecl->getDeclName() << ExpectedFirstParamType;
11663 
11664   // Check that the first parameter type is what we expect.
11665   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11666       ExpectedFirstParamType)
11667     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11668     << FnDecl->getDeclName() << ExpectedFirstParamType;
11669 
11670   return false;
11671 }
11672 
11673 static bool
11674 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11675   // C++ [basic.stc.dynamic.allocation]p1:
11676   //   A program is ill-formed if an allocation function is declared in a
11677   //   namespace scope other than global scope or declared static in global
11678   //   scope.
11679   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11680     return true;
11681 
11682   CanQualType SizeTy =
11683     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11684 
11685   // C++ [basic.stc.dynamic.allocation]p1:
11686   //  The return type shall be void*. The first parameter shall have type
11687   //  std::size_t.
11688   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11689                                   SizeTy,
11690                                   diag::err_operator_new_dependent_param_type,
11691                                   diag::err_operator_new_param_type))
11692     return true;
11693 
11694   // C++ [basic.stc.dynamic.allocation]p1:
11695   //  The first parameter shall not have an associated default argument.
11696   if (FnDecl->getParamDecl(0)->hasDefaultArg())
11697     return SemaRef.Diag(FnDecl->getLocation(),
11698                         diag::err_operator_new_default_arg)
11699       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11700 
11701   return false;
11702 }
11703 
11704 static bool
11705 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11706   // C++ [basic.stc.dynamic.deallocation]p1:
11707   //   A program is ill-formed if deallocation functions are declared in a
11708   //   namespace scope other than global scope or declared static in global
11709   //   scope.
11710   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11711     return true;
11712 
11713   // C++ [basic.stc.dynamic.deallocation]p2:
11714   //   Each deallocation function shall return void and its first parameter
11715   //   shall be void*.
11716   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11717                                   SemaRef.Context.VoidPtrTy,
11718                                  diag::err_operator_delete_dependent_param_type,
11719                                  diag::err_operator_delete_param_type))
11720     return true;
11721 
11722   return false;
11723 }
11724 
11725 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11726 /// of this overloaded operator is well-formed. If so, returns false;
11727 /// otherwise, emits appropriate diagnostics and returns true.
11728 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11729   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11730          "Expected an overloaded operator declaration");
11731 
11732   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11733 
11734   // C++ [over.oper]p5:
11735   //   The allocation and deallocation functions, operator new,
11736   //   operator new[], operator delete and operator delete[], are
11737   //   described completely in 3.7.3. The attributes and restrictions
11738   //   found in the rest of this subclause do not apply to them unless
11739   //   explicitly stated in 3.7.3.
11740   if (Op == OO_Delete || Op == OO_Array_Delete)
11741     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11742 
11743   if (Op == OO_New || Op == OO_Array_New)
11744     return CheckOperatorNewDeclaration(*this, FnDecl);
11745 
11746   // C++ [over.oper]p6:
11747   //   An operator function shall either be a non-static member
11748   //   function or be a non-member function and have at least one
11749   //   parameter whose type is a class, a reference to a class, an
11750   //   enumeration, or a reference to an enumeration.
11751   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11752     if (MethodDecl->isStatic())
11753       return Diag(FnDecl->getLocation(),
11754                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11755   } else {
11756     bool ClassOrEnumParam = false;
11757     for (auto Param : FnDecl->params()) {
11758       QualType ParamType = Param->getType().getNonReferenceType();
11759       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11760           ParamType->isEnumeralType()) {
11761         ClassOrEnumParam = true;
11762         break;
11763       }
11764     }
11765 
11766     if (!ClassOrEnumParam)
11767       return Diag(FnDecl->getLocation(),
11768                   diag::err_operator_overload_needs_class_or_enum)
11769         << FnDecl->getDeclName();
11770   }
11771 
11772   // C++ [over.oper]p8:
11773   //   An operator function cannot have default arguments (8.3.6),
11774   //   except where explicitly stated below.
11775   //
11776   // Only the function-call operator allows default arguments
11777   // (C++ [over.call]p1).
11778   if (Op != OO_Call) {
11779     for (auto Param : FnDecl->params()) {
11780       if (Param->hasDefaultArg())
11781         return Diag(Param->getLocation(),
11782                     diag::err_operator_overload_default_arg)
11783           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11784     }
11785   }
11786 
11787   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11788     { false, false, false }
11789 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11790     , { Unary, Binary, MemberOnly }
11791 #include "clang/Basic/OperatorKinds.def"
11792   };
11793 
11794   bool CanBeUnaryOperator = OperatorUses[Op][0];
11795   bool CanBeBinaryOperator = OperatorUses[Op][1];
11796   bool MustBeMemberOperator = OperatorUses[Op][2];
11797 
11798   // C++ [over.oper]p8:
11799   //   [...] Operator functions cannot have more or fewer parameters
11800   //   than the number required for the corresponding operator, as
11801   //   described in the rest of this subclause.
11802   unsigned NumParams = FnDecl->getNumParams()
11803                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11804   if (Op != OO_Call &&
11805       ((NumParams == 1 && !CanBeUnaryOperator) ||
11806        (NumParams == 2 && !CanBeBinaryOperator) ||
11807        (NumParams < 1) || (NumParams > 2))) {
11808     // We have the wrong number of parameters.
11809     unsigned ErrorKind;
11810     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11811       ErrorKind = 2;  // 2 -> unary or binary.
11812     } else if (CanBeUnaryOperator) {
11813       ErrorKind = 0;  // 0 -> unary
11814     } else {
11815       assert(CanBeBinaryOperator &&
11816              "All non-call overloaded operators are unary or binary!");
11817       ErrorKind = 1;  // 1 -> binary
11818     }
11819 
11820     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11821       << FnDecl->getDeclName() << NumParams << ErrorKind;
11822   }
11823 
11824   // Overloaded operators other than operator() cannot be variadic.
11825   if (Op != OO_Call &&
11826       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11827     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11828       << FnDecl->getDeclName();
11829   }
11830 
11831   // Some operators must be non-static member functions.
11832   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11833     return Diag(FnDecl->getLocation(),
11834                 diag::err_operator_overload_must_be_member)
11835       << FnDecl->getDeclName();
11836   }
11837 
11838   // C++ [over.inc]p1:
11839   //   The user-defined function called operator++ implements the
11840   //   prefix and postfix ++ operator. If this function is a member
11841   //   function with no parameters, or a non-member function with one
11842   //   parameter of class or enumeration type, it defines the prefix
11843   //   increment operator ++ for objects of that type. If the function
11844   //   is a member function with one parameter (which shall be of type
11845   //   int) or a non-member function with two parameters (the second
11846   //   of which shall be of type int), it defines the postfix
11847   //   increment operator ++ for objects of that type.
11848   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11849     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11850     QualType ParamType = LastParam->getType();
11851 
11852     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11853         !ParamType->isDependentType())
11854       return Diag(LastParam->getLocation(),
11855                   diag::err_operator_overload_post_incdec_must_be_int)
11856         << LastParam->getType() << (Op == OO_MinusMinus);
11857   }
11858 
11859   return false;
11860 }
11861 
11862 static bool
11863 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
11864                                           FunctionTemplateDecl *TpDecl) {
11865   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
11866 
11867   // Must have one or two template parameters.
11868   if (TemplateParams->size() == 1) {
11869     NonTypeTemplateParmDecl *PmDecl =
11870         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
11871 
11872     // The template parameter must be a char parameter pack.
11873     if (PmDecl && PmDecl->isTemplateParameterPack() &&
11874         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
11875       return false;
11876 
11877   } else if (TemplateParams->size() == 2) {
11878     TemplateTypeParmDecl *PmType =
11879         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
11880     NonTypeTemplateParmDecl *PmArgs =
11881         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
11882 
11883     // The second template parameter must be a parameter pack with the
11884     // first template parameter as its type.
11885     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
11886         PmArgs->isTemplateParameterPack()) {
11887       const TemplateTypeParmType *TArgs =
11888           PmArgs->getType()->getAs<TemplateTypeParmType>();
11889       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11890           TArgs->getIndex() == PmType->getIndex()) {
11891         if (SemaRef.ActiveTemplateInstantiations.empty())
11892           SemaRef.Diag(TpDecl->getLocation(),
11893                        diag::ext_string_literal_operator_template);
11894         return false;
11895       }
11896     }
11897   }
11898 
11899   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
11900                diag::err_literal_operator_template)
11901       << TpDecl->getTemplateParameters()->getSourceRange();
11902   return true;
11903 }
11904 
11905 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11906 /// of this literal operator function is well-formed. If so, returns
11907 /// false; otherwise, emits appropriate diagnostics and returns true.
11908 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11909   if (isa<CXXMethodDecl>(FnDecl)) {
11910     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11911       << FnDecl->getDeclName();
11912     return true;
11913   }
11914 
11915   if (FnDecl->isExternC()) {
11916     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11917     return true;
11918   }
11919 
11920   // This might be the definition of a literal operator template.
11921   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11922 
11923   // This might be a specialization of a literal operator template.
11924   if (!TpDecl)
11925     TpDecl = FnDecl->getPrimaryTemplate();
11926 
11927   // template <char...> type operator "" name() and
11928   // template <class T, T...> type operator "" name() are the only valid
11929   // template signatures, and the only valid signatures with no parameters.
11930   if (TpDecl) {
11931     if (FnDecl->param_size() != 0) {
11932       Diag(FnDecl->getLocation(),
11933            diag::err_literal_operator_template_with_params);
11934       return true;
11935     }
11936 
11937     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
11938       return true;
11939 
11940   } else if (FnDecl->param_size() == 1) {
11941     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
11942 
11943     QualType ParamType = Param->getType().getUnqualifiedType();
11944 
11945     // Only unsigned long long int, long double, any character type, and const
11946     // char * are allowed as the only parameters.
11947     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
11948         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
11949         Context.hasSameType(ParamType, Context.CharTy) ||
11950         Context.hasSameType(ParamType, Context.WideCharTy) ||
11951         Context.hasSameType(ParamType, Context.Char16Ty) ||
11952         Context.hasSameType(ParamType, Context.Char32Ty)) {
11953     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
11954       QualType InnerType = Ptr->getPointeeType();
11955 
11956       // Pointer parameter must be a const char *.
11957       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
11958                                 Context.CharTy) &&
11959             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
11960         Diag(Param->getSourceRange().getBegin(),
11961              diag::err_literal_operator_param)
11962             << ParamType << "'const char *'" << Param->getSourceRange();
11963         return true;
11964       }
11965 
11966     } else if (ParamType->isRealFloatingType()) {
11967       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
11968           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
11969       return true;
11970 
11971     } else if (ParamType->isIntegerType()) {
11972       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
11973           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
11974       return true;
11975 
11976     } else {
11977       Diag(Param->getSourceRange().getBegin(),
11978            diag::err_literal_operator_invalid_param)
11979           << ParamType << Param->getSourceRange();
11980       return true;
11981     }
11982 
11983   } else if (FnDecl->param_size() == 2) {
11984     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11985 
11986     // First, verify that the first parameter is correct.
11987 
11988     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
11989 
11990     // Two parameter function must have a pointer to const as a
11991     // first parameter; let's strip those qualifiers.
11992     const PointerType *PT = FirstParamType->getAs<PointerType>();
11993 
11994     if (!PT) {
11995       Diag((*Param)->getSourceRange().getBegin(),
11996            diag::err_literal_operator_param)
11997           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
11998       return true;
11999     }
12000 
12001     QualType PointeeType = PT->getPointeeType();
12002     // First parameter must be const
12003     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12004       Diag((*Param)->getSourceRange().getBegin(),
12005            diag::err_literal_operator_param)
12006           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12007       return true;
12008     }
12009 
12010     QualType InnerType = PointeeType.getUnqualifiedType();
12011     // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12012     // are allowed as the first parameter to a two-parameter function
12013     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12014           Context.hasSameType(InnerType, Context.WideCharTy) ||
12015           Context.hasSameType(InnerType, Context.Char16Ty) ||
12016           Context.hasSameType(InnerType, Context.Char32Ty))) {
12017       Diag((*Param)->getSourceRange().getBegin(),
12018            diag::err_literal_operator_param)
12019           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12020       return true;
12021     }
12022 
12023     // Move on to the second and final parameter.
12024     ++Param;
12025 
12026     // The second parameter must be a std::size_t.
12027     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12028     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12029       Diag((*Param)->getSourceRange().getBegin(),
12030            diag::err_literal_operator_param)
12031           << SecondParamType << Context.getSizeType()
12032           << (*Param)->getSourceRange();
12033       return true;
12034     }
12035   } else {
12036     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
12037     return true;
12038   }
12039 
12040   // Parameters are good.
12041 
12042   // A parameter-declaration-clause containing a default argument is not
12043   // equivalent to any of the permitted forms.
12044   for (auto Param : FnDecl->params()) {
12045     if (Param->hasDefaultArg()) {
12046       Diag(Param->getDefaultArgRange().getBegin(),
12047            diag::err_literal_operator_default_argument)
12048         << Param->getDefaultArgRange();
12049       break;
12050     }
12051   }
12052 
12053   StringRef LiteralName
12054     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12055   if (LiteralName[0] != '_') {
12056     // C++11 [usrlit.suffix]p1:
12057     //   Literal suffix identifiers that do not start with an underscore
12058     //   are reserved for future standardization.
12059     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12060       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
12061   }
12062 
12063   return false;
12064 }
12065 
12066 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12067 /// linkage specification, including the language and (if present)
12068 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
12069 /// language string literal. LBraceLoc, if valid, provides the location of
12070 /// the '{' brace. Otherwise, this linkage specification does not
12071 /// have any braces.
12072 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
12073                                            Expr *LangStr,
12074                                            SourceLocation LBraceLoc) {
12075   StringLiteral *Lit = cast<StringLiteral>(LangStr);
12076   if (!Lit->isAscii()) {
12077     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12078       << LangStr->getSourceRange();
12079     return nullptr;
12080   }
12081 
12082   StringRef Lang = Lit->getString();
12083   LinkageSpecDecl::LanguageIDs Language;
12084   if (Lang == "C")
12085     Language = LinkageSpecDecl::lang_c;
12086   else if (Lang == "C++")
12087     Language = LinkageSpecDecl::lang_cxx;
12088   else {
12089     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12090       << LangStr->getSourceRange();
12091     return nullptr;
12092   }
12093 
12094   // FIXME: Add all the various semantics of linkage specifications
12095 
12096   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12097                                                LangStr->getExprLoc(), Language,
12098                                                LBraceLoc.isValid());
12099   CurContext->addDecl(D);
12100   PushDeclContext(S, D);
12101   return D;
12102 }
12103 
12104 /// ActOnFinishLinkageSpecification - Complete the definition of
12105 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
12106 /// valid, it's the position of the closing '}' brace in a linkage
12107 /// specification that uses braces.
12108 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
12109                                             Decl *LinkageSpec,
12110                                             SourceLocation RBraceLoc) {
12111   if (RBraceLoc.isValid()) {
12112     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12113     LSDecl->setRBraceLoc(RBraceLoc);
12114   }
12115   PopDeclContext();
12116   return LinkageSpec;
12117 }
12118 
12119 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12120                                   AttributeList *AttrList,
12121                                   SourceLocation SemiLoc) {
12122   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12123   // Attribute declarations appertain to empty declaration so we handle
12124   // them here.
12125   if (AttrList)
12126     ProcessDeclAttributeList(S, ED, AttrList);
12127 
12128   CurContext->addDecl(ED);
12129   return ED;
12130 }
12131 
12132 /// \brief Perform semantic analysis for the variable declaration that
12133 /// occurs within a C++ catch clause, returning the newly-created
12134 /// variable.
12135 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
12136                                          TypeSourceInfo *TInfo,
12137                                          SourceLocation StartLoc,
12138                                          SourceLocation Loc,
12139                                          IdentifierInfo *Name) {
12140   bool Invalid = false;
12141   QualType ExDeclType = TInfo->getType();
12142 
12143   // Arrays and functions decay.
12144   if (ExDeclType->isArrayType())
12145     ExDeclType = Context.getArrayDecayedType(ExDeclType);
12146   else if (ExDeclType->isFunctionType())
12147     ExDeclType = Context.getPointerType(ExDeclType);
12148 
12149   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
12150   // The exception-declaration shall not denote a pointer or reference to an
12151   // incomplete type, other than [cv] void*.
12152   // N2844 forbids rvalue references.
12153   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
12154     Diag(Loc, diag::err_catch_rvalue_ref);
12155     Invalid = true;
12156   }
12157 
12158   QualType BaseType = ExDeclType;
12159   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
12160   unsigned DK = diag::err_catch_incomplete;
12161   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
12162     BaseType = Ptr->getPointeeType();
12163     Mode = 1;
12164     DK = diag::err_catch_incomplete_ptr;
12165   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
12166     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
12167     BaseType = Ref->getPointeeType();
12168     Mode = 2;
12169     DK = diag::err_catch_incomplete_ref;
12170   }
12171   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
12172       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
12173     Invalid = true;
12174 
12175   if (!Invalid && !ExDeclType->isDependentType() &&
12176       RequireNonAbstractType(Loc, ExDeclType,
12177                              diag::err_abstract_type_in_decl,
12178                              AbstractVariableType))
12179     Invalid = true;
12180 
12181   // Only the non-fragile NeXT runtime currently supports C++ catches
12182   // of ObjC types, and no runtime supports catching ObjC types by value.
12183   if (!Invalid && getLangOpts().ObjC1) {
12184     QualType T = ExDeclType;
12185     if (const ReferenceType *RT = T->getAs<ReferenceType>())
12186       T = RT->getPointeeType();
12187 
12188     if (T->isObjCObjectType()) {
12189       Diag(Loc, diag::err_objc_object_catch);
12190       Invalid = true;
12191     } else if (T->isObjCObjectPointerType()) {
12192       // FIXME: should this be a test for macosx-fragile specifically?
12193       if (getLangOpts().ObjCRuntime.isFragile())
12194         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12195     }
12196   }
12197 
12198   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
12199                                     ExDeclType, TInfo, SC_None);
12200   ExDecl->setExceptionVariable(true);
12201 
12202   // In ARC, infer 'retaining' for variables of retainable type.
12203   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
12204     Invalid = true;
12205 
12206   if (!Invalid && !ExDeclType->isDependentType()) {
12207     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
12208       // Insulate this from anything else we might currently be parsing.
12209       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12210 
12211       // C++ [except.handle]p16:
12212       //   The object declared in an exception-declaration or, if the
12213       //   exception-declaration does not specify a name, a temporary (12.2) is
12214       //   copy-initialized (8.5) from the exception object. [...]
12215       //   The object is destroyed when the handler exits, after the destruction
12216       //   of any automatic objects initialized within the handler.
12217       //
12218       // We just pretend to initialize the object with itself, then make sure
12219       // it can be destroyed later.
12220       QualType initType = Context.getExceptionObjectType(ExDeclType);
12221 
12222       InitializedEntity entity =
12223         InitializedEntity::InitializeVariable(ExDecl);
12224       InitializationKind initKind =
12225         InitializationKind::CreateCopy(Loc, SourceLocation());
12226 
12227       Expr *opaqueValue =
12228         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
12229       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12230       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
12231       if (result.isInvalid())
12232         Invalid = true;
12233       else {
12234         // If the constructor used was non-trivial, set this as the
12235         // "initializer".
12236         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
12237         if (!construct->getConstructor()->isTrivial()) {
12238           Expr *init = MaybeCreateExprWithCleanups(construct);
12239           ExDecl->setInit(init);
12240         }
12241 
12242         // And make sure it's destructable.
12243         FinalizeVarWithDestructor(ExDecl, recordType);
12244       }
12245     }
12246   }
12247 
12248   if (Invalid)
12249     ExDecl->setInvalidDecl();
12250 
12251   return ExDecl;
12252 }
12253 
12254 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12255 /// handler.
12256 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
12257   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12258   bool Invalid = D.isInvalidType();
12259 
12260   // Check for unexpanded parameter packs.
12261   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12262                                       UPPC_ExceptionType)) {
12263     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12264                                              D.getIdentifierLoc());
12265     Invalid = true;
12266   }
12267 
12268   IdentifierInfo *II = D.getIdentifier();
12269   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
12270                                              LookupOrdinaryName,
12271                                              ForRedeclaration)) {
12272     // The scope should be freshly made just for us. There is just no way
12273     // it contains any previous declaration, except for function parameters in
12274     // a function-try-block's catch statement.
12275     assert(!S->isDeclScope(PrevDecl));
12276     if (isDeclInScope(PrevDecl, CurContext, S)) {
12277       Diag(D.getIdentifierLoc(), diag::err_redefinition)
12278         << D.getIdentifier();
12279       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12280       Invalid = true;
12281     } else if (PrevDecl->isTemplateParameter())
12282       // Maybe we will complain about the shadowed template parameter.
12283       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12284   }
12285 
12286   if (D.getCXXScopeSpec().isSet() && !Invalid) {
12287     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12288       << D.getCXXScopeSpec().getRange();
12289     Invalid = true;
12290   }
12291 
12292   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12293                                               D.getLocStart(),
12294                                               D.getIdentifierLoc(),
12295                                               D.getIdentifier());
12296   if (Invalid)
12297     ExDecl->setInvalidDecl();
12298 
12299   // Add the exception declaration into this scope.
12300   if (II)
12301     PushOnScopeChains(ExDecl, S);
12302   else
12303     CurContext->addDecl(ExDecl);
12304 
12305   ProcessDeclAttributes(S, ExDecl, D);
12306   return ExDecl;
12307 }
12308 
12309 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12310                                          Expr *AssertExpr,
12311                                          Expr *AssertMessageExpr,
12312                                          SourceLocation RParenLoc) {
12313   StringLiteral *AssertMessage =
12314       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12315 
12316   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
12317     return nullptr;
12318 
12319   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12320                                       AssertMessage, RParenLoc, false);
12321 }
12322 
12323 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12324                                          Expr *AssertExpr,
12325                                          StringLiteral *AssertMessage,
12326                                          SourceLocation RParenLoc,
12327                                          bool Failed) {
12328   assert(AssertExpr != nullptr && "Expected non-null condition");
12329   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12330       !Failed) {
12331     // In a static_assert-declaration, the constant-expression shall be a
12332     // constant expression that can be contextually converted to bool.
12333     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12334     if (Converted.isInvalid())
12335       Failed = true;
12336 
12337     llvm::APSInt Cond;
12338     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12339           diag::err_static_assert_expression_is_not_constant,
12340           /*AllowFold=*/false).isInvalid())
12341       Failed = true;
12342 
12343     if (!Failed && !Cond) {
12344       SmallString<256> MsgBuffer;
12345       llvm::raw_svector_ostream Msg(MsgBuffer);
12346       if (AssertMessage)
12347         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12348       Diag(StaticAssertLoc, diag::err_static_assert_failed)
12349         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12350       Failed = true;
12351     }
12352   }
12353 
12354   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12355                                         AssertExpr, AssertMessage, RParenLoc,
12356                                         Failed);
12357 
12358   CurContext->addDecl(Decl);
12359   return Decl;
12360 }
12361 
12362 /// \brief Perform semantic analysis of the given friend type declaration.
12363 ///
12364 /// \returns A friend declaration that.
12365 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12366                                       SourceLocation FriendLoc,
12367                                       TypeSourceInfo *TSInfo) {
12368   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12369 
12370   QualType T = TSInfo->getType();
12371   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12372 
12373   // C++03 [class.friend]p2:
12374   //   An elaborated-type-specifier shall be used in a friend declaration
12375   //   for a class.*
12376   //
12377   //   * The class-key of the elaborated-type-specifier is required.
12378   if (!ActiveTemplateInstantiations.empty()) {
12379     // Do not complain about the form of friend template types during
12380     // template instantiation; we will already have complained when the
12381     // template was declared.
12382   } else {
12383     if (!T->isElaboratedTypeSpecifier()) {
12384       // If we evaluated the type to a record type, suggest putting
12385       // a tag in front.
12386       if (const RecordType *RT = T->getAs<RecordType>()) {
12387         RecordDecl *RD = RT->getDecl();
12388 
12389         SmallString<16> InsertionText(" ");
12390         InsertionText += RD->getKindName();
12391 
12392         Diag(TypeRange.getBegin(),
12393              getLangOpts().CPlusPlus11 ?
12394                diag::warn_cxx98_compat_unelaborated_friend_type :
12395                diag::ext_unelaborated_friend_type)
12396           << (unsigned) RD->getTagKind()
12397           << T
12398           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
12399                                         InsertionText);
12400       } else {
12401         Diag(FriendLoc,
12402              getLangOpts().CPlusPlus11 ?
12403                diag::warn_cxx98_compat_nonclass_type_friend :
12404                diag::ext_nonclass_type_friend)
12405           << T
12406           << TypeRange;
12407       }
12408     } else if (T->getAs<EnumType>()) {
12409       Diag(FriendLoc,
12410            getLangOpts().CPlusPlus11 ?
12411              diag::warn_cxx98_compat_enum_friend :
12412              diag::ext_enum_friend)
12413         << T
12414         << TypeRange;
12415     }
12416 
12417     // C++11 [class.friend]p3:
12418     //   A friend declaration that does not declare a function shall have one
12419     //   of the following forms:
12420     //     friend elaborated-type-specifier ;
12421     //     friend simple-type-specifier ;
12422     //     friend typename-specifier ;
12423     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12424       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12425   }
12426 
12427   //   If the type specifier in a friend declaration designates a (possibly
12428   //   cv-qualified) class type, that class is declared as a friend; otherwise,
12429   //   the friend declaration is ignored.
12430   return FriendDecl::Create(Context, CurContext,
12431                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
12432                             FriendLoc);
12433 }
12434 
12435 /// Handle a friend tag declaration where the scope specifier was
12436 /// templated.
12437 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12438                                     unsigned TagSpec, SourceLocation TagLoc,
12439                                     CXXScopeSpec &SS,
12440                                     IdentifierInfo *Name,
12441                                     SourceLocation NameLoc,
12442                                     AttributeList *Attr,
12443                                     MultiTemplateParamsArg TempParamLists) {
12444   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12445 
12446   bool isExplicitSpecialization = false;
12447   bool Invalid = false;
12448 
12449   if (TemplateParameterList *TemplateParams =
12450           MatchTemplateParametersToScopeSpecifier(
12451               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12452               isExplicitSpecialization, Invalid)) {
12453     if (TemplateParams->size() > 0) {
12454       // This is a declaration of a class template.
12455       if (Invalid)
12456         return nullptr;
12457 
12458       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12459                                 NameLoc, Attr, TemplateParams, AS_public,
12460                                 /*ModulePrivateLoc=*/SourceLocation(),
12461                                 FriendLoc, TempParamLists.size() - 1,
12462                                 TempParamLists.data()).get();
12463     } else {
12464       // The "template<>" header is extraneous.
12465       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12466         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12467       isExplicitSpecialization = true;
12468     }
12469   }
12470 
12471   if (Invalid) return nullptr;
12472 
12473   bool isAllExplicitSpecializations = true;
12474   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12475     if (TempParamLists[I]->size()) {
12476       isAllExplicitSpecializations = false;
12477       break;
12478     }
12479   }
12480 
12481   // FIXME: don't ignore attributes.
12482 
12483   // If it's explicit specializations all the way down, just forget
12484   // about the template header and build an appropriate non-templated
12485   // friend.  TODO: for source fidelity, remember the headers.
12486   if (isAllExplicitSpecializations) {
12487     if (SS.isEmpty()) {
12488       bool Owned = false;
12489       bool IsDependent = false;
12490       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12491                       Attr, AS_public,
12492                       /*ModulePrivateLoc=*/SourceLocation(),
12493                       MultiTemplateParamsArg(), Owned, IsDependent,
12494                       /*ScopedEnumKWLoc=*/SourceLocation(),
12495                       /*ScopedEnumUsesClassTag=*/false,
12496                       /*UnderlyingType=*/TypeResult(),
12497                       /*IsTypeSpecifier=*/false);
12498     }
12499 
12500     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12501     ElaboratedTypeKeyword Keyword
12502       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12503     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12504                                    *Name, NameLoc);
12505     if (T.isNull())
12506       return nullptr;
12507 
12508     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12509     if (isa<DependentNameType>(T)) {
12510       DependentNameTypeLoc TL =
12511           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12512       TL.setElaboratedKeywordLoc(TagLoc);
12513       TL.setQualifierLoc(QualifierLoc);
12514       TL.setNameLoc(NameLoc);
12515     } else {
12516       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12517       TL.setElaboratedKeywordLoc(TagLoc);
12518       TL.setQualifierLoc(QualifierLoc);
12519       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12520     }
12521 
12522     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12523                                             TSI, FriendLoc, TempParamLists);
12524     Friend->setAccess(AS_public);
12525     CurContext->addDecl(Friend);
12526     return Friend;
12527   }
12528 
12529   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12530 
12531 
12532 
12533   // Handle the case of a templated-scope friend class.  e.g.
12534   //   template <class T> class A<T>::B;
12535   // FIXME: we don't support these right now.
12536   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12537     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12538   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12539   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12540   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12541   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12542   TL.setElaboratedKeywordLoc(TagLoc);
12543   TL.setQualifierLoc(SS.getWithLocInContext(Context));
12544   TL.setNameLoc(NameLoc);
12545 
12546   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12547                                           TSI, FriendLoc, TempParamLists);
12548   Friend->setAccess(AS_public);
12549   Friend->setUnsupportedFriend(true);
12550   CurContext->addDecl(Friend);
12551   return Friend;
12552 }
12553 
12554 
12555 /// Handle a friend type declaration.  This works in tandem with
12556 /// ActOnTag.
12557 ///
12558 /// Notes on friend class templates:
12559 ///
12560 /// We generally treat friend class declarations as if they were
12561 /// declaring a class.  So, for example, the elaborated type specifier
12562 /// in a friend declaration is required to obey the restrictions of a
12563 /// class-head (i.e. no typedefs in the scope chain), template
12564 /// parameters are required to match up with simple template-ids, &c.
12565 /// However, unlike when declaring a template specialization, it's
12566 /// okay to refer to a template specialization without an empty
12567 /// template parameter declaration, e.g.
12568 ///   friend class A<T>::B<unsigned>;
12569 /// We permit this as a special case; if there are any template
12570 /// parameters present at all, require proper matching, i.e.
12571 ///   template <> template \<class T> friend class A<int>::B;
12572 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12573                                 MultiTemplateParamsArg TempParams) {
12574   SourceLocation Loc = DS.getLocStart();
12575 
12576   assert(DS.isFriendSpecified());
12577   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12578 
12579   // Try to convert the decl specifier to a type.  This works for
12580   // friend templates because ActOnTag never produces a ClassTemplateDecl
12581   // for a TUK_Friend.
12582   Declarator TheDeclarator(DS, Declarator::MemberContext);
12583   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12584   QualType T = TSI->getType();
12585   if (TheDeclarator.isInvalidType())
12586     return nullptr;
12587 
12588   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12589     return nullptr;
12590 
12591   // This is definitely an error in C++98.  It's probably meant to
12592   // be forbidden in C++0x, too, but the specification is just
12593   // poorly written.
12594   //
12595   // The problem is with declarations like the following:
12596   //   template <T> friend A<T>::foo;
12597   // where deciding whether a class C is a friend or not now hinges
12598   // on whether there exists an instantiation of A that causes
12599   // 'foo' to equal C.  There are restrictions on class-heads
12600   // (which we declare (by fiat) elaborated friend declarations to
12601   // be) that makes this tractable.
12602   //
12603   // FIXME: handle "template <> friend class A<T>;", which
12604   // is possibly well-formed?  Who even knows?
12605   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12606     Diag(Loc, diag::err_tagless_friend_type_template)
12607       << DS.getSourceRange();
12608     return nullptr;
12609   }
12610 
12611   // C++98 [class.friend]p1: A friend of a class is a function
12612   //   or class that is not a member of the class . . .
12613   // This is fixed in DR77, which just barely didn't make the C++03
12614   // deadline.  It's also a very silly restriction that seriously
12615   // affects inner classes and which nobody else seems to implement;
12616   // thus we never diagnose it, not even in -pedantic.
12617   //
12618   // But note that we could warn about it: it's always useless to
12619   // friend one of your own members (it's not, however, worthless to
12620   // friend a member of an arbitrary specialization of your template).
12621 
12622   Decl *D;
12623   if (unsigned NumTempParamLists = TempParams.size())
12624     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12625                                    NumTempParamLists,
12626                                    TempParams.data(),
12627                                    TSI,
12628                                    DS.getFriendSpecLoc());
12629   else
12630     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12631 
12632   if (!D)
12633     return nullptr;
12634 
12635   D->setAccess(AS_public);
12636   CurContext->addDecl(D);
12637 
12638   return D;
12639 }
12640 
12641 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12642                                         MultiTemplateParamsArg TemplateParams) {
12643   const DeclSpec &DS = D.getDeclSpec();
12644 
12645   assert(DS.isFriendSpecified());
12646   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12647 
12648   SourceLocation Loc = D.getIdentifierLoc();
12649   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12650 
12651   // C++ [class.friend]p1
12652   //   A friend of a class is a function or class....
12653   // Note that this sees through typedefs, which is intended.
12654   // It *doesn't* see through dependent types, which is correct
12655   // according to [temp.arg.type]p3:
12656   //   If a declaration acquires a function type through a
12657   //   type dependent on a template-parameter and this causes
12658   //   a declaration that does not use the syntactic form of a
12659   //   function declarator to have a function type, the program
12660   //   is ill-formed.
12661   if (!TInfo->getType()->isFunctionType()) {
12662     Diag(Loc, diag::err_unexpected_friend);
12663 
12664     // It might be worthwhile to try to recover by creating an
12665     // appropriate declaration.
12666     return nullptr;
12667   }
12668 
12669   // C++ [namespace.memdef]p3
12670   //  - If a friend declaration in a non-local class first declares a
12671   //    class or function, the friend class or function is a member
12672   //    of the innermost enclosing namespace.
12673   //  - The name of the friend is not found by simple name lookup
12674   //    until a matching declaration is provided in that namespace
12675   //    scope (either before or after the class declaration granting
12676   //    friendship).
12677   //  - If a friend function is called, its name may be found by the
12678   //    name lookup that considers functions from namespaces and
12679   //    classes associated with the types of the function arguments.
12680   //  - When looking for a prior declaration of a class or a function
12681   //    declared as a friend, scopes outside the innermost enclosing
12682   //    namespace scope are not considered.
12683 
12684   CXXScopeSpec &SS = D.getCXXScopeSpec();
12685   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12686   DeclarationName Name = NameInfo.getName();
12687   assert(Name);
12688 
12689   // Check for unexpanded parameter packs.
12690   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12691       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12692       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12693     return nullptr;
12694 
12695   // The context we found the declaration in, or in which we should
12696   // create the declaration.
12697   DeclContext *DC;
12698   Scope *DCScope = S;
12699   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12700                         ForRedeclaration);
12701 
12702   // There are five cases here.
12703   //   - There's no scope specifier and we're in a local class. Only look
12704   //     for functions declared in the immediately-enclosing block scope.
12705   // We recover from invalid scope qualifiers as if they just weren't there.
12706   FunctionDecl *FunctionContainingLocalClass = nullptr;
12707   if ((SS.isInvalid() || !SS.isSet()) &&
12708       (FunctionContainingLocalClass =
12709            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12710     // C++11 [class.friend]p11:
12711     //   If a friend declaration appears in a local class and the name
12712     //   specified is an unqualified name, a prior declaration is
12713     //   looked up without considering scopes that are outside the
12714     //   innermost enclosing non-class scope. For a friend function
12715     //   declaration, if there is no prior declaration, the program is
12716     //   ill-formed.
12717 
12718     // Find the innermost enclosing non-class scope. This is the block
12719     // scope containing the local class definition (or for a nested class,
12720     // the outer local class).
12721     DCScope = S->getFnParent();
12722 
12723     // Look up the function name in the scope.
12724     Previous.clear(LookupLocalFriendName);
12725     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12726 
12727     if (!Previous.empty()) {
12728       // All possible previous declarations must have the same context:
12729       // either they were declared at block scope or they are members of
12730       // one of the enclosing local classes.
12731       DC = Previous.getRepresentativeDecl()->getDeclContext();
12732     } else {
12733       // This is ill-formed, but provide the context that we would have
12734       // declared the function in, if we were permitted to, for error recovery.
12735       DC = FunctionContainingLocalClass;
12736     }
12737     adjustContextForLocalExternDecl(DC);
12738 
12739     // C++ [class.friend]p6:
12740     //   A function can be defined in a friend declaration of a class if and
12741     //   only if the class is a non-local class (9.8), the function name is
12742     //   unqualified, and the function has namespace scope.
12743     if (D.isFunctionDefinition()) {
12744       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12745     }
12746 
12747   //   - There's no scope specifier, in which case we just go to the
12748   //     appropriate scope and look for a function or function template
12749   //     there as appropriate.
12750   } else if (SS.isInvalid() || !SS.isSet()) {
12751     // C++11 [namespace.memdef]p3:
12752     //   If the name in a friend declaration is neither qualified nor
12753     //   a template-id and the declaration is a function or an
12754     //   elaborated-type-specifier, the lookup to determine whether
12755     //   the entity has been previously declared shall not consider
12756     //   any scopes outside the innermost enclosing namespace.
12757     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12758 
12759     // Find the appropriate context according to the above.
12760     DC = CurContext;
12761 
12762     // Skip class contexts.  If someone can cite chapter and verse
12763     // for this behavior, that would be nice --- it's what GCC and
12764     // EDG do, and it seems like a reasonable intent, but the spec
12765     // really only says that checks for unqualified existing
12766     // declarations should stop at the nearest enclosing namespace,
12767     // not that they should only consider the nearest enclosing
12768     // namespace.
12769     while (DC->isRecord())
12770       DC = DC->getParent();
12771 
12772     DeclContext *LookupDC = DC;
12773     while (LookupDC->isTransparentContext())
12774       LookupDC = LookupDC->getParent();
12775 
12776     while (true) {
12777       LookupQualifiedName(Previous, LookupDC);
12778 
12779       if (!Previous.empty()) {
12780         DC = LookupDC;
12781         break;
12782       }
12783 
12784       if (isTemplateId) {
12785         if (isa<TranslationUnitDecl>(LookupDC)) break;
12786       } else {
12787         if (LookupDC->isFileContext()) break;
12788       }
12789       LookupDC = LookupDC->getParent();
12790     }
12791 
12792     DCScope = getScopeForDeclContext(S, DC);
12793 
12794   //   - There's a non-dependent scope specifier, in which case we
12795   //     compute it and do a previous lookup there for a function
12796   //     or function template.
12797   } else if (!SS.getScopeRep()->isDependent()) {
12798     DC = computeDeclContext(SS);
12799     if (!DC) return nullptr;
12800 
12801     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12802 
12803     LookupQualifiedName(Previous, DC);
12804 
12805     // Ignore things found implicitly in the wrong scope.
12806     // TODO: better diagnostics for this case.  Suggesting the right
12807     // qualified scope would be nice...
12808     LookupResult::Filter F = Previous.makeFilter();
12809     while (F.hasNext()) {
12810       NamedDecl *D = F.next();
12811       if (!DC->InEnclosingNamespaceSetOf(
12812               D->getDeclContext()->getRedeclContext()))
12813         F.erase();
12814     }
12815     F.done();
12816 
12817     if (Previous.empty()) {
12818       D.setInvalidType();
12819       Diag(Loc, diag::err_qualified_friend_not_found)
12820           << Name << TInfo->getType();
12821       return nullptr;
12822     }
12823 
12824     // C++ [class.friend]p1: A friend of a class is a function or
12825     //   class that is not a member of the class . . .
12826     if (DC->Equals(CurContext))
12827       Diag(DS.getFriendSpecLoc(),
12828            getLangOpts().CPlusPlus11 ?
12829              diag::warn_cxx98_compat_friend_is_member :
12830              diag::err_friend_is_member);
12831 
12832     if (D.isFunctionDefinition()) {
12833       // C++ [class.friend]p6:
12834       //   A function can be defined in a friend declaration of a class if and
12835       //   only if the class is a non-local class (9.8), the function name is
12836       //   unqualified, and the function has namespace scope.
12837       SemaDiagnosticBuilder DB
12838         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12839 
12840       DB << SS.getScopeRep();
12841       if (DC->isFileContext())
12842         DB << FixItHint::CreateRemoval(SS.getRange());
12843       SS.clear();
12844     }
12845 
12846   //   - There's a scope specifier that does not match any template
12847   //     parameter lists, in which case we use some arbitrary context,
12848   //     create a method or method template, and wait for instantiation.
12849   //   - There's a scope specifier that does match some template
12850   //     parameter lists, which we don't handle right now.
12851   } else {
12852     if (D.isFunctionDefinition()) {
12853       // C++ [class.friend]p6:
12854       //   A function can be defined in a friend declaration of a class if and
12855       //   only if the class is a non-local class (9.8), the function name is
12856       //   unqualified, and the function has namespace scope.
12857       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12858         << SS.getScopeRep();
12859     }
12860 
12861     DC = CurContext;
12862     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12863   }
12864 
12865   if (!DC->isRecord()) {
12866     int DiagArg = -1;
12867     switch (D.getName().getKind()) {
12868     case UnqualifiedId::IK_ConstructorTemplateId:
12869     case UnqualifiedId::IK_ConstructorName:
12870       DiagArg = 0;
12871       break;
12872     case UnqualifiedId::IK_DestructorName:
12873       DiagArg = 1;
12874       break;
12875     case UnqualifiedId::IK_ConversionFunctionId:
12876       DiagArg = 2;
12877       break;
12878     case UnqualifiedId::IK_Identifier:
12879     case UnqualifiedId::IK_ImplicitSelfParam:
12880     case UnqualifiedId::IK_LiteralOperatorId:
12881     case UnqualifiedId::IK_OperatorFunctionId:
12882     case UnqualifiedId::IK_TemplateId:
12883       break;
12884     }
12885     // This implies that it has to be an operator or function.
12886     if (DiagArg >= 0) {
12887       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
12888       return nullptr;
12889     }
12890   }
12891 
12892   // FIXME: This is an egregious hack to cope with cases where the scope stack
12893   // does not contain the declaration context, i.e., in an out-of-line
12894   // definition of a class.
12895   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12896   if (!DCScope) {
12897     FakeDCScope.setEntity(DC);
12898     DCScope = &FakeDCScope;
12899   }
12900 
12901   bool AddToScope = true;
12902   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12903                                           TemplateParams, AddToScope);
12904   if (!ND) return nullptr;
12905 
12906   assert(ND->getLexicalDeclContext() == CurContext);
12907 
12908   // If we performed typo correction, we might have added a scope specifier
12909   // and changed the decl context.
12910   DC = ND->getDeclContext();
12911 
12912   // Add the function declaration to the appropriate lookup tables,
12913   // adjusting the redeclarations list as necessary.  We don't
12914   // want to do this yet if the friending class is dependent.
12915   //
12916   // Also update the scope-based lookup if the target context's
12917   // lookup context is in lexical scope.
12918   if (!CurContext->isDependentContext()) {
12919     DC = DC->getRedeclContext();
12920     DC->makeDeclVisibleInContext(ND);
12921     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12922       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12923   }
12924 
12925   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12926                                        D.getIdentifierLoc(), ND,
12927                                        DS.getFriendSpecLoc());
12928   FrD->setAccess(AS_public);
12929   CurContext->addDecl(FrD);
12930 
12931   if (ND->isInvalidDecl()) {
12932     FrD->setInvalidDecl();
12933   } else {
12934     if (DC->isRecord()) CheckFriendAccess(ND);
12935 
12936     FunctionDecl *FD;
12937     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12938       FD = FTD->getTemplatedDecl();
12939     else
12940       FD = cast<FunctionDecl>(ND);
12941 
12942     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12943     // default argument expression, that declaration shall be a definition
12944     // and shall be the only declaration of the function or function
12945     // template in the translation unit.
12946     if (functionDeclHasDefaultArgument(FD)) {
12947       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12948         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12949         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12950       } else if (!D.isFunctionDefinition())
12951         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12952     }
12953 
12954     // Mark templated-scope function declarations as unsupported.
12955     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12956       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12957         << SS.getScopeRep() << SS.getRange()
12958         << cast<CXXRecordDecl>(CurContext);
12959       FrD->setUnsupportedFriend(true);
12960     }
12961   }
12962 
12963   return ND;
12964 }
12965 
12966 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12967   AdjustDeclIfTemplate(Dcl);
12968 
12969   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12970   if (!Fn) {
12971     Diag(DelLoc, diag::err_deleted_non_function);
12972     return;
12973   }
12974 
12975   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12976     // Don't consider the implicit declaration we generate for explicit
12977     // specializations. FIXME: Do not generate these implicit declarations.
12978     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12979          Prev->getPreviousDecl()) &&
12980         !Prev->isDefined()) {
12981       Diag(DelLoc, diag::err_deleted_decl_not_first);
12982       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12983            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12984                               : diag::note_previous_declaration);
12985     }
12986     // If the declaration wasn't the first, we delete the function anyway for
12987     // recovery.
12988     Fn = Fn->getCanonicalDecl();
12989   }
12990 
12991   // dllimport/dllexport cannot be deleted.
12992   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12993     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12994     Fn->setInvalidDecl();
12995   }
12996 
12997   if (Fn->isDeleted())
12998     return;
12999 
13000   // See if we're deleting a function which is already known to override a
13001   // non-deleted virtual function.
13002   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13003     bool IssuedDiagnostic = false;
13004     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13005                                         E = MD->end_overridden_methods();
13006          I != E; ++I) {
13007       if (!(*MD->begin_overridden_methods())->isDeleted()) {
13008         if (!IssuedDiagnostic) {
13009           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13010           IssuedDiagnostic = true;
13011         }
13012         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13013       }
13014     }
13015   }
13016 
13017   // C++11 [basic.start.main]p3:
13018   //   A program that defines main as deleted [...] is ill-formed.
13019   if (Fn->isMain())
13020     Diag(DelLoc, diag::err_deleted_main);
13021 
13022   Fn->setDeletedAsWritten();
13023 }
13024 
13025 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
13026   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
13027 
13028   if (MD) {
13029     if (MD->getParent()->isDependentType()) {
13030       MD->setDefaulted();
13031       MD->setExplicitlyDefaulted();
13032       return;
13033     }
13034 
13035     CXXSpecialMember Member = getSpecialMember(MD);
13036     if (Member == CXXInvalid) {
13037       if (!MD->isInvalidDecl())
13038         Diag(DefaultLoc, diag::err_default_special_members);
13039       return;
13040     }
13041 
13042     MD->setDefaulted();
13043     MD->setExplicitlyDefaulted();
13044 
13045     // If this definition appears within the record, do the checking when
13046     // the record is complete.
13047     const FunctionDecl *Primary = MD;
13048     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
13049       // Find the uninstantiated declaration that actually had the '= default'
13050       // on it.
13051       Pattern->isDefined(Primary);
13052 
13053     // If the method was defaulted on its first declaration, we will have
13054     // already performed the checking in CheckCompletedCXXClass. Such a
13055     // declaration doesn't trigger an implicit definition.
13056     if (Primary == Primary->getCanonicalDecl())
13057       return;
13058 
13059     CheckExplicitlyDefaultedSpecialMember(MD);
13060 
13061     if (MD->isInvalidDecl())
13062       return;
13063 
13064     switch (Member) {
13065     case CXXDefaultConstructor:
13066       DefineImplicitDefaultConstructor(DefaultLoc,
13067                                        cast<CXXConstructorDecl>(MD));
13068       break;
13069     case CXXCopyConstructor:
13070       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
13071       break;
13072     case CXXCopyAssignment:
13073       DefineImplicitCopyAssignment(DefaultLoc, MD);
13074       break;
13075     case CXXDestructor:
13076       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
13077       break;
13078     case CXXMoveConstructor:
13079       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
13080       break;
13081     case CXXMoveAssignment:
13082       DefineImplicitMoveAssignment(DefaultLoc, MD);
13083       break;
13084     case CXXInvalid:
13085       llvm_unreachable("Invalid special member.");
13086     }
13087   } else {
13088     Diag(DefaultLoc, diag::err_default_special_members);
13089   }
13090 }
13091 
13092 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
13093   for (Stmt *SubStmt : S->children()) {
13094     if (!SubStmt)
13095       continue;
13096     if (isa<ReturnStmt>(SubStmt))
13097       Self.Diag(SubStmt->getLocStart(),
13098            diag::err_return_in_constructor_handler);
13099     if (!isa<Expr>(SubStmt))
13100       SearchForReturnInStmt(Self, SubStmt);
13101   }
13102 }
13103 
13104 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13105   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13106     CXXCatchStmt *Handler = TryBlock->getHandler(I);
13107     SearchForReturnInStmt(*this, Handler);
13108   }
13109 }
13110 
13111 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
13112                                              const CXXMethodDecl *Old) {
13113   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13114   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13115 
13116   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13117 
13118   // If the calling conventions match, everything is fine
13119   if (NewCC == OldCC)
13120     return false;
13121 
13122   // If the calling conventions mismatch because the new function is static,
13123   // suppress the calling convention mismatch error; the error about static
13124   // function override (err_static_overrides_virtual from
13125   // Sema::CheckFunctionDeclaration) is more clear.
13126   if (New->getStorageClass() == SC_Static)
13127     return false;
13128 
13129   Diag(New->getLocation(),
13130        diag::err_conflicting_overriding_cc_attributes)
13131     << New->getDeclName() << New->getType() << Old->getType();
13132   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13133   return true;
13134 }
13135 
13136 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
13137                                              const CXXMethodDecl *Old) {
13138   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13139   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
13140 
13141   if (Context.hasSameType(NewTy, OldTy) ||
13142       NewTy->isDependentType() || OldTy->isDependentType())
13143     return false;
13144 
13145   // Check if the return types are covariant
13146   QualType NewClassTy, OldClassTy;
13147 
13148   /// Both types must be pointers or references to classes.
13149   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13150     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
13151       NewClassTy = NewPT->getPointeeType();
13152       OldClassTy = OldPT->getPointeeType();
13153     }
13154   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
13155     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
13156       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
13157         NewClassTy = NewRT->getPointeeType();
13158         OldClassTy = OldRT->getPointeeType();
13159       }
13160     }
13161   }
13162 
13163   // The return types aren't either both pointers or references to a class type.
13164   if (NewClassTy.isNull()) {
13165     Diag(New->getLocation(),
13166          diag::err_different_return_type_for_overriding_virtual_function)
13167         << New->getDeclName() << NewTy << OldTy
13168         << New->getReturnTypeSourceRange();
13169     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13170         << Old->getReturnTypeSourceRange();
13171 
13172     return true;
13173   }
13174 
13175   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
13176     // C++14 [class.virtual]p8:
13177     //   If the class type in the covariant return type of D::f differs from
13178     //   that of B::f, the class type in the return type of D::f shall be
13179     //   complete at the point of declaration of D::f or shall be the class
13180     //   type D.
13181     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
13182       if (!RT->isBeingDefined() &&
13183           RequireCompleteType(New->getLocation(), NewClassTy,
13184                               diag::err_covariant_return_incomplete,
13185                               New->getDeclName()))
13186         return true;
13187     }
13188 
13189     // Check if the new class derives from the old class.
13190     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
13191       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
13192           << New->getDeclName() << NewTy << OldTy
13193           << New->getReturnTypeSourceRange();
13194       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13195           << Old->getReturnTypeSourceRange();
13196       return true;
13197     }
13198 
13199     // Check if we the conversion from derived to base is valid.
13200     if (CheckDerivedToBaseConversion(
13201             NewClassTy, OldClassTy,
13202             diag::err_covariant_return_inaccessible_base,
13203             diag::err_covariant_return_ambiguous_derived_to_base_conv,
13204             New->getLocation(), New->getReturnTypeSourceRange(),
13205             New->getDeclName(), nullptr)) {
13206       // FIXME: this note won't trigger for delayed access control
13207       // diagnostics, and it's impossible to get an undelayed error
13208       // here from access control during the original parse because
13209       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13210       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13211           << Old->getReturnTypeSourceRange();
13212       return true;
13213     }
13214   }
13215 
13216   // The qualifiers of the return types must be the same.
13217   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13218     Diag(New->getLocation(),
13219          diag::err_covariant_return_type_different_qualifications)
13220         << New->getDeclName() << NewTy << OldTy
13221         << New->getReturnTypeSourceRange();
13222     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13223         << Old->getReturnTypeSourceRange();
13224     return true;
13225   }
13226 
13227 
13228   // The new class type must have the same or less qualifiers as the old type.
13229   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13230     Diag(New->getLocation(),
13231          diag::err_covariant_return_type_class_type_more_qualified)
13232         << New->getDeclName() << NewTy << OldTy
13233         << New->getReturnTypeSourceRange();
13234     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13235         << Old->getReturnTypeSourceRange();
13236     return true;
13237   }
13238 
13239   return false;
13240 }
13241 
13242 /// \brief Mark the given method pure.
13243 ///
13244 /// \param Method the method to be marked pure.
13245 ///
13246 /// \param InitRange the source range that covers the "0" initializer.
13247 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
13248   SourceLocation EndLoc = InitRange.getEnd();
13249   if (EndLoc.isValid())
13250     Method->setRangeEnd(EndLoc);
13251 
13252   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13253     Method->setPure();
13254     return false;
13255   }
13256 
13257   if (!Method->isInvalidDecl())
13258     Diag(Method->getLocation(), diag::err_non_virtual_pure)
13259       << Method->getDeclName() << InitRange;
13260   return true;
13261 }
13262 
13263 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
13264   if (D->getFriendObjectKind())
13265     Diag(D->getLocation(), diag::err_pure_friend);
13266   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13267     CheckPureMethod(M, ZeroLoc);
13268   else
13269     Diag(D->getLocation(), diag::err_illegal_initializer);
13270 }
13271 
13272 /// \brief Determine whether the given declaration is a static data member.
13273 static bool isStaticDataMember(const Decl *D) {
13274   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13275     return Var->isStaticDataMember();
13276 
13277   return false;
13278 }
13279 
13280 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13281 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
13282 /// is a fresh scope pushed for just this purpose.
13283 ///
13284 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13285 /// static data member of class X, names should be looked up in the scope of
13286 /// class X.
13287 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
13288   // If there is no declaration, there was an error parsing it.
13289   if (!D || D->isInvalidDecl())
13290     return;
13291 
13292   // We will always have a nested name specifier here, but this declaration
13293   // might not be out of line if the specifier names the current namespace:
13294   //   extern int n;
13295   //   int ::n = 0;
13296   if (D->isOutOfLine())
13297     EnterDeclaratorContext(S, D->getDeclContext());
13298 
13299   // If we are parsing the initializer for a static data member, push a
13300   // new expression evaluation context that is associated with this static
13301   // data member.
13302   if (isStaticDataMember(D))
13303     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
13304 }
13305 
13306 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
13307 /// initializer for the out-of-line declaration 'D'.
13308 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
13309   // If there is no declaration, there was an error parsing it.
13310   if (!D || D->isInvalidDecl())
13311     return;
13312 
13313   if (isStaticDataMember(D))
13314     PopExpressionEvaluationContext();
13315 
13316   if (D->isOutOfLine())
13317     ExitDeclaratorContext(S);
13318 }
13319 
13320 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13321 /// C++ if/switch/while/for statement.
13322 /// e.g: "if (int x = f()) {...}"
13323 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
13324   // C++ 6.4p2:
13325   // The declarator shall not specify a function or an array.
13326   // The type-specifier-seq shall not contain typedef and shall not declare a
13327   // new class or enumeration.
13328   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13329          "Parser allowed 'typedef' as storage class of condition decl.");
13330 
13331   Decl *Dcl = ActOnDeclarator(S, D);
13332   if (!Dcl)
13333     return true;
13334 
13335   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13336     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13337       << D.getSourceRange();
13338     return true;
13339   }
13340 
13341   return Dcl;
13342 }
13343 
13344 void Sema::LoadExternalVTableUses() {
13345   if (!ExternalSource)
13346     return;
13347 
13348   SmallVector<ExternalVTableUse, 4> VTables;
13349   ExternalSource->ReadUsedVTables(VTables);
13350   SmallVector<VTableUse, 4> NewUses;
13351   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13352     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13353       = VTablesUsed.find(VTables[I].Record);
13354     // Even if a definition wasn't required before, it may be required now.
13355     if (Pos != VTablesUsed.end()) {
13356       if (!Pos->second && VTables[I].DefinitionRequired)
13357         Pos->second = true;
13358       continue;
13359     }
13360 
13361     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13362     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13363   }
13364 
13365   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13366 }
13367 
13368 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13369                           bool DefinitionRequired) {
13370   // Ignore any vtable uses in unevaluated operands or for classes that do
13371   // not have a vtable.
13372   if (!Class->isDynamicClass() || Class->isDependentContext() ||
13373       CurContext->isDependentContext() || isUnevaluatedContext())
13374     return;
13375 
13376   // Try to insert this class into the map.
13377   LoadExternalVTableUses();
13378   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13379   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13380     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13381   if (!Pos.second) {
13382     // If we already had an entry, check to see if we are promoting this vtable
13383     // to require a definition. If so, we need to reappend to the VTableUses
13384     // list, since we may have already processed the first entry.
13385     if (DefinitionRequired && !Pos.first->second) {
13386       Pos.first->second = true;
13387     } else {
13388       // Otherwise, we can early exit.
13389       return;
13390     }
13391   } else {
13392     // The Microsoft ABI requires that we perform the destructor body
13393     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13394     // the deleting destructor is emitted with the vtable, not with the
13395     // destructor definition as in the Itanium ABI.
13396     // If it has a definition, we do the check at that point instead.
13397     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13398       if (Class->hasUserDeclaredDestructor() &&
13399           !Class->getDestructor()->isDefined() &&
13400           !Class->getDestructor()->isDeleted()) {
13401         CXXDestructorDecl *DD = Class->getDestructor();
13402         ContextRAII SavedContext(*this, DD);
13403         CheckDestructor(DD);
13404       } else if (Class->hasAttr<DLLImportAttr>()) {
13405         // We always synthesize vtables on the import side. To make sure
13406         // CheckDestructor gets called, mark the destructor referenced.
13407         assert(Class->getDestructor() &&
13408                "The destructor has always been declared on a dllimport class");
13409         MarkFunctionReferenced(Loc, Class->getDestructor());
13410       }
13411     }
13412   }
13413 
13414   // Local classes need to have their virtual members marked
13415   // immediately. For all other classes, we mark their virtual members
13416   // at the end of the translation unit.
13417   if (Class->isLocalClass())
13418     MarkVirtualMembersReferenced(Loc, Class);
13419   else
13420     VTableUses.push_back(std::make_pair(Class, Loc));
13421 }
13422 
13423 bool Sema::DefineUsedVTables() {
13424   LoadExternalVTableUses();
13425   if (VTableUses.empty())
13426     return false;
13427 
13428   // Note: The VTableUses vector could grow as a result of marking
13429   // the members of a class as "used", so we check the size each
13430   // time through the loop and prefer indices (which are stable) to
13431   // iterators (which are not).
13432   bool DefinedAnything = false;
13433   for (unsigned I = 0; I != VTableUses.size(); ++I) {
13434     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13435     if (!Class)
13436       continue;
13437 
13438     SourceLocation Loc = VTableUses[I].second;
13439 
13440     bool DefineVTable = true;
13441 
13442     // If this class has a key function, but that key function is
13443     // defined in another translation unit, we don't need to emit the
13444     // vtable even though we're using it.
13445     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13446     if (KeyFunction && !KeyFunction->hasBody()) {
13447       // The key function is in another translation unit.
13448       DefineVTable = false;
13449       TemplateSpecializationKind TSK =
13450           KeyFunction->getTemplateSpecializationKind();
13451       assert(TSK != TSK_ExplicitInstantiationDefinition &&
13452              TSK != TSK_ImplicitInstantiation &&
13453              "Instantiations don't have key functions");
13454       (void)TSK;
13455     } else if (!KeyFunction) {
13456       // If we have a class with no key function that is the subject
13457       // of an explicit instantiation declaration, suppress the
13458       // vtable; it will live with the explicit instantiation
13459       // definition.
13460       bool IsExplicitInstantiationDeclaration
13461         = Class->getTemplateSpecializationKind()
13462                                       == TSK_ExplicitInstantiationDeclaration;
13463       for (auto R : Class->redecls()) {
13464         TemplateSpecializationKind TSK
13465           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13466         if (TSK == TSK_ExplicitInstantiationDeclaration)
13467           IsExplicitInstantiationDeclaration = true;
13468         else if (TSK == TSK_ExplicitInstantiationDefinition) {
13469           IsExplicitInstantiationDeclaration = false;
13470           break;
13471         }
13472       }
13473 
13474       if (IsExplicitInstantiationDeclaration)
13475         DefineVTable = false;
13476     }
13477 
13478     // The exception specifications for all virtual members may be needed even
13479     // if we are not providing an authoritative form of the vtable in this TU.
13480     // We may choose to emit it available_externally anyway.
13481     if (!DefineVTable) {
13482       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13483       continue;
13484     }
13485 
13486     // Mark all of the virtual members of this class as referenced, so
13487     // that we can build a vtable. Then, tell the AST consumer that a
13488     // vtable for this class is required.
13489     DefinedAnything = true;
13490     MarkVirtualMembersReferenced(Loc, Class);
13491     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13492     if (VTablesUsed[Canonical])
13493       Consumer.HandleVTable(Class);
13494 
13495     // Optionally warn if we're emitting a weak vtable.
13496     if (Class->isExternallyVisible() &&
13497         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13498       const FunctionDecl *KeyFunctionDef = nullptr;
13499       if (!KeyFunction ||
13500           (KeyFunction->hasBody(KeyFunctionDef) &&
13501            KeyFunctionDef->isInlined()))
13502         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13503              TSK_ExplicitInstantiationDefinition
13504              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13505           << Class;
13506     }
13507   }
13508   VTableUses.clear();
13509 
13510   return DefinedAnything;
13511 }
13512 
13513 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13514                                                  const CXXRecordDecl *RD) {
13515   for (const auto *I : RD->methods())
13516     if (I->isVirtual() && !I->isPure())
13517       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13518 }
13519 
13520 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13521                                         const CXXRecordDecl *RD) {
13522   // Mark all functions which will appear in RD's vtable as used.
13523   CXXFinalOverriderMap FinalOverriders;
13524   RD->getFinalOverriders(FinalOverriders);
13525   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13526                                             E = FinalOverriders.end();
13527        I != E; ++I) {
13528     for (OverridingMethods::const_iterator OI = I->second.begin(),
13529                                            OE = I->second.end();
13530          OI != OE; ++OI) {
13531       assert(OI->second.size() > 0 && "no final overrider");
13532       CXXMethodDecl *Overrider = OI->second.front().Method;
13533 
13534       // C++ [basic.def.odr]p2:
13535       //   [...] A virtual member function is used if it is not pure. [...]
13536       if (!Overrider->isPure())
13537         MarkFunctionReferenced(Loc, Overrider);
13538     }
13539   }
13540 
13541   // Only classes that have virtual bases need a VTT.
13542   if (RD->getNumVBases() == 0)
13543     return;
13544 
13545   for (const auto &I : RD->bases()) {
13546     const CXXRecordDecl *Base =
13547         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13548     if (Base->getNumVBases() == 0)
13549       continue;
13550     MarkVirtualMembersReferenced(Loc, Base);
13551   }
13552 }
13553 
13554 /// SetIvarInitializers - This routine builds initialization ASTs for the
13555 /// Objective-C implementation whose ivars need be initialized.
13556 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13557   if (!getLangOpts().CPlusPlus)
13558     return;
13559   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13560     SmallVector<ObjCIvarDecl*, 8> ivars;
13561     CollectIvarsToConstructOrDestruct(OID, ivars);
13562     if (ivars.empty())
13563       return;
13564     SmallVector<CXXCtorInitializer*, 32> AllToInit;
13565     for (unsigned i = 0; i < ivars.size(); i++) {
13566       FieldDecl *Field = ivars[i];
13567       if (Field->isInvalidDecl())
13568         continue;
13569 
13570       CXXCtorInitializer *Member;
13571       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13572       InitializationKind InitKind =
13573         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13574 
13575       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13576       ExprResult MemberInit =
13577         InitSeq.Perform(*this, InitEntity, InitKind, None);
13578       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13579       // Note, MemberInit could actually come back empty if no initialization
13580       // is required (e.g., because it would call a trivial default constructor)
13581       if (!MemberInit.get() || MemberInit.isInvalid())
13582         continue;
13583 
13584       Member =
13585         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13586                                          SourceLocation(),
13587                                          MemberInit.getAs<Expr>(),
13588                                          SourceLocation());
13589       AllToInit.push_back(Member);
13590 
13591       // Be sure that the destructor is accessible and is marked as referenced.
13592       if (const RecordType *RecordTy =
13593               Context.getBaseElementType(Field->getType())
13594                   ->getAs<RecordType>()) {
13595         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13596         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13597           MarkFunctionReferenced(Field->getLocation(), Destructor);
13598           CheckDestructorAccess(Field->getLocation(), Destructor,
13599                             PDiag(diag::err_access_dtor_ivar)
13600                               << Context.getBaseElementType(Field->getType()));
13601         }
13602       }
13603     }
13604     ObjCImplementation->setIvarInitializers(Context,
13605                                             AllToInit.data(), AllToInit.size());
13606   }
13607 }
13608 
13609 static
13610 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13611                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13612                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13613                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13614                            Sema &S) {
13615   if (Ctor->isInvalidDecl())
13616     return;
13617 
13618   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13619 
13620   // Target may not be determinable yet, for instance if this is a dependent
13621   // call in an uninstantiated template.
13622   if (Target) {
13623     const FunctionDecl *FNTarget = nullptr;
13624     (void)Target->hasBody(FNTarget);
13625     Target = const_cast<CXXConstructorDecl*>(
13626       cast_or_null<CXXConstructorDecl>(FNTarget));
13627   }
13628 
13629   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13630                      // Avoid dereferencing a null pointer here.
13631                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13632 
13633   if (!Current.insert(Canonical).second)
13634     return;
13635 
13636   // We know that beyond here, we aren't chaining into a cycle.
13637   if (!Target || !Target->isDelegatingConstructor() ||
13638       Target->isInvalidDecl() || Valid.count(TCanonical)) {
13639     Valid.insert(Current.begin(), Current.end());
13640     Current.clear();
13641   // We've hit a cycle.
13642   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13643              Current.count(TCanonical)) {
13644     // If we haven't diagnosed this cycle yet, do so now.
13645     if (!Invalid.count(TCanonical)) {
13646       S.Diag((*Ctor->init_begin())->getSourceLocation(),
13647              diag::warn_delegating_ctor_cycle)
13648         << Ctor;
13649 
13650       // Don't add a note for a function delegating directly to itself.
13651       if (TCanonical != Canonical)
13652         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13653 
13654       CXXConstructorDecl *C = Target;
13655       while (C->getCanonicalDecl() != Canonical) {
13656         const FunctionDecl *FNTarget = nullptr;
13657         (void)C->getTargetConstructor()->hasBody(FNTarget);
13658         assert(FNTarget && "Ctor cycle through bodiless function");
13659 
13660         C = const_cast<CXXConstructorDecl*>(
13661           cast<CXXConstructorDecl>(FNTarget));
13662         S.Diag(C->getLocation(), diag::note_which_delegates_to);
13663       }
13664     }
13665 
13666     Invalid.insert(Current.begin(), Current.end());
13667     Current.clear();
13668   } else {
13669     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13670   }
13671 }
13672 
13673 
13674 void Sema::CheckDelegatingCtorCycles() {
13675   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13676 
13677   for (DelegatingCtorDeclsType::iterator
13678          I = DelegatingCtorDecls.begin(ExternalSource),
13679          E = DelegatingCtorDecls.end();
13680        I != E; ++I)
13681     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13682 
13683   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13684                                                          CE = Invalid.end();
13685        CI != CE; ++CI)
13686     (*CI)->setInvalidDecl();
13687 }
13688 
13689 namespace {
13690   /// \brief AST visitor that finds references to the 'this' expression.
13691   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13692     Sema &S;
13693 
13694   public:
13695     explicit FindCXXThisExpr(Sema &S) : S(S) { }
13696 
13697     bool VisitCXXThisExpr(CXXThisExpr *E) {
13698       S.Diag(E->getLocation(), diag::err_this_static_member_func)
13699         << E->isImplicit();
13700       return false;
13701     }
13702   };
13703 }
13704 
13705 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13706   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13707   if (!TSInfo)
13708     return false;
13709 
13710   TypeLoc TL = TSInfo->getTypeLoc();
13711   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13712   if (!ProtoTL)
13713     return false;
13714 
13715   // C++11 [expr.prim.general]p3:
13716   //   [The expression this] shall not appear before the optional
13717   //   cv-qualifier-seq and it shall not appear within the declaration of a
13718   //   static member function (although its type and value category are defined
13719   //   within a static member function as they are within a non-static member
13720   //   function). [ Note: this is because declaration matching does not occur
13721   //  until the complete declarator is known. - end note ]
13722   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13723   FindCXXThisExpr Finder(*this);
13724 
13725   // If the return type came after the cv-qualifier-seq, check it now.
13726   if (Proto->hasTrailingReturn() &&
13727       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13728     return true;
13729 
13730   // Check the exception specification.
13731   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13732     return true;
13733 
13734   return checkThisInStaticMemberFunctionAttributes(Method);
13735 }
13736 
13737 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13738   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13739   if (!TSInfo)
13740     return false;
13741 
13742   TypeLoc TL = TSInfo->getTypeLoc();
13743   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13744   if (!ProtoTL)
13745     return false;
13746 
13747   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13748   FindCXXThisExpr Finder(*this);
13749 
13750   switch (Proto->getExceptionSpecType()) {
13751   case EST_Unparsed:
13752   case EST_Uninstantiated:
13753   case EST_Unevaluated:
13754   case EST_BasicNoexcept:
13755   case EST_DynamicNone:
13756   case EST_MSAny:
13757   case EST_None:
13758     break;
13759 
13760   case EST_ComputedNoexcept:
13761     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13762       return true;
13763 
13764   case EST_Dynamic:
13765     for (const auto &E : Proto->exceptions()) {
13766       if (!Finder.TraverseType(E))
13767         return true;
13768     }
13769     break;
13770   }
13771 
13772   return false;
13773 }
13774 
13775 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13776   FindCXXThisExpr Finder(*this);
13777 
13778   // Check attributes.
13779   for (const auto *A : Method->attrs()) {
13780     // FIXME: This should be emitted by tblgen.
13781     Expr *Arg = nullptr;
13782     ArrayRef<Expr *> Args;
13783     if (const auto *G = dyn_cast<GuardedByAttr>(A))
13784       Arg = G->getArg();
13785     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13786       Arg = G->getArg();
13787     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13788       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13789     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13790       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13791     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13792       Arg = ETLF->getSuccessValue();
13793       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13794     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13795       Arg = STLF->getSuccessValue();
13796       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13797     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13798       Arg = LR->getArg();
13799     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13800       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13801     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13802       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13803     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13804       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13805     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13806       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13807     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13808       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13809 
13810     if (Arg && !Finder.TraverseStmt(Arg))
13811       return true;
13812 
13813     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13814       if (!Finder.TraverseStmt(Args[I]))
13815         return true;
13816     }
13817   }
13818 
13819   return false;
13820 }
13821 
13822 void Sema::checkExceptionSpecification(
13823     bool IsTopLevel, ExceptionSpecificationType EST,
13824     ArrayRef<ParsedType> DynamicExceptions,
13825     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13826     SmallVectorImpl<QualType> &Exceptions,
13827     FunctionProtoType::ExceptionSpecInfo &ESI) {
13828   Exceptions.clear();
13829   ESI.Type = EST;
13830   if (EST == EST_Dynamic) {
13831     Exceptions.reserve(DynamicExceptions.size());
13832     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13833       // FIXME: Preserve type source info.
13834       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13835 
13836       if (IsTopLevel) {
13837         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13838         collectUnexpandedParameterPacks(ET, Unexpanded);
13839         if (!Unexpanded.empty()) {
13840           DiagnoseUnexpandedParameterPacks(
13841               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13842               Unexpanded);
13843           continue;
13844         }
13845       }
13846 
13847       // Check that the type is valid for an exception spec, and
13848       // drop it if not.
13849       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13850         Exceptions.push_back(ET);
13851     }
13852     ESI.Exceptions = Exceptions;
13853     return;
13854   }
13855 
13856   if (EST == EST_ComputedNoexcept) {
13857     // If an error occurred, there's no expression here.
13858     if (NoexceptExpr) {
13859       assert((NoexceptExpr->isTypeDependent() ||
13860               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13861               Context.BoolTy) &&
13862              "Parser should have made sure that the expression is boolean");
13863       if (IsTopLevel && NoexceptExpr &&
13864           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13865         ESI.Type = EST_BasicNoexcept;
13866         return;
13867       }
13868 
13869       if (!NoexceptExpr->isValueDependent())
13870         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13871                          diag::err_noexcept_needs_constant_expression,
13872                          /*AllowFold*/ false).get();
13873       ESI.NoexceptExpr = NoexceptExpr;
13874     }
13875     return;
13876   }
13877 }
13878 
13879 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13880              ExceptionSpecificationType EST,
13881              SourceRange SpecificationRange,
13882              ArrayRef<ParsedType> DynamicExceptions,
13883              ArrayRef<SourceRange> DynamicExceptionRanges,
13884              Expr *NoexceptExpr) {
13885   if (!MethodD)
13886     return;
13887 
13888   // Dig out the method we're referring to.
13889   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13890     MethodD = FunTmpl->getTemplatedDecl();
13891 
13892   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13893   if (!Method)
13894     return;
13895 
13896   // Check the exception specification.
13897   llvm::SmallVector<QualType, 4> Exceptions;
13898   FunctionProtoType::ExceptionSpecInfo ESI;
13899   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13900                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
13901                               ESI);
13902 
13903   // Update the exception specification on the function type.
13904   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13905 
13906   if (Method->isStatic())
13907     checkThisInStaticMemberFunctionExceptionSpec(Method);
13908 
13909   if (Method->isVirtual()) {
13910     // Check overrides, which we previously had to delay.
13911     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13912                                      OEnd = Method->end_overridden_methods();
13913          O != OEnd; ++O)
13914       CheckOverridingFunctionExceptionSpec(Method, *O);
13915   }
13916 }
13917 
13918 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13919 ///
13920 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13921                                        SourceLocation DeclStart,
13922                                        Declarator &D, Expr *BitWidth,
13923                                        InClassInitStyle InitStyle,
13924                                        AccessSpecifier AS,
13925                                        AttributeList *MSPropertyAttr) {
13926   IdentifierInfo *II = D.getIdentifier();
13927   if (!II) {
13928     Diag(DeclStart, diag::err_anonymous_property);
13929     return nullptr;
13930   }
13931   SourceLocation Loc = D.getIdentifierLoc();
13932 
13933   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13934   QualType T = TInfo->getType();
13935   if (getLangOpts().CPlusPlus) {
13936     CheckExtraCXXDefaultArguments(D);
13937 
13938     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13939                                         UPPC_DataMemberType)) {
13940       D.setInvalidType();
13941       T = Context.IntTy;
13942       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13943     }
13944   }
13945 
13946   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13947 
13948   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13949     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13950          diag::err_invalid_thread)
13951       << DeclSpec::getSpecifierName(TSCS);
13952 
13953   // Check to see if this name was declared as a member previously
13954   NamedDecl *PrevDecl = nullptr;
13955   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13956   LookupName(Previous, S);
13957   switch (Previous.getResultKind()) {
13958   case LookupResult::Found:
13959   case LookupResult::FoundUnresolvedValue:
13960     PrevDecl = Previous.getAsSingle<NamedDecl>();
13961     break;
13962 
13963   case LookupResult::FoundOverloaded:
13964     PrevDecl = Previous.getRepresentativeDecl();
13965     break;
13966 
13967   case LookupResult::NotFound:
13968   case LookupResult::NotFoundInCurrentInstantiation:
13969   case LookupResult::Ambiguous:
13970     break;
13971   }
13972 
13973   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13974     // Maybe we will complain about the shadowed template parameter.
13975     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13976     // Just pretend that we didn't see the previous declaration.
13977     PrevDecl = nullptr;
13978   }
13979 
13980   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13981     PrevDecl = nullptr;
13982 
13983   SourceLocation TSSL = D.getLocStart();
13984   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13985   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13986       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13987   ProcessDeclAttributes(TUScope, NewPD, D);
13988   NewPD->setAccess(AS);
13989 
13990   if (NewPD->isInvalidDecl())
13991     Record->setInvalidDecl();
13992 
13993   if (D.getDeclSpec().isModulePrivateSpecified())
13994     NewPD->setModulePrivate();
13995 
13996   if (NewPD->isInvalidDecl() && PrevDecl) {
13997     // Don't introduce NewFD into scope; there's already something
13998     // with the same name in the same scope.
13999   } else if (II) {
14000     PushOnScopeChains(NewPD, S);
14001   } else
14002     Record->addDecl(NewPD);
14003 
14004   return NewPD;
14005 }
14006