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::child_range I = Node->children(); I; ++I)
77       IsInvalid |= Visit(*I);
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 } // namespace
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 this function can throw any exceptions, make a note of that.
166   if (EST == EST_MSAny || EST == EST_None) {
167     ClearExceptions();
168     ComputedEST = EST;
169     return;
170   }
171 
172   // FIXME: If the call to this decl is using any of its default arguments, we
173   // need to search them for potentially-throwing calls.
174 
175   // If this function has a basic noexcept, it doesn't affect the outcome.
176   if (EST == EST_BasicNoexcept)
177     return;
178 
179   // If we have a throw-all spec at this point, ignore the function.
180   if (ComputedEST == EST_None)
181     return;
182 
183   // If we're still at noexcept(true) and there's a nothrow() callee,
184   // change to that specification.
185   if (EST == EST_DynamicNone) {
186     if (ComputedEST == EST_BasicNoexcept)
187       ComputedEST = EST_DynamicNone;
188     return;
189   }
190 
191   // Check out noexcept specs.
192   if (EST == EST_ComputedNoexcept) {
193     FunctionProtoType::NoexceptResult NR =
194         Proto->getNoexceptSpec(Self->Context);
195     assert(NR != FunctionProtoType::NR_NoNoexcept &&
196            "Must have noexcept result for EST_ComputedNoexcept.");
197     assert(NR != FunctionProtoType::NR_Dependent &&
198            "Should not generate implicit declarations for dependent cases, "
199            "and don't know how to handle them anyway.");
200 
201     // noexcept(false) -> no spec on the new function
202     if (NR == FunctionProtoType::NR_Throw) {
203       ClearExceptions();
204       ComputedEST = EST_None;
205     }
206     // noexcept(true) won't change anything either.
207     return;
208   }
209 
210   assert(EST == EST_Dynamic && "EST case not considered earlier.");
211   assert(ComputedEST != EST_None &&
212          "Shouldn't collect exceptions when throw-all is guaranteed.");
213   ComputedEST = EST_Dynamic;
214   // Record the exceptions in this function's exception specification.
215   for (const auto &E : Proto->exceptions())
216     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
217       Exceptions.push_back(E);
218 }
219 
220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221   if (!E || ComputedEST == EST_MSAny)
222     return;
223 
224   // FIXME:
225   //
226   // C++0x [except.spec]p14:
227   //   [An] implicit exception-specification specifies the type-id T if and
228   // only if T is allowed by the exception-specification of a function directly
229   // invoked by f's implicit definition; f shall allow all exceptions if any
230   // function it directly invokes allows all exceptions, and f shall allow no
231   // exceptions if every function it directly invokes allows no exceptions.
232   //
233   // Note in particular that if an implicit exception-specification is generated
234   // for a function containing a throw-expression, that specification can still
235   // be noexcept(true).
236   //
237   // Note also that 'directly invoked' is not defined in the standard, and there
238   // is no indication that we should only consider potentially-evaluated calls.
239   //
240   // Ultimately we should implement the intent of the standard: the exception
241   // specification should be the set of exceptions which can be thrown by the
242   // implicit definition. For now, we assume that any non-nothrow expression can
243   // throw any exception.
244 
245   if (Self->canThrow(E))
246     ComputedEST = EST_None;
247 }
248 
249 bool
250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251                               SourceLocation EqualLoc) {
252   if (RequireCompleteType(Param->getLocation(), Param->getType(),
253                           diag::err_typecheck_decl_incomplete_type)) {
254     Param->setInvalidDecl();
255     return true;
256   }
257 
258   // C++ [dcl.fct.default]p5
259   //   A default argument expression is implicitly converted (clause
260   //   4) to the parameter type. The default argument expression has
261   //   the same semantic constraints as the initializer expression in
262   //   a declaration of a variable of the parameter type, using the
263   //   copy-initialization semantics (8.5).
264   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265                                                                     Param);
266   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267                                                            EqualLoc);
268   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270   if (Result.isInvalid())
271     return true;
272   Arg = Result.getAs<Expr>();
273 
274   CheckCompletedExpr(Arg, EqualLoc);
275   Arg = MaybeCreateExprWithCleanups(Arg);
276 
277   // Okay: add the default argument to the parameter
278   Param->setDefaultArg(Arg);
279 
280   // We have already instantiated this parameter; provide each of the
281   // instantiations with the uninstantiated default argument.
282   UnparsedDefaultArgInstantiationsMap::iterator InstPos
283     = UnparsedDefaultArgInstantiations.find(Param);
284   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287 
288     // We're done tracking this parameter's instantiations.
289     UnparsedDefaultArgInstantiations.erase(InstPos);
290   }
291 
292   return false;
293 }
294 
295 /// ActOnParamDefaultArgument - Check whether the default argument
296 /// provided for a function parameter is well-formed. If so, attach it
297 /// to the parameter declaration.
298 void
299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300                                 Expr *DefaultArg) {
301   if (!param || !DefaultArg)
302     return;
303 
304   ParmVarDecl *Param = cast<ParmVarDecl>(param);
305   UnparsedDefaultArgLocs.erase(Param);
306 
307   // Default arguments are only permitted in C++
308   if (!getLangOpts().CPlusPlus) {
309     Diag(EqualLoc, diag::err_param_default_argument)
310       << DefaultArg->getSourceRange();
311     Param->setInvalidDecl();
312     return;
313   }
314 
315   // Check for unexpanded parameter packs.
316   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317     Param->setInvalidDecl();
318     return;
319   }
320 
321   // C++11 [dcl.fct.default]p3
322   //   A default argument expression [...] shall not be specified for a
323   //   parameter pack.
324   if (Param->isParameterPack()) {
325     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
326         << DefaultArg->getSourceRange();
327     return;
328   }
329 
330   // Check that the default argument is well-formed
331   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
332   if (DefaultArgChecker.Visit(DefaultArg)) {
333     Param->setInvalidDecl();
334     return;
335   }
336 
337   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
338 }
339 
340 /// ActOnParamUnparsedDefaultArgument - We've seen a default
341 /// argument for a function parameter, but we can't parse it yet
342 /// because we're inside a class definition. Note that this default
343 /// argument will be parsed later.
344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
345                                              SourceLocation EqualLoc,
346                                              SourceLocation ArgLoc) {
347   if (!param)
348     return;
349 
350   ParmVarDecl *Param = cast<ParmVarDecl>(param);
351   Param->setUnparsedDefaultArg();
352   UnparsedDefaultArgLocs[Param] = ArgLoc;
353 }
354 
355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
356 /// the default argument for the parameter param failed.
357 void Sema::ActOnParamDefaultArgumentError(Decl *param,
358                                           SourceLocation EqualLoc) {
359   if (!param)
360     return;
361 
362   ParmVarDecl *Param = cast<ParmVarDecl>(param);
363   Param->setInvalidDecl();
364   UnparsedDefaultArgLocs.erase(Param);
365   Param->setDefaultArg(new(Context)
366                        OpaqueValueExpr(EqualLoc,
367                                        Param->getType().getNonReferenceType(),
368                                        VK_RValue));
369 }
370 
371 /// CheckExtraCXXDefaultArguments - Check for any extra default
372 /// arguments in the declarator, which is not a function declaration
373 /// or definition and therefore is not permitted to have default
374 /// arguments. This routine should be invoked for every declarator
375 /// that is not a function declaration or definition.
376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
377   // C++ [dcl.fct.default]p3
378   //   A default argument expression shall be specified only in the
379   //   parameter-declaration-clause of a function declaration or in a
380   //   template-parameter (14.1). It shall not be specified for a
381   //   parameter pack. If it is specified in a
382   //   parameter-declaration-clause, it shall not occur within a
383   //   declarator or abstract-declarator of a parameter-declaration.
384   bool MightBeFunction = D.isFunctionDeclarationContext();
385   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
386     DeclaratorChunk &chunk = D.getTypeObject(i);
387     if (chunk.Kind == DeclaratorChunk::Function) {
388       if (MightBeFunction) {
389         // This is a function declaration. It can have default arguments, but
390         // keep looking in case its return type is a function type with default
391         // arguments.
392         MightBeFunction = false;
393         continue;
394       }
395       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
396            ++argIdx) {
397         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
398         if (Param->hasUnparsedDefaultArg()) {
399           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
400           SourceRange SR;
401           if (Toks->size() > 1)
402             SR = SourceRange((*Toks)[1].getLocation(),
403                              Toks->back().getLocation());
404           else
405             SR = UnparsedDefaultArgLocs[Param];
406           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407             << SR;
408           delete Toks;
409           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
410         } else if (Param->getDefaultArg()) {
411           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
412             << Param->getDefaultArg()->getSourceRange();
413           Param->setDefaultArg(nullptr);
414         }
415       }
416     } else if (chunk.Kind != DeclaratorChunk::Paren) {
417       MightBeFunction = false;
418     }
419   }
420 }
421 
422 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
423   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
424     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
425     if (!PVD->hasDefaultArg())
426       return false;
427     if (!PVD->hasInheritedDefaultArg())
428       return true;
429   }
430   return false;
431 }
432 
433 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
434 /// function, once we already know that they have the same
435 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
436 /// error, false otherwise.
437 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
438                                 Scope *S) {
439   bool Invalid = false;
440 
441   // The declaration context corresponding to the scope is the semantic
442   // parent, unless this is a local function declaration, in which case
443   // it is that surrounding function.
444   DeclContext *ScopeDC = New->isLocalExternDecl()
445                              ? New->getLexicalDeclContext()
446                              : New->getDeclContext();
447 
448   // Find the previous declaration for the purpose of default arguments.
449   FunctionDecl *PrevForDefaultArgs = Old;
450   for (/**/; PrevForDefaultArgs;
451        // Don't bother looking back past the latest decl if this is a local
452        // extern declaration; nothing else could work.
453        PrevForDefaultArgs = New->isLocalExternDecl()
454                                 ? nullptr
455                                 : PrevForDefaultArgs->getPreviousDecl()) {
456     // Ignore hidden declarations.
457     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
458       continue;
459 
460     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
461         !New->isCXXClassMember()) {
462       // Ignore default arguments of old decl if they are not in
463       // the same scope and this is not an out-of-line definition of
464       // a member function.
465       continue;
466     }
467 
468     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
469       // If only one of these is a local function declaration, then they are
470       // declared in different scopes, even though isDeclInScope may think
471       // they're in the same scope. (If both are local, the scope check is
472       // sufficent, and if neither is local, then they are in the same scope.)
473       continue;
474     }
475 
476     // We found our guy.
477     break;
478   }
479 
480   // C++ [dcl.fct.default]p4:
481   //   For non-template functions, default arguments can be added in
482   //   later declarations of a function in the same
483   //   scope. Declarations in different scopes have completely
484   //   distinct sets of default arguments. That is, declarations in
485   //   inner scopes do not acquire default arguments from
486   //   declarations in outer scopes, and vice versa. In a given
487   //   function declaration, all parameters subsequent to a
488   //   parameter with a default argument shall have default
489   //   arguments supplied in this or previous declarations. A
490   //   default argument shall not be redefined by a later
491   //   declaration (not even to the same value).
492   //
493   // C++ [dcl.fct.default]p6:
494   //   Except for member functions of class templates, the default arguments
495   //   in a member function definition that appears outside of the class
496   //   definition are added to the set of default arguments provided by the
497   //   member function declaration in the class definition.
498   for (unsigned p = 0, NumParams = PrevForDefaultArgs
499                                        ? PrevForDefaultArgs->getNumParams()
500                                        : 0;
501        p < NumParams; ++p) {
502     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
503     ParmVarDecl *NewParam = New->getParamDecl(p);
504 
505     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
506     bool NewParamHasDfl = NewParam->hasDefaultArg();
507 
508     if (OldParamHasDfl && NewParamHasDfl) {
509       unsigned DiagDefaultParamID =
510         diag::err_param_default_argument_redefinition;
511 
512       // MSVC accepts that default parameters be redefined for member functions
513       // of template class. The new default parameter's value is ignored.
514       Invalid = true;
515       if (getLangOpts().MicrosoftExt) {
516         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
517         if (MD && MD->getParent()->getDescribedClassTemplate()) {
518           // Merge the old default argument into the new parameter.
519           NewParam->setHasInheritedDefaultArg();
520           if (OldParam->hasUninstantiatedDefaultArg())
521             NewParam->setUninstantiatedDefaultArg(
522                                       OldParam->getUninstantiatedDefaultArg());
523           else
524             NewParam->setDefaultArg(OldParam->getInit());
525           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
526           Invalid = false;
527         }
528       }
529 
530       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
531       // hint here. Alternatively, we could walk the type-source information
532       // for NewParam to find the last source location in the type... but it
533       // isn't worth the effort right now. This is the kind of test case that
534       // is hard to get right:
535       //   int f(int);
536       //   void g(int (*fp)(int) = f);
537       //   void g(int (*fp)(int) = &f);
538       Diag(NewParam->getLocation(), DiagDefaultParamID)
539         << NewParam->getDefaultArgRange();
540 
541       // Look for the function declaration where the default argument was
542       // actually written, which may be a declaration prior to Old.
543       for (auto Older = PrevForDefaultArgs;
544            OldParam->hasInheritedDefaultArg(); /**/) {
545         Older = Older->getPreviousDecl();
546         OldParam = Older->getParamDecl(p);
547       }
548 
549       Diag(OldParam->getLocation(), diag::note_previous_definition)
550         << OldParam->getDefaultArgRange();
551     } else if (OldParamHasDfl) {
552       // Merge the old default argument into the new parameter.
553       // It's important to use getInit() here;  getDefaultArg()
554       // strips off any top-level ExprWithCleanups.
555       NewParam->setHasInheritedDefaultArg();
556       if (OldParam->hasUnparsedDefaultArg())
557         NewParam->setUnparsedDefaultArg();
558       else if (OldParam->hasUninstantiatedDefaultArg())
559         NewParam->setUninstantiatedDefaultArg(
560                                       OldParam->getUninstantiatedDefaultArg());
561       else
562         NewParam->setDefaultArg(OldParam->getInit());
563     } else if (NewParamHasDfl) {
564       if (New->getDescribedFunctionTemplate()) {
565         // Paragraph 4, quoted above, only applies to non-template functions.
566         Diag(NewParam->getLocation(),
567              diag::err_param_default_argument_template_redecl)
568           << NewParam->getDefaultArgRange();
569         Diag(PrevForDefaultArgs->getLocation(),
570              diag::note_template_prev_declaration)
571             << false;
572       } else if (New->getTemplateSpecializationKind()
573                    != TSK_ImplicitInstantiation &&
574                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
575         // C++ [temp.expr.spec]p21:
576         //   Default function arguments shall not be specified in a declaration
577         //   or a definition for one of the following explicit specializations:
578         //     - the explicit specialization of a function template;
579         //     - the explicit specialization of a member function template;
580         //     - the explicit specialization of a member function of a class
581         //       template where the class template specialization to which the
582         //       member function specialization belongs is implicitly
583         //       instantiated.
584         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
585           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
586           << New->getDeclName()
587           << NewParam->getDefaultArgRange();
588       } else if (New->getDeclContext()->isDependentContext()) {
589         // C++ [dcl.fct.default]p6 (DR217):
590         //   Default arguments for a member function of a class template shall
591         //   be specified on the initial declaration of the member function
592         //   within the class template.
593         //
594         // Reading the tea leaves a bit in DR217 and its reference to DR205
595         // leads me to the conclusion that one cannot add default function
596         // arguments for an out-of-line definition of a member function of a
597         // dependent type.
598         int WhichKind = 2;
599         if (CXXRecordDecl *Record
600               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
601           if (Record->getDescribedClassTemplate())
602             WhichKind = 0;
603           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
604             WhichKind = 1;
605           else
606             WhichKind = 2;
607         }
608 
609         Diag(NewParam->getLocation(),
610              diag::err_param_default_argument_member_template_redecl)
611           << WhichKind
612           << NewParam->getDefaultArgRange();
613       }
614     }
615   }
616 
617   // DR1344: If a default argument is added outside a class definition and that
618   // default argument makes the function a special member function, the program
619   // is ill-formed. This can only happen for constructors.
620   if (isa<CXXConstructorDecl>(New) &&
621       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
622     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
623                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
624     if (NewSM != OldSM) {
625       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
626       assert(NewParam->hasDefaultArg());
627       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
628         << NewParam->getDefaultArgRange() << NewSM;
629       Diag(Old->getLocation(), diag::note_previous_declaration);
630     }
631   }
632 
633   const FunctionDecl *Def;
634   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
635   // template has a constexpr specifier then all its declarations shall
636   // contain the constexpr specifier.
637   if (New->isConstexpr() != Old->isConstexpr()) {
638     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
639       << New << New->isConstexpr();
640     Diag(Old->getLocation(), diag::note_previous_declaration);
641     Invalid = true;
642   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
643              Old->isDefined(Def)) {
644     // C++11 [dcl.fcn.spec]p4:
645     //   If the definition of a function appears in a translation unit before its
646     //   first declaration as inline, the program is ill-formed.
647     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
648     Diag(Def->getLocation(), diag::note_previous_definition);
649     Invalid = true;
650   }
651 
652   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
653   // argument expression, that declaration shall be a definition and shall be
654   // the only declaration of the function or function template in the
655   // translation unit.
656   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
657       functionDeclHasDefaultArgument(Old)) {
658     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
659     Diag(Old->getLocation(), diag::note_previous_declaration);
660     Invalid = true;
661   }
662 
663   if (CheckEquivalentExceptionSpec(Old, New))
664     Invalid = true;
665 
666   return Invalid;
667 }
668 
669 /// \brief Merge the exception specifications of two variable declarations.
670 ///
671 /// This is called when there's a redeclaration of a VarDecl. The function
672 /// checks if the redeclaration might have an exception specification and
673 /// validates compatibility and merges the specs if necessary.
674 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
675   // Shortcut if exceptions are disabled.
676   if (!getLangOpts().CXXExceptions)
677     return;
678 
679   assert(Context.hasSameType(New->getType(), Old->getType()) &&
680          "Should only be called if types are otherwise the same.");
681 
682   QualType NewType = New->getType();
683   QualType OldType = Old->getType();
684 
685   // We're only interested in pointers and references to functions, as well
686   // as pointers to member functions.
687   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
688     NewType = R->getPointeeType();
689     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
690   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
691     NewType = P->getPointeeType();
692     OldType = OldType->getAs<PointerType>()->getPointeeType();
693   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
694     NewType = M->getPointeeType();
695     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
696   }
697 
698   if (!NewType->isFunctionProtoType())
699     return;
700 
701   // There's lots of special cases for functions. For function pointers, system
702   // libraries are hopefully not as broken so that we don't need these
703   // workarounds.
704   if (CheckEquivalentExceptionSpec(
705         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
706         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
707     New->setInvalidDecl();
708   }
709 }
710 
711 /// CheckCXXDefaultArguments - Verify that the default arguments for a
712 /// function declaration are well-formed according to C++
713 /// [dcl.fct.default].
714 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
715   unsigned NumParams = FD->getNumParams();
716   unsigned p;
717 
718   // Find first parameter with a default argument
719   for (p = 0; p < NumParams; ++p) {
720     ParmVarDecl *Param = FD->getParamDecl(p);
721     if (Param->hasDefaultArg())
722       break;
723   }
724 
725   // C++11 [dcl.fct.default]p4:
726   //   In a given function declaration, each parameter subsequent to a parameter
727   //   with a default argument shall have a default argument supplied in this or
728   //   a previous declaration or shall be a function parameter pack. A default
729   //   argument shall not be redefined by a later declaration (not even to the
730   //   same value).
731   unsigned LastMissingDefaultArg = 0;
732   for (; p < NumParams; ++p) {
733     ParmVarDecl *Param = FD->getParamDecl(p);
734     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
735       if (Param->isInvalidDecl())
736         /* We already complained about this parameter. */;
737       else if (Param->getIdentifier())
738         Diag(Param->getLocation(),
739              diag::err_param_default_argument_missing_name)
740           << Param->getIdentifier();
741       else
742         Diag(Param->getLocation(),
743              diag::err_param_default_argument_missing);
744 
745       LastMissingDefaultArg = p;
746     }
747   }
748 
749   if (LastMissingDefaultArg > 0) {
750     // Some default arguments were missing. Clear out all of the
751     // default arguments up to (and including) the last missing
752     // default argument, so that we leave the function parameters
753     // in a semantically valid state.
754     for (p = 0; p <= LastMissingDefaultArg; ++p) {
755       ParmVarDecl *Param = FD->getParamDecl(p);
756       if (Param->hasDefaultArg()) {
757         Param->setDefaultArg(nullptr);
758       }
759     }
760   }
761 }
762 
763 // CheckConstexprParameterTypes - Check whether a function's parameter types
764 // are all literal types. If so, return true. If not, produce a suitable
765 // diagnostic and return false.
766 static bool CheckConstexprParameterTypes(Sema &SemaRef,
767                                          const FunctionDecl *FD) {
768   unsigned ArgIndex = 0;
769   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
770   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
771                                               e = FT->param_type_end();
772        i != e; ++i, ++ArgIndex) {
773     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
774     SourceLocation ParamLoc = PD->getLocation();
775     if (!(*i)->isDependentType() &&
776         SemaRef.RequireLiteralType(ParamLoc, *i,
777                                    diag::err_constexpr_non_literal_param,
778                                    ArgIndex+1, PD->getSourceRange(),
779                                    isa<CXXConstructorDecl>(FD)))
780       return false;
781   }
782   return true;
783 }
784 
785 /// \brief Get diagnostic %select index for tag kind for
786 /// record diagnostic message.
787 /// WARNING: Indexes apply to particular diagnostics only!
788 ///
789 /// \returns diagnostic %select index.
790 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
791   switch (Tag) {
792   case TTK_Struct: return 0;
793   case TTK_Interface: return 1;
794   case TTK_Class:  return 2;
795   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
796   }
797 }
798 
799 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
800 // the requirements of a constexpr function definition or a constexpr
801 // constructor definition. If so, return true. If not, produce appropriate
802 // diagnostics and return false.
803 //
804 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
805 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
806   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
807   if (MD && MD->isInstance()) {
808     // C++11 [dcl.constexpr]p4:
809     //  The definition of a constexpr constructor shall satisfy the following
810     //  constraints:
811     //  - the class shall not have any virtual base classes;
812     const CXXRecordDecl *RD = MD->getParent();
813     if (RD->getNumVBases()) {
814       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
815         << isa<CXXConstructorDecl>(NewFD)
816         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
817       for (const auto &I : RD->vbases())
818         Diag(I.getLocStart(),
819              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
820       return false;
821     }
822   }
823 
824   if (!isa<CXXConstructorDecl>(NewFD)) {
825     // C++11 [dcl.constexpr]p3:
826     //  The definition of a constexpr function shall satisfy the following
827     //  constraints:
828     // - it shall not be virtual;
829     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
830     if (Method && Method->isVirtual()) {
831       Method = Method->getCanonicalDecl();
832       Diag(Method->getLocation(), diag::err_constexpr_virtual);
833 
834       // If it's not obvious why this function is virtual, find an overridden
835       // function which uses the 'virtual' keyword.
836       const CXXMethodDecl *WrittenVirtual = Method;
837       while (!WrittenVirtual->isVirtualAsWritten())
838         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
839       if (WrittenVirtual != Method)
840         Diag(WrittenVirtual->getLocation(),
841              diag::note_overridden_virtual_function);
842       return false;
843     }
844 
845     // - its return type shall be a literal type;
846     QualType RT = NewFD->getReturnType();
847     if (!RT->isDependentType() &&
848         RequireLiteralType(NewFD->getLocation(), RT,
849                            diag::err_constexpr_non_literal_return))
850       return false;
851   }
852 
853   // - each of its parameter types shall be a literal type;
854   if (!CheckConstexprParameterTypes(*this, NewFD))
855     return false;
856 
857   return true;
858 }
859 
860 /// Check the given declaration statement is legal within a constexpr function
861 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
862 ///
863 /// \return true if the body is OK (maybe only as an extension), false if we
864 ///         have diagnosed a problem.
865 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
866                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
867   // C++11 [dcl.constexpr]p3 and p4:
868   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
869   //  contain only
870   for (const auto *DclIt : DS->decls()) {
871     switch (DclIt->getKind()) {
872     case Decl::StaticAssert:
873     case Decl::Using:
874     case Decl::UsingShadow:
875     case Decl::UsingDirective:
876     case Decl::UnresolvedUsingTypename:
877     case Decl::UnresolvedUsingValue:
878       //   - static_assert-declarations
879       //   - using-declarations,
880       //   - using-directives,
881       continue;
882 
883     case Decl::Typedef:
884     case Decl::TypeAlias: {
885       //   - typedef declarations and alias-declarations that do not define
886       //     classes or enumerations,
887       const auto *TN = cast<TypedefNameDecl>(DclIt);
888       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
889         // Don't allow variably-modified types in constexpr functions.
890         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
891         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
892           << TL.getSourceRange() << TL.getType()
893           << isa<CXXConstructorDecl>(Dcl);
894         return false;
895       }
896       continue;
897     }
898 
899     case Decl::Enum:
900     case Decl::CXXRecord:
901       // C++1y allows types to be defined, not just declared.
902       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
903         SemaRef.Diag(DS->getLocStart(),
904                      SemaRef.getLangOpts().CPlusPlus14
905                        ? diag::warn_cxx11_compat_constexpr_type_definition
906                        : diag::ext_constexpr_type_definition)
907           << isa<CXXConstructorDecl>(Dcl);
908       continue;
909 
910     case Decl::EnumConstant:
911     case Decl::IndirectField:
912     case Decl::ParmVar:
913       // These can only appear with other declarations which are banned in
914       // C++11 and permitted in C++1y, so ignore them.
915       continue;
916 
917     case Decl::Var: {
918       // C++1y [dcl.constexpr]p3 allows anything except:
919       //   a definition of a variable of non-literal type or of static or
920       //   thread storage duration or for which no initialization is performed.
921       const auto *VD = cast<VarDecl>(DclIt);
922       if (VD->isThisDeclarationADefinition()) {
923         if (VD->isStaticLocal()) {
924           SemaRef.Diag(VD->getLocation(),
925                        diag::err_constexpr_local_var_static)
926             << isa<CXXConstructorDecl>(Dcl)
927             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
928           return false;
929         }
930         if (!VD->getType()->isDependentType() &&
931             SemaRef.RequireLiteralType(
932               VD->getLocation(), VD->getType(),
933               diag::err_constexpr_local_var_non_literal_type,
934               isa<CXXConstructorDecl>(Dcl)))
935           return false;
936         if (!VD->getType()->isDependentType() &&
937             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
938           SemaRef.Diag(VD->getLocation(),
939                        diag::err_constexpr_local_var_no_init)
940             << isa<CXXConstructorDecl>(Dcl);
941           return false;
942         }
943       }
944       SemaRef.Diag(VD->getLocation(),
945                    SemaRef.getLangOpts().CPlusPlus14
946                     ? diag::warn_cxx11_compat_constexpr_local_var
947                     : diag::ext_constexpr_local_var)
948         << isa<CXXConstructorDecl>(Dcl);
949       continue;
950     }
951 
952     case Decl::NamespaceAlias:
953     case Decl::Function:
954       // These are disallowed in C++11 and permitted in C++1y. Allow them
955       // everywhere as an extension.
956       if (!Cxx1yLoc.isValid())
957         Cxx1yLoc = DS->getLocStart();
958       continue;
959 
960     default:
961       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
962         << isa<CXXConstructorDecl>(Dcl);
963       return false;
964     }
965   }
966 
967   return true;
968 }
969 
970 /// Check that the given field is initialized within a constexpr constructor.
971 ///
972 /// \param Dcl The constexpr constructor being checked.
973 /// \param Field The field being checked. This may be a member of an anonymous
974 ///        struct or union nested within the class being checked.
975 /// \param Inits All declarations, including anonymous struct/union members and
976 ///        indirect members, for which any initialization was provided.
977 /// \param Diagnosed Set to true if an error is produced.
978 static void CheckConstexprCtorInitializer(Sema &SemaRef,
979                                           const FunctionDecl *Dcl,
980                                           FieldDecl *Field,
981                                           llvm::SmallSet<Decl*, 16> &Inits,
982                                           bool &Diagnosed) {
983   if (Field->isInvalidDecl())
984     return;
985 
986   if (Field->isUnnamedBitfield())
987     return;
988 
989   // Anonymous unions with no variant members and empty anonymous structs do not
990   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
991   // indirect fields don't need initializing.
992   if (Field->isAnonymousStructOrUnion() &&
993       (Field->getType()->isUnionType()
994            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
995            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
996     return;
997 
998   if (!Inits.count(Field)) {
999     if (!Diagnosed) {
1000       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1001       Diagnosed = true;
1002     }
1003     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1004   } else if (Field->isAnonymousStructOrUnion()) {
1005     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1006     for (auto *I : RD->fields())
1007       // If an anonymous union contains an anonymous struct of which any member
1008       // is initialized, all members must be initialized.
1009       if (!RD->isUnion() || Inits.count(I))
1010         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1011   }
1012 }
1013 
1014 /// Check the provided statement is allowed in a constexpr function
1015 /// definition.
1016 static bool
1017 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1018                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1019                            SourceLocation &Cxx1yLoc) {
1020   // - its function-body shall be [...] a compound-statement that contains only
1021   switch (S->getStmtClass()) {
1022   case Stmt::NullStmtClass:
1023     //   - null statements,
1024     return true;
1025 
1026   case Stmt::DeclStmtClass:
1027     //   - static_assert-declarations
1028     //   - using-declarations,
1029     //   - using-directives,
1030     //   - typedef declarations and alias-declarations that do not define
1031     //     classes or enumerations,
1032     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1033       return false;
1034     return true;
1035 
1036   case Stmt::ReturnStmtClass:
1037     //   - and exactly one return statement;
1038     if (isa<CXXConstructorDecl>(Dcl)) {
1039       // C++1y allows return statements in constexpr constructors.
1040       if (!Cxx1yLoc.isValid())
1041         Cxx1yLoc = S->getLocStart();
1042       return true;
1043     }
1044 
1045     ReturnStmts.push_back(S->getLocStart());
1046     return true;
1047 
1048   case Stmt::CompoundStmtClass: {
1049     // C++1y allows compound-statements.
1050     if (!Cxx1yLoc.isValid())
1051       Cxx1yLoc = S->getLocStart();
1052 
1053     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1054     for (auto *BodyIt : CompStmt->body()) {
1055       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1056                                       Cxx1yLoc))
1057         return false;
1058     }
1059     return true;
1060   }
1061 
1062   case Stmt::AttributedStmtClass:
1063     if (!Cxx1yLoc.isValid())
1064       Cxx1yLoc = S->getLocStart();
1065     return true;
1066 
1067   case Stmt::IfStmtClass: {
1068     // C++1y allows if-statements.
1069     if (!Cxx1yLoc.isValid())
1070       Cxx1yLoc = S->getLocStart();
1071 
1072     IfStmt *If = cast<IfStmt>(S);
1073     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1074                                     Cxx1yLoc))
1075       return false;
1076     if (If->getElse() &&
1077         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1078                                     Cxx1yLoc))
1079       return false;
1080     return true;
1081   }
1082 
1083   case Stmt::WhileStmtClass:
1084   case Stmt::DoStmtClass:
1085   case Stmt::ForStmtClass:
1086   case Stmt::CXXForRangeStmtClass:
1087   case Stmt::ContinueStmtClass:
1088     // C++1y allows all of these. We don't allow them as extensions in C++11,
1089     // because they don't make sense without variable mutation.
1090     if (!SemaRef.getLangOpts().CPlusPlus14)
1091       break;
1092     if (!Cxx1yLoc.isValid())
1093       Cxx1yLoc = S->getLocStart();
1094     for (Stmt::child_range Children = S->children(); Children; ++Children)
1095       if (*Children &&
1096           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1097                                       Cxx1yLoc))
1098         return false;
1099     return true;
1100 
1101   case Stmt::SwitchStmtClass:
1102   case Stmt::CaseStmtClass:
1103   case Stmt::DefaultStmtClass:
1104   case Stmt::BreakStmtClass:
1105     // C++1y allows switch-statements, and since they don't need variable
1106     // mutation, we can reasonably allow them in C++11 as an extension.
1107     if (!Cxx1yLoc.isValid())
1108       Cxx1yLoc = S->getLocStart();
1109     for (Stmt::child_range Children = S->children(); Children; ++Children)
1110       if (*Children &&
1111           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1112                                       Cxx1yLoc))
1113         return false;
1114     return true;
1115 
1116   default:
1117     if (!isa<Expr>(S))
1118       break;
1119 
1120     // C++1y allows expression-statements.
1121     if (!Cxx1yLoc.isValid())
1122       Cxx1yLoc = S->getLocStart();
1123     return true;
1124   }
1125 
1126   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1127     << isa<CXXConstructorDecl>(Dcl);
1128   return false;
1129 }
1130 
1131 /// Check the body for the given constexpr function declaration only contains
1132 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1133 ///
1134 /// \return true if the body is OK, false if we have diagnosed a problem.
1135 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1136   if (isa<CXXTryStmt>(Body)) {
1137     // C++11 [dcl.constexpr]p3:
1138     //  The definition of a constexpr function shall satisfy the following
1139     //  constraints: [...]
1140     // - its function-body shall be = delete, = default, or a
1141     //   compound-statement
1142     //
1143     // C++11 [dcl.constexpr]p4:
1144     //  In the definition of a constexpr constructor, [...]
1145     // - its function-body shall not be a function-try-block;
1146     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1147       << isa<CXXConstructorDecl>(Dcl);
1148     return false;
1149   }
1150 
1151   SmallVector<SourceLocation, 4> ReturnStmts;
1152 
1153   // - its function-body shall be [...] a compound-statement that contains only
1154   //   [... list of cases ...]
1155   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1156   SourceLocation Cxx1yLoc;
1157   for (auto *BodyIt : CompBody->body()) {
1158     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1159       return false;
1160   }
1161 
1162   if (Cxx1yLoc.isValid())
1163     Diag(Cxx1yLoc,
1164          getLangOpts().CPlusPlus14
1165            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1166            : diag::ext_constexpr_body_invalid_stmt)
1167       << isa<CXXConstructorDecl>(Dcl);
1168 
1169   if (const CXXConstructorDecl *Constructor
1170         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1171     const CXXRecordDecl *RD = Constructor->getParent();
1172     // DR1359:
1173     // - every non-variant non-static data member and base class sub-object
1174     //   shall be initialized;
1175     // DR1460:
1176     // - if the class is a union having variant members, exactly one of them
1177     //   shall be initialized;
1178     if (RD->isUnion()) {
1179       if (Constructor->getNumCtorInitializers() == 0 &&
1180           RD->hasVariantMembers()) {
1181         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1182         return false;
1183       }
1184     } else if (!Constructor->isDependentContext() &&
1185                !Constructor->isDelegatingConstructor()) {
1186       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1187 
1188       // Skip detailed checking if we have enough initializers, and we would
1189       // allow at most one initializer per member.
1190       bool AnyAnonStructUnionMembers = false;
1191       unsigned Fields = 0;
1192       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1193            E = RD->field_end(); I != E; ++I, ++Fields) {
1194         if (I->isAnonymousStructOrUnion()) {
1195           AnyAnonStructUnionMembers = true;
1196           break;
1197         }
1198       }
1199       // DR1460:
1200       // - if the class is a union-like class, but is not a union, for each of
1201       //   its anonymous union members having variant members, exactly one of
1202       //   them shall be initialized;
1203       if (AnyAnonStructUnionMembers ||
1204           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1205         // Check initialization of non-static data members. Base classes are
1206         // always initialized so do not need to be checked. Dependent bases
1207         // might not have initializers in the member initializer list.
1208         llvm::SmallSet<Decl*, 16> Inits;
1209         for (const auto *I: Constructor->inits()) {
1210           if (FieldDecl *FD = I->getMember())
1211             Inits.insert(FD);
1212           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1213             Inits.insert(ID->chain_begin(), ID->chain_end());
1214         }
1215 
1216         bool Diagnosed = false;
1217         for (auto *I : RD->fields())
1218           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1219         if (Diagnosed)
1220           return false;
1221       }
1222     }
1223   } else {
1224     if (ReturnStmts.empty()) {
1225       // C++1y doesn't require constexpr functions to contain a 'return'
1226       // statement. We still do, unless the return type might be void, because
1227       // otherwise if there's no return statement, the function cannot
1228       // be used in a core constant expression.
1229       bool OK = getLangOpts().CPlusPlus14 &&
1230                 (Dcl->getReturnType()->isVoidType() ||
1231                  Dcl->getReturnType()->isDependentType());
1232       Diag(Dcl->getLocation(),
1233            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1234               : diag::err_constexpr_body_no_return);
1235       return OK;
1236     }
1237     if (ReturnStmts.size() > 1) {
1238       Diag(ReturnStmts.back(),
1239            getLangOpts().CPlusPlus14
1240              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1241              : diag::ext_constexpr_body_multiple_return);
1242       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1243         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1244     }
1245   }
1246 
1247   // C++11 [dcl.constexpr]p5:
1248   //   if no function argument values exist such that the function invocation
1249   //   substitution would produce a constant expression, the program is
1250   //   ill-formed; no diagnostic required.
1251   // C++11 [dcl.constexpr]p3:
1252   //   - every constructor call and implicit conversion used in initializing the
1253   //     return value shall be one of those allowed in a constant expression.
1254   // C++11 [dcl.constexpr]p4:
1255   //   - every constructor involved in initializing non-static data members and
1256   //     base class sub-objects shall be a constexpr constructor.
1257   SmallVector<PartialDiagnosticAt, 8> Diags;
1258   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1259     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1260       << isa<CXXConstructorDecl>(Dcl);
1261     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1262       Diag(Diags[I].first, Diags[I].second);
1263     // Don't return false here: we allow this for compatibility in
1264     // system headers.
1265   }
1266 
1267   return true;
1268 }
1269 
1270 /// isCurrentClassName - Determine whether the identifier II is the
1271 /// name of the class type currently being defined. In the case of
1272 /// nested classes, this will only return true if II is the name of
1273 /// the innermost class.
1274 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1275                               const CXXScopeSpec *SS) {
1276   assert(getLangOpts().CPlusPlus && "No class names in C!");
1277 
1278   CXXRecordDecl *CurDecl;
1279   if (SS && SS->isSet() && !SS->isInvalid()) {
1280     DeclContext *DC = computeDeclContext(*SS, true);
1281     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1282   } else
1283     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1284 
1285   if (CurDecl && CurDecl->getIdentifier())
1286     return &II == CurDecl->getIdentifier();
1287   return false;
1288 }
1289 
1290 /// \brief Determine whether the identifier II is a typo for the name of
1291 /// the class type currently being defined. If so, update it to the identifier
1292 /// that should have been used.
1293 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1294   assert(getLangOpts().CPlusPlus && "No class names in C!");
1295 
1296   if (!getLangOpts().SpellChecking)
1297     return false;
1298 
1299   CXXRecordDecl *CurDecl;
1300   if (SS && SS->isSet() && !SS->isInvalid()) {
1301     DeclContext *DC = computeDeclContext(*SS, true);
1302     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1303   } else
1304     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1305 
1306   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1307       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1308           < II->getLength()) {
1309     II = CurDecl->getIdentifier();
1310     return true;
1311   }
1312 
1313   return false;
1314 }
1315 
1316 /// \brief Determine whether the given class is a base class of the given
1317 /// class, including looking at dependent bases.
1318 static bool findCircularInheritance(const CXXRecordDecl *Class,
1319                                     const CXXRecordDecl *Current) {
1320   SmallVector<const CXXRecordDecl*, 8> Queue;
1321 
1322   Class = Class->getCanonicalDecl();
1323   while (true) {
1324     for (const auto &I : Current->bases()) {
1325       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1326       if (!Base)
1327         continue;
1328 
1329       Base = Base->getDefinition();
1330       if (!Base)
1331         continue;
1332 
1333       if (Base->getCanonicalDecl() == Class)
1334         return true;
1335 
1336       Queue.push_back(Base);
1337     }
1338 
1339     if (Queue.empty())
1340       return false;
1341 
1342     Current = Queue.pop_back_val();
1343   }
1344 
1345   return false;
1346 }
1347 
1348 /// \brief Check the validity of a C++ base class specifier.
1349 ///
1350 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1351 /// and returns NULL otherwise.
1352 CXXBaseSpecifier *
1353 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1354                          SourceRange SpecifierRange,
1355                          bool Virtual, AccessSpecifier Access,
1356                          TypeSourceInfo *TInfo,
1357                          SourceLocation EllipsisLoc) {
1358   QualType BaseType = TInfo->getType();
1359 
1360   // C++ [class.union]p1:
1361   //   A union shall not have base classes.
1362   if (Class->isUnion()) {
1363     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1364       << SpecifierRange;
1365     return nullptr;
1366   }
1367 
1368   if (EllipsisLoc.isValid() &&
1369       !TInfo->getType()->containsUnexpandedParameterPack()) {
1370     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1371       << TInfo->getTypeLoc().getSourceRange();
1372     EllipsisLoc = SourceLocation();
1373   }
1374 
1375   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1376 
1377   if (BaseType->isDependentType()) {
1378     // Make sure that we don't have circular inheritance among our dependent
1379     // bases. For non-dependent bases, the check for completeness below handles
1380     // this.
1381     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1382       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1383           ((BaseDecl = BaseDecl->getDefinition()) &&
1384            findCircularInheritance(Class, BaseDecl))) {
1385         Diag(BaseLoc, diag::err_circular_inheritance)
1386           << BaseType << Context.getTypeDeclType(Class);
1387 
1388         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1389           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1390             << BaseType;
1391 
1392         return nullptr;
1393       }
1394     }
1395 
1396     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1397                                           Class->getTagKind() == TTK_Class,
1398                                           Access, TInfo, EllipsisLoc);
1399   }
1400 
1401   // Base specifiers must be record types.
1402   if (!BaseType->isRecordType()) {
1403     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1404     return nullptr;
1405   }
1406 
1407   // C++ [class.union]p1:
1408   //   A union shall not be used as a base class.
1409   if (BaseType->isUnionType()) {
1410     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1411     return nullptr;
1412   }
1413 
1414   // For the MS ABI, propagate DLL attributes to base class templates.
1415   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1416     if (Attr *ClassAttr = getDLLAttr(Class)) {
1417       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1418               BaseType->getAsCXXRecordDecl())) {
1419         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
1420                                             BaseLoc);
1421       }
1422     }
1423   }
1424 
1425   // C++ [class.derived]p2:
1426   //   The class-name in a base-specifier shall not be an incompletely
1427   //   defined class.
1428   if (RequireCompleteType(BaseLoc, BaseType,
1429                           diag::err_incomplete_base_class, SpecifierRange)) {
1430     Class->setInvalidDecl();
1431     return nullptr;
1432   }
1433 
1434   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1435   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1436   assert(BaseDecl && "Record type has no declaration");
1437   BaseDecl = BaseDecl->getDefinition();
1438   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1439   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1440   assert(CXXBaseDecl && "Base type is not a C++ type");
1441 
1442   // A class which contains a flexible array member is not suitable for use as a
1443   // base class:
1444   //   - If the layout determines that a base comes before another base,
1445   //     the flexible array member would index into the subsequent base.
1446   //   - If the layout determines that base comes before the derived class,
1447   //     the flexible array member would index into the derived class.
1448   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1449     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1450       << CXXBaseDecl->getDeclName();
1451     return nullptr;
1452   }
1453 
1454   // C++ [class]p3:
1455   //   If a class is marked final and it appears as a base-type-specifier in
1456   //   base-clause, the program is ill-formed.
1457   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1458     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1459       << CXXBaseDecl->getDeclName()
1460       << FA->isSpelledAsSealed();
1461     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1462         << CXXBaseDecl->getDeclName() << FA->getRange();
1463     return nullptr;
1464   }
1465 
1466   if (BaseDecl->isInvalidDecl())
1467     Class->setInvalidDecl();
1468 
1469   // Create the base specifier.
1470   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1471                                         Class->getTagKind() == TTK_Class,
1472                                         Access, TInfo, EllipsisLoc);
1473 }
1474 
1475 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1476 /// one entry in the base class list of a class specifier, for
1477 /// example:
1478 ///    class foo : public bar, virtual private baz {
1479 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1480 BaseResult
1481 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1482                          ParsedAttributes &Attributes,
1483                          bool Virtual, AccessSpecifier Access,
1484                          ParsedType basetype, SourceLocation BaseLoc,
1485                          SourceLocation EllipsisLoc) {
1486   if (!classdecl)
1487     return true;
1488 
1489   AdjustDeclIfTemplate(classdecl);
1490   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1491   if (!Class)
1492     return true;
1493 
1494   // We haven't yet attached the base specifiers.
1495   Class->setIsParsingBaseSpecifiers();
1496 
1497   // We do not support any C++11 attributes on base-specifiers yet.
1498   // Diagnose any attributes we see.
1499   if (!Attributes.empty()) {
1500     for (AttributeList *Attr = Attributes.getList(); Attr;
1501          Attr = Attr->getNext()) {
1502       if (Attr->isInvalid() ||
1503           Attr->getKind() == AttributeList::IgnoredAttribute)
1504         continue;
1505       Diag(Attr->getLoc(),
1506            Attr->getKind() == AttributeList::UnknownAttribute
1507              ? diag::warn_unknown_attribute_ignored
1508              : diag::err_base_specifier_attribute)
1509         << Attr->getName();
1510     }
1511   }
1512 
1513   TypeSourceInfo *TInfo = nullptr;
1514   GetTypeFromParser(basetype, &TInfo);
1515 
1516   if (EllipsisLoc.isInvalid() &&
1517       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1518                                       UPPC_BaseType))
1519     return true;
1520 
1521   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1522                                                       Virtual, Access, TInfo,
1523                                                       EllipsisLoc))
1524     return BaseSpec;
1525   else
1526     Class->setInvalidDecl();
1527 
1528   return true;
1529 }
1530 
1531 /// Use small set to collect indirect bases.  As this is only used
1532 /// locally, there's no need to abstract the small size parameter.
1533 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1534 
1535 /// \brief Recursively add the bases of Type.  Don't add Type itself.
1536 static void
1537 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1538                   const QualType &Type)
1539 {
1540   // Even though the incoming type is a base, it might not be
1541   // a class -- it could be a template parm, for instance.
1542   if (auto Rec = Type->getAs<RecordType>()) {
1543     auto Decl = Rec->getAsCXXRecordDecl();
1544 
1545     // Iterate over its bases.
1546     for (const auto &BaseSpec : Decl->bases()) {
1547       QualType Base = Context.getCanonicalType(BaseSpec.getType())
1548         .getUnqualifiedType();
1549       if (Set.insert(Base).second)
1550         // If we've not already seen it, recurse.
1551         NoteIndirectBases(Context, Set, Base);
1552     }
1553   }
1554 }
1555 
1556 /// \brief Performs the actual work of attaching the given base class
1557 /// specifiers to a C++ class.
1558 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1559                                 unsigned NumBases) {
1560  if (NumBases == 0)
1561     return false;
1562 
1563   // Used to keep track of which base types we have already seen, so
1564   // that we can properly diagnose redundant direct base types. Note
1565   // that the key is always the unqualified canonical type of the base
1566   // class.
1567   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1568 
1569   // Used to track indirect bases so we can see if a direct base is
1570   // ambiguous.
1571   IndirectBaseSet IndirectBaseTypes;
1572 
1573   // Copy non-redundant base specifiers into permanent storage.
1574   unsigned NumGoodBases = 0;
1575   bool Invalid = false;
1576   for (unsigned idx = 0; idx < NumBases; ++idx) {
1577     QualType NewBaseType
1578       = Context.getCanonicalType(Bases[idx]->getType());
1579     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1580 
1581     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1582     if (KnownBase) {
1583       // C++ [class.mi]p3:
1584       //   A class shall not be specified as a direct base class of a
1585       //   derived class more than once.
1586       Diag(Bases[idx]->getLocStart(),
1587            diag::err_duplicate_base_class)
1588         << KnownBase->getType()
1589         << Bases[idx]->getSourceRange();
1590 
1591       // Delete the duplicate base class specifier; we're going to
1592       // overwrite its pointer later.
1593       Context.Deallocate(Bases[idx]);
1594 
1595       Invalid = true;
1596     } else {
1597       // Okay, add this new base class.
1598       KnownBase = Bases[idx];
1599       Bases[NumGoodBases++] = Bases[idx];
1600 
1601       // Note this base's direct & indirect bases, if there could be ambiguity.
1602       if (NumBases > 1)
1603         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1604 
1605       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1606         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1607         if (Class->isInterface() &&
1608               (!RD->isInterface() ||
1609                KnownBase->getAccessSpecifier() != AS_public)) {
1610           // The Microsoft extension __interface does not permit bases that
1611           // are not themselves public interfaces.
1612           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1613             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1614             << RD->getSourceRange();
1615           Invalid = true;
1616         }
1617         if (RD->hasAttr<WeakAttr>())
1618           Class->addAttr(WeakAttr::CreateImplicit(Context));
1619       }
1620     }
1621   }
1622 
1623   // Attach the remaining base class specifiers to the derived class.
1624   Class->setBases(Bases, NumGoodBases);
1625 
1626   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1627     // Check whether this direct base is inaccessible due to ambiguity.
1628     QualType BaseType = Bases[idx]->getType();
1629     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1630       .getUnqualifiedType();
1631 
1632     if (IndirectBaseTypes.count(CanonicalBase)) {
1633       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1634                          /*DetectVirtual=*/true);
1635       bool found
1636         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1637       assert(found);
1638       (void)found;
1639 
1640       if (Paths.isAmbiguous(CanonicalBase))
1641         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1642           << BaseType << getAmbiguousPathsDisplayString(Paths)
1643           << Bases[idx]->getSourceRange();
1644       else
1645         assert(Bases[idx]->isVirtual());
1646     }
1647 
1648     // Delete the base class specifier, since its data has been copied
1649     // into the CXXRecordDecl.
1650     Context.Deallocate(Bases[idx]);
1651   }
1652 
1653   return Invalid;
1654 }
1655 
1656 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1657 /// class, after checking whether there are any duplicate base
1658 /// classes.
1659 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1660                                unsigned NumBases) {
1661   if (!ClassDecl || !Bases || !NumBases)
1662     return;
1663 
1664   AdjustDeclIfTemplate(ClassDecl);
1665   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1666 }
1667 
1668 /// \brief Determine whether the type \p Derived is a C++ class that is
1669 /// derived from the type \p Base.
1670 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1671   if (!getLangOpts().CPlusPlus)
1672     return false;
1673 
1674   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1675   if (!DerivedRD)
1676     return false;
1677 
1678   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1679   if (!BaseRD)
1680     return false;
1681 
1682   // If either the base or the derived type is invalid, don't try to
1683   // check whether one is derived from the other.
1684   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1685     return false;
1686 
1687   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1688   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1689 }
1690 
1691 /// \brief Determine whether the type \p Derived is a C++ class that is
1692 /// derived from the type \p Base.
1693 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1694   if (!getLangOpts().CPlusPlus)
1695     return false;
1696 
1697   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1698   if (!DerivedRD)
1699     return false;
1700 
1701   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1702   if (!BaseRD)
1703     return false;
1704 
1705   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1706 }
1707 
1708 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1709                               CXXCastPath &BasePathArray) {
1710   assert(BasePathArray.empty() && "Base path array must be empty!");
1711   assert(Paths.isRecordingPaths() && "Must record paths!");
1712 
1713   const CXXBasePath &Path = Paths.front();
1714 
1715   // We first go backward and check if we have a virtual base.
1716   // FIXME: It would be better if CXXBasePath had the base specifier for
1717   // the nearest virtual base.
1718   unsigned Start = 0;
1719   for (unsigned I = Path.size(); I != 0; --I) {
1720     if (Path[I - 1].Base->isVirtual()) {
1721       Start = I - 1;
1722       break;
1723     }
1724   }
1725 
1726   // Now add all bases.
1727   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1728     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1729 }
1730 
1731 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1732 /// conversion (where Derived and Base are class types) is
1733 /// well-formed, meaning that the conversion is unambiguous (and
1734 /// that all of the base classes are accessible). Returns true
1735 /// and emits a diagnostic if the code is ill-formed, returns false
1736 /// otherwise. Loc is the location where this routine should point to
1737 /// if there is an error, and Range is the source range to highlight
1738 /// if there is an error.
1739 bool
1740 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1741                                    unsigned InaccessibleBaseID,
1742                                    unsigned AmbigiousBaseConvID,
1743                                    SourceLocation Loc, SourceRange Range,
1744                                    DeclarationName Name,
1745                                    CXXCastPath *BasePath) {
1746   // First, determine whether the path from Derived to Base is
1747   // ambiguous. This is slightly more expensive than checking whether
1748   // the Derived to Base conversion exists, because here we need to
1749   // explore multiple paths to determine if there is an ambiguity.
1750   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1751                      /*DetectVirtual=*/false);
1752   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1753   assert(DerivationOkay &&
1754          "Can only be used with a derived-to-base conversion");
1755   (void)DerivationOkay;
1756 
1757   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1758     if (InaccessibleBaseID) {
1759       // Check that the base class can be accessed.
1760       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1761                                    InaccessibleBaseID)) {
1762         case AR_inaccessible:
1763           return true;
1764         case AR_accessible:
1765         case AR_dependent:
1766         case AR_delayed:
1767           break;
1768       }
1769     }
1770 
1771     // Build a base path if necessary.
1772     if (BasePath)
1773       BuildBasePathArray(Paths, *BasePath);
1774     return false;
1775   }
1776 
1777   if (AmbigiousBaseConvID) {
1778     // We know that the derived-to-base conversion is ambiguous, and
1779     // we're going to produce a diagnostic. Perform the derived-to-base
1780     // search just one more time to compute all of the possible paths so
1781     // that we can print them out. This is more expensive than any of
1782     // the previous derived-to-base checks we've done, but at this point
1783     // performance isn't as much of an issue.
1784     Paths.clear();
1785     Paths.setRecordingPaths(true);
1786     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1787     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1788     (void)StillOkay;
1789 
1790     // Build up a textual representation of the ambiguous paths, e.g.,
1791     // D -> B -> A, that will be used to illustrate the ambiguous
1792     // conversions in the diagnostic. We only print one of the paths
1793     // to each base class subobject.
1794     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1795 
1796     Diag(Loc, AmbigiousBaseConvID)
1797     << Derived << Base << PathDisplayStr << Range << Name;
1798   }
1799   return true;
1800 }
1801 
1802 bool
1803 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1804                                    SourceLocation Loc, SourceRange Range,
1805                                    CXXCastPath *BasePath,
1806                                    bool IgnoreAccess) {
1807   return CheckDerivedToBaseConversion(Derived, Base,
1808                                       IgnoreAccess ? 0
1809                                        : diag::err_upcast_to_inaccessible_base,
1810                                       diag::err_ambiguous_derived_to_base_conv,
1811                                       Loc, Range, DeclarationName(),
1812                                       BasePath);
1813 }
1814 
1815 
1816 /// @brief Builds a string representing ambiguous paths from a
1817 /// specific derived class to different subobjects of the same base
1818 /// class.
1819 ///
1820 /// This function builds a string that can be used in error messages
1821 /// to show the different paths that one can take through the
1822 /// inheritance hierarchy to go from the derived class to different
1823 /// subobjects of a base class. The result looks something like this:
1824 /// @code
1825 /// struct D -> struct B -> struct A
1826 /// struct D -> struct C -> struct A
1827 /// @endcode
1828 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1829   std::string PathDisplayStr;
1830   std::set<unsigned> DisplayedPaths;
1831   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1832        Path != Paths.end(); ++Path) {
1833     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1834       // We haven't displayed a path to this particular base
1835       // class subobject yet.
1836       PathDisplayStr += "\n    ";
1837       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1838       for (CXXBasePath::const_iterator Element = Path->begin();
1839            Element != Path->end(); ++Element)
1840         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1841     }
1842   }
1843 
1844   return PathDisplayStr;
1845 }
1846 
1847 //===----------------------------------------------------------------------===//
1848 // C++ class member Handling
1849 //===----------------------------------------------------------------------===//
1850 
1851 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1852 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1853                                 SourceLocation ASLoc,
1854                                 SourceLocation ColonLoc,
1855                                 AttributeList *Attrs) {
1856   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1857   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1858                                                   ASLoc, ColonLoc);
1859   CurContext->addHiddenDecl(ASDecl);
1860   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1861 }
1862 
1863 /// CheckOverrideControl - Check C++11 override control semantics.
1864 void Sema::CheckOverrideControl(NamedDecl *D) {
1865   if (D->isInvalidDecl())
1866     return;
1867 
1868   // We only care about "override" and "final" declarations.
1869   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1870     return;
1871 
1872   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1873 
1874   // We can't check dependent instance methods.
1875   if (MD && MD->isInstance() &&
1876       (MD->getParent()->hasAnyDependentBases() ||
1877        MD->getType()->isDependentType()))
1878     return;
1879 
1880   if (MD && !MD->isVirtual()) {
1881     // If we have a non-virtual method, check if if hides a virtual method.
1882     // (In that case, it's most likely the method has the wrong type.)
1883     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1884     FindHiddenVirtualMethods(MD, OverloadedMethods);
1885 
1886     if (!OverloadedMethods.empty()) {
1887       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1888         Diag(OA->getLocation(),
1889              diag::override_keyword_hides_virtual_member_function)
1890           << "override" << (OverloadedMethods.size() > 1);
1891       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1892         Diag(FA->getLocation(),
1893              diag::override_keyword_hides_virtual_member_function)
1894           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1895           << (OverloadedMethods.size() > 1);
1896       }
1897       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1898       MD->setInvalidDecl();
1899       return;
1900     }
1901     // Fall through into the general case diagnostic.
1902     // FIXME: We might want to attempt typo correction here.
1903   }
1904 
1905   if (!MD || !MD->isVirtual()) {
1906     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1907       Diag(OA->getLocation(),
1908            diag::override_keyword_only_allowed_on_virtual_member_functions)
1909         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1910       D->dropAttr<OverrideAttr>();
1911     }
1912     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1913       Diag(FA->getLocation(),
1914            diag::override_keyword_only_allowed_on_virtual_member_functions)
1915         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1916         << FixItHint::CreateRemoval(FA->getLocation());
1917       D->dropAttr<FinalAttr>();
1918     }
1919     return;
1920   }
1921 
1922   // C++11 [class.virtual]p5:
1923   //   If a function is marked with the virt-specifier override and
1924   //   does not override a member function of a base class, the program is
1925   //   ill-formed.
1926   bool HasOverriddenMethods =
1927     MD->begin_overridden_methods() != MD->end_overridden_methods();
1928   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1929     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1930       << MD->getDeclName();
1931 }
1932 
1933 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1934   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1935     return;
1936   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1937   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1938       isa<CXXDestructorDecl>(MD))
1939     return;
1940 
1941   SourceLocation Loc = MD->getLocation();
1942   SourceLocation SpellingLoc = Loc;
1943   if (getSourceManager().isMacroArgExpansion(Loc))
1944     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1945   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1946   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1947       return;
1948 
1949   if (MD->size_overridden_methods() > 0) {
1950     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1951       << MD->getDeclName();
1952     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1953     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1954   }
1955 }
1956 
1957 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1958 /// function overrides a virtual member function marked 'final', according to
1959 /// C++11 [class.virtual]p4.
1960 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1961                                                   const CXXMethodDecl *Old) {
1962   FinalAttr *FA = Old->getAttr<FinalAttr>();
1963   if (!FA)
1964     return false;
1965 
1966   Diag(New->getLocation(), diag::err_final_function_overridden)
1967     << New->getDeclName()
1968     << FA->isSpelledAsSealed();
1969   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1970   return true;
1971 }
1972 
1973 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1974   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1975   // FIXME: Destruction of ObjC lifetime types has side-effects.
1976   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1977     return !RD->isCompleteDefinition() ||
1978            !RD->hasTrivialDefaultConstructor() ||
1979            !RD->hasTrivialDestructor();
1980   return false;
1981 }
1982 
1983 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1984   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1985     if (it->isDeclspecPropertyAttribute())
1986       return it;
1987   return nullptr;
1988 }
1989 
1990 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1991 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1992 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1993 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1994 /// present (but parsing it has been deferred).
1995 NamedDecl *
1996 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1997                                MultiTemplateParamsArg TemplateParameterLists,
1998                                Expr *BW, const VirtSpecifiers &VS,
1999                                InClassInitStyle InitStyle) {
2000   const DeclSpec &DS = D.getDeclSpec();
2001   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2002   DeclarationName Name = NameInfo.getName();
2003   SourceLocation Loc = NameInfo.getLoc();
2004 
2005   // For anonymous bitfields, the location should point to the type.
2006   if (Loc.isInvalid())
2007     Loc = D.getLocStart();
2008 
2009   Expr *BitWidth = static_cast<Expr*>(BW);
2010 
2011   assert(isa<CXXRecordDecl>(CurContext));
2012   assert(!DS.isFriendSpecified());
2013 
2014   bool isFunc = D.isDeclarationOfFunction();
2015 
2016   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2017     // The Microsoft extension __interface only permits public member functions
2018     // and prohibits constructors, destructors, operators, non-public member
2019     // functions, static methods and data members.
2020     unsigned InvalidDecl;
2021     bool ShowDeclName = true;
2022     if (!isFunc)
2023       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2024     else if (AS != AS_public)
2025       InvalidDecl = 2;
2026     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2027       InvalidDecl = 3;
2028     else switch (Name.getNameKind()) {
2029       case DeclarationName::CXXConstructorName:
2030         InvalidDecl = 4;
2031         ShowDeclName = false;
2032         break;
2033 
2034       case DeclarationName::CXXDestructorName:
2035         InvalidDecl = 5;
2036         ShowDeclName = false;
2037         break;
2038 
2039       case DeclarationName::CXXOperatorName:
2040       case DeclarationName::CXXConversionFunctionName:
2041         InvalidDecl = 6;
2042         break;
2043 
2044       default:
2045         InvalidDecl = 0;
2046         break;
2047     }
2048 
2049     if (InvalidDecl) {
2050       if (ShowDeclName)
2051         Diag(Loc, diag::err_invalid_member_in_interface)
2052           << (InvalidDecl-1) << Name;
2053       else
2054         Diag(Loc, diag::err_invalid_member_in_interface)
2055           << (InvalidDecl-1) << "";
2056       return nullptr;
2057     }
2058   }
2059 
2060   // C++ 9.2p6: A member shall not be declared to have automatic storage
2061   // duration (auto, register) or with the extern storage-class-specifier.
2062   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2063   // data members and cannot be applied to names declared const or static,
2064   // and cannot be applied to reference members.
2065   switch (DS.getStorageClassSpec()) {
2066   case DeclSpec::SCS_unspecified:
2067   case DeclSpec::SCS_typedef:
2068   case DeclSpec::SCS_static:
2069     break;
2070   case DeclSpec::SCS_mutable:
2071     if (isFunc) {
2072       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2073 
2074       // FIXME: It would be nicer if the keyword was ignored only for this
2075       // declarator. Otherwise we could get follow-up errors.
2076       D.getMutableDeclSpec().ClearStorageClassSpecs();
2077     }
2078     break;
2079   default:
2080     Diag(DS.getStorageClassSpecLoc(),
2081          diag::err_storageclass_invalid_for_member);
2082     D.getMutableDeclSpec().ClearStorageClassSpecs();
2083     break;
2084   }
2085 
2086   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2087                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2088                       !isFunc);
2089 
2090   if (DS.isConstexprSpecified() && isInstField) {
2091     SemaDiagnosticBuilder B =
2092         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2093     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2094     if (InitStyle == ICIS_NoInit) {
2095       B << 0 << 0;
2096       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2097         B << FixItHint::CreateRemoval(ConstexprLoc);
2098       else {
2099         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2100         D.getMutableDeclSpec().ClearConstexprSpec();
2101         const char *PrevSpec;
2102         unsigned DiagID;
2103         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2104             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2105         (void)Failed;
2106         assert(!Failed && "Making a constexpr member const shouldn't fail");
2107       }
2108     } else {
2109       B << 1;
2110       const char *PrevSpec;
2111       unsigned DiagID;
2112       if (D.getMutableDeclSpec().SetStorageClassSpec(
2113           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2114           Context.getPrintingPolicy())) {
2115         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2116                "This is the only DeclSpec that should fail to be applied");
2117         B << 1;
2118       } else {
2119         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2120         isInstField = false;
2121       }
2122     }
2123   }
2124 
2125   NamedDecl *Member;
2126   if (isInstField) {
2127     CXXScopeSpec &SS = D.getCXXScopeSpec();
2128 
2129     // Data members must have identifiers for names.
2130     if (!Name.isIdentifier()) {
2131       Diag(Loc, diag::err_bad_variable_name)
2132         << Name;
2133       return nullptr;
2134     }
2135 
2136     IdentifierInfo *II = Name.getAsIdentifierInfo();
2137 
2138     // Member field could not be with "template" keyword.
2139     // So TemplateParameterLists should be empty in this case.
2140     if (TemplateParameterLists.size()) {
2141       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2142       if (TemplateParams->size()) {
2143         // There is no such thing as a member field template.
2144         Diag(D.getIdentifierLoc(), diag::err_template_member)
2145             << II
2146             << SourceRange(TemplateParams->getTemplateLoc(),
2147                 TemplateParams->getRAngleLoc());
2148       } else {
2149         // There is an extraneous 'template<>' for this member.
2150         Diag(TemplateParams->getTemplateLoc(),
2151             diag::err_template_member_noparams)
2152             << II
2153             << SourceRange(TemplateParams->getTemplateLoc(),
2154                 TemplateParams->getRAngleLoc());
2155       }
2156       return nullptr;
2157     }
2158 
2159     if (SS.isSet() && !SS.isInvalid()) {
2160       // The user provided a superfluous scope specifier inside a class
2161       // definition:
2162       //
2163       // class X {
2164       //   int X::member;
2165       // };
2166       if (DeclContext *DC = computeDeclContext(SS, false))
2167         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2168       else
2169         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2170           << Name << SS.getRange();
2171 
2172       SS.clear();
2173     }
2174 
2175     AttributeList *MSPropertyAttr =
2176       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2177     if (MSPropertyAttr) {
2178       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2179                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2180       if (!Member)
2181         return nullptr;
2182       isInstField = false;
2183     } else {
2184       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2185                                 BitWidth, InitStyle, AS);
2186       assert(Member && "HandleField never returns null");
2187     }
2188   } else {
2189     assert(InitStyle == ICIS_NoInit ||
2190            D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2191 
2192     Member = HandleDeclarator(S, D, TemplateParameterLists);
2193     if (!Member)
2194       return nullptr;
2195 
2196     // Non-instance-fields can't have a bitfield.
2197     if (BitWidth) {
2198       if (Member->isInvalidDecl()) {
2199         // don't emit another diagnostic.
2200       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2201         // C++ 9.6p3: A bit-field shall not be a static member.
2202         // "static member 'A' cannot be a bit-field"
2203         Diag(Loc, diag::err_static_not_bitfield)
2204           << Name << BitWidth->getSourceRange();
2205       } else if (isa<TypedefDecl>(Member)) {
2206         // "typedef member 'x' cannot be a bit-field"
2207         Diag(Loc, diag::err_typedef_not_bitfield)
2208           << Name << BitWidth->getSourceRange();
2209       } else {
2210         // A function typedef ("typedef int f(); f a;").
2211         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2212         Diag(Loc, diag::err_not_integral_type_bitfield)
2213           << Name << cast<ValueDecl>(Member)->getType()
2214           << BitWidth->getSourceRange();
2215       }
2216 
2217       BitWidth = nullptr;
2218       Member->setInvalidDecl();
2219     }
2220 
2221     Member->setAccess(AS);
2222 
2223     // If we have declared a member function template or static data member
2224     // template, set the access of the templated declaration as well.
2225     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2226       FunTmpl->getTemplatedDecl()->setAccess(AS);
2227     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2228       VarTmpl->getTemplatedDecl()->setAccess(AS);
2229   }
2230 
2231   if (VS.isOverrideSpecified())
2232     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2233   if (VS.isFinalSpecified())
2234     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2235                                             VS.isFinalSpelledSealed()));
2236 
2237   if (VS.getLastLocation().isValid()) {
2238     // Update the end location of a method that has a virt-specifiers.
2239     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2240       MD->setRangeEnd(VS.getLastLocation());
2241   }
2242 
2243   CheckOverrideControl(Member);
2244 
2245   assert((Name || isInstField) && "No identifier for non-field ?");
2246 
2247   if (isInstField) {
2248     FieldDecl *FD = cast<FieldDecl>(Member);
2249     FieldCollector->Add(FD);
2250 
2251     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2252       // Remember all explicit private FieldDecls that have a name, no side
2253       // effects and are not part of a dependent type declaration.
2254       if (!FD->isImplicit() && FD->getDeclName() &&
2255           FD->getAccess() == AS_private &&
2256           !FD->hasAttr<UnusedAttr>() &&
2257           !FD->getParent()->isDependentContext() &&
2258           !InitializationHasSideEffects(*FD))
2259         UnusedPrivateFields.insert(FD);
2260     }
2261   }
2262 
2263   return Member;
2264 }
2265 
2266 namespace {
2267   class UninitializedFieldVisitor
2268       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2269     Sema &S;
2270     // List of Decls to generate a warning on.  Also remove Decls that become
2271     // initialized.
2272     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2273     // List of base classes of the record.  Classes are removed after their
2274     // initializers.
2275     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2276     // Vector of decls to be removed from the Decl set prior to visiting the
2277     // nodes.  These Decls may have been initialized in the prior initializer.
2278     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2279     // If non-null, add a note to the warning pointing back to the constructor.
2280     const CXXConstructorDecl *Constructor;
2281     // Variables to hold state when processing an initializer list.  When
2282     // InitList is true, special case initialization of FieldDecls matching
2283     // InitListFieldDecl.
2284     bool InitList;
2285     FieldDecl *InitListFieldDecl;
2286     llvm::SmallVector<unsigned, 4> InitFieldIndex;
2287 
2288   public:
2289     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2290     UninitializedFieldVisitor(Sema &S,
2291                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2292                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2293       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2294         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2295 
2296     // Returns true if the use of ME is not an uninitialized use.
2297     bool IsInitListMemberExprInitialized(MemberExpr *ME,
2298                                          bool CheckReferenceOnly) {
2299       llvm::SmallVector<FieldDecl*, 4> Fields;
2300       bool ReferenceField = false;
2301       while (ME) {
2302         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2303         if (!FD)
2304           return false;
2305         Fields.push_back(FD);
2306         if (FD->getType()->isReferenceType())
2307           ReferenceField = true;
2308         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2309       }
2310 
2311       // Binding a reference to an unintialized field is not an
2312       // uninitialized use.
2313       if (CheckReferenceOnly && !ReferenceField)
2314         return true;
2315 
2316       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2317       // Discard the first field since it is the field decl that is being
2318       // initialized.
2319       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2320         UsedFieldIndex.push_back((*I)->getFieldIndex());
2321       }
2322 
2323       for (auto UsedIter = UsedFieldIndex.begin(),
2324                 UsedEnd = UsedFieldIndex.end(),
2325                 OrigIter = InitFieldIndex.begin(),
2326                 OrigEnd = InitFieldIndex.end();
2327            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2328         if (*UsedIter < *OrigIter)
2329           return true;
2330         if (*UsedIter > *OrigIter)
2331           break;
2332       }
2333 
2334       return false;
2335     }
2336 
2337     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2338                           bool AddressOf) {
2339       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2340         return;
2341 
2342       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2343       // or union.
2344       MemberExpr *FieldME = ME;
2345 
2346       bool AllPODFields = FieldME->getType().isPODType(S.Context);
2347 
2348       Expr *Base = ME;
2349       while (MemberExpr *SubME =
2350                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2351 
2352         if (isa<VarDecl>(SubME->getMemberDecl()))
2353           return;
2354 
2355         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2356           if (!FD->isAnonymousStructOrUnion())
2357             FieldME = SubME;
2358 
2359         if (!FieldME->getType().isPODType(S.Context))
2360           AllPODFields = false;
2361 
2362         Base = SubME->getBase();
2363       }
2364 
2365       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2366         return;
2367 
2368       if (AddressOf && AllPODFields)
2369         return;
2370 
2371       ValueDecl* FoundVD = FieldME->getMemberDecl();
2372 
2373       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2374         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2375           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2376         }
2377 
2378         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2379           QualType T = BaseCast->getType();
2380           if (T->isPointerType() &&
2381               BaseClasses.count(T->getPointeeType())) {
2382             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2383                 << T->getPointeeType() << FoundVD;
2384           }
2385         }
2386       }
2387 
2388       if (!Decls.count(FoundVD))
2389         return;
2390 
2391       const bool IsReference = FoundVD->getType()->isReferenceType();
2392 
2393       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2394         // Special checking for initializer lists.
2395         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2396           return;
2397         }
2398       } else {
2399         // Prevent double warnings on use of unbounded references.
2400         if (CheckReferenceOnly && !IsReference)
2401           return;
2402       }
2403 
2404       unsigned diag = IsReference
2405           ? diag::warn_reference_field_is_uninit
2406           : diag::warn_field_is_uninit;
2407       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2408       if (Constructor)
2409         S.Diag(Constructor->getLocation(),
2410                diag::note_uninit_in_this_constructor)
2411           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2412 
2413     }
2414 
2415     void HandleValue(Expr *E, bool AddressOf) {
2416       E = E->IgnoreParens();
2417 
2418       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2419         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2420                          AddressOf /*AddressOf*/);
2421         return;
2422       }
2423 
2424       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2425         Visit(CO->getCond());
2426         HandleValue(CO->getTrueExpr(), AddressOf);
2427         HandleValue(CO->getFalseExpr(), AddressOf);
2428         return;
2429       }
2430 
2431       if (BinaryConditionalOperator *BCO =
2432               dyn_cast<BinaryConditionalOperator>(E)) {
2433         Visit(BCO->getCond());
2434         HandleValue(BCO->getFalseExpr(), AddressOf);
2435         return;
2436       }
2437 
2438       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2439         HandleValue(OVE->getSourceExpr(), AddressOf);
2440         return;
2441       }
2442 
2443       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2444         switch (BO->getOpcode()) {
2445         default:
2446           break;
2447         case(BO_PtrMemD):
2448         case(BO_PtrMemI):
2449           HandleValue(BO->getLHS(), AddressOf);
2450           Visit(BO->getRHS());
2451           return;
2452         case(BO_Comma):
2453           Visit(BO->getLHS());
2454           HandleValue(BO->getRHS(), AddressOf);
2455           return;
2456         }
2457       }
2458 
2459       Visit(E);
2460     }
2461 
2462     void CheckInitListExpr(InitListExpr *ILE) {
2463       InitFieldIndex.push_back(0);
2464       for (auto Child : ILE->children()) {
2465         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2466           CheckInitListExpr(SubList);
2467         } else {
2468           Visit(Child);
2469         }
2470         ++InitFieldIndex.back();
2471       }
2472       InitFieldIndex.pop_back();
2473     }
2474 
2475     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2476                           FieldDecl *Field, const Type *BaseClass) {
2477       // Remove Decls that may have been initialized in the previous
2478       // initializer.
2479       for (ValueDecl* VD : DeclsToRemove)
2480         Decls.erase(VD);
2481       DeclsToRemove.clear();
2482 
2483       Constructor = FieldConstructor;
2484       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2485 
2486       if (ILE && Field) {
2487         InitList = true;
2488         InitListFieldDecl = Field;
2489         InitFieldIndex.clear();
2490         CheckInitListExpr(ILE);
2491       } else {
2492         InitList = false;
2493         Visit(E);
2494       }
2495 
2496       if (Field)
2497         Decls.erase(Field);
2498       if (BaseClass)
2499         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2500     }
2501 
2502     void VisitMemberExpr(MemberExpr *ME) {
2503       // All uses of unbounded reference fields will warn.
2504       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2505     }
2506 
2507     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2508       if (E->getCastKind() == CK_LValueToRValue) {
2509         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2510         return;
2511       }
2512 
2513       Inherited::VisitImplicitCastExpr(E);
2514     }
2515 
2516     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2517       if (E->getConstructor()->isCopyConstructor()) {
2518         Expr *ArgExpr = E->getArg(0);
2519         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2520           if (ILE->getNumInits() == 1)
2521             ArgExpr = ILE->getInit(0);
2522         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2523           if (ICE->getCastKind() == CK_NoOp)
2524             ArgExpr = ICE->getSubExpr();
2525         HandleValue(ArgExpr, false /*AddressOf*/);
2526         return;
2527       }
2528       Inherited::VisitCXXConstructExpr(E);
2529     }
2530 
2531     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2532       Expr *Callee = E->getCallee();
2533       if (isa<MemberExpr>(Callee)) {
2534         HandleValue(Callee, false /*AddressOf*/);
2535         for (auto Arg : E->arguments())
2536           Visit(Arg);
2537         return;
2538       }
2539 
2540       Inherited::VisitCXXMemberCallExpr(E);
2541     }
2542 
2543     void VisitCallExpr(CallExpr *E) {
2544       // Treat std::move as a use.
2545       if (E->getNumArgs() == 1) {
2546         if (FunctionDecl *FD = E->getDirectCallee()) {
2547           if (FD->isInStdNamespace() && FD->getIdentifier() &&
2548               FD->getIdentifier()->isStr("move")) {
2549             HandleValue(E->getArg(0), false /*AddressOf*/);
2550             return;
2551           }
2552         }
2553       }
2554 
2555       Inherited::VisitCallExpr(E);
2556     }
2557 
2558     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2559       Expr *Callee = E->getCallee();
2560 
2561       if (isa<UnresolvedLookupExpr>(Callee))
2562         return Inherited::VisitCXXOperatorCallExpr(E);
2563 
2564       Visit(Callee);
2565       for (auto Arg : E->arguments())
2566         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2567     }
2568 
2569     void VisitBinaryOperator(BinaryOperator *E) {
2570       // If a field assignment is detected, remove the field from the
2571       // uninitiailized field set.
2572       if (E->getOpcode() == BO_Assign)
2573         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2574           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2575             if (!FD->getType()->isReferenceType())
2576               DeclsToRemove.push_back(FD);
2577 
2578       if (E->isCompoundAssignmentOp()) {
2579         HandleValue(E->getLHS(), false /*AddressOf*/);
2580         Visit(E->getRHS());
2581         return;
2582       }
2583 
2584       Inherited::VisitBinaryOperator(E);
2585     }
2586 
2587     void VisitUnaryOperator(UnaryOperator *E) {
2588       if (E->isIncrementDecrementOp()) {
2589         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2590         return;
2591       }
2592       if (E->getOpcode() == UO_AddrOf) {
2593         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2594           HandleValue(ME->getBase(), true /*AddressOf*/);
2595           return;
2596         }
2597       }
2598 
2599       Inherited::VisitUnaryOperator(E);
2600     }
2601   };
2602 
2603   // Diagnose value-uses of fields to initialize themselves, e.g.
2604   //   foo(foo)
2605   // where foo is not also a parameter to the constructor.
2606   // Also diagnose across field uninitialized use such as
2607   //   x(y), y(x)
2608   // TODO: implement -Wuninitialized and fold this into that framework.
2609   static void DiagnoseUninitializedFields(
2610       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2611 
2612     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2613                                            Constructor->getLocation())) {
2614       return;
2615     }
2616 
2617     if (Constructor->isInvalidDecl())
2618       return;
2619 
2620     const CXXRecordDecl *RD = Constructor->getParent();
2621 
2622     if (RD->getDescribedClassTemplate())
2623       return;
2624 
2625     // Holds fields that are uninitialized.
2626     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2627 
2628     // At the beginning, all fields are uninitialized.
2629     for (auto *I : RD->decls()) {
2630       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2631         UninitializedFields.insert(FD);
2632       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2633         UninitializedFields.insert(IFD->getAnonField());
2634       }
2635     }
2636 
2637     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2638     for (auto I : RD->bases())
2639       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2640 
2641     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2642       return;
2643 
2644     UninitializedFieldVisitor UninitializedChecker(SemaRef,
2645                                                    UninitializedFields,
2646                                                    UninitializedBaseClasses);
2647 
2648     for (const auto *FieldInit : Constructor->inits()) {
2649       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2650         break;
2651 
2652       Expr *InitExpr = FieldInit->getInit();
2653       if (!InitExpr)
2654         continue;
2655 
2656       if (CXXDefaultInitExpr *Default =
2657               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2658         InitExpr = Default->getExpr();
2659         if (!InitExpr)
2660           continue;
2661         // In class initializers will point to the constructor.
2662         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2663                                               FieldInit->getAnyMember(),
2664                                               FieldInit->getBaseClass());
2665       } else {
2666         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2667                                               FieldInit->getAnyMember(),
2668                                               FieldInit->getBaseClass());
2669       }
2670     }
2671   }
2672 } // namespace
2673 
2674 /// \brief Enter a new C++ default initializer scope. After calling this, the
2675 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2676 /// parsing or instantiating the initializer failed.
2677 void Sema::ActOnStartCXXInClassMemberInitializer() {
2678   // Create a synthetic function scope to represent the call to the constructor
2679   // that notionally surrounds a use of this initializer.
2680   PushFunctionScope();
2681 }
2682 
2683 /// \brief This is invoked after parsing an in-class initializer for a
2684 /// non-static C++ class member, and after instantiating an in-class initializer
2685 /// in a class template. Such actions are deferred until the class is complete.
2686 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2687                                                   SourceLocation InitLoc,
2688                                                   Expr *InitExpr) {
2689   // Pop the notional constructor scope we created earlier.
2690   PopFunctionScopeInfo(nullptr, D);
2691 
2692   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2693   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2694          "must set init style when field is created");
2695 
2696   if (!InitExpr) {
2697     D->setInvalidDecl();
2698     if (FD)
2699       FD->removeInClassInitializer();
2700     return;
2701   }
2702 
2703   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2704     FD->setInvalidDecl();
2705     FD->removeInClassInitializer();
2706     return;
2707   }
2708 
2709   ExprResult Init = InitExpr;
2710   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2711     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2712     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2713         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2714         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2715     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2716     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2717     if (Init.isInvalid()) {
2718       FD->setInvalidDecl();
2719       return;
2720     }
2721   }
2722 
2723   // C++11 [class.base.init]p7:
2724   //   The initialization of each base and member constitutes a
2725   //   full-expression.
2726   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2727   if (Init.isInvalid()) {
2728     FD->setInvalidDecl();
2729     return;
2730   }
2731 
2732   InitExpr = Init.get();
2733 
2734   FD->setInClassInitializer(InitExpr);
2735 }
2736 
2737 /// \brief Find the direct and/or virtual base specifiers that
2738 /// correspond to the given base type, for use in base initialization
2739 /// within a constructor.
2740 static bool FindBaseInitializer(Sema &SemaRef,
2741                                 CXXRecordDecl *ClassDecl,
2742                                 QualType BaseType,
2743                                 const CXXBaseSpecifier *&DirectBaseSpec,
2744                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2745   // First, check for a direct base class.
2746   DirectBaseSpec = nullptr;
2747   for (const auto &Base : ClassDecl->bases()) {
2748     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2749       // We found a direct base of this type. That's what we're
2750       // initializing.
2751       DirectBaseSpec = &Base;
2752       break;
2753     }
2754   }
2755 
2756   // Check for a virtual base class.
2757   // FIXME: We might be able to short-circuit this if we know in advance that
2758   // there are no virtual bases.
2759   VirtualBaseSpec = nullptr;
2760   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2761     // We haven't found a base yet; search the class hierarchy for a
2762     // virtual base class.
2763     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2764                        /*DetectVirtual=*/false);
2765     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2766                               BaseType, Paths)) {
2767       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2768            Path != Paths.end(); ++Path) {
2769         if (Path->back().Base->isVirtual()) {
2770           VirtualBaseSpec = Path->back().Base;
2771           break;
2772         }
2773       }
2774     }
2775   }
2776 
2777   return DirectBaseSpec || VirtualBaseSpec;
2778 }
2779 
2780 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2781 MemInitResult
2782 Sema::ActOnMemInitializer(Decl *ConstructorD,
2783                           Scope *S,
2784                           CXXScopeSpec &SS,
2785                           IdentifierInfo *MemberOrBase,
2786                           ParsedType TemplateTypeTy,
2787                           const DeclSpec &DS,
2788                           SourceLocation IdLoc,
2789                           Expr *InitList,
2790                           SourceLocation EllipsisLoc) {
2791   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2792                              DS, IdLoc, InitList,
2793                              EllipsisLoc);
2794 }
2795 
2796 /// \brief Handle a C++ member initializer using parentheses syntax.
2797 MemInitResult
2798 Sema::ActOnMemInitializer(Decl *ConstructorD,
2799                           Scope *S,
2800                           CXXScopeSpec &SS,
2801                           IdentifierInfo *MemberOrBase,
2802                           ParsedType TemplateTypeTy,
2803                           const DeclSpec &DS,
2804                           SourceLocation IdLoc,
2805                           SourceLocation LParenLoc,
2806                           ArrayRef<Expr *> Args,
2807                           SourceLocation RParenLoc,
2808                           SourceLocation EllipsisLoc) {
2809   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2810                                            Args, RParenLoc);
2811   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2812                              DS, IdLoc, List, EllipsisLoc);
2813 }
2814 
2815 namespace {
2816 
2817 // Callback to only accept typo corrections that can be a valid C++ member
2818 // intializer: either a non-static field member or a base class.
2819 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2820 public:
2821   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2822       : ClassDecl(ClassDecl) {}
2823 
2824   bool ValidateCandidate(const TypoCorrection &candidate) override {
2825     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2826       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2827         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2828       return isa<TypeDecl>(ND);
2829     }
2830     return false;
2831   }
2832 
2833 private:
2834   CXXRecordDecl *ClassDecl;
2835 };
2836 
2837 } // namespace
2838 
2839 /// \brief Handle a C++ member initializer.
2840 MemInitResult
2841 Sema::BuildMemInitializer(Decl *ConstructorD,
2842                           Scope *S,
2843                           CXXScopeSpec &SS,
2844                           IdentifierInfo *MemberOrBase,
2845                           ParsedType TemplateTypeTy,
2846                           const DeclSpec &DS,
2847                           SourceLocation IdLoc,
2848                           Expr *Init,
2849                           SourceLocation EllipsisLoc) {
2850   ExprResult Res = CorrectDelayedTyposInExpr(Init);
2851   if (!Res.isUsable())
2852     return true;
2853   Init = Res.get();
2854 
2855   if (!ConstructorD)
2856     return true;
2857 
2858   AdjustDeclIfTemplate(ConstructorD);
2859 
2860   CXXConstructorDecl *Constructor
2861     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2862   if (!Constructor) {
2863     // The user wrote a constructor initializer on a function that is
2864     // not a C++ constructor. Ignore the error for now, because we may
2865     // have more member initializers coming; we'll diagnose it just
2866     // once in ActOnMemInitializers.
2867     return true;
2868   }
2869 
2870   CXXRecordDecl *ClassDecl = Constructor->getParent();
2871 
2872   // C++ [class.base.init]p2:
2873   //   Names in a mem-initializer-id are looked up in the scope of the
2874   //   constructor's class and, if not found in that scope, are looked
2875   //   up in the scope containing the constructor's definition.
2876   //   [Note: if the constructor's class contains a member with the
2877   //   same name as a direct or virtual base class of the class, a
2878   //   mem-initializer-id naming the member or base class and composed
2879   //   of a single identifier refers to the class member. A
2880   //   mem-initializer-id for the hidden base class may be specified
2881   //   using a qualified name. ]
2882   if (!SS.getScopeRep() && !TemplateTypeTy) {
2883     // Look for a member, first.
2884     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2885     if (!Result.empty()) {
2886       ValueDecl *Member;
2887       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2888           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2889         if (EllipsisLoc.isValid())
2890           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2891             << MemberOrBase
2892             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2893 
2894         return BuildMemberInitializer(Member, Init, IdLoc);
2895       }
2896     }
2897   }
2898   // It didn't name a member, so see if it names a class.
2899   QualType BaseType;
2900   TypeSourceInfo *TInfo = nullptr;
2901 
2902   if (TemplateTypeTy) {
2903     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2904   } else if (DS.getTypeSpecType() == TST_decltype) {
2905     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2906   } else {
2907     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2908     LookupParsedName(R, S, &SS);
2909 
2910     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2911     if (!TyD) {
2912       if (R.isAmbiguous()) return true;
2913 
2914       // We don't want access-control diagnostics here.
2915       R.suppressDiagnostics();
2916 
2917       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2918         bool NotUnknownSpecialization = false;
2919         DeclContext *DC = computeDeclContext(SS, false);
2920         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2921           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2922 
2923         if (!NotUnknownSpecialization) {
2924           // When the scope specifier can refer to a member of an unknown
2925           // specialization, we take it as a type name.
2926           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2927                                        SS.getWithLocInContext(Context),
2928                                        *MemberOrBase, IdLoc);
2929           if (BaseType.isNull())
2930             return true;
2931 
2932           R.clear();
2933           R.setLookupName(MemberOrBase);
2934         }
2935       }
2936 
2937       // If no results were found, try to correct typos.
2938       TypoCorrection Corr;
2939       if (R.empty() && BaseType.isNull() &&
2940           (Corr = CorrectTypo(
2941                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2942                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2943                CTK_ErrorRecovery, ClassDecl))) {
2944         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2945           // We have found a non-static data member with a similar
2946           // name to what was typed; complain and initialize that
2947           // member.
2948           diagnoseTypo(Corr,
2949                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2950                          << MemberOrBase << true);
2951           return BuildMemberInitializer(Member, Init, IdLoc);
2952         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2953           const CXXBaseSpecifier *DirectBaseSpec;
2954           const CXXBaseSpecifier *VirtualBaseSpec;
2955           if (FindBaseInitializer(*this, ClassDecl,
2956                                   Context.getTypeDeclType(Type),
2957                                   DirectBaseSpec, VirtualBaseSpec)) {
2958             // We have found a direct or virtual base class with a
2959             // similar name to what was typed; complain and initialize
2960             // that base class.
2961             diagnoseTypo(Corr,
2962                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2963                            << MemberOrBase << false,
2964                          PDiag() /*Suppress note, we provide our own.*/);
2965 
2966             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2967                                                               : VirtualBaseSpec;
2968             Diag(BaseSpec->getLocStart(),
2969                  diag::note_base_class_specified_here)
2970               << BaseSpec->getType()
2971               << BaseSpec->getSourceRange();
2972 
2973             TyD = Type;
2974           }
2975         }
2976       }
2977 
2978       if (!TyD && BaseType.isNull()) {
2979         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2980           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2981         return true;
2982       }
2983     }
2984 
2985     if (BaseType.isNull()) {
2986       BaseType = Context.getTypeDeclType(TyD);
2987       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
2988       if (SS.isSet())
2989         // FIXME: preserve source range information
2990         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2991                                              BaseType);
2992     }
2993   }
2994 
2995   if (!TInfo)
2996     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2997 
2998   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2999 }
3000 
3001 /// Checks a member initializer expression for cases where reference (or
3002 /// pointer) members are bound to by-value parameters (or their addresses).
3003 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3004                                                Expr *Init,
3005                                                SourceLocation IdLoc) {
3006   QualType MemberTy = Member->getType();
3007 
3008   // We only handle pointers and references currently.
3009   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3010   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3011     return;
3012 
3013   const bool IsPointer = MemberTy->isPointerType();
3014   if (IsPointer) {
3015     if (const UnaryOperator *Op
3016           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3017       // The only case we're worried about with pointers requires taking the
3018       // address.
3019       if (Op->getOpcode() != UO_AddrOf)
3020         return;
3021 
3022       Init = Op->getSubExpr();
3023     } else {
3024       // We only handle address-of expression initializers for pointers.
3025       return;
3026     }
3027   }
3028 
3029   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3030     // We only warn when referring to a non-reference parameter declaration.
3031     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3032     if (!Parameter || Parameter->getType()->isReferenceType())
3033       return;
3034 
3035     S.Diag(Init->getExprLoc(),
3036            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3037                      : diag::warn_bind_ref_member_to_parameter)
3038       << Member << Parameter << Init->getSourceRange();
3039   } else {
3040     // Other initializers are fine.
3041     return;
3042   }
3043 
3044   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3045     << (unsigned)IsPointer;
3046 }
3047 
3048 MemInitResult
3049 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3050                              SourceLocation IdLoc) {
3051   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3052   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3053   assert((DirectMember || IndirectMember) &&
3054          "Member must be a FieldDecl or IndirectFieldDecl");
3055 
3056   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3057     return true;
3058 
3059   if (Member->isInvalidDecl())
3060     return true;
3061 
3062   MultiExprArg Args;
3063   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3064     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3065   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3066     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3067   } else {
3068     // Template instantiation doesn't reconstruct ParenListExprs for us.
3069     Args = Init;
3070   }
3071 
3072   SourceRange InitRange = Init->getSourceRange();
3073 
3074   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3075     // Can't check initialization for a member of dependent type or when
3076     // any of the arguments are type-dependent expressions.
3077     DiscardCleanupsInEvaluationContext();
3078   } else {
3079     bool InitList = false;
3080     if (isa<InitListExpr>(Init)) {
3081       InitList = true;
3082       Args = Init;
3083     }
3084 
3085     // Initialize the member.
3086     InitializedEntity MemberEntity =
3087       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3088                    : InitializedEntity::InitializeMember(IndirectMember,
3089                                                          nullptr);
3090     InitializationKind Kind =
3091       InitList ? InitializationKind::CreateDirectList(IdLoc)
3092                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3093                                                   InitRange.getEnd());
3094 
3095     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3096     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3097                                             nullptr);
3098     if (MemberInit.isInvalid())
3099       return true;
3100 
3101     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3102 
3103     // C++11 [class.base.init]p7:
3104     //   The initialization of each base and member constitutes a
3105     //   full-expression.
3106     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3107     if (MemberInit.isInvalid())
3108       return true;
3109 
3110     Init = MemberInit.get();
3111   }
3112 
3113   if (DirectMember) {
3114     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3115                                             InitRange.getBegin(), Init,
3116                                             InitRange.getEnd());
3117   } else {
3118     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3119                                             InitRange.getBegin(), Init,
3120                                             InitRange.getEnd());
3121   }
3122 }
3123 
3124 MemInitResult
3125 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3126                                  CXXRecordDecl *ClassDecl) {
3127   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3128   if (!LangOpts.CPlusPlus11)
3129     return Diag(NameLoc, diag::err_delegating_ctor)
3130       << TInfo->getTypeLoc().getLocalSourceRange();
3131   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3132 
3133   bool InitList = true;
3134   MultiExprArg Args = Init;
3135   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3136     InitList = false;
3137     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3138   }
3139 
3140   SourceRange InitRange = Init->getSourceRange();
3141   // Initialize the object.
3142   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3143                                      QualType(ClassDecl->getTypeForDecl(), 0));
3144   InitializationKind Kind =
3145     InitList ? InitializationKind::CreateDirectList(NameLoc)
3146              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3147                                                 InitRange.getEnd());
3148   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3149   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3150                                               Args, nullptr);
3151   if (DelegationInit.isInvalid())
3152     return true;
3153 
3154   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3155          "Delegating constructor with no target?");
3156 
3157   // C++11 [class.base.init]p7:
3158   //   The initialization of each base and member constitutes a
3159   //   full-expression.
3160   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3161                                        InitRange.getBegin());
3162   if (DelegationInit.isInvalid())
3163     return true;
3164 
3165   // If we are in a dependent context, template instantiation will
3166   // perform this type-checking again. Just save the arguments that we
3167   // received in a ParenListExpr.
3168   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3169   // of the information that we have about the base
3170   // initializer. However, deconstructing the ASTs is a dicey process,
3171   // and this approach is far more likely to get the corner cases right.
3172   if (CurContext->isDependentContext())
3173     DelegationInit = Init;
3174 
3175   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3176                                           DelegationInit.getAs<Expr>(),
3177                                           InitRange.getEnd());
3178 }
3179 
3180 MemInitResult
3181 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3182                            Expr *Init, CXXRecordDecl *ClassDecl,
3183                            SourceLocation EllipsisLoc) {
3184   SourceLocation BaseLoc
3185     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3186 
3187   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3188     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3189              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3190 
3191   // C++ [class.base.init]p2:
3192   //   [...] Unless the mem-initializer-id names a nonstatic data
3193   //   member of the constructor's class or a direct or virtual base
3194   //   of that class, the mem-initializer is ill-formed. A
3195   //   mem-initializer-list can initialize a base class using any
3196   //   name that denotes that base class type.
3197   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3198 
3199   SourceRange InitRange = Init->getSourceRange();
3200   if (EllipsisLoc.isValid()) {
3201     // This is a pack expansion.
3202     if (!BaseType->containsUnexpandedParameterPack())  {
3203       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3204         << SourceRange(BaseLoc, InitRange.getEnd());
3205 
3206       EllipsisLoc = SourceLocation();
3207     }
3208   } else {
3209     // Check for any unexpanded parameter packs.
3210     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3211       return true;
3212 
3213     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3214       return true;
3215   }
3216 
3217   // Check for direct and virtual base classes.
3218   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3219   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3220   if (!Dependent) {
3221     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3222                                        BaseType))
3223       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3224 
3225     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3226                         VirtualBaseSpec);
3227 
3228     // C++ [base.class.init]p2:
3229     // Unless the mem-initializer-id names a nonstatic data member of the
3230     // constructor's class or a direct or virtual base of that class, the
3231     // mem-initializer is ill-formed.
3232     if (!DirectBaseSpec && !VirtualBaseSpec) {
3233       // If the class has any dependent bases, then it's possible that
3234       // one of those types will resolve to the same type as
3235       // BaseType. Therefore, just treat this as a dependent base
3236       // class initialization.  FIXME: Should we try to check the
3237       // initialization anyway? It seems odd.
3238       if (ClassDecl->hasAnyDependentBases())
3239         Dependent = true;
3240       else
3241         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3242           << BaseType << Context.getTypeDeclType(ClassDecl)
3243           << BaseTInfo->getTypeLoc().getLocalSourceRange();
3244     }
3245   }
3246 
3247   if (Dependent) {
3248     DiscardCleanupsInEvaluationContext();
3249 
3250     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3251                                             /*IsVirtual=*/false,
3252                                             InitRange.getBegin(), Init,
3253                                             InitRange.getEnd(), EllipsisLoc);
3254   }
3255 
3256   // C++ [base.class.init]p2:
3257   //   If a mem-initializer-id is ambiguous because it designates both
3258   //   a direct non-virtual base class and an inherited virtual base
3259   //   class, the mem-initializer is ill-formed.
3260   if (DirectBaseSpec && VirtualBaseSpec)
3261     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3262       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3263 
3264   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3265   if (!BaseSpec)
3266     BaseSpec = VirtualBaseSpec;
3267 
3268   // Initialize the base.
3269   bool InitList = true;
3270   MultiExprArg Args = Init;
3271   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3272     InitList = false;
3273     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3274   }
3275 
3276   InitializedEntity BaseEntity =
3277     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3278   InitializationKind Kind =
3279     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3280              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3281                                                 InitRange.getEnd());
3282   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3283   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3284   if (BaseInit.isInvalid())
3285     return true;
3286 
3287   // C++11 [class.base.init]p7:
3288   //   The initialization of each base and member constitutes a
3289   //   full-expression.
3290   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3291   if (BaseInit.isInvalid())
3292     return true;
3293 
3294   // If we are in a dependent context, template instantiation will
3295   // perform this type-checking again. Just save the arguments that we
3296   // received in a ParenListExpr.
3297   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3298   // of the information that we have about the base
3299   // initializer. However, deconstructing the ASTs is a dicey process,
3300   // and this approach is far more likely to get the corner cases right.
3301   if (CurContext->isDependentContext())
3302     BaseInit = Init;
3303 
3304   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3305                                           BaseSpec->isVirtual(),
3306                                           InitRange.getBegin(),
3307                                           BaseInit.getAs<Expr>(),
3308                                           InitRange.getEnd(), EllipsisLoc);
3309 }
3310 
3311 // Create a static_cast\<T&&>(expr).
3312 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3313   if (T.isNull()) T = E->getType();
3314   QualType TargetType = SemaRef.BuildReferenceType(
3315       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3316   SourceLocation ExprLoc = E->getLocStart();
3317   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3318       TargetType, ExprLoc);
3319 
3320   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3321                                    SourceRange(ExprLoc, ExprLoc),
3322                                    E->getSourceRange()).get();
3323 }
3324 
3325 /// ImplicitInitializerKind - How an implicit base or member initializer should
3326 /// initialize its base or member.
3327 enum ImplicitInitializerKind {
3328   IIK_Default,
3329   IIK_Copy,
3330   IIK_Move,
3331   IIK_Inherit
3332 };
3333 
3334 static bool
3335 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3336                              ImplicitInitializerKind ImplicitInitKind,
3337                              CXXBaseSpecifier *BaseSpec,
3338                              bool IsInheritedVirtualBase,
3339                              CXXCtorInitializer *&CXXBaseInit) {
3340   InitializedEntity InitEntity
3341     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3342                                         IsInheritedVirtualBase);
3343 
3344   ExprResult BaseInit;
3345 
3346   switch (ImplicitInitKind) {
3347   case IIK_Inherit: {
3348     const CXXRecordDecl *Inherited =
3349         Constructor->getInheritedConstructor()->getParent();
3350     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3351     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3352       // C++11 [class.inhctor]p8:
3353       //   Each expression in the expression-list is of the form
3354       //   static_cast<T&&>(p), where p is the name of the corresponding
3355       //   constructor parameter and T is the declared type of p.
3356       SmallVector<Expr*, 16> Args;
3357       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3358         ParmVarDecl *PD = Constructor->getParamDecl(I);
3359         ExprResult ArgExpr =
3360             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3361                                      VK_LValue, SourceLocation());
3362         if (ArgExpr.isInvalid())
3363           return true;
3364         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3365       }
3366 
3367       InitializationKind InitKind = InitializationKind::CreateDirect(
3368           Constructor->getLocation(), SourceLocation(), SourceLocation());
3369       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3370       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3371       break;
3372     }
3373   }
3374   // Fall through.
3375   case IIK_Default: {
3376     InitializationKind InitKind
3377       = InitializationKind::CreateDefault(Constructor->getLocation());
3378     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3379     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3380     break;
3381   }
3382 
3383   case IIK_Move:
3384   case IIK_Copy: {
3385     bool Moving = ImplicitInitKind == IIK_Move;
3386     ParmVarDecl *Param = Constructor->getParamDecl(0);
3387     QualType ParamType = Param->getType().getNonReferenceType();
3388 
3389     Expr *CopyCtorArg =
3390       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3391                           SourceLocation(), Param, false,
3392                           Constructor->getLocation(), ParamType,
3393                           VK_LValue, nullptr);
3394 
3395     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3396 
3397     // Cast to the base class to avoid ambiguities.
3398     QualType ArgTy =
3399       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3400                                        ParamType.getQualifiers());
3401 
3402     if (Moving) {
3403       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3404     }
3405 
3406     CXXCastPath BasePath;
3407     BasePath.push_back(BaseSpec);
3408     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3409                                             CK_UncheckedDerivedToBase,
3410                                             Moving ? VK_XValue : VK_LValue,
3411                                             &BasePath).get();
3412 
3413     InitializationKind InitKind
3414       = InitializationKind::CreateDirect(Constructor->getLocation(),
3415                                          SourceLocation(), SourceLocation());
3416     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3417     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3418     break;
3419   }
3420   }
3421 
3422   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3423   if (BaseInit.isInvalid())
3424     return true;
3425 
3426   CXXBaseInit =
3427     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3428                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3429                                                         SourceLocation()),
3430                                              BaseSpec->isVirtual(),
3431                                              SourceLocation(),
3432                                              BaseInit.getAs<Expr>(),
3433                                              SourceLocation(),
3434                                              SourceLocation());
3435 
3436   return false;
3437 }
3438 
3439 static bool RefersToRValueRef(Expr *MemRef) {
3440   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3441   return Referenced->getType()->isRValueReferenceType();
3442 }
3443 
3444 static bool
3445 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3446                                ImplicitInitializerKind ImplicitInitKind,
3447                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3448                                CXXCtorInitializer *&CXXMemberInit) {
3449   if (Field->isInvalidDecl())
3450     return true;
3451 
3452   SourceLocation Loc = Constructor->getLocation();
3453 
3454   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3455     bool Moving = ImplicitInitKind == IIK_Move;
3456     ParmVarDecl *Param = Constructor->getParamDecl(0);
3457     QualType ParamType = Param->getType().getNonReferenceType();
3458 
3459     // Suppress copying zero-width bitfields.
3460     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3461       return false;
3462 
3463     Expr *MemberExprBase =
3464       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3465                           SourceLocation(), Param, false,
3466                           Loc, ParamType, VK_LValue, nullptr);
3467 
3468     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3469 
3470     if (Moving) {
3471       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3472     }
3473 
3474     // Build a reference to this field within the parameter.
3475     CXXScopeSpec SS;
3476     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3477                               Sema::LookupMemberName);
3478     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3479                                   : cast<ValueDecl>(Field), AS_public);
3480     MemberLookup.resolveKind();
3481     ExprResult CtorArg
3482       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3483                                          ParamType, Loc,
3484                                          /*IsArrow=*/false,
3485                                          SS,
3486                                          /*TemplateKWLoc=*/SourceLocation(),
3487                                          /*FirstQualifierInScope=*/nullptr,
3488                                          MemberLookup,
3489                                          /*TemplateArgs=*/nullptr);
3490     if (CtorArg.isInvalid())
3491       return true;
3492 
3493     // C++11 [class.copy]p15:
3494     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3495     //     with static_cast<T&&>(x.m);
3496     if (RefersToRValueRef(CtorArg.get())) {
3497       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3498     }
3499 
3500     // When the field we are copying is an array, create index variables for
3501     // each dimension of the array. We use these index variables to subscript
3502     // the source array, and other clients (e.g., CodeGen) will perform the
3503     // necessary iteration with these index variables.
3504     SmallVector<VarDecl *, 4> IndexVariables;
3505     QualType BaseType = Field->getType();
3506     QualType SizeType = SemaRef.Context.getSizeType();
3507     bool InitializingArray = false;
3508     while (const ConstantArrayType *Array
3509                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3510       InitializingArray = true;
3511       // Create the iteration variable for this array index.
3512       IdentifierInfo *IterationVarName = nullptr;
3513       {
3514         SmallString<8> Str;
3515         llvm::raw_svector_ostream OS(Str);
3516         OS << "__i" << IndexVariables.size();
3517         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3518       }
3519       VarDecl *IterationVar
3520         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3521                           IterationVarName, SizeType,
3522                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3523                           SC_None);
3524       IndexVariables.push_back(IterationVar);
3525 
3526       // Create a reference to the iteration variable.
3527       ExprResult IterationVarRef
3528         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3529       assert(!IterationVarRef.isInvalid() &&
3530              "Reference to invented variable cannot fail!");
3531       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3532       assert(!IterationVarRef.isInvalid() &&
3533              "Conversion of invented variable cannot fail!");
3534 
3535       // Subscript the array with this iteration variable.
3536       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3537                                                         IterationVarRef.get(),
3538                                                         Loc);
3539       if (CtorArg.isInvalid())
3540         return true;
3541 
3542       BaseType = Array->getElementType();
3543     }
3544 
3545     // The array subscript expression is an lvalue, which is wrong for moving.
3546     if (Moving && InitializingArray)
3547       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3548 
3549     // Construct the entity that we will be initializing. For an array, this
3550     // will be first element in the array, which may require several levels
3551     // of array-subscript entities.
3552     SmallVector<InitializedEntity, 4> Entities;
3553     Entities.reserve(1 + IndexVariables.size());
3554     if (Indirect)
3555       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3556     else
3557       Entities.push_back(InitializedEntity::InitializeMember(Field));
3558     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3559       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3560                                                               0,
3561                                                               Entities.back()));
3562 
3563     // Direct-initialize to use the copy constructor.
3564     InitializationKind InitKind =
3565       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3566 
3567     Expr *CtorArgE = CtorArg.getAs<Expr>();
3568     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3569                                    CtorArgE);
3570 
3571     ExprResult MemberInit
3572       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3573                         MultiExprArg(&CtorArgE, 1));
3574     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3575     if (MemberInit.isInvalid())
3576       return true;
3577 
3578     if (Indirect) {
3579       assert(IndexVariables.size() == 0 &&
3580              "Indirect field improperly initialized");
3581       CXXMemberInit
3582         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3583                                                    Loc, Loc,
3584                                                    MemberInit.getAs<Expr>(),
3585                                                    Loc);
3586     } else
3587       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3588                                                  Loc, MemberInit.getAs<Expr>(),
3589                                                  Loc,
3590                                                  IndexVariables.data(),
3591                                                  IndexVariables.size());
3592     return false;
3593   }
3594 
3595   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3596          "Unhandled implicit init kind!");
3597 
3598   QualType FieldBaseElementType =
3599     SemaRef.Context.getBaseElementType(Field->getType());
3600 
3601   if (FieldBaseElementType->isRecordType()) {
3602     InitializedEntity InitEntity
3603       = Indirect? InitializedEntity::InitializeMember(Indirect)
3604                 : InitializedEntity::InitializeMember(Field);
3605     InitializationKind InitKind =
3606       InitializationKind::CreateDefault(Loc);
3607 
3608     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3609     ExprResult MemberInit =
3610       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3611 
3612     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3613     if (MemberInit.isInvalid())
3614       return true;
3615 
3616     if (Indirect)
3617       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3618                                                                Indirect, Loc,
3619                                                                Loc,
3620                                                                MemberInit.get(),
3621                                                                Loc);
3622     else
3623       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3624                                                                Field, Loc, Loc,
3625                                                                MemberInit.get(),
3626                                                                Loc);
3627     return false;
3628   }
3629 
3630   if (!Field->getParent()->isUnion()) {
3631     if (FieldBaseElementType->isReferenceType()) {
3632       SemaRef.Diag(Constructor->getLocation(),
3633                    diag::err_uninitialized_member_in_ctor)
3634       << (int)Constructor->isImplicit()
3635       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3636       << 0 << Field->getDeclName();
3637       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3638       return true;
3639     }
3640 
3641     if (FieldBaseElementType.isConstQualified()) {
3642       SemaRef.Diag(Constructor->getLocation(),
3643                    diag::err_uninitialized_member_in_ctor)
3644       << (int)Constructor->isImplicit()
3645       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3646       << 1 << Field->getDeclName();
3647       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3648       return true;
3649     }
3650   }
3651 
3652   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3653       FieldBaseElementType->isObjCRetainableType() &&
3654       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3655       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3656     // ARC:
3657     //   Default-initialize Objective-C pointers to NULL.
3658     CXXMemberInit
3659       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3660                                                  Loc, Loc,
3661                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3662                                                  Loc);
3663     return false;
3664   }
3665 
3666   // Nothing to initialize.
3667   CXXMemberInit = nullptr;
3668   return false;
3669 }
3670 
3671 namespace {
3672 struct BaseAndFieldInfo {
3673   Sema &S;
3674   CXXConstructorDecl *Ctor;
3675   bool AnyErrorsInInits;
3676   ImplicitInitializerKind IIK;
3677   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3678   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3679   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3680 
3681   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3682     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3683     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3684     if (Generated && Ctor->isCopyConstructor())
3685       IIK = IIK_Copy;
3686     else if (Generated && Ctor->isMoveConstructor())
3687       IIK = IIK_Move;
3688     else if (Ctor->getInheritedConstructor())
3689       IIK = IIK_Inherit;
3690     else
3691       IIK = IIK_Default;
3692   }
3693 
3694   bool isImplicitCopyOrMove() const {
3695     switch (IIK) {
3696     case IIK_Copy:
3697     case IIK_Move:
3698       return true;
3699 
3700     case IIK_Default:
3701     case IIK_Inherit:
3702       return false;
3703     }
3704 
3705     llvm_unreachable("Invalid ImplicitInitializerKind!");
3706   }
3707 
3708   bool addFieldInitializer(CXXCtorInitializer *Init) {
3709     AllToInit.push_back(Init);
3710 
3711     // Check whether this initializer makes the field "used".
3712     if (Init->getInit()->HasSideEffects(S.Context))
3713       S.UnusedPrivateFields.remove(Init->getAnyMember());
3714 
3715     return false;
3716   }
3717 
3718   bool isInactiveUnionMember(FieldDecl *Field) {
3719     RecordDecl *Record = Field->getParent();
3720     if (!Record->isUnion())
3721       return false;
3722 
3723     if (FieldDecl *Active =
3724             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3725       return Active != Field->getCanonicalDecl();
3726 
3727     // In an implicit copy or move constructor, ignore any in-class initializer.
3728     if (isImplicitCopyOrMove())
3729       return true;
3730 
3731     // If there's no explicit initialization, the field is active only if it
3732     // has an in-class initializer...
3733     if (Field->hasInClassInitializer())
3734       return false;
3735     // ... or it's an anonymous struct or union whose class has an in-class
3736     // initializer.
3737     if (!Field->isAnonymousStructOrUnion())
3738       return true;
3739     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3740     return !FieldRD->hasInClassInitializer();
3741   }
3742 
3743   /// \brief Determine whether the given field is, or is within, a union member
3744   /// that is inactive (because there was an initializer given for a different
3745   /// member of the union, or because the union was not initialized at all).
3746   bool isWithinInactiveUnionMember(FieldDecl *Field,
3747                                    IndirectFieldDecl *Indirect) {
3748     if (!Indirect)
3749       return isInactiveUnionMember(Field);
3750 
3751     for (auto *C : Indirect->chain()) {
3752       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3753       if (Field && isInactiveUnionMember(Field))
3754         return true;
3755     }
3756     return false;
3757   }
3758 };
3759 } // namespace
3760 
3761 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3762 /// array type.
3763 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3764   if (T->isIncompleteArrayType())
3765     return true;
3766 
3767   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3768     if (!ArrayT->getSize())
3769       return true;
3770 
3771     T = ArrayT->getElementType();
3772   }
3773 
3774   return false;
3775 }
3776 
3777 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3778                                     FieldDecl *Field,
3779                                     IndirectFieldDecl *Indirect = nullptr) {
3780   if (Field->isInvalidDecl())
3781     return false;
3782 
3783   // Overwhelmingly common case: we have a direct initializer for this field.
3784   if (CXXCtorInitializer *Init =
3785           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3786     return Info.addFieldInitializer(Init);
3787 
3788   // C++11 [class.base.init]p8:
3789   //   if the entity is a non-static data member that has a
3790   //   brace-or-equal-initializer and either
3791   //   -- the constructor's class is a union and no other variant member of that
3792   //      union is designated by a mem-initializer-id or
3793   //   -- the constructor's class is not a union, and, if the entity is a member
3794   //      of an anonymous union, no other member of that union is designated by
3795   //      a mem-initializer-id,
3796   //   the entity is initialized as specified in [dcl.init].
3797   //
3798   // We also apply the same rules to handle anonymous structs within anonymous
3799   // unions.
3800   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3801     return false;
3802 
3803   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3804     ExprResult DIE =
3805         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3806     if (DIE.isInvalid())
3807       return true;
3808     CXXCtorInitializer *Init;
3809     if (Indirect)
3810       Init = new (SemaRef.Context)
3811           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3812                              SourceLocation(), DIE.get(), SourceLocation());
3813     else
3814       Init = new (SemaRef.Context)
3815           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3816                              SourceLocation(), DIE.get(), SourceLocation());
3817     return Info.addFieldInitializer(Init);
3818   }
3819 
3820   // Don't initialize incomplete or zero-length arrays.
3821   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3822     return false;
3823 
3824   // Don't try to build an implicit initializer if there were semantic
3825   // errors in any of the initializers (and therefore we might be
3826   // missing some that the user actually wrote).
3827   if (Info.AnyErrorsInInits)
3828     return false;
3829 
3830   CXXCtorInitializer *Init = nullptr;
3831   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3832                                      Indirect, Init))
3833     return true;
3834 
3835   if (!Init)
3836     return false;
3837 
3838   return Info.addFieldInitializer(Init);
3839 }
3840 
3841 bool
3842 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3843                                CXXCtorInitializer *Initializer) {
3844   assert(Initializer->isDelegatingInitializer());
3845   Constructor->setNumCtorInitializers(1);
3846   CXXCtorInitializer **initializer =
3847     new (Context) CXXCtorInitializer*[1];
3848   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3849   Constructor->setCtorInitializers(initializer);
3850 
3851   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3852     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3853     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3854   }
3855 
3856   DelegatingCtorDecls.push_back(Constructor);
3857 
3858   DiagnoseUninitializedFields(*this, Constructor);
3859 
3860   return false;
3861 }
3862 
3863 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3864                                ArrayRef<CXXCtorInitializer *> Initializers) {
3865   if (Constructor->isDependentContext()) {
3866     // Just store the initializers as written, they will be checked during
3867     // instantiation.
3868     if (!Initializers.empty()) {
3869       Constructor->setNumCtorInitializers(Initializers.size());
3870       CXXCtorInitializer **baseOrMemberInitializers =
3871         new (Context) CXXCtorInitializer*[Initializers.size()];
3872       memcpy(baseOrMemberInitializers, Initializers.data(),
3873              Initializers.size() * sizeof(CXXCtorInitializer*));
3874       Constructor->setCtorInitializers(baseOrMemberInitializers);
3875     }
3876 
3877     // Let template instantiation know whether we had errors.
3878     if (AnyErrors)
3879       Constructor->setInvalidDecl();
3880 
3881     return false;
3882   }
3883 
3884   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3885 
3886   // We need to build the initializer AST according to order of construction
3887   // and not what user specified in the Initializers list.
3888   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3889   if (!ClassDecl)
3890     return true;
3891 
3892   bool HadError = false;
3893 
3894   for (unsigned i = 0; i < Initializers.size(); i++) {
3895     CXXCtorInitializer *Member = Initializers[i];
3896 
3897     if (Member->isBaseInitializer())
3898       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3899     else {
3900       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3901 
3902       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3903         for (auto *C : F->chain()) {
3904           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3905           if (FD && FD->getParent()->isUnion())
3906             Info.ActiveUnionMember.insert(std::make_pair(
3907                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3908         }
3909       } else if (FieldDecl *FD = Member->getMember()) {
3910         if (FD->getParent()->isUnion())
3911           Info.ActiveUnionMember.insert(std::make_pair(
3912               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3913       }
3914     }
3915   }
3916 
3917   // Keep track of the direct virtual bases.
3918   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3919   for (auto &I : ClassDecl->bases()) {
3920     if (I.isVirtual())
3921       DirectVBases.insert(&I);
3922   }
3923 
3924   // Push virtual bases before others.
3925   for (auto &VBase : ClassDecl->vbases()) {
3926     if (CXXCtorInitializer *Value
3927         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3928       // [class.base.init]p7, per DR257:
3929       //   A mem-initializer where the mem-initializer-id names a virtual base
3930       //   class is ignored during execution of a constructor of any class that
3931       //   is not the most derived class.
3932       if (ClassDecl->isAbstract()) {
3933         // FIXME: Provide a fixit to remove the base specifier. This requires
3934         // tracking the location of the associated comma for a base specifier.
3935         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3936           << VBase.getType() << ClassDecl;
3937         DiagnoseAbstractType(ClassDecl);
3938       }
3939 
3940       Info.AllToInit.push_back(Value);
3941     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3942       // [class.base.init]p8, per DR257:
3943       //   If a given [...] base class is not named by a mem-initializer-id
3944       //   [...] and the entity is not a virtual base class of an abstract
3945       //   class, then [...] the entity is default-initialized.
3946       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3947       CXXCtorInitializer *CXXBaseInit;
3948       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3949                                        &VBase, IsInheritedVirtualBase,
3950                                        CXXBaseInit)) {
3951         HadError = true;
3952         continue;
3953       }
3954 
3955       Info.AllToInit.push_back(CXXBaseInit);
3956     }
3957   }
3958 
3959   // Non-virtual bases.
3960   for (auto &Base : ClassDecl->bases()) {
3961     // Virtuals are in the virtual base list and already constructed.
3962     if (Base.isVirtual())
3963       continue;
3964 
3965     if (CXXCtorInitializer *Value
3966           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3967       Info.AllToInit.push_back(Value);
3968     } else if (!AnyErrors) {
3969       CXXCtorInitializer *CXXBaseInit;
3970       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3971                                        &Base, /*IsInheritedVirtualBase=*/false,
3972                                        CXXBaseInit)) {
3973         HadError = true;
3974         continue;
3975       }
3976 
3977       Info.AllToInit.push_back(CXXBaseInit);
3978     }
3979   }
3980 
3981   // Fields.
3982   for (auto *Mem : ClassDecl->decls()) {
3983     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3984       // C++ [class.bit]p2:
3985       //   A declaration for a bit-field that omits the identifier declares an
3986       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3987       //   initialized.
3988       if (F->isUnnamedBitfield())
3989         continue;
3990 
3991       // If we're not generating the implicit copy/move constructor, then we'll
3992       // handle anonymous struct/union fields based on their individual
3993       // indirect fields.
3994       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3995         continue;
3996 
3997       if (CollectFieldInitializer(*this, Info, F))
3998         HadError = true;
3999       continue;
4000     }
4001 
4002     // Beyond this point, we only consider default initialization.
4003     if (Info.isImplicitCopyOrMove())
4004       continue;
4005 
4006     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4007       if (F->getType()->isIncompleteArrayType()) {
4008         assert(ClassDecl->hasFlexibleArrayMember() &&
4009                "Incomplete array type is not valid");
4010         continue;
4011       }
4012 
4013       // Initialize each field of an anonymous struct individually.
4014       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4015         HadError = true;
4016 
4017       continue;
4018     }
4019   }
4020 
4021   unsigned NumInitializers = Info.AllToInit.size();
4022   if (NumInitializers > 0) {
4023     Constructor->setNumCtorInitializers(NumInitializers);
4024     CXXCtorInitializer **baseOrMemberInitializers =
4025       new (Context) CXXCtorInitializer*[NumInitializers];
4026     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4027            NumInitializers * sizeof(CXXCtorInitializer*));
4028     Constructor->setCtorInitializers(baseOrMemberInitializers);
4029 
4030     // Constructors implicitly reference the base and member
4031     // destructors.
4032     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4033                                            Constructor->getParent());
4034   }
4035 
4036   return HadError;
4037 }
4038 
4039 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4040   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4041     const RecordDecl *RD = RT->getDecl();
4042     if (RD->isAnonymousStructOrUnion()) {
4043       for (auto *Field : RD->fields())
4044         PopulateKeysForFields(Field, IdealInits);
4045       return;
4046     }
4047   }
4048   IdealInits.push_back(Field->getCanonicalDecl());
4049 }
4050 
4051 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4052   return Context.getCanonicalType(BaseType).getTypePtr();
4053 }
4054 
4055 static const void *GetKeyForMember(ASTContext &Context,
4056                                    CXXCtorInitializer *Member) {
4057   if (!Member->isAnyMemberInitializer())
4058     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4059 
4060   return Member->getAnyMember()->getCanonicalDecl();
4061 }
4062 
4063 static void DiagnoseBaseOrMemInitializerOrder(
4064     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4065     ArrayRef<CXXCtorInitializer *> Inits) {
4066   if (Constructor->getDeclContext()->isDependentContext())
4067     return;
4068 
4069   // Don't check initializers order unless the warning is enabled at the
4070   // location of at least one initializer.
4071   bool ShouldCheckOrder = false;
4072   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4073     CXXCtorInitializer *Init = Inits[InitIndex];
4074     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4075                                  Init->getSourceLocation())) {
4076       ShouldCheckOrder = true;
4077       break;
4078     }
4079   }
4080   if (!ShouldCheckOrder)
4081     return;
4082 
4083   // Build the list of bases and members in the order that they'll
4084   // actually be initialized.  The explicit initializers should be in
4085   // this same order but may be missing things.
4086   SmallVector<const void*, 32> IdealInitKeys;
4087 
4088   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4089 
4090   // 1. Virtual bases.
4091   for (const auto &VBase : ClassDecl->vbases())
4092     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4093 
4094   // 2. Non-virtual bases.
4095   for (const auto &Base : ClassDecl->bases()) {
4096     if (Base.isVirtual())
4097       continue;
4098     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4099   }
4100 
4101   // 3. Direct fields.
4102   for (auto *Field : ClassDecl->fields()) {
4103     if (Field->isUnnamedBitfield())
4104       continue;
4105 
4106     PopulateKeysForFields(Field, IdealInitKeys);
4107   }
4108 
4109   unsigned NumIdealInits = IdealInitKeys.size();
4110   unsigned IdealIndex = 0;
4111 
4112   CXXCtorInitializer *PrevInit = nullptr;
4113   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4114     CXXCtorInitializer *Init = Inits[InitIndex];
4115     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4116 
4117     // Scan forward to try to find this initializer in the idealized
4118     // initializers list.
4119     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4120       if (InitKey == IdealInitKeys[IdealIndex])
4121         break;
4122 
4123     // If we didn't find this initializer, it must be because we
4124     // scanned past it on a previous iteration.  That can only
4125     // happen if we're out of order;  emit a warning.
4126     if (IdealIndex == NumIdealInits && PrevInit) {
4127       Sema::SemaDiagnosticBuilder D =
4128         SemaRef.Diag(PrevInit->getSourceLocation(),
4129                      diag::warn_initializer_out_of_order);
4130 
4131       if (PrevInit->isAnyMemberInitializer())
4132         D << 0 << PrevInit->getAnyMember()->getDeclName();
4133       else
4134         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4135 
4136       if (Init->isAnyMemberInitializer())
4137         D << 0 << Init->getAnyMember()->getDeclName();
4138       else
4139         D << 1 << Init->getTypeSourceInfo()->getType();
4140 
4141       // Move back to the initializer's location in the ideal list.
4142       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4143         if (InitKey == IdealInitKeys[IdealIndex])
4144           break;
4145 
4146       assert(IdealIndex != NumIdealInits &&
4147              "initializer not found in initializer list");
4148     }
4149 
4150     PrevInit = Init;
4151   }
4152 }
4153 
4154 namespace {
4155 bool CheckRedundantInit(Sema &S,
4156                         CXXCtorInitializer *Init,
4157                         CXXCtorInitializer *&PrevInit) {
4158   if (!PrevInit) {
4159     PrevInit = Init;
4160     return false;
4161   }
4162 
4163   if (FieldDecl *Field = Init->getAnyMember())
4164     S.Diag(Init->getSourceLocation(),
4165            diag::err_multiple_mem_initialization)
4166       << Field->getDeclName()
4167       << Init->getSourceRange();
4168   else {
4169     const Type *BaseClass = Init->getBaseClass();
4170     assert(BaseClass && "neither field nor base");
4171     S.Diag(Init->getSourceLocation(),
4172            diag::err_multiple_base_initialization)
4173       << QualType(BaseClass, 0)
4174       << Init->getSourceRange();
4175   }
4176   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4177     << 0 << PrevInit->getSourceRange();
4178 
4179   return true;
4180 }
4181 
4182 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4183 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4184 
4185 bool CheckRedundantUnionInit(Sema &S,
4186                              CXXCtorInitializer *Init,
4187                              RedundantUnionMap &Unions) {
4188   FieldDecl *Field = Init->getAnyMember();
4189   RecordDecl *Parent = Field->getParent();
4190   NamedDecl *Child = Field;
4191 
4192   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4193     if (Parent->isUnion()) {
4194       UnionEntry &En = Unions[Parent];
4195       if (En.first && En.first != Child) {
4196         S.Diag(Init->getSourceLocation(),
4197                diag::err_multiple_mem_union_initialization)
4198           << Field->getDeclName()
4199           << Init->getSourceRange();
4200         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4201           << 0 << En.second->getSourceRange();
4202         return true;
4203       }
4204       if (!En.first) {
4205         En.first = Child;
4206         En.second = Init;
4207       }
4208       if (!Parent->isAnonymousStructOrUnion())
4209         return false;
4210     }
4211 
4212     Child = Parent;
4213     Parent = cast<RecordDecl>(Parent->getDeclContext());
4214   }
4215 
4216   return false;
4217 }
4218 } // namespace
4219 
4220 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4221 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4222                                 SourceLocation ColonLoc,
4223                                 ArrayRef<CXXCtorInitializer*> MemInits,
4224                                 bool AnyErrors) {
4225   if (!ConstructorDecl)
4226     return;
4227 
4228   AdjustDeclIfTemplate(ConstructorDecl);
4229 
4230   CXXConstructorDecl *Constructor
4231     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4232 
4233   if (!Constructor) {
4234     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4235     return;
4236   }
4237 
4238   // Mapping for the duplicate initializers check.
4239   // For member initializers, this is keyed with a FieldDecl*.
4240   // For base initializers, this is keyed with a Type*.
4241   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4242 
4243   // Mapping for the inconsistent anonymous-union initializers check.
4244   RedundantUnionMap MemberUnions;
4245 
4246   bool HadError = false;
4247   for (unsigned i = 0; i < MemInits.size(); i++) {
4248     CXXCtorInitializer *Init = MemInits[i];
4249 
4250     // Set the source order index.
4251     Init->setSourceOrder(i);
4252 
4253     if (Init->isAnyMemberInitializer()) {
4254       const void *Key = GetKeyForMember(Context, Init);
4255       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4256           CheckRedundantUnionInit(*this, Init, MemberUnions))
4257         HadError = true;
4258     } else if (Init->isBaseInitializer()) {
4259       const void *Key = GetKeyForMember(Context, Init);
4260       if (CheckRedundantInit(*this, Init, Members[Key]))
4261         HadError = true;
4262     } else {
4263       assert(Init->isDelegatingInitializer());
4264       // This must be the only initializer
4265       if (MemInits.size() != 1) {
4266         Diag(Init->getSourceLocation(),
4267              diag::err_delegating_initializer_alone)
4268           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4269         // We will treat this as being the only initializer.
4270       }
4271       SetDelegatingInitializer(Constructor, MemInits[i]);
4272       // Return immediately as the initializer is set.
4273       return;
4274     }
4275   }
4276 
4277   if (HadError)
4278     return;
4279 
4280   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4281 
4282   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4283 
4284   DiagnoseUninitializedFields(*this, Constructor);
4285 }
4286 
4287 void
4288 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4289                                              CXXRecordDecl *ClassDecl) {
4290   // Ignore dependent contexts. Also ignore unions, since their members never
4291   // have destructors implicitly called.
4292   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4293     return;
4294 
4295   // FIXME: all the access-control diagnostics are positioned on the
4296   // field/base declaration.  That's probably good; that said, the
4297   // user might reasonably want to know why the destructor is being
4298   // emitted, and we currently don't say.
4299 
4300   // Non-static data members.
4301   for (auto *Field : ClassDecl->fields()) {
4302     if (Field->isInvalidDecl())
4303       continue;
4304 
4305     // Don't destroy incomplete or zero-length arrays.
4306     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4307       continue;
4308 
4309     QualType FieldType = Context.getBaseElementType(Field->getType());
4310 
4311     const RecordType* RT = FieldType->getAs<RecordType>();
4312     if (!RT)
4313       continue;
4314 
4315     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4316     if (FieldClassDecl->isInvalidDecl())
4317       continue;
4318     if (FieldClassDecl->hasIrrelevantDestructor())
4319       continue;
4320     // The destructor for an implicit anonymous union member is never invoked.
4321     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4322       continue;
4323 
4324     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4325     assert(Dtor && "No dtor found for FieldClassDecl!");
4326     CheckDestructorAccess(Field->getLocation(), Dtor,
4327                           PDiag(diag::err_access_dtor_field)
4328                             << Field->getDeclName()
4329                             << FieldType);
4330 
4331     MarkFunctionReferenced(Location, Dtor);
4332     DiagnoseUseOfDecl(Dtor, Location);
4333   }
4334 
4335   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4336 
4337   // Bases.
4338   for (const auto &Base : ClassDecl->bases()) {
4339     // Bases are always records in a well-formed non-dependent class.
4340     const RecordType *RT = Base.getType()->getAs<RecordType>();
4341 
4342     // Remember direct virtual bases.
4343     if (Base.isVirtual())
4344       DirectVirtualBases.insert(RT);
4345 
4346     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4347     // If our base class is invalid, we probably can't get its dtor anyway.
4348     if (BaseClassDecl->isInvalidDecl())
4349       continue;
4350     if (BaseClassDecl->hasIrrelevantDestructor())
4351       continue;
4352 
4353     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4354     assert(Dtor && "No dtor found for BaseClassDecl!");
4355 
4356     // FIXME: caret should be on the start of the class name
4357     CheckDestructorAccess(Base.getLocStart(), Dtor,
4358                           PDiag(diag::err_access_dtor_base)
4359                             << Base.getType()
4360                             << Base.getSourceRange(),
4361                           Context.getTypeDeclType(ClassDecl));
4362 
4363     MarkFunctionReferenced(Location, Dtor);
4364     DiagnoseUseOfDecl(Dtor, Location);
4365   }
4366 
4367   // Virtual bases.
4368   for (const auto &VBase : ClassDecl->vbases()) {
4369     // Bases are always records in a well-formed non-dependent class.
4370     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4371 
4372     // Ignore direct virtual bases.
4373     if (DirectVirtualBases.count(RT))
4374       continue;
4375 
4376     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4377     // If our base class is invalid, we probably can't get its dtor anyway.
4378     if (BaseClassDecl->isInvalidDecl())
4379       continue;
4380     if (BaseClassDecl->hasIrrelevantDestructor())
4381       continue;
4382 
4383     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4384     assert(Dtor && "No dtor found for BaseClassDecl!");
4385     if (CheckDestructorAccess(
4386             ClassDecl->getLocation(), Dtor,
4387             PDiag(diag::err_access_dtor_vbase)
4388                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4389             Context.getTypeDeclType(ClassDecl)) ==
4390         AR_accessible) {
4391       CheckDerivedToBaseConversion(
4392           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4393           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4394           SourceRange(), DeclarationName(), nullptr);
4395     }
4396 
4397     MarkFunctionReferenced(Location, Dtor);
4398     DiagnoseUseOfDecl(Dtor, Location);
4399   }
4400 }
4401 
4402 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4403   if (!CDtorDecl)
4404     return;
4405 
4406   if (CXXConstructorDecl *Constructor
4407       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4408     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4409     DiagnoseUninitializedFields(*this, Constructor);
4410   }
4411 }
4412 
4413 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4414                                   unsigned DiagID, AbstractDiagSelID SelID) {
4415   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4416     unsigned DiagID;
4417     AbstractDiagSelID SelID;
4418 
4419   public:
4420     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4421       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4422 
4423     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4424       if (Suppressed) return;
4425       if (SelID == -1)
4426         S.Diag(Loc, DiagID) << T;
4427       else
4428         S.Diag(Loc, DiagID) << SelID << T;
4429     }
4430   } Diagnoser(DiagID, SelID);
4431 
4432   return RequireNonAbstractType(Loc, T, Diagnoser);
4433 }
4434 
4435 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4436                                   TypeDiagnoser &Diagnoser) {
4437   if (!getLangOpts().CPlusPlus)
4438     return false;
4439 
4440   if (const ArrayType *AT = Context.getAsArrayType(T))
4441     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4442 
4443   if (const PointerType *PT = T->getAs<PointerType>()) {
4444     // Find the innermost pointer type.
4445     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4446       PT = T;
4447 
4448     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4449       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4450   }
4451 
4452   const RecordType *RT = T->getAs<RecordType>();
4453   if (!RT)
4454     return false;
4455 
4456   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4457 
4458   // We can't answer whether something is abstract until it has a
4459   // definition.  If it's currently being defined, we'll walk back
4460   // over all the declarations when we have a full definition.
4461   const CXXRecordDecl *Def = RD->getDefinition();
4462   if (!Def || Def->isBeingDefined())
4463     return false;
4464 
4465   if (!RD->isAbstract())
4466     return false;
4467 
4468   Diagnoser.diagnose(*this, Loc, T);
4469   DiagnoseAbstractType(RD);
4470 
4471   return true;
4472 }
4473 
4474 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4475   // Check if we've already emitted the list of pure virtual functions
4476   // for this class.
4477   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4478     return;
4479 
4480   // If the diagnostic is suppressed, don't emit the notes. We're only
4481   // going to emit them once, so try to attach them to a diagnostic we're
4482   // actually going to show.
4483   if (Diags.isLastDiagnosticIgnored())
4484     return;
4485 
4486   CXXFinalOverriderMap FinalOverriders;
4487   RD->getFinalOverriders(FinalOverriders);
4488 
4489   // Keep a set of seen pure methods so we won't diagnose the same method
4490   // more than once.
4491   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4492 
4493   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4494                                    MEnd = FinalOverriders.end();
4495        M != MEnd;
4496        ++M) {
4497     for (OverridingMethods::iterator SO = M->second.begin(),
4498                                   SOEnd = M->second.end();
4499          SO != SOEnd; ++SO) {
4500       // C++ [class.abstract]p4:
4501       //   A class is abstract if it contains or inherits at least one
4502       //   pure virtual function for which the final overrider is pure
4503       //   virtual.
4504 
4505       //
4506       if (SO->second.size() != 1)
4507         continue;
4508 
4509       if (!SO->second.front().Method->isPure())
4510         continue;
4511 
4512       if (!SeenPureMethods.insert(SO->second.front().Method).second)
4513         continue;
4514 
4515       Diag(SO->second.front().Method->getLocation(),
4516            diag::note_pure_virtual_function)
4517         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4518     }
4519   }
4520 
4521   if (!PureVirtualClassDiagSet)
4522     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4523   PureVirtualClassDiagSet->insert(RD);
4524 }
4525 
4526 namespace {
4527 struct AbstractUsageInfo {
4528   Sema &S;
4529   CXXRecordDecl *Record;
4530   CanQualType AbstractType;
4531   bool Invalid;
4532 
4533   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4534     : S(S), Record(Record),
4535       AbstractType(S.Context.getCanonicalType(
4536                    S.Context.getTypeDeclType(Record))),
4537       Invalid(false) {}
4538 
4539   void DiagnoseAbstractType() {
4540     if (Invalid) return;
4541     S.DiagnoseAbstractType(Record);
4542     Invalid = true;
4543   }
4544 
4545   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4546 };
4547 
4548 struct CheckAbstractUsage {
4549   AbstractUsageInfo &Info;
4550   const NamedDecl *Ctx;
4551 
4552   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4553     : Info(Info), Ctx(Ctx) {}
4554 
4555   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4556     switch (TL.getTypeLocClass()) {
4557 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4558 #define TYPELOC(CLASS, PARENT) \
4559     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4560 #include "clang/AST/TypeLocNodes.def"
4561     }
4562   }
4563 
4564   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4565     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4566     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4567       if (!TL.getParam(I))
4568         continue;
4569 
4570       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4571       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4572     }
4573   }
4574 
4575   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4576     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4577   }
4578 
4579   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4580     // Visit the type parameters from a permissive context.
4581     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4582       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4583       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4584         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4585           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4586       // TODO: other template argument types?
4587     }
4588   }
4589 
4590   // Visit pointee types from a permissive context.
4591 #define CheckPolymorphic(Type) \
4592   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4593     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4594   }
4595   CheckPolymorphic(PointerTypeLoc)
4596   CheckPolymorphic(ReferenceTypeLoc)
4597   CheckPolymorphic(MemberPointerTypeLoc)
4598   CheckPolymorphic(BlockPointerTypeLoc)
4599   CheckPolymorphic(AtomicTypeLoc)
4600 
4601   /// Handle all the types we haven't given a more specific
4602   /// implementation for above.
4603   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4604     // Every other kind of type that we haven't called out already
4605     // that has an inner type is either (1) sugar or (2) contains that
4606     // inner type in some way as a subobject.
4607     if (TypeLoc Next = TL.getNextTypeLoc())
4608       return Visit(Next, Sel);
4609 
4610     // If there's no inner type and we're in a permissive context,
4611     // don't diagnose.
4612     if (Sel == Sema::AbstractNone) return;
4613 
4614     // Check whether the type matches the abstract type.
4615     QualType T = TL.getType();
4616     if (T->isArrayType()) {
4617       Sel = Sema::AbstractArrayType;
4618       T = Info.S.Context.getBaseElementType(T);
4619     }
4620     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4621     if (CT != Info.AbstractType) return;
4622 
4623     // It matched; do some magic.
4624     if (Sel == Sema::AbstractArrayType) {
4625       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4626         << T << TL.getSourceRange();
4627     } else {
4628       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4629         << Sel << T << TL.getSourceRange();
4630     }
4631     Info.DiagnoseAbstractType();
4632   }
4633 };
4634 
4635 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4636                                   Sema::AbstractDiagSelID Sel) {
4637   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4638 }
4639 
4640 } // namespace
4641 
4642 /// Check for invalid uses of an abstract type in a method declaration.
4643 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4644                                     CXXMethodDecl *MD) {
4645   // No need to do the check on definitions, which require that
4646   // the return/param types be complete.
4647   if (MD->doesThisDeclarationHaveABody())
4648     return;
4649 
4650   // For safety's sake, just ignore it if we don't have type source
4651   // information.  This should never happen for non-implicit methods,
4652   // but...
4653   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4654     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4655 }
4656 
4657 /// Check for invalid uses of an abstract type within a class definition.
4658 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4659                                     CXXRecordDecl *RD) {
4660   for (auto *D : RD->decls()) {
4661     if (D->isImplicit()) continue;
4662 
4663     // Methods and method templates.
4664     if (isa<CXXMethodDecl>(D)) {
4665       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4666     } else if (isa<FunctionTemplateDecl>(D)) {
4667       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4668       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4669 
4670     // Fields and static variables.
4671     } else if (isa<FieldDecl>(D)) {
4672       FieldDecl *FD = cast<FieldDecl>(D);
4673       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4674         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4675     } else if (isa<VarDecl>(D)) {
4676       VarDecl *VD = cast<VarDecl>(D);
4677       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4678         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4679 
4680     // Nested classes and class templates.
4681     } else if (isa<CXXRecordDecl>(D)) {
4682       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4683     } else if (isa<ClassTemplateDecl>(D)) {
4684       CheckAbstractClassUsage(Info,
4685                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4686     }
4687   }
4688 }
4689 
4690 /// \brief Check class-level dllimport/dllexport attribute.
4691 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
4692   Attr *ClassAttr = getDLLAttr(Class);
4693 
4694   // MSVC inherits DLL attributes to partial class template specializations.
4695   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4696     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4697       if (Attr *TemplateAttr =
4698               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4699         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
4700         A->setInherited(true);
4701         ClassAttr = A;
4702       }
4703     }
4704   }
4705 
4706   if (!ClassAttr)
4707     return;
4708 
4709   if (!Class->isExternallyVisible()) {
4710     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4711         << Class << ClassAttr;
4712     return;
4713   }
4714 
4715   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4716       !ClassAttr->isInherited()) {
4717     // Diagnose dll attributes on members of class with dll attribute.
4718     for (Decl *Member : Class->decls()) {
4719       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4720         continue;
4721       InheritableAttr *MemberAttr = getDLLAttr(Member);
4722       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4723         continue;
4724 
4725       Diag(MemberAttr->getLocation(),
4726              diag::err_attribute_dll_member_of_dll_class)
4727           << MemberAttr << ClassAttr;
4728       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4729       Member->setInvalidDecl();
4730     }
4731   }
4732 
4733   if (Class->getDescribedClassTemplate())
4734     // Don't inherit dll attribute until the template is instantiated.
4735     return;
4736 
4737   // The class is either imported or exported.
4738   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4739   const bool ClassImported = !ClassExported;
4740 
4741   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4742 
4743   // Ignore explicit dllexport on explicit class template instantiation declarations.
4744   if (ClassExported && !ClassAttr->isInherited() &&
4745       TSK == TSK_ExplicitInstantiationDeclaration) {
4746     Class->dropAttr<DLLExportAttr>();
4747     return;
4748   }
4749 
4750   // Force declaration of implicit members so they can inherit the attribute.
4751   ForceDeclarationOfImplicitMembers(Class);
4752 
4753   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4754   // seem to be true in practice?
4755 
4756   for (Decl *Member : Class->decls()) {
4757     VarDecl *VD = dyn_cast<VarDecl>(Member);
4758     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4759 
4760     // Only methods and static fields inherit the attributes.
4761     if (!VD && !MD)
4762       continue;
4763 
4764     if (MD) {
4765       // Don't process deleted methods.
4766       if (MD->isDeleted())
4767         continue;
4768 
4769       if (MD->isInlined()) {
4770         // MinGW does not import or export inline methods.
4771         if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
4772           continue;
4773 
4774         // MSVC versions before 2015 don't export the move assignment operators,
4775         // so don't attempt to import them if we have a definition.
4776         if (ClassImported && MD->isMoveAssignmentOperator() &&
4777             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
4778           continue;
4779       }
4780     }
4781 
4782     if (!cast<NamedDecl>(Member)->isExternallyVisible())
4783       continue;
4784 
4785     if (!getDLLAttr(Member)) {
4786       auto *NewAttr =
4787           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4788       NewAttr->setInherited(true);
4789       Member->addAttr(NewAttr);
4790     }
4791 
4792     if (MD && ClassExported) {
4793       if (TSK == TSK_ExplicitInstantiationDeclaration)
4794         // Don't go any further if this is just an explicit instantiation
4795         // declaration.
4796         continue;
4797 
4798       if (MD->isUserProvided()) {
4799         // Instantiate non-default class member functions ...
4800 
4801         // .. except for certain kinds of template specializations.
4802         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4803           continue;
4804 
4805         MarkFunctionReferenced(Class->getLocation(), MD);
4806 
4807         // The function will be passed to the consumer when its definition is
4808         // encountered.
4809       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4810                  MD->isCopyAssignmentOperator() ||
4811                  MD->isMoveAssignmentOperator()) {
4812         // Synthesize and instantiate non-trivial implicit methods, explicitly
4813         // defaulted methods, and the copy and move assignment operators. The
4814         // latter are exported even if they are trivial, because the address of
4815         // an operator can be taken and should compare equal accross libraries.
4816         DiagnosticErrorTrap Trap(Diags);
4817         MarkFunctionReferenced(Class->getLocation(), MD);
4818         if (Trap.hasErrorOccurred()) {
4819           Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4820               << Class->getName() << !getLangOpts().CPlusPlus11;
4821           break;
4822         }
4823 
4824         // There is no later point when we will see the definition of this
4825         // function, so pass it to the consumer now.
4826         Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4827       }
4828     }
4829   }
4830 }
4831 
4832 /// \brief Perform propagation of DLL attributes from a derived class to a
4833 /// templated base class for MS compatibility.
4834 void Sema::propagateDLLAttrToBaseClassTemplate(
4835     CXXRecordDecl *Class, Attr *ClassAttr,
4836     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4837   if (getDLLAttr(
4838           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4839     // If the base class template has a DLL attribute, don't try to change it.
4840     return;
4841   }
4842 
4843   auto TSK = BaseTemplateSpec->getSpecializationKind();
4844   if (!getDLLAttr(BaseTemplateSpec) &&
4845       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4846        TSK == TSK_ImplicitInstantiation)) {
4847     // The template hasn't been instantiated yet (or it has, but only as an
4848     // explicit instantiation declaration or implicit instantiation, which means
4849     // we haven't codegenned any members yet), so propagate the attribute.
4850     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4851     NewAttr->setInherited(true);
4852     BaseTemplateSpec->addAttr(NewAttr);
4853 
4854     // If the template is already instantiated, checkDLLAttributeRedeclaration()
4855     // needs to be run again to work see the new attribute. Otherwise this will
4856     // get run whenever the template is instantiated.
4857     if (TSK != TSK_Undeclared)
4858       checkClassLevelDLLAttribute(BaseTemplateSpec);
4859 
4860     return;
4861   }
4862 
4863   if (getDLLAttr(BaseTemplateSpec)) {
4864     // The template has already been specialized or instantiated with an
4865     // attribute, explicitly or through propagation. We should not try to change
4866     // it.
4867     return;
4868   }
4869 
4870   // The template was previously instantiated or explicitly specialized without
4871   // a dll attribute, It's too late for us to add an attribute, so warn that
4872   // this is unsupported.
4873   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4874       << BaseTemplateSpec->isExplicitSpecialization();
4875   Diag(ClassAttr->getLocation(), diag::note_attribute);
4876   if (BaseTemplateSpec->isExplicitSpecialization()) {
4877     Diag(BaseTemplateSpec->getLocation(),
4878            diag::note_template_class_explicit_specialization_was_here)
4879         << BaseTemplateSpec;
4880   } else {
4881     Diag(BaseTemplateSpec->getPointOfInstantiation(),
4882            diag::note_template_class_instantiation_was_here)
4883         << BaseTemplateSpec;
4884   }
4885 }
4886 
4887 /// \brief Perform semantic checks on a class definition that has been
4888 /// completing, introducing implicitly-declared members, checking for
4889 /// abstract types, etc.
4890 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4891   if (!Record)
4892     return;
4893 
4894   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4895     AbstractUsageInfo Info(*this, Record);
4896     CheckAbstractClassUsage(Info, Record);
4897   }
4898 
4899   // If this is not an aggregate type and has no user-declared constructor,
4900   // complain about any non-static data members of reference or const scalar
4901   // type, since they will never get initializers.
4902   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4903       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4904       !Record->isLambda()) {
4905     bool Complained = false;
4906     for (const auto *F : Record->fields()) {
4907       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4908         continue;
4909 
4910       if (F->getType()->isReferenceType() ||
4911           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4912         if (!Complained) {
4913           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4914             << Record->getTagKind() << Record;
4915           Complained = true;
4916         }
4917 
4918         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4919           << F->getType()->isReferenceType()
4920           << F->getDeclName();
4921       }
4922     }
4923   }
4924 
4925   if (Record->getIdentifier()) {
4926     // C++ [class.mem]p13:
4927     //   If T is the name of a class, then each of the following shall have a
4928     //   name different from T:
4929     //     - every member of every anonymous union that is a member of class T.
4930     //
4931     // C++ [class.mem]p14:
4932     //   In addition, if class T has a user-declared constructor (12.1), every
4933     //   non-static data member of class T shall have a name different from T.
4934     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4935     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4936          ++I) {
4937       NamedDecl *D = *I;
4938       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4939           isa<IndirectFieldDecl>(D)) {
4940         Diag(D->getLocation(), diag::err_member_name_of_class)
4941           << D->getDeclName();
4942         break;
4943       }
4944     }
4945   }
4946 
4947   // Warn if the class has virtual methods but non-virtual public destructor.
4948   if (Record->isPolymorphic() && !Record->isDependentType()) {
4949     CXXDestructorDecl *dtor = Record->getDestructor();
4950     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4951         !Record->hasAttr<FinalAttr>())
4952       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4953            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4954   }
4955 
4956   if (Record->isAbstract()) {
4957     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4958       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4959         << FA->isSpelledAsSealed();
4960       DiagnoseAbstractType(Record);
4961     }
4962   }
4963 
4964   bool HasMethodWithOverrideControl = false,
4965        HasOverridingMethodWithoutOverrideControl = false;
4966   if (!Record->isDependentType()) {
4967     for (auto *M : Record->methods()) {
4968       // See if a method overloads virtual methods in a base
4969       // class without overriding any.
4970       if (!M->isStatic())
4971         DiagnoseHiddenVirtualMethods(M);
4972       if (M->hasAttr<OverrideAttr>())
4973         HasMethodWithOverrideControl = true;
4974       else if (M->size_overridden_methods() > 0)
4975         HasOverridingMethodWithoutOverrideControl = true;
4976       // Check whether the explicitly-defaulted special members are valid.
4977       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4978         CheckExplicitlyDefaultedSpecialMember(M);
4979 
4980       // For an explicitly defaulted or deleted special member, we defer
4981       // determining triviality until the class is complete. That time is now!
4982       if (!M->isImplicit() && !M->isUserProvided()) {
4983         CXXSpecialMember CSM = getSpecialMember(M);
4984         if (CSM != CXXInvalid) {
4985           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4986 
4987           // Inform the class that we've finished declaring this member.
4988           Record->finishedDefaultedOrDeletedMember(M);
4989         }
4990       }
4991     }
4992   }
4993 
4994   if (HasMethodWithOverrideControl &&
4995       HasOverridingMethodWithoutOverrideControl) {
4996     // At least one method has the 'override' control declared.
4997     // Diagnose all other overridden methods which do not have 'override' specified on them.
4998     for (auto *M : Record->methods())
4999       DiagnoseAbsenceOfOverrideControl(M);
5000   }
5001 
5002   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5003   // whether this class uses any C++ features that are implemented
5004   // completely differently in MSVC, and if so, emit a diagnostic.
5005   // That diagnostic defaults to an error, but we allow projects to
5006   // map it down to a warning (or ignore it).  It's a fairly common
5007   // practice among users of the ms_struct pragma to mass-annotate
5008   // headers, sweeping up a bunch of types that the project doesn't
5009   // really rely on MSVC-compatible layout for.  We must therefore
5010   // support "ms_struct except for C++ stuff" as a secondary ABI.
5011   if (Record->isMsStruct(Context) &&
5012       (Record->isPolymorphic() || Record->getNumBases())) {
5013     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5014   }
5015 
5016   // Declare inheriting constructors. We do this eagerly here because:
5017   // - The standard requires an eager diagnostic for conflicting inheriting
5018   //   constructors from different classes.
5019   // - The lazy declaration of the other implicit constructors is so as to not
5020   //   waste space and performance on classes that are not meant to be
5021   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
5022   //   have inheriting constructors.
5023   DeclareInheritingConstructors(Record);
5024 
5025   checkClassLevelDLLAttribute(Record);
5026 }
5027 
5028 /// Look up the special member function that would be called by a special
5029 /// member function for a subobject of class type.
5030 ///
5031 /// \param Class The class type of the subobject.
5032 /// \param CSM The kind of special member function.
5033 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5034 /// \param ConstRHS True if this is a copy operation with a const object
5035 ///        on its RHS, that is, if the argument to the outer special member
5036 ///        function is 'const' and this is not a field marked 'mutable'.
5037 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5038     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5039     unsigned FieldQuals, bool ConstRHS) {
5040   unsigned LHSQuals = 0;
5041   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5042     LHSQuals = FieldQuals;
5043 
5044   unsigned RHSQuals = FieldQuals;
5045   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5046     RHSQuals = 0;
5047   else if (ConstRHS)
5048     RHSQuals |= Qualifiers::Const;
5049 
5050   return S.LookupSpecialMember(Class, CSM,
5051                                RHSQuals & Qualifiers::Const,
5052                                RHSQuals & Qualifiers::Volatile,
5053                                false,
5054                                LHSQuals & Qualifiers::Const,
5055                                LHSQuals & Qualifiers::Volatile);
5056 }
5057 
5058 /// Is the special member function which would be selected to perform the
5059 /// specified operation on the specified class type a constexpr constructor?
5060 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5061                                      Sema::CXXSpecialMember CSM,
5062                                      unsigned Quals, bool ConstRHS) {
5063   Sema::SpecialMemberOverloadResult *SMOR =
5064       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5065   if (!SMOR || !SMOR->getMethod())
5066     // A constructor we wouldn't select can't be "involved in initializing"
5067     // anything.
5068     return true;
5069   return SMOR->getMethod()->isConstexpr();
5070 }
5071 
5072 /// Determine whether the specified special member function would be constexpr
5073 /// if it were implicitly defined.
5074 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5075                                               Sema::CXXSpecialMember CSM,
5076                                               bool ConstArg) {
5077   if (!S.getLangOpts().CPlusPlus11)
5078     return false;
5079 
5080   // C++11 [dcl.constexpr]p4:
5081   // In the definition of a constexpr constructor [...]
5082   bool Ctor = true;
5083   switch (CSM) {
5084   case Sema::CXXDefaultConstructor:
5085     // Since default constructor lookup is essentially trivial (and cannot
5086     // involve, for instance, template instantiation), we compute whether a
5087     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5088     //
5089     // This is important for performance; we need to know whether the default
5090     // constructor is constexpr to determine whether the type is a literal type.
5091     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5092 
5093   case Sema::CXXCopyConstructor:
5094   case Sema::CXXMoveConstructor:
5095     // For copy or move constructors, we need to perform overload resolution.
5096     break;
5097 
5098   case Sema::CXXCopyAssignment:
5099   case Sema::CXXMoveAssignment:
5100     if (!S.getLangOpts().CPlusPlus14)
5101       return false;
5102     // In C++1y, we need to perform overload resolution.
5103     Ctor = false;
5104     break;
5105 
5106   case Sema::CXXDestructor:
5107   case Sema::CXXInvalid:
5108     return false;
5109   }
5110 
5111   //   -- if the class is a non-empty union, or for each non-empty anonymous
5112   //      union member of a non-union class, exactly one non-static data member
5113   //      shall be initialized; [DR1359]
5114   //
5115   // If we squint, this is guaranteed, since exactly one non-static data member
5116   // will be initialized (if the constructor isn't deleted), we just don't know
5117   // which one.
5118   if (Ctor && ClassDecl->isUnion())
5119     return true;
5120 
5121   //   -- the class shall not have any virtual base classes;
5122   if (Ctor && ClassDecl->getNumVBases())
5123     return false;
5124 
5125   // C++1y [class.copy]p26:
5126   //   -- [the class] is a literal type, and
5127   if (!Ctor && !ClassDecl->isLiteral())
5128     return false;
5129 
5130   //   -- every constructor involved in initializing [...] base class
5131   //      sub-objects shall be a constexpr constructor;
5132   //   -- the assignment operator selected to copy/move each direct base
5133   //      class is a constexpr function, and
5134   for (const auto &B : ClassDecl->bases()) {
5135     const RecordType *BaseType = B.getType()->getAs<RecordType>();
5136     if (!BaseType) continue;
5137 
5138     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5139     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
5140       return false;
5141   }
5142 
5143   //   -- every constructor involved in initializing non-static data members
5144   //      [...] shall be a constexpr constructor;
5145   //   -- every non-static data member and base class sub-object shall be
5146   //      initialized
5147   //   -- for each non-static data member of X that is of class type (or array
5148   //      thereof), the assignment operator selected to copy/move that member is
5149   //      a constexpr function
5150   for (const auto *F : ClassDecl->fields()) {
5151     if (F->isInvalidDecl())
5152       continue;
5153     QualType BaseType = S.Context.getBaseElementType(F->getType());
5154     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5155       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5156       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5157                                     BaseType.getCVRQualifiers(),
5158                                     ConstArg && !F->isMutable()))
5159         return false;
5160     }
5161   }
5162 
5163   // All OK, it's constexpr!
5164   return true;
5165 }
5166 
5167 static Sema::ImplicitExceptionSpecification
5168 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5169   switch (S.getSpecialMember(MD)) {
5170   case Sema::CXXDefaultConstructor:
5171     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5172   case Sema::CXXCopyConstructor:
5173     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5174   case Sema::CXXCopyAssignment:
5175     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5176   case Sema::CXXMoveConstructor:
5177     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5178   case Sema::CXXMoveAssignment:
5179     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5180   case Sema::CXXDestructor:
5181     return S.ComputeDefaultedDtorExceptionSpec(MD);
5182   case Sema::CXXInvalid:
5183     break;
5184   }
5185   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5186          "only special members have implicit exception specs");
5187   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5188 }
5189 
5190 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5191                                                             CXXMethodDecl *MD) {
5192   FunctionProtoType::ExtProtoInfo EPI;
5193 
5194   // Build an exception specification pointing back at this member.
5195   EPI.ExceptionSpec.Type = EST_Unevaluated;
5196   EPI.ExceptionSpec.SourceDecl = MD;
5197 
5198   // Set the calling convention to the default for C++ instance methods.
5199   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5200       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5201                                             /*IsCXXMethod=*/true));
5202   return EPI;
5203 }
5204 
5205 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5206   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5207   if (FPT->getExceptionSpecType() != EST_Unevaluated)
5208     return;
5209 
5210   // Evaluate the exception specification.
5211   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5212 
5213   // Update the type of the special member to use it.
5214   UpdateExceptionSpec(MD, ESI);
5215 
5216   // A user-provided destructor can be defined outside the class. When that
5217   // happens, be sure to update the exception specification on both
5218   // declarations.
5219   const FunctionProtoType *CanonicalFPT =
5220     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5221   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5222     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5223 }
5224 
5225 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5226   CXXRecordDecl *RD = MD->getParent();
5227   CXXSpecialMember CSM = getSpecialMember(MD);
5228 
5229   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5230          "not an explicitly-defaulted special member");
5231 
5232   // Whether this was the first-declared instance of the constructor.
5233   // This affects whether we implicitly add an exception spec and constexpr.
5234   bool First = MD == MD->getCanonicalDecl();
5235 
5236   bool HadError = false;
5237 
5238   // C++11 [dcl.fct.def.default]p1:
5239   //   A function that is explicitly defaulted shall
5240   //     -- be a special member function (checked elsewhere),
5241   //     -- have the same type (except for ref-qualifiers, and except that a
5242   //        copy operation can take a non-const reference) as an implicit
5243   //        declaration, and
5244   //     -- not have default arguments.
5245   unsigned ExpectedParams = 1;
5246   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5247     ExpectedParams = 0;
5248   if (MD->getNumParams() != ExpectedParams) {
5249     // This also checks for default arguments: a copy or move constructor with a
5250     // default argument is classified as a default constructor, and assignment
5251     // operations and destructors can't have default arguments.
5252     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5253       << CSM << MD->getSourceRange();
5254     HadError = true;
5255   } else if (MD->isVariadic()) {
5256     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5257       << CSM << MD->getSourceRange();
5258     HadError = true;
5259   }
5260 
5261   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5262 
5263   bool CanHaveConstParam = false;
5264   if (CSM == CXXCopyConstructor)
5265     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5266   else if (CSM == CXXCopyAssignment)
5267     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5268 
5269   QualType ReturnType = Context.VoidTy;
5270   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5271     // Check for return type matching.
5272     ReturnType = Type->getReturnType();
5273     QualType ExpectedReturnType =
5274         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5275     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5276       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5277         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5278       HadError = true;
5279     }
5280 
5281     // A defaulted special member cannot have cv-qualifiers.
5282     if (Type->getTypeQuals()) {
5283       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5284         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5285       HadError = true;
5286     }
5287   }
5288 
5289   // Check for parameter type matching.
5290   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5291   bool HasConstParam = false;
5292   if (ExpectedParams && ArgType->isReferenceType()) {
5293     // Argument must be reference to possibly-const T.
5294     QualType ReferentType = ArgType->getPointeeType();
5295     HasConstParam = ReferentType.isConstQualified();
5296 
5297     if (ReferentType.isVolatileQualified()) {
5298       Diag(MD->getLocation(),
5299            diag::err_defaulted_special_member_volatile_param) << CSM;
5300       HadError = true;
5301     }
5302 
5303     if (HasConstParam && !CanHaveConstParam) {
5304       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5305         Diag(MD->getLocation(),
5306              diag::err_defaulted_special_member_copy_const_param)
5307           << (CSM == CXXCopyAssignment);
5308         // FIXME: Explain why this special member can't be const.
5309       } else {
5310         Diag(MD->getLocation(),
5311              diag::err_defaulted_special_member_move_const_param)
5312           << (CSM == CXXMoveAssignment);
5313       }
5314       HadError = true;
5315     }
5316   } else if (ExpectedParams) {
5317     // A copy assignment operator can take its argument by value, but a
5318     // defaulted one cannot.
5319     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5320     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5321     HadError = true;
5322   }
5323 
5324   // C++11 [dcl.fct.def.default]p2:
5325   //   An explicitly-defaulted function may be declared constexpr only if it
5326   //   would have been implicitly declared as constexpr,
5327   // Do not apply this rule to members of class templates, since core issue 1358
5328   // makes such functions always instantiate to constexpr functions. For
5329   // functions which cannot be constexpr (for non-constructors in C++11 and for
5330   // destructors in C++1y), this is checked elsewhere.
5331   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5332                                                      HasConstParam);
5333   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5334                                  : isa<CXXConstructorDecl>(MD)) &&
5335       MD->isConstexpr() && !Constexpr &&
5336       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5337     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5338     // FIXME: Explain why the special member can't be constexpr.
5339     HadError = true;
5340   }
5341 
5342   //   and may have an explicit exception-specification only if it is compatible
5343   //   with the exception-specification on the implicit declaration.
5344   if (Type->hasExceptionSpec()) {
5345     // Delay the check if this is the first declaration of the special member,
5346     // since we may not have parsed some necessary in-class initializers yet.
5347     if (First) {
5348       // If the exception specification needs to be instantiated, do so now,
5349       // before we clobber it with an EST_Unevaluated specification below.
5350       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5351         InstantiateExceptionSpec(MD->getLocStart(), MD);
5352         Type = MD->getType()->getAs<FunctionProtoType>();
5353       }
5354       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5355     } else
5356       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5357   }
5358 
5359   //   If a function is explicitly defaulted on its first declaration,
5360   if (First) {
5361     //  -- it is implicitly considered to be constexpr if the implicit
5362     //     definition would be,
5363     MD->setConstexpr(Constexpr);
5364 
5365     //  -- it is implicitly considered to have the same exception-specification
5366     //     as if it had been implicitly declared,
5367     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5368     EPI.ExceptionSpec.Type = EST_Unevaluated;
5369     EPI.ExceptionSpec.SourceDecl = MD;
5370     MD->setType(Context.getFunctionType(ReturnType,
5371                                         llvm::makeArrayRef(&ArgType,
5372                                                            ExpectedParams),
5373                                         EPI));
5374   }
5375 
5376   if (ShouldDeleteSpecialMember(MD, CSM)) {
5377     if (First) {
5378       SetDeclDeleted(MD, MD->getLocation());
5379     } else {
5380       // C++11 [dcl.fct.def.default]p4:
5381       //   [For a] user-provided explicitly-defaulted function [...] if such a
5382       //   function is implicitly defined as deleted, the program is ill-formed.
5383       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5384       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5385       HadError = true;
5386     }
5387   }
5388 
5389   if (HadError)
5390     MD->setInvalidDecl();
5391 }
5392 
5393 /// Check whether the exception specification provided for an
5394 /// explicitly-defaulted special member matches the exception specification
5395 /// that would have been generated for an implicit special member, per
5396 /// C++11 [dcl.fct.def.default]p2.
5397 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5398     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5399   // If the exception specification was explicitly specified but hadn't been
5400   // parsed when the method was defaulted, grab it now.
5401   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5402     SpecifiedType =
5403         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5404 
5405   // Compute the implicit exception specification.
5406   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5407                                                        /*IsCXXMethod=*/true);
5408   FunctionProtoType::ExtProtoInfo EPI(CC);
5409   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5410                           .getExceptionSpec();
5411   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5412     Context.getFunctionType(Context.VoidTy, None, EPI));
5413 
5414   // Ensure that it matches.
5415   CheckEquivalentExceptionSpec(
5416     PDiag(diag::err_incorrect_defaulted_exception_spec)
5417       << getSpecialMember(MD), PDiag(),
5418     ImplicitType, SourceLocation(),
5419     SpecifiedType, MD->getLocation());
5420 }
5421 
5422 void Sema::CheckDelayedMemberExceptionSpecs() {
5423   decltype(DelayedExceptionSpecChecks) Checks;
5424   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5425 
5426   std::swap(Checks, DelayedExceptionSpecChecks);
5427   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5428 
5429   // Perform any deferred checking of exception specifications for virtual
5430   // destructors.
5431   for (auto &Check : Checks)
5432     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5433 
5434   // Check that any explicitly-defaulted methods have exception specifications
5435   // compatible with their implicit exception specifications.
5436   for (auto &Spec : Specs)
5437     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5438 }
5439 
5440 namespace {
5441 struct SpecialMemberDeletionInfo {
5442   Sema &S;
5443   CXXMethodDecl *MD;
5444   Sema::CXXSpecialMember CSM;
5445   bool Diagnose;
5446 
5447   // Properties of the special member, computed for convenience.
5448   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5449   SourceLocation Loc;
5450 
5451   bool AllFieldsAreConst;
5452 
5453   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5454                             Sema::CXXSpecialMember CSM, bool Diagnose)
5455     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5456       IsConstructor(false), IsAssignment(false), IsMove(false),
5457       ConstArg(false), Loc(MD->getLocation()),
5458       AllFieldsAreConst(true) {
5459     switch (CSM) {
5460       case Sema::CXXDefaultConstructor:
5461       case Sema::CXXCopyConstructor:
5462         IsConstructor = true;
5463         break;
5464       case Sema::CXXMoveConstructor:
5465         IsConstructor = true;
5466         IsMove = true;
5467         break;
5468       case Sema::CXXCopyAssignment:
5469         IsAssignment = true;
5470         break;
5471       case Sema::CXXMoveAssignment:
5472         IsAssignment = true;
5473         IsMove = true;
5474         break;
5475       case Sema::CXXDestructor:
5476         break;
5477       case Sema::CXXInvalid:
5478         llvm_unreachable("invalid special member kind");
5479     }
5480 
5481     if (MD->getNumParams()) {
5482       if (const ReferenceType *RT =
5483               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5484         ConstArg = RT->getPointeeType().isConstQualified();
5485     }
5486   }
5487 
5488   bool inUnion() const { return MD->getParent()->isUnion(); }
5489 
5490   /// Look up the corresponding special member in the given class.
5491   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5492                                               unsigned Quals, bool IsMutable) {
5493     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5494                                        ConstArg && !IsMutable);
5495   }
5496 
5497   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5498 
5499   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5500   bool shouldDeleteForField(FieldDecl *FD);
5501   bool shouldDeleteForAllConstMembers();
5502 
5503   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5504                                      unsigned Quals);
5505   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5506                                     Sema::SpecialMemberOverloadResult *SMOR,
5507                                     bool IsDtorCallInCtor);
5508 
5509   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5510 };
5511 } // namespace
5512 
5513 /// Is the given special member inaccessible when used on the given
5514 /// sub-object.
5515 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5516                                              CXXMethodDecl *target) {
5517   /// If we're operating on a base class, the object type is the
5518   /// type of this special member.
5519   QualType objectTy;
5520   AccessSpecifier access = target->getAccess();
5521   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5522     objectTy = S.Context.getTypeDeclType(MD->getParent());
5523     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5524 
5525   // If we're operating on a field, the object type is the type of the field.
5526   } else {
5527     objectTy = S.Context.getTypeDeclType(target->getParent());
5528   }
5529 
5530   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5531 }
5532 
5533 /// Check whether we should delete a special member due to the implicit
5534 /// definition containing a call to a special member of a subobject.
5535 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5536     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5537     bool IsDtorCallInCtor) {
5538   CXXMethodDecl *Decl = SMOR->getMethod();
5539   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5540 
5541   int DiagKind = -1;
5542 
5543   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5544     DiagKind = !Decl ? 0 : 1;
5545   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5546     DiagKind = 2;
5547   else if (!isAccessible(Subobj, Decl))
5548     DiagKind = 3;
5549   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5550            !Decl->isTrivial()) {
5551     // A member of a union must have a trivial corresponding special member.
5552     // As a weird special case, a destructor call from a union's constructor
5553     // must be accessible and non-deleted, but need not be trivial. Such a
5554     // destructor is never actually called, but is semantically checked as
5555     // if it were.
5556     DiagKind = 4;
5557   }
5558 
5559   if (DiagKind == -1)
5560     return false;
5561 
5562   if (Diagnose) {
5563     if (Field) {
5564       S.Diag(Field->getLocation(),
5565              diag::note_deleted_special_member_class_subobject)
5566         << CSM << MD->getParent() << /*IsField*/true
5567         << Field << DiagKind << IsDtorCallInCtor;
5568     } else {
5569       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5570       S.Diag(Base->getLocStart(),
5571              diag::note_deleted_special_member_class_subobject)
5572         << CSM << MD->getParent() << /*IsField*/false
5573         << Base->getType() << DiagKind << IsDtorCallInCtor;
5574     }
5575 
5576     if (DiagKind == 1)
5577       S.NoteDeletedFunction(Decl);
5578     // FIXME: Explain inaccessibility if DiagKind == 3.
5579   }
5580 
5581   return true;
5582 }
5583 
5584 /// Check whether we should delete a special member function due to having a
5585 /// direct or virtual base class or non-static data member of class type M.
5586 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5587     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5588   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5589   bool IsMutable = Field && Field->isMutable();
5590 
5591   // C++11 [class.ctor]p5:
5592   // -- any direct or virtual base class, or non-static data member with no
5593   //    brace-or-equal-initializer, has class type M (or array thereof) and
5594   //    either M has no default constructor or overload resolution as applied
5595   //    to M's default constructor results in an ambiguity or in a function
5596   //    that is deleted or inaccessible
5597   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5598   // -- a direct or virtual base class B that cannot be copied/moved because
5599   //    overload resolution, as applied to B's corresponding special member,
5600   //    results in an ambiguity or a function that is deleted or inaccessible
5601   //    from the defaulted special member
5602   // C++11 [class.dtor]p5:
5603   // -- any direct or virtual base class [...] has a type with a destructor
5604   //    that is deleted or inaccessible
5605   if (!(CSM == Sema::CXXDefaultConstructor &&
5606         Field && Field->hasInClassInitializer()) &&
5607       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5608                                    false))
5609     return true;
5610 
5611   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5612   // -- any direct or virtual base class or non-static data member has a
5613   //    type with a destructor that is deleted or inaccessible
5614   if (IsConstructor) {
5615     Sema::SpecialMemberOverloadResult *SMOR =
5616         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5617                               false, false, false, false, false);
5618     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5619       return true;
5620   }
5621 
5622   return false;
5623 }
5624 
5625 /// Check whether we should delete a special member function due to the class
5626 /// having a particular direct or virtual base class.
5627 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5628   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5629   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5630 }
5631 
5632 /// Check whether we should delete a special member function due to the class
5633 /// having a particular non-static data member.
5634 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5635   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5636   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5637 
5638   if (CSM == Sema::CXXDefaultConstructor) {
5639     // For a default constructor, all references must be initialized in-class
5640     // and, if a union, it must have a non-const member.
5641     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5642       if (Diagnose)
5643         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5644           << MD->getParent() << FD << FieldType << /*Reference*/0;
5645       return true;
5646     }
5647     // C++11 [class.ctor]p5: any non-variant non-static data member of
5648     // const-qualified type (or array thereof) with no
5649     // brace-or-equal-initializer does not have a user-provided default
5650     // constructor.
5651     if (!inUnion() && FieldType.isConstQualified() &&
5652         !FD->hasInClassInitializer() &&
5653         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5654       if (Diagnose)
5655         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5656           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5657       return true;
5658     }
5659 
5660     if (inUnion() && !FieldType.isConstQualified())
5661       AllFieldsAreConst = false;
5662   } else if (CSM == Sema::CXXCopyConstructor) {
5663     // For a copy constructor, data members must not be of rvalue reference
5664     // type.
5665     if (FieldType->isRValueReferenceType()) {
5666       if (Diagnose)
5667         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5668           << MD->getParent() << FD << FieldType;
5669       return true;
5670     }
5671   } else if (IsAssignment) {
5672     // For an assignment operator, data members must not be of reference type.
5673     if (FieldType->isReferenceType()) {
5674       if (Diagnose)
5675         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5676           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5677       return true;
5678     }
5679     if (!FieldRecord && FieldType.isConstQualified()) {
5680       // C++11 [class.copy]p23:
5681       // -- a non-static data member of const non-class type (or array thereof)
5682       if (Diagnose)
5683         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5684           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5685       return true;
5686     }
5687   }
5688 
5689   if (FieldRecord) {
5690     // Some additional restrictions exist on the variant members.
5691     if (!inUnion() && FieldRecord->isUnion() &&
5692         FieldRecord->isAnonymousStructOrUnion()) {
5693       bool AllVariantFieldsAreConst = true;
5694 
5695       // FIXME: Handle anonymous unions declared within anonymous unions.
5696       for (auto *UI : FieldRecord->fields()) {
5697         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5698 
5699         if (!UnionFieldType.isConstQualified())
5700           AllVariantFieldsAreConst = false;
5701 
5702         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5703         if (UnionFieldRecord &&
5704             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5705                                           UnionFieldType.getCVRQualifiers()))
5706           return true;
5707       }
5708 
5709       // At least one member in each anonymous union must be non-const
5710       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5711           !FieldRecord->field_empty()) {
5712         if (Diagnose)
5713           S.Diag(FieldRecord->getLocation(),
5714                  diag::note_deleted_default_ctor_all_const)
5715             << MD->getParent() << /*anonymous union*/1;
5716         return true;
5717       }
5718 
5719       // Don't check the implicit member of the anonymous union type.
5720       // This is technically non-conformant, but sanity demands it.
5721       return false;
5722     }
5723 
5724     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5725                                       FieldType.getCVRQualifiers()))
5726       return true;
5727   }
5728 
5729   return false;
5730 }
5731 
5732 /// C++11 [class.ctor] p5:
5733 ///   A defaulted default constructor for a class X is defined as deleted if
5734 /// X is a union and all of its variant members are of const-qualified type.
5735 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5736   // This is a silly definition, because it gives an empty union a deleted
5737   // default constructor. Don't do that.
5738   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5739       !MD->getParent()->field_empty()) {
5740     if (Diagnose)
5741       S.Diag(MD->getParent()->getLocation(),
5742              diag::note_deleted_default_ctor_all_const)
5743         << MD->getParent() << /*not anonymous union*/0;
5744     return true;
5745   }
5746   return false;
5747 }
5748 
5749 /// Determine whether a defaulted special member function should be defined as
5750 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5751 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5752 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5753                                      bool Diagnose) {
5754   if (MD->isInvalidDecl())
5755     return false;
5756   CXXRecordDecl *RD = MD->getParent();
5757   assert(!RD->isDependentType() && "do deletion after instantiation");
5758   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5759     return false;
5760 
5761   // C++11 [expr.lambda.prim]p19:
5762   //   The closure type associated with a lambda-expression has a
5763   //   deleted (8.4.3) default constructor and a deleted copy
5764   //   assignment operator.
5765   if (RD->isLambda() &&
5766       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5767     if (Diagnose)
5768       Diag(RD->getLocation(), diag::note_lambda_decl);
5769     return true;
5770   }
5771 
5772   // For an anonymous struct or union, the copy and assignment special members
5773   // will never be used, so skip the check. For an anonymous union declared at
5774   // namespace scope, the constructor and destructor are used.
5775   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5776       RD->isAnonymousStructOrUnion())
5777     return false;
5778 
5779   // C++11 [class.copy]p7, p18:
5780   //   If the class definition declares a move constructor or move assignment
5781   //   operator, an implicitly declared copy constructor or copy assignment
5782   //   operator is defined as deleted.
5783   if (MD->isImplicit() &&
5784       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5785     CXXMethodDecl *UserDeclaredMove = nullptr;
5786 
5787     // In Microsoft mode, a user-declared move only causes the deletion of the
5788     // corresponding copy operation, not both copy operations.
5789     if (RD->hasUserDeclaredMoveConstructor() &&
5790         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5791       if (!Diagnose) return true;
5792 
5793       // Find any user-declared move constructor.
5794       for (auto *I : RD->ctors()) {
5795         if (I->isMoveConstructor()) {
5796           UserDeclaredMove = I;
5797           break;
5798         }
5799       }
5800       assert(UserDeclaredMove);
5801     } else if (RD->hasUserDeclaredMoveAssignment() &&
5802                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5803       if (!Diagnose) return true;
5804 
5805       // Find any user-declared move assignment operator.
5806       for (auto *I : RD->methods()) {
5807         if (I->isMoveAssignmentOperator()) {
5808           UserDeclaredMove = I;
5809           break;
5810         }
5811       }
5812       assert(UserDeclaredMove);
5813     }
5814 
5815     if (UserDeclaredMove) {
5816       Diag(UserDeclaredMove->getLocation(),
5817            diag::note_deleted_copy_user_declared_move)
5818         << (CSM == CXXCopyAssignment) << RD
5819         << UserDeclaredMove->isMoveAssignmentOperator();
5820       return true;
5821     }
5822   }
5823 
5824   // Do access control from the special member function
5825   ContextRAII MethodContext(*this, MD);
5826 
5827   // C++11 [class.dtor]p5:
5828   // -- for a virtual destructor, lookup of the non-array deallocation function
5829   //    results in an ambiguity or in a function that is deleted or inaccessible
5830   if (CSM == CXXDestructor && MD->isVirtual()) {
5831     FunctionDecl *OperatorDelete = nullptr;
5832     DeclarationName Name =
5833       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5834     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5835                                  OperatorDelete, false)) {
5836       if (Diagnose)
5837         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5838       return true;
5839     }
5840   }
5841 
5842   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5843 
5844   for (auto &BI : RD->bases())
5845     if (!BI.isVirtual() &&
5846         SMI.shouldDeleteForBase(&BI))
5847       return true;
5848 
5849   // Per DR1611, do not consider virtual bases of constructors of abstract
5850   // classes, since we are not going to construct them.
5851   if (!RD->isAbstract() || !SMI.IsConstructor) {
5852     for (auto &BI : RD->vbases())
5853       if (SMI.shouldDeleteForBase(&BI))
5854         return true;
5855   }
5856 
5857   for (auto *FI : RD->fields())
5858     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5859         SMI.shouldDeleteForField(FI))
5860       return true;
5861 
5862   if (SMI.shouldDeleteForAllConstMembers())
5863     return true;
5864 
5865   if (getLangOpts().CUDA) {
5866     // We should delete the special member in CUDA mode if target inference
5867     // failed.
5868     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5869                                                    Diagnose);
5870   }
5871 
5872   return false;
5873 }
5874 
5875 /// Perform lookup for a special member of the specified kind, and determine
5876 /// whether it is trivial. If the triviality can be determined without the
5877 /// lookup, skip it. This is intended for use when determining whether a
5878 /// special member of a containing object is trivial, and thus does not ever
5879 /// perform overload resolution for default constructors.
5880 ///
5881 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5882 /// member that was most likely to be intended to be trivial, if any.
5883 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5884                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5885                                      bool ConstRHS, CXXMethodDecl **Selected) {
5886   if (Selected)
5887     *Selected = nullptr;
5888 
5889   switch (CSM) {
5890   case Sema::CXXInvalid:
5891     llvm_unreachable("not a special member");
5892 
5893   case Sema::CXXDefaultConstructor:
5894     // C++11 [class.ctor]p5:
5895     //   A default constructor is trivial if:
5896     //    - all the [direct subobjects] have trivial default constructors
5897     //
5898     // Note, no overload resolution is performed in this case.
5899     if (RD->hasTrivialDefaultConstructor())
5900       return true;
5901 
5902     if (Selected) {
5903       // If there's a default constructor which could have been trivial, dig it
5904       // out. Otherwise, if there's any user-provided default constructor, point
5905       // to that as an example of why there's not a trivial one.
5906       CXXConstructorDecl *DefCtor = nullptr;
5907       if (RD->needsImplicitDefaultConstructor())
5908         S.DeclareImplicitDefaultConstructor(RD);
5909       for (auto *CI : RD->ctors()) {
5910         if (!CI->isDefaultConstructor())
5911           continue;
5912         DefCtor = CI;
5913         if (!DefCtor->isUserProvided())
5914           break;
5915       }
5916 
5917       *Selected = DefCtor;
5918     }
5919 
5920     return false;
5921 
5922   case Sema::CXXDestructor:
5923     // C++11 [class.dtor]p5:
5924     //   A destructor is trivial if:
5925     //    - all the direct [subobjects] have trivial destructors
5926     if (RD->hasTrivialDestructor())
5927       return true;
5928 
5929     if (Selected) {
5930       if (RD->needsImplicitDestructor())
5931         S.DeclareImplicitDestructor(RD);
5932       *Selected = RD->getDestructor();
5933     }
5934 
5935     return false;
5936 
5937   case Sema::CXXCopyConstructor:
5938     // C++11 [class.copy]p12:
5939     //   A copy constructor is trivial if:
5940     //    - the constructor selected to copy each direct [subobject] is trivial
5941     if (RD->hasTrivialCopyConstructor()) {
5942       if (Quals == Qualifiers::Const)
5943         // We must either select the trivial copy constructor or reach an
5944         // ambiguity; no need to actually perform overload resolution.
5945         return true;
5946     } else if (!Selected) {
5947       return false;
5948     }
5949     // In C++98, we are not supposed to perform overload resolution here, but we
5950     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5951     // cases like B as having a non-trivial copy constructor:
5952     //   struct A { template<typename T> A(T&); };
5953     //   struct B { mutable A a; };
5954     goto NeedOverloadResolution;
5955 
5956   case Sema::CXXCopyAssignment:
5957     // C++11 [class.copy]p25:
5958     //   A copy assignment operator is trivial if:
5959     //    - the assignment operator selected to copy each direct [subobject] is
5960     //      trivial
5961     if (RD->hasTrivialCopyAssignment()) {
5962       if (Quals == Qualifiers::Const)
5963         return true;
5964     } else if (!Selected) {
5965       return false;
5966     }
5967     // In C++98, we are not supposed to perform overload resolution here, but we
5968     // treat that as a language defect.
5969     goto NeedOverloadResolution;
5970 
5971   case Sema::CXXMoveConstructor:
5972   case Sema::CXXMoveAssignment:
5973   NeedOverloadResolution:
5974     Sema::SpecialMemberOverloadResult *SMOR =
5975         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5976 
5977     // The standard doesn't describe how to behave if the lookup is ambiguous.
5978     // We treat it as not making the member non-trivial, just like the standard
5979     // mandates for the default constructor. This should rarely matter, because
5980     // the member will also be deleted.
5981     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5982       return true;
5983 
5984     if (!SMOR->getMethod()) {
5985       assert(SMOR->getKind() ==
5986              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5987       return false;
5988     }
5989 
5990     // We deliberately don't check if we found a deleted special member. We're
5991     // not supposed to!
5992     if (Selected)
5993       *Selected = SMOR->getMethod();
5994     return SMOR->getMethod()->isTrivial();
5995   }
5996 
5997   llvm_unreachable("unknown special method kind");
5998 }
5999 
6000 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6001   for (auto *CI : RD->ctors())
6002     if (!CI->isImplicit())
6003       return CI;
6004 
6005   // Look for constructor templates.
6006   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6007   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6008     if (CXXConstructorDecl *CD =
6009           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6010       return CD;
6011   }
6012 
6013   return nullptr;
6014 }
6015 
6016 /// The kind of subobject we are checking for triviality. The values of this
6017 /// enumeration are used in diagnostics.
6018 enum TrivialSubobjectKind {
6019   /// The subobject is a base class.
6020   TSK_BaseClass,
6021   /// The subobject is a non-static data member.
6022   TSK_Field,
6023   /// The object is actually the complete object.
6024   TSK_CompleteObject
6025 };
6026 
6027 /// Check whether the special member selected for a given type would be trivial.
6028 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6029                                       QualType SubType, bool ConstRHS,
6030                                       Sema::CXXSpecialMember CSM,
6031                                       TrivialSubobjectKind Kind,
6032                                       bool Diagnose) {
6033   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6034   if (!SubRD)
6035     return true;
6036 
6037   CXXMethodDecl *Selected;
6038   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6039                                ConstRHS, Diagnose ? &Selected : nullptr))
6040     return true;
6041 
6042   if (Diagnose) {
6043     if (ConstRHS)
6044       SubType.addConst();
6045 
6046     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6047       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6048         << Kind << SubType.getUnqualifiedType();
6049       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6050         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6051     } else if (!Selected)
6052       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6053         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6054     else if (Selected->isUserProvided()) {
6055       if (Kind == TSK_CompleteObject)
6056         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6057           << Kind << SubType.getUnqualifiedType() << CSM;
6058       else {
6059         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6060           << Kind << SubType.getUnqualifiedType() << CSM;
6061         S.Diag(Selected->getLocation(), diag::note_declared_at);
6062       }
6063     } else {
6064       if (Kind != TSK_CompleteObject)
6065         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6066           << Kind << SubType.getUnqualifiedType() << CSM;
6067 
6068       // Explain why the defaulted or deleted special member isn't trivial.
6069       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6070     }
6071   }
6072 
6073   return false;
6074 }
6075 
6076 /// Check whether the members of a class type allow a special member to be
6077 /// trivial.
6078 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6079                                      Sema::CXXSpecialMember CSM,
6080                                      bool ConstArg, bool Diagnose) {
6081   for (const auto *FI : RD->fields()) {
6082     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6083       continue;
6084 
6085     QualType FieldType = S.Context.getBaseElementType(FI->getType());
6086 
6087     // Pretend anonymous struct or union members are members of this class.
6088     if (FI->isAnonymousStructOrUnion()) {
6089       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6090                                     CSM, ConstArg, Diagnose))
6091         return false;
6092       continue;
6093     }
6094 
6095     // C++11 [class.ctor]p5:
6096     //   A default constructor is trivial if [...]
6097     //    -- no non-static data member of its class has a
6098     //       brace-or-equal-initializer
6099     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6100       if (Diagnose)
6101         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6102       return false;
6103     }
6104 
6105     // Objective C ARC 4.3.5:
6106     //   [...] nontrivally ownership-qualified types are [...] not trivially
6107     //   default constructible, copy constructible, move constructible, copy
6108     //   assignable, move assignable, or destructible [...]
6109     if (S.getLangOpts().ObjCAutoRefCount &&
6110         FieldType.hasNonTrivialObjCLifetime()) {
6111       if (Diagnose)
6112         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6113           << RD << FieldType.getObjCLifetime();
6114       return false;
6115     }
6116 
6117     bool ConstRHS = ConstArg && !FI->isMutable();
6118     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6119                                    CSM, TSK_Field, Diagnose))
6120       return false;
6121   }
6122 
6123   return true;
6124 }
6125 
6126 /// Diagnose why the specified class does not have a trivial special member of
6127 /// the given kind.
6128 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6129   QualType Ty = Context.getRecordType(RD);
6130 
6131   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6132   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6133                             TSK_CompleteObject, /*Diagnose*/true);
6134 }
6135 
6136 /// Determine whether a defaulted or deleted special member function is trivial,
6137 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6138 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6139 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6140                                   bool Diagnose) {
6141   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6142 
6143   CXXRecordDecl *RD = MD->getParent();
6144 
6145   bool ConstArg = false;
6146 
6147   // C++11 [class.copy]p12, p25: [DR1593]
6148   //   A [special member] is trivial if [...] its parameter-type-list is
6149   //   equivalent to the parameter-type-list of an implicit declaration [...]
6150   switch (CSM) {
6151   case CXXDefaultConstructor:
6152   case CXXDestructor:
6153     // Trivial default constructors and destructors cannot have parameters.
6154     break;
6155 
6156   case CXXCopyConstructor:
6157   case CXXCopyAssignment: {
6158     // Trivial copy operations always have const, non-volatile parameter types.
6159     ConstArg = true;
6160     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6161     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6162     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6163       if (Diagnose)
6164         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6165           << Param0->getSourceRange() << Param0->getType()
6166           << Context.getLValueReferenceType(
6167                Context.getRecordType(RD).withConst());
6168       return false;
6169     }
6170     break;
6171   }
6172 
6173   case CXXMoveConstructor:
6174   case CXXMoveAssignment: {
6175     // Trivial move operations always have non-cv-qualified parameters.
6176     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6177     const RValueReferenceType *RT =
6178       Param0->getType()->getAs<RValueReferenceType>();
6179     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6180       if (Diagnose)
6181         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6182           << Param0->getSourceRange() << Param0->getType()
6183           << Context.getRValueReferenceType(Context.getRecordType(RD));
6184       return false;
6185     }
6186     break;
6187   }
6188 
6189   case CXXInvalid:
6190     llvm_unreachable("not a special member");
6191   }
6192 
6193   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6194     if (Diagnose)
6195       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6196            diag::note_nontrivial_default_arg)
6197         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6198     return false;
6199   }
6200   if (MD->isVariadic()) {
6201     if (Diagnose)
6202       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6203     return false;
6204   }
6205 
6206   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6207   //   A copy/move [constructor or assignment operator] is trivial if
6208   //    -- the [member] selected to copy/move each direct base class subobject
6209   //       is trivial
6210   //
6211   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6212   //   A [default constructor or destructor] is trivial if
6213   //    -- all the direct base classes have trivial [default constructors or
6214   //       destructors]
6215   for (const auto &BI : RD->bases())
6216     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6217                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
6218       return false;
6219 
6220   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6221   //   A copy/move [constructor or assignment operator] for a class X is
6222   //   trivial if
6223   //    -- for each non-static data member of X that is of class type (or array
6224   //       thereof), the constructor selected to copy/move that member is
6225   //       trivial
6226   //
6227   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6228   //   A [default constructor or destructor] is trivial if
6229   //    -- for all of the non-static data members of its class that are of class
6230   //       type (or array thereof), each such class has a trivial [default
6231   //       constructor or destructor]
6232   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6233     return false;
6234 
6235   // C++11 [class.dtor]p5:
6236   //   A destructor is trivial if [...]
6237   //    -- the destructor is not virtual
6238   if (CSM == CXXDestructor && MD->isVirtual()) {
6239     if (Diagnose)
6240       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6241     return false;
6242   }
6243 
6244   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6245   //   A [special member] for class X is trivial if [...]
6246   //    -- class X has no virtual functions and no virtual base classes
6247   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6248     if (!Diagnose)
6249       return false;
6250 
6251     if (RD->getNumVBases()) {
6252       // Check for virtual bases. We already know that the corresponding
6253       // member in all bases is trivial, so vbases must all be direct.
6254       CXXBaseSpecifier &BS = *RD->vbases_begin();
6255       assert(BS.isVirtual());
6256       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6257       return false;
6258     }
6259 
6260     // Must have a virtual method.
6261     for (const auto *MI : RD->methods()) {
6262       if (MI->isVirtual()) {
6263         SourceLocation MLoc = MI->getLocStart();
6264         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6265         return false;
6266       }
6267     }
6268 
6269     llvm_unreachable("dynamic class with no vbases and no virtual functions");
6270   }
6271 
6272   // Looks like it's trivial!
6273   return true;
6274 }
6275 
6276 /// \brief Data used with FindHiddenVirtualMethod
6277 namespace {
6278   struct FindHiddenVirtualMethodData {
6279     Sema *S;
6280     CXXMethodDecl *Method;
6281     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6282     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6283   };
6284 }
6285 
6286 /// \brief Check whether any most overriden method from MD in Methods
6287 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
6288                   const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6289   if (MD->size_overridden_methods() == 0)
6290     return Methods.count(MD->getCanonicalDecl());
6291   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6292                                       E = MD->end_overridden_methods();
6293        I != E; ++I)
6294     if (CheckMostOverridenMethods(*I, Methods))
6295       return true;
6296   return false;
6297 }
6298 
6299 /// \brief Member lookup function that determines whether a given C++
6300 /// method overloads virtual methods in a base class without overriding any,
6301 /// to be used with CXXRecordDecl::lookupInBases().
6302 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6303                                     CXXBasePath &Path,
6304                                     void *UserData) {
6305   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6306 
6307   FindHiddenVirtualMethodData &Data
6308     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6309 
6310   DeclarationName Name = Data.Method->getDeclName();
6311   assert(Name.getNameKind() == DeclarationName::Identifier);
6312 
6313   bool foundSameNameMethod = false;
6314   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6315   for (Path.Decls = BaseRecord->lookup(Name);
6316        !Path.Decls.empty();
6317        Path.Decls = Path.Decls.slice(1)) {
6318     NamedDecl *D = Path.Decls.front();
6319     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6320       MD = MD->getCanonicalDecl();
6321       foundSameNameMethod = true;
6322       // Interested only in hidden virtual methods.
6323       if (!MD->isVirtual())
6324         continue;
6325       // If the method we are checking overrides a method from its base
6326       // don't warn about the other overloaded methods. Clang deviates from GCC
6327       // by only diagnosing overloads of inherited virtual functions that do not
6328       // override any other virtual functions in the base. GCC's
6329       // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6330       // function from a base class. These cases may be better served by a
6331       // warning (not specific to virtual functions) on call sites when the call
6332       // would select a different function from the base class, were it visible.
6333       // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6334       if (!Data.S->IsOverload(Data.Method, MD, false))
6335         return true;
6336       // Collect the overload only if its hidden.
6337       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
6338         overloadedMethods.push_back(MD);
6339     }
6340   }
6341 
6342   if (foundSameNameMethod)
6343     Data.OverloadedMethods.append(overloadedMethods.begin(),
6344                                    overloadedMethods.end());
6345   return foundSameNameMethod;
6346 }
6347 
6348 /// \brief Add the most overriden methods from MD to Methods
6349 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6350                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6351   if (MD->size_overridden_methods() == 0)
6352     Methods.insert(MD->getCanonicalDecl());
6353   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6354                                       E = MD->end_overridden_methods();
6355        I != E; ++I)
6356     AddMostOverridenMethods(*I, Methods);
6357 }
6358 
6359 /// \brief Check if a method overloads virtual methods in a base class without
6360 /// overriding any.
6361 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6362                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6363   if (!MD->getDeclName().isIdentifier())
6364     return;
6365 
6366   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6367                      /*bool RecordPaths=*/false,
6368                      /*bool DetectVirtual=*/false);
6369   FindHiddenVirtualMethodData Data;
6370   Data.Method = MD;
6371   Data.S = this;
6372 
6373   // Keep the base methods that were overriden or introduced in the subclass
6374   // by 'using' in a set. A base method not in this set is hidden.
6375   CXXRecordDecl *DC = MD->getParent();
6376   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6377   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6378     NamedDecl *ND = *I;
6379     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6380       ND = shad->getTargetDecl();
6381     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6382       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
6383   }
6384 
6385   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6386     OverloadedMethods = Data.OverloadedMethods;
6387 }
6388 
6389 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6390                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6391   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6392     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6393     PartialDiagnostic PD = PDiag(
6394          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6395     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6396     Diag(overloadedMD->getLocation(), PD);
6397   }
6398 }
6399 
6400 /// \brief Diagnose methods which overload virtual methods in a base class
6401 /// without overriding any.
6402 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6403   if (MD->isInvalidDecl())
6404     return;
6405 
6406   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6407     return;
6408 
6409   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6410   FindHiddenVirtualMethods(MD, OverloadedMethods);
6411   if (!OverloadedMethods.empty()) {
6412     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6413       << MD << (OverloadedMethods.size() > 1);
6414 
6415     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6416   }
6417 }
6418 
6419 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6420                                              Decl *TagDecl,
6421                                              SourceLocation LBrac,
6422                                              SourceLocation RBrac,
6423                                              AttributeList *AttrList) {
6424   if (!TagDecl)
6425     return;
6426 
6427   AdjustDeclIfTemplate(TagDecl);
6428 
6429   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6430     if (l->getKind() != AttributeList::AT_Visibility)
6431       continue;
6432     l->setInvalid();
6433     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6434       l->getName();
6435   }
6436 
6437   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6438               // strict aliasing violation!
6439               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6440               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6441 
6442   CheckCompletedCXXClass(
6443                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6444 }
6445 
6446 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6447 /// special functions, such as the default constructor, copy
6448 /// constructor, or destructor, to the given C++ class (C++
6449 /// [special]p1).  This routine can only be executed just before the
6450 /// definition of the class is complete.
6451 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6452   if (!ClassDecl->hasUserDeclaredConstructor())
6453     ++ASTContext::NumImplicitDefaultConstructors;
6454 
6455   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6456     ++ASTContext::NumImplicitCopyConstructors;
6457 
6458     // If the properties or semantics of the copy constructor couldn't be
6459     // determined while the class was being declared, force a declaration
6460     // of it now.
6461     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6462       DeclareImplicitCopyConstructor(ClassDecl);
6463   }
6464 
6465   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6466     ++ASTContext::NumImplicitMoveConstructors;
6467 
6468     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6469       DeclareImplicitMoveConstructor(ClassDecl);
6470   }
6471 
6472   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6473     ++ASTContext::NumImplicitCopyAssignmentOperators;
6474 
6475     // If we have a dynamic class, then the copy assignment operator may be
6476     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6477     // it shows up in the right place in the vtable and that we diagnose
6478     // problems with the implicit exception specification.
6479     if (ClassDecl->isDynamicClass() ||
6480         ClassDecl->needsOverloadResolutionForCopyAssignment())
6481       DeclareImplicitCopyAssignment(ClassDecl);
6482   }
6483 
6484   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6485     ++ASTContext::NumImplicitMoveAssignmentOperators;
6486 
6487     // Likewise for the move assignment operator.
6488     if (ClassDecl->isDynamicClass() ||
6489         ClassDecl->needsOverloadResolutionForMoveAssignment())
6490       DeclareImplicitMoveAssignment(ClassDecl);
6491   }
6492 
6493   if (!ClassDecl->hasUserDeclaredDestructor()) {
6494     ++ASTContext::NumImplicitDestructors;
6495 
6496     // If we have a dynamic class, then the destructor may be virtual, so we
6497     // have to declare the destructor immediately. This ensures that, e.g., it
6498     // shows up in the right place in the vtable and that we diagnose problems
6499     // with the implicit exception specification.
6500     if (ClassDecl->isDynamicClass() ||
6501         ClassDecl->needsOverloadResolutionForDestructor())
6502       DeclareImplicitDestructor(ClassDecl);
6503   }
6504 }
6505 
6506 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6507   if (!D)
6508     return 0;
6509 
6510   // The order of template parameters is not important here. All names
6511   // get added to the same scope.
6512   SmallVector<TemplateParameterList *, 4> ParameterLists;
6513 
6514   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6515     D = TD->getTemplatedDecl();
6516 
6517   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6518     ParameterLists.push_back(PSD->getTemplateParameters());
6519 
6520   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6521     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6522       ParameterLists.push_back(DD->getTemplateParameterList(i));
6523 
6524     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6525       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6526         ParameterLists.push_back(FTD->getTemplateParameters());
6527     }
6528   }
6529 
6530   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6531     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6532       ParameterLists.push_back(TD->getTemplateParameterList(i));
6533 
6534     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6535       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6536         ParameterLists.push_back(CTD->getTemplateParameters());
6537     }
6538   }
6539 
6540   unsigned Count = 0;
6541   for (TemplateParameterList *Params : ParameterLists) {
6542     if (Params->size() > 0)
6543       // Ignore explicit specializations; they don't contribute to the template
6544       // depth.
6545       ++Count;
6546     for (NamedDecl *Param : *Params) {
6547       if (Param->getDeclName()) {
6548         S->AddDecl(Param);
6549         IdResolver.AddDecl(Param);
6550       }
6551     }
6552   }
6553 
6554   return Count;
6555 }
6556 
6557 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6558   if (!RecordD) return;
6559   AdjustDeclIfTemplate(RecordD);
6560   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6561   PushDeclContext(S, Record);
6562 }
6563 
6564 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6565   if (!RecordD) return;
6566   PopDeclContext();
6567 }
6568 
6569 /// This is used to implement the constant expression evaluation part of the
6570 /// attribute enable_if extension. There is nothing in standard C++ which would
6571 /// require reentering parameters.
6572 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6573   if (!Param)
6574     return;
6575 
6576   S->AddDecl(Param);
6577   if (Param->getDeclName())
6578     IdResolver.AddDecl(Param);
6579 }
6580 
6581 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6582 /// parsing a top-level (non-nested) C++ class, and we are now
6583 /// parsing those parts of the given Method declaration that could
6584 /// not be parsed earlier (C++ [class.mem]p2), such as default
6585 /// arguments. This action should enter the scope of the given
6586 /// Method declaration as if we had just parsed the qualified method
6587 /// name. However, it should not bring the parameters into scope;
6588 /// that will be performed by ActOnDelayedCXXMethodParameter.
6589 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6590 }
6591 
6592 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6593 /// C++ method declaration. We're (re-)introducing the given
6594 /// function parameter into scope for use in parsing later parts of
6595 /// the method declaration. For example, we could see an
6596 /// ActOnParamDefaultArgument event for this parameter.
6597 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6598   if (!ParamD)
6599     return;
6600 
6601   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6602 
6603   // If this parameter has an unparsed default argument, clear it out
6604   // to make way for the parsed default argument.
6605   if (Param->hasUnparsedDefaultArg())
6606     Param->setDefaultArg(nullptr);
6607 
6608   S->AddDecl(Param);
6609   if (Param->getDeclName())
6610     IdResolver.AddDecl(Param);
6611 }
6612 
6613 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6614 /// processing the delayed method declaration for Method. The method
6615 /// declaration is now considered finished. There may be a separate
6616 /// ActOnStartOfFunctionDef action later (not necessarily
6617 /// immediately!) for this method, if it was also defined inside the
6618 /// class body.
6619 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6620   if (!MethodD)
6621     return;
6622 
6623   AdjustDeclIfTemplate(MethodD);
6624 
6625   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6626 
6627   // Now that we have our default arguments, check the constructor
6628   // again. It could produce additional diagnostics or affect whether
6629   // the class has implicitly-declared destructors, among other
6630   // things.
6631   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6632     CheckConstructor(Constructor);
6633 
6634   // Check the default arguments, which we may have added.
6635   if (!Method->isInvalidDecl())
6636     CheckCXXDefaultArguments(Method);
6637 }
6638 
6639 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6640 /// the well-formedness of the constructor declarator @p D with type @p
6641 /// R. If there are any errors in the declarator, this routine will
6642 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6643 /// will be updated to reflect a well-formed type for the constructor and
6644 /// returned.
6645 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6646                                           StorageClass &SC) {
6647   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6648 
6649   // C++ [class.ctor]p3:
6650   //   A constructor shall not be virtual (10.3) or static (9.4). A
6651   //   constructor can be invoked for a const, volatile or const
6652   //   volatile object. A constructor shall not be declared const,
6653   //   volatile, or const volatile (9.3.2).
6654   if (isVirtual) {
6655     if (!D.isInvalidType())
6656       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6657         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6658         << SourceRange(D.getIdentifierLoc());
6659     D.setInvalidType();
6660   }
6661   if (SC == SC_Static) {
6662     if (!D.isInvalidType())
6663       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6664         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6665         << SourceRange(D.getIdentifierLoc());
6666     D.setInvalidType();
6667     SC = SC_None;
6668   }
6669 
6670   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6671     diagnoseIgnoredQualifiers(
6672         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6673         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6674         D.getDeclSpec().getRestrictSpecLoc(),
6675         D.getDeclSpec().getAtomicSpecLoc());
6676     D.setInvalidType();
6677   }
6678 
6679   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6680   if (FTI.TypeQuals != 0) {
6681     if (FTI.TypeQuals & Qualifiers::Const)
6682       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6683         << "const" << SourceRange(D.getIdentifierLoc());
6684     if (FTI.TypeQuals & Qualifiers::Volatile)
6685       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6686         << "volatile" << SourceRange(D.getIdentifierLoc());
6687     if (FTI.TypeQuals & Qualifiers::Restrict)
6688       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6689         << "restrict" << SourceRange(D.getIdentifierLoc());
6690     D.setInvalidType();
6691   }
6692 
6693   // C++0x [class.ctor]p4:
6694   //   A constructor shall not be declared with a ref-qualifier.
6695   if (FTI.hasRefQualifier()) {
6696     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6697       << FTI.RefQualifierIsLValueRef
6698       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6699     D.setInvalidType();
6700   }
6701 
6702   // Rebuild the function type "R" without any type qualifiers (in
6703   // case any of the errors above fired) and with "void" as the
6704   // return type, since constructors don't have return types.
6705   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6706   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6707     return R;
6708 
6709   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6710   EPI.TypeQuals = 0;
6711   EPI.RefQualifier = RQ_None;
6712 
6713   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6714 }
6715 
6716 /// CheckConstructor - Checks a fully-formed constructor for
6717 /// well-formedness, issuing any diagnostics required. Returns true if
6718 /// the constructor declarator is invalid.
6719 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6720   CXXRecordDecl *ClassDecl
6721     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6722   if (!ClassDecl)
6723     return Constructor->setInvalidDecl();
6724 
6725   // C++ [class.copy]p3:
6726   //   A declaration of a constructor for a class X is ill-formed if
6727   //   its first parameter is of type (optionally cv-qualified) X and
6728   //   either there are no other parameters or else all other
6729   //   parameters have default arguments.
6730   if (!Constructor->isInvalidDecl() &&
6731       ((Constructor->getNumParams() == 1) ||
6732        (Constructor->getNumParams() > 1 &&
6733         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6734       Constructor->getTemplateSpecializationKind()
6735                                               != TSK_ImplicitInstantiation) {
6736     QualType ParamType = Constructor->getParamDecl(0)->getType();
6737     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6738     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6739       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6740       const char *ConstRef
6741         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6742                                                         : " const &";
6743       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6744         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6745 
6746       // FIXME: Rather that making the constructor invalid, we should endeavor
6747       // to fix the type.
6748       Constructor->setInvalidDecl();
6749     }
6750   }
6751 }
6752 
6753 /// CheckDestructor - Checks a fully-formed destructor definition for
6754 /// well-formedness, issuing any diagnostics required.  Returns true
6755 /// on error.
6756 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6757   CXXRecordDecl *RD = Destructor->getParent();
6758 
6759   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6760     SourceLocation Loc;
6761 
6762     if (!Destructor->isImplicit())
6763       Loc = Destructor->getLocation();
6764     else
6765       Loc = RD->getLocation();
6766 
6767     // If we have a virtual destructor, look up the deallocation function
6768     FunctionDecl *OperatorDelete = nullptr;
6769     DeclarationName Name =
6770     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6771     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6772       return true;
6773     // If there's no class-specific operator delete, look up the global
6774     // non-array delete.
6775     if (!OperatorDelete)
6776       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6777 
6778     MarkFunctionReferenced(Loc, OperatorDelete);
6779 
6780     Destructor->setOperatorDelete(OperatorDelete);
6781   }
6782 
6783   return false;
6784 }
6785 
6786 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6787 /// the well-formednes of the destructor declarator @p D with type @p
6788 /// R. If there are any errors in the declarator, this routine will
6789 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6790 /// will be updated to reflect a well-formed type for the destructor and
6791 /// returned.
6792 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6793                                          StorageClass& SC) {
6794   // C++ [class.dtor]p1:
6795   //   [...] A typedef-name that names a class is a class-name
6796   //   (7.1.3); however, a typedef-name that names a class shall not
6797   //   be used as the identifier in the declarator for a destructor
6798   //   declaration.
6799   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6800   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6801     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6802       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6803   else if (const TemplateSpecializationType *TST =
6804              DeclaratorType->getAs<TemplateSpecializationType>())
6805     if (TST->isTypeAlias())
6806       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6807         << DeclaratorType << 1;
6808 
6809   // C++ [class.dtor]p2:
6810   //   A destructor is used to destroy objects of its class type. A
6811   //   destructor takes no parameters, and no return type can be
6812   //   specified for it (not even void). The address of a destructor
6813   //   shall not be taken. A destructor shall not be static. A
6814   //   destructor can be invoked for a const, volatile or const
6815   //   volatile object. A destructor shall not be declared const,
6816   //   volatile or const volatile (9.3.2).
6817   if (SC == SC_Static) {
6818     if (!D.isInvalidType())
6819       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6820         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6821         << SourceRange(D.getIdentifierLoc())
6822         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6823 
6824     SC = SC_None;
6825   }
6826   if (!D.isInvalidType()) {
6827     // Destructors don't have return types, but the parser will
6828     // happily parse something like:
6829     //
6830     //   class X {
6831     //     float ~X();
6832     //   };
6833     //
6834     // The return type will be eliminated later.
6835     if (D.getDeclSpec().hasTypeSpecifier())
6836       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6837         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6838         << SourceRange(D.getIdentifierLoc());
6839     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6840       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6841                                 SourceLocation(),
6842                                 D.getDeclSpec().getConstSpecLoc(),
6843                                 D.getDeclSpec().getVolatileSpecLoc(),
6844                                 D.getDeclSpec().getRestrictSpecLoc(),
6845                                 D.getDeclSpec().getAtomicSpecLoc());
6846       D.setInvalidType();
6847     }
6848   }
6849 
6850   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6851   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6852     if (FTI.TypeQuals & Qualifiers::Const)
6853       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6854         << "const" << SourceRange(D.getIdentifierLoc());
6855     if (FTI.TypeQuals & Qualifiers::Volatile)
6856       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6857         << "volatile" << SourceRange(D.getIdentifierLoc());
6858     if (FTI.TypeQuals & Qualifiers::Restrict)
6859       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6860         << "restrict" << SourceRange(D.getIdentifierLoc());
6861     D.setInvalidType();
6862   }
6863 
6864   // C++0x [class.dtor]p2:
6865   //   A destructor shall not be declared with a ref-qualifier.
6866   if (FTI.hasRefQualifier()) {
6867     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6868       << FTI.RefQualifierIsLValueRef
6869       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6870     D.setInvalidType();
6871   }
6872 
6873   // Make sure we don't have any parameters.
6874   if (FTIHasNonVoidParameters(FTI)) {
6875     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6876 
6877     // Delete the parameters.
6878     FTI.freeParams();
6879     D.setInvalidType();
6880   }
6881 
6882   // Make sure the destructor isn't variadic.
6883   if (FTI.isVariadic) {
6884     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6885     D.setInvalidType();
6886   }
6887 
6888   // Rebuild the function type "R" without any type qualifiers or
6889   // parameters (in case any of the errors above fired) and with
6890   // "void" as the return type, since destructors don't have return
6891   // types.
6892   if (!D.isInvalidType())
6893     return R;
6894 
6895   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6896   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6897   EPI.Variadic = false;
6898   EPI.TypeQuals = 0;
6899   EPI.RefQualifier = RQ_None;
6900   return Context.getFunctionType(Context.VoidTy, None, EPI);
6901 }
6902 
6903 static void extendLeft(SourceRange &R, const SourceRange &Before) {
6904   if (Before.isInvalid())
6905     return;
6906   R.setBegin(Before.getBegin());
6907   if (R.getEnd().isInvalid())
6908     R.setEnd(Before.getEnd());
6909 }
6910 
6911 static void extendRight(SourceRange &R, const SourceRange &After) {
6912   if (After.isInvalid())
6913     return;
6914   if (R.getBegin().isInvalid())
6915     R.setBegin(After.getBegin());
6916   R.setEnd(After.getEnd());
6917 }
6918 
6919 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6920 /// well-formednes of the conversion function declarator @p D with
6921 /// type @p R. If there are any errors in the declarator, this routine
6922 /// will emit diagnostics and return true. Otherwise, it will return
6923 /// false. Either way, the type @p R will be updated to reflect a
6924 /// well-formed type for the conversion operator.
6925 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6926                                      StorageClass& SC) {
6927   // C++ [class.conv.fct]p1:
6928   //   Neither parameter types nor return type can be specified. The
6929   //   type of a conversion function (8.3.5) is "function taking no
6930   //   parameter returning conversion-type-id."
6931   if (SC == SC_Static) {
6932     if (!D.isInvalidType())
6933       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6934         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6935         << D.getName().getSourceRange();
6936     D.setInvalidType();
6937     SC = SC_None;
6938   }
6939 
6940   TypeSourceInfo *ConvTSI = nullptr;
6941   QualType ConvType =
6942       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
6943 
6944   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6945     // Conversion functions don't have return types, but the parser will
6946     // happily parse something like:
6947     //
6948     //   class X {
6949     //     float operator bool();
6950     //   };
6951     //
6952     // The return type will be changed later anyway.
6953     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6954       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6955       << SourceRange(D.getIdentifierLoc());
6956     D.setInvalidType();
6957   }
6958 
6959   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6960 
6961   // Make sure we don't have any parameters.
6962   if (Proto->getNumParams() > 0) {
6963     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6964 
6965     // Delete the parameters.
6966     D.getFunctionTypeInfo().freeParams();
6967     D.setInvalidType();
6968   } else if (Proto->isVariadic()) {
6969     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6970     D.setInvalidType();
6971   }
6972 
6973   // Diagnose "&operator bool()" and other such nonsense.  This
6974   // is actually a gcc extension which we don't support.
6975   if (Proto->getReturnType() != ConvType) {
6976     bool NeedsTypedef = false;
6977     SourceRange Before, After;
6978 
6979     // Walk the chunks and extract information on them for our diagnostic.
6980     bool PastFunctionChunk = false;
6981     for (auto &Chunk : D.type_objects()) {
6982       switch (Chunk.Kind) {
6983       case DeclaratorChunk::Function:
6984         if (!PastFunctionChunk) {
6985           if (Chunk.Fun.HasTrailingReturnType) {
6986             TypeSourceInfo *TRT = nullptr;
6987             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6988             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6989           }
6990           PastFunctionChunk = true;
6991           break;
6992         }
6993         // Fall through.
6994       case DeclaratorChunk::Array:
6995         NeedsTypedef = true;
6996         extendRight(After, Chunk.getSourceRange());
6997         break;
6998 
6999       case DeclaratorChunk::Pointer:
7000       case DeclaratorChunk::BlockPointer:
7001       case DeclaratorChunk::Reference:
7002       case DeclaratorChunk::MemberPointer:
7003         extendLeft(Before, Chunk.getSourceRange());
7004         break;
7005 
7006       case DeclaratorChunk::Paren:
7007         extendLeft(Before, Chunk.Loc);
7008         extendRight(After, Chunk.EndLoc);
7009         break;
7010       }
7011     }
7012 
7013     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7014                          After.isValid()  ? After.getBegin() :
7015                                             D.getIdentifierLoc();
7016     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7017     DB << Before << After;
7018 
7019     if (!NeedsTypedef) {
7020       DB << /*don't need a typedef*/0;
7021 
7022       // If we can provide a correct fix-it hint, do so.
7023       if (After.isInvalid() && ConvTSI) {
7024         SourceLocation InsertLoc =
7025             PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7026         DB << FixItHint::CreateInsertion(InsertLoc, " ")
7027            << FixItHint::CreateInsertionFromRange(
7028                   InsertLoc, CharSourceRange::getTokenRange(Before))
7029            << FixItHint::CreateRemoval(Before);
7030       }
7031     } else if (!Proto->getReturnType()->isDependentType()) {
7032       DB << /*typedef*/1 << Proto->getReturnType();
7033     } else if (getLangOpts().CPlusPlus11) {
7034       DB << /*alias template*/2 << Proto->getReturnType();
7035     } else {
7036       DB << /*might not be fixable*/3;
7037     }
7038 
7039     // Recover by incorporating the other type chunks into the result type.
7040     // Note, this does *not* change the name of the function. This is compatible
7041     // with the GCC extension:
7042     //   struct S { &operator int(); } s;
7043     //   int &r = s.operator int(); // ok in GCC
7044     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
7045     ConvType = Proto->getReturnType();
7046   }
7047 
7048   // C++ [class.conv.fct]p4:
7049   //   The conversion-type-id shall not represent a function type nor
7050   //   an array type.
7051   if (ConvType->isArrayType()) {
7052     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7053     ConvType = Context.getPointerType(ConvType);
7054     D.setInvalidType();
7055   } else if (ConvType->isFunctionType()) {
7056     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7057     ConvType = Context.getPointerType(ConvType);
7058     D.setInvalidType();
7059   }
7060 
7061   // Rebuild the function type "R" without any parameters (in case any
7062   // of the errors above fired) and with the conversion type as the
7063   // return type.
7064   if (D.isInvalidType())
7065     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7066 
7067   // C++0x explicit conversion operators.
7068   if (D.getDeclSpec().isExplicitSpecified())
7069     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7070          getLangOpts().CPlusPlus11 ?
7071            diag::warn_cxx98_compat_explicit_conversion_functions :
7072            diag::ext_explicit_conversion_functions)
7073       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7074 }
7075 
7076 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7077 /// the declaration of the given C++ conversion function. This routine
7078 /// is responsible for recording the conversion function in the C++
7079 /// class, if possible.
7080 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7081   assert(Conversion && "Expected to receive a conversion function declaration");
7082 
7083   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7084 
7085   // Make sure we aren't redeclaring the conversion function.
7086   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7087 
7088   // C++ [class.conv.fct]p1:
7089   //   [...] A conversion function is never used to convert a
7090   //   (possibly cv-qualified) object to the (possibly cv-qualified)
7091   //   same object type (or a reference to it), to a (possibly
7092   //   cv-qualified) base class of that type (or a reference to it),
7093   //   or to (possibly cv-qualified) void.
7094   // FIXME: Suppress this warning if the conversion function ends up being a
7095   // virtual function that overrides a virtual function in a base class.
7096   QualType ClassType
7097     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7098   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7099     ConvType = ConvTypeRef->getPointeeType();
7100   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7101       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7102     /* Suppress diagnostics for instantiations. */;
7103   else if (ConvType->isRecordType()) {
7104     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7105     if (ConvType == ClassType)
7106       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7107         << ClassType;
7108     else if (IsDerivedFrom(ClassType, ConvType))
7109       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7110         <<  ClassType << ConvType;
7111   } else if (ConvType->isVoidType()) {
7112     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7113       << ClassType << ConvType;
7114   }
7115 
7116   if (FunctionTemplateDecl *ConversionTemplate
7117                                 = Conversion->getDescribedFunctionTemplate())
7118     return ConversionTemplate;
7119 
7120   return Conversion;
7121 }
7122 
7123 //===----------------------------------------------------------------------===//
7124 // Namespace Handling
7125 //===----------------------------------------------------------------------===//
7126 
7127 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7128 /// reopened.
7129 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7130                                             SourceLocation Loc,
7131                                             IdentifierInfo *II, bool *IsInline,
7132                                             NamespaceDecl *PrevNS) {
7133   assert(*IsInline != PrevNS->isInline());
7134 
7135   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7136   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7137   // inline namespaces, with the intention of bringing names into namespace std.
7138   //
7139   // We support this just well enough to get that case working; this is not
7140   // sufficient to support reopening namespaces as inline in general.
7141   if (*IsInline && II && II->getName().startswith("__atomic") &&
7142       S.getSourceManager().isInSystemHeader(Loc)) {
7143     // Mark all prior declarations of the namespace as inline.
7144     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7145          NS = NS->getPreviousDecl())
7146       NS->setInline(*IsInline);
7147     // Patch up the lookup table for the containing namespace. This isn't really
7148     // correct, but it's good enough for this particular case.
7149     for (auto *I : PrevNS->decls())
7150       if (auto *ND = dyn_cast<NamedDecl>(I))
7151         PrevNS->getParent()->makeDeclVisibleInContext(ND);
7152     return;
7153   }
7154 
7155   if (PrevNS->isInline())
7156     // The user probably just forgot the 'inline', so suggest that it
7157     // be added back.
7158     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7159       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7160   else
7161     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7162 
7163   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7164   *IsInline = PrevNS->isInline();
7165 }
7166 
7167 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7168 /// definition.
7169 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7170                                    SourceLocation InlineLoc,
7171                                    SourceLocation NamespaceLoc,
7172                                    SourceLocation IdentLoc,
7173                                    IdentifierInfo *II,
7174                                    SourceLocation LBrace,
7175                                    AttributeList *AttrList) {
7176   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7177   // For anonymous namespace, take the location of the left brace.
7178   SourceLocation Loc = II ? IdentLoc : LBrace;
7179   bool IsInline = InlineLoc.isValid();
7180   bool IsInvalid = false;
7181   bool IsStd = false;
7182   bool AddToKnown = false;
7183   Scope *DeclRegionScope = NamespcScope->getParent();
7184 
7185   NamespaceDecl *PrevNS = nullptr;
7186   if (II) {
7187     // C++ [namespace.def]p2:
7188     //   The identifier in an original-namespace-definition shall not
7189     //   have been previously defined in the declarative region in
7190     //   which the original-namespace-definition appears. The
7191     //   identifier in an original-namespace-definition is the name of
7192     //   the namespace. Subsequently in that declarative region, it is
7193     //   treated as an original-namespace-name.
7194     //
7195     // Since namespace names are unique in their scope, and we don't
7196     // look through using directives, just look for any ordinary names.
7197 
7198     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
7199     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7200     Decl::IDNS_Namespace;
7201     NamedDecl *PrevDecl = nullptr;
7202     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7203     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7204          ++I) {
7205       if ((*I)->getIdentifierNamespace() & IDNS) {
7206         PrevDecl = *I;
7207         break;
7208       }
7209     }
7210 
7211     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7212 
7213     if (PrevNS) {
7214       // This is an extended namespace definition.
7215       if (IsInline != PrevNS->isInline())
7216         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7217                                         &IsInline, PrevNS);
7218     } else if (PrevDecl) {
7219       // This is an invalid name redefinition.
7220       Diag(Loc, diag::err_redefinition_different_kind)
7221         << II;
7222       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7223       IsInvalid = true;
7224       // Continue on to push Namespc as current DeclContext and return it.
7225     } else if (II->isStr("std") &&
7226                CurContext->getRedeclContext()->isTranslationUnit()) {
7227       // This is the first "real" definition of the namespace "std", so update
7228       // our cache of the "std" namespace to point at this definition.
7229       PrevNS = getStdNamespace();
7230       IsStd = true;
7231       AddToKnown = !IsInline;
7232     } else {
7233       // We've seen this namespace for the first time.
7234       AddToKnown = !IsInline;
7235     }
7236   } else {
7237     // Anonymous namespaces.
7238 
7239     // Determine whether the parent already has an anonymous namespace.
7240     DeclContext *Parent = CurContext->getRedeclContext();
7241     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7242       PrevNS = TU->getAnonymousNamespace();
7243     } else {
7244       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7245       PrevNS = ND->getAnonymousNamespace();
7246     }
7247 
7248     if (PrevNS && IsInline != PrevNS->isInline())
7249       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7250                                       &IsInline, PrevNS);
7251   }
7252 
7253   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7254                                                  StartLoc, Loc, II, PrevNS);
7255   if (IsInvalid)
7256     Namespc->setInvalidDecl();
7257 
7258   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7259 
7260   // FIXME: Should we be merging attributes?
7261   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7262     PushNamespaceVisibilityAttr(Attr, Loc);
7263 
7264   if (IsStd)
7265     StdNamespace = Namespc;
7266   if (AddToKnown)
7267     KnownNamespaces[Namespc] = false;
7268 
7269   if (II) {
7270     PushOnScopeChains(Namespc, DeclRegionScope);
7271   } else {
7272     // Link the anonymous namespace into its parent.
7273     DeclContext *Parent = CurContext->getRedeclContext();
7274     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7275       TU->setAnonymousNamespace(Namespc);
7276     } else {
7277       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7278     }
7279 
7280     CurContext->addDecl(Namespc);
7281 
7282     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
7283     //   behaves as if it were replaced by
7284     //     namespace unique { /* empty body */ }
7285     //     using namespace unique;
7286     //     namespace unique { namespace-body }
7287     //   where all occurrences of 'unique' in a translation unit are
7288     //   replaced by the same identifier and this identifier differs
7289     //   from all other identifiers in the entire program.
7290 
7291     // We just create the namespace with an empty name and then add an
7292     // implicit using declaration, just like the standard suggests.
7293     //
7294     // CodeGen enforces the "universally unique" aspect by giving all
7295     // declarations semantically contained within an anonymous
7296     // namespace internal linkage.
7297 
7298     if (!PrevNS) {
7299       UsingDirectiveDecl* UD
7300         = UsingDirectiveDecl::Create(Context, Parent,
7301                                      /* 'using' */ LBrace,
7302                                      /* 'namespace' */ SourceLocation(),
7303                                      /* qualifier */ NestedNameSpecifierLoc(),
7304                                      /* identifier */ SourceLocation(),
7305                                      Namespc,
7306                                      /* Ancestor */ Parent);
7307       UD->setImplicit();
7308       Parent->addDecl(UD);
7309     }
7310   }
7311 
7312   ActOnDocumentableDecl(Namespc);
7313 
7314   // Although we could have an invalid decl (i.e. the namespace name is a
7315   // redefinition), push it as current DeclContext and try to continue parsing.
7316   // FIXME: We should be able to push Namespc here, so that the each DeclContext
7317   // for the namespace has the declarations that showed up in that particular
7318   // namespace definition.
7319   PushDeclContext(NamespcScope, Namespc);
7320   return Namespc;
7321 }
7322 
7323 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7324 /// is a namespace alias, returns the namespace it points to.
7325 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7326   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7327     return AD->getNamespace();
7328   return dyn_cast_or_null<NamespaceDecl>(D);
7329 }
7330 
7331 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7332 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7333 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7334   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7335   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7336   Namespc->setRBraceLoc(RBrace);
7337   PopDeclContext();
7338   if (Namespc->hasAttr<VisibilityAttr>())
7339     PopPragmaVisibility(true, RBrace);
7340 }
7341 
7342 CXXRecordDecl *Sema::getStdBadAlloc() const {
7343   return cast_or_null<CXXRecordDecl>(
7344                                   StdBadAlloc.get(Context.getExternalSource()));
7345 }
7346 
7347 NamespaceDecl *Sema::getStdNamespace() const {
7348   return cast_or_null<NamespaceDecl>(
7349                                  StdNamespace.get(Context.getExternalSource()));
7350 }
7351 
7352 /// \brief Retrieve the special "std" namespace, which may require us to
7353 /// implicitly define the namespace.
7354 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7355   if (!StdNamespace) {
7356     // The "std" namespace has not yet been defined, so build one implicitly.
7357     StdNamespace = NamespaceDecl::Create(Context,
7358                                          Context.getTranslationUnitDecl(),
7359                                          /*Inline=*/false,
7360                                          SourceLocation(), SourceLocation(),
7361                                          &PP.getIdentifierTable().get("std"),
7362                                          /*PrevDecl=*/nullptr);
7363     getStdNamespace()->setImplicit(true);
7364   }
7365 
7366   return getStdNamespace();
7367 }
7368 
7369 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7370   assert(getLangOpts().CPlusPlus &&
7371          "Looking for std::initializer_list outside of C++.");
7372 
7373   // We're looking for implicit instantiations of
7374   // template <typename E> class std::initializer_list.
7375 
7376   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7377     return false;
7378 
7379   ClassTemplateDecl *Template = nullptr;
7380   const TemplateArgument *Arguments = nullptr;
7381 
7382   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7383 
7384     ClassTemplateSpecializationDecl *Specialization =
7385         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7386     if (!Specialization)
7387       return false;
7388 
7389     Template = Specialization->getSpecializedTemplate();
7390     Arguments = Specialization->getTemplateArgs().data();
7391   } else if (const TemplateSpecializationType *TST =
7392                  Ty->getAs<TemplateSpecializationType>()) {
7393     Template = dyn_cast_or_null<ClassTemplateDecl>(
7394         TST->getTemplateName().getAsTemplateDecl());
7395     Arguments = TST->getArgs();
7396   }
7397   if (!Template)
7398     return false;
7399 
7400   if (!StdInitializerList) {
7401     // Haven't recognized std::initializer_list yet, maybe this is it.
7402     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7403     if (TemplateClass->getIdentifier() !=
7404             &PP.getIdentifierTable().get("initializer_list") ||
7405         !getStdNamespace()->InEnclosingNamespaceSetOf(
7406             TemplateClass->getDeclContext()))
7407       return false;
7408     // This is a template called std::initializer_list, but is it the right
7409     // template?
7410     TemplateParameterList *Params = Template->getTemplateParameters();
7411     if (Params->getMinRequiredArguments() != 1)
7412       return false;
7413     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7414       return false;
7415 
7416     // It's the right template.
7417     StdInitializerList = Template;
7418   }
7419 
7420   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
7421     return false;
7422 
7423   // This is an instance of std::initializer_list. Find the argument type.
7424   if (Element)
7425     *Element = Arguments[0].getAsType();
7426   return true;
7427 }
7428 
7429 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7430   NamespaceDecl *Std = S.getStdNamespace();
7431   if (!Std) {
7432     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7433     return nullptr;
7434   }
7435 
7436   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7437                       Loc, Sema::LookupOrdinaryName);
7438   if (!S.LookupQualifiedName(Result, Std)) {
7439     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7440     return nullptr;
7441   }
7442   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7443   if (!Template) {
7444     Result.suppressDiagnostics();
7445     // We found something weird. Complain about the first thing we found.
7446     NamedDecl *Found = *Result.begin();
7447     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7448     return nullptr;
7449   }
7450 
7451   // We found some template called std::initializer_list. Now verify that it's
7452   // correct.
7453   TemplateParameterList *Params = Template->getTemplateParameters();
7454   if (Params->getMinRequiredArguments() != 1 ||
7455       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7456     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7457     return nullptr;
7458   }
7459 
7460   return Template;
7461 }
7462 
7463 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7464   if (!StdInitializerList) {
7465     StdInitializerList = LookupStdInitializerList(*this, Loc);
7466     if (!StdInitializerList)
7467       return QualType();
7468   }
7469 
7470   TemplateArgumentListInfo Args(Loc, Loc);
7471   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7472                                        Context.getTrivialTypeSourceInfo(Element,
7473                                                                         Loc)));
7474   return Context.getCanonicalType(
7475       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7476 }
7477 
7478 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7479   // C++ [dcl.init.list]p2:
7480   //   A constructor is an initializer-list constructor if its first parameter
7481   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7482   //   std::initializer_list<E> for some type E, and either there are no other
7483   //   parameters or else all other parameters have default arguments.
7484   if (Ctor->getNumParams() < 1 ||
7485       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7486     return false;
7487 
7488   QualType ArgType = Ctor->getParamDecl(0)->getType();
7489   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7490     ArgType = RT->getPointeeType().getUnqualifiedType();
7491 
7492   return isStdInitializerList(ArgType, nullptr);
7493 }
7494 
7495 /// \brief Determine whether a using statement is in a context where it will be
7496 /// apply in all contexts.
7497 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7498   switch (CurContext->getDeclKind()) {
7499     case Decl::TranslationUnit:
7500       return true;
7501     case Decl::LinkageSpec:
7502       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7503     default:
7504       return false;
7505   }
7506 }
7507 
7508 namespace {
7509 
7510 // Callback to only accept typo corrections that are namespaces.
7511 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7512 public:
7513   bool ValidateCandidate(const TypoCorrection &candidate) override {
7514     if (NamedDecl *ND = candidate.getCorrectionDecl())
7515       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7516     return false;
7517   }
7518 };
7519 
7520 } // namespace
7521 
7522 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7523                                        CXXScopeSpec &SS,
7524                                        SourceLocation IdentLoc,
7525                                        IdentifierInfo *Ident) {
7526   R.clear();
7527   if (TypoCorrection Corrected =
7528           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7529                         llvm::make_unique<NamespaceValidatorCCC>(),
7530                         Sema::CTK_ErrorRecovery)) {
7531     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7532       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7533       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7534                               Ident->getName().equals(CorrectedStr);
7535       S.diagnoseTypo(Corrected,
7536                      S.PDiag(diag::err_using_directive_member_suggest)
7537                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7538                      S.PDiag(diag::note_namespace_defined_here));
7539     } else {
7540       S.diagnoseTypo(Corrected,
7541                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7542                      S.PDiag(diag::note_namespace_defined_here));
7543     }
7544     R.addDecl(Corrected.getCorrectionDecl());
7545     return true;
7546   }
7547   return false;
7548 }
7549 
7550 Decl *Sema::ActOnUsingDirective(Scope *S,
7551                                           SourceLocation UsingLoc,
7552                                           SourceLocation NamespcLoc,
7553                                           CXXScopeSpec &SS,
7554                                           SourceLocation IdentLoc,
7555                                           IdentifierInfo *NamespcName,
7556                                           AttributeList *AttrList) {
7557   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7558   assert(NamespcName && "Invalid NamespcName.");
7559   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7560 
7561   // This can only happen along a recovery path.
7562   while (S->getFlags() & Scope::TemplateParamScope)
7563     S = S->getParent();
7564   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7565 
7566   UsingDirectiveDecl *UDir = nullptr;
7567   NestedNameSpecifier *Qualifier = nullptr;
7568   if (SS.isSet())
7569     Qualifier = SS.getScopeRep();
7570 
7571   // Lookup namespace name.
7572   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7573   LookupParsedName(R, S, &SS);
7574   if (R.isAmbiguous())
7575     return nullptr;
7576 
7577   if (R.empty()) {
7578     R.clear();
7579     // Allow "using namespace std;" or "using namespace ::std;" even if
7580     // "std" hasn't been defined yet, for GCC compatibility.
7581     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7582         NamespcName->isStr("std")) {
7583       Diag(IdentLoc, diag::ext_using_undefined_std);
7584       R.addDecl(getOrCreateStdNamespace());
7585       R.resolveKind();
7586     }
7587     // Otherwise, attempt typo correction.
7588     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7589   }
7590 
7591   if (!R.empty()) {
7592     NamedDecl *Named = R.getFoundDecl();
7593     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7594         && "expected namespace decl");
7595 
7596     // The use of a nested name specifier may trigger deprecation warnings.
7597     DiagnoseUseOfDecl(Named, IdentLoc);
7598 
7599     // C++ [namespace.udir]p1:
7600     //   A using-directive specifies that the names in the nominated
7601     //   namespace can be used in the scope in which the
7602     //   using-directive appears after the using-directive. During
7603     //   unqualified name lookup (3.4.1), the names appear as if they
7604     //   were declared in the nearest enclosing namespace which
7605     //   contains both the using-directive and the nominated
7606     //   namespace. [Note: in this context, "contains" means "contains
7607     //   directly or indirectly". ]
7608 
7609     // Find enclosing context containing both using-directive and
7610     // nominated namespace.
7611     NamespaceDecl *NS = getNamespaceDecl(Named);
7612     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7613     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7614       CommonAncestor = CommonAncestor->getParent();
7615 
7616     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7617                                       SS.getWithLocInContext(Context),
7618                                       IdentLoc, Named, CommonAncestor);
7619 
7620     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7621         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7622       Diag(IdentLoc, diag::warn_using_directive_in_header);
7623     }
7624 
7625     PushUsingDirective(S, UDir);
7626   } else {
7627     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7628   }
7629 
7630   if (UDir)
7631     ProcessDeclAttributeList(S, UDir, AttrList);
7632 
7633   return UDir;
7634 }
7635 
7636 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7637   // If the scope has an associated entity and the using directive is at
7638   // namespace or translation unit scope, add the UsingDirectiveDecl into
7639   // its lookup structure so qualified name lookup can find it.
7640   DeclContext *Ctx = S->getEntity();
7641   if (Ctx && !Ctx->isFunctionOrMethod())
7642     Ctx->addDecl(UDir);
7643   else
7644     // Otherwise, it is at block scope. The using-directives will affect lookup
7645     // only to the end of the scope.
7646     S->PushUsingDirective(UDir);
7647 }
7648 
7649 
7650 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7651                                   AccessSpecifier AS,
7652                                   bool HasUsingKeyword,
7653                                   SourceLocation UsingLoc,
7654                                   CXXScopeSpec &SS,
7655                                   UnqualifiedId &Name,
7656                                   AttributeList *AttrList,
7657                                   bool HasTypenameKeyword,
7658                                   SourceLocation TypenameLoc) {
7659   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7660 
7661   switch (Name.getKind()) {
7662   case UnqualifiedId::IK_ImplicitSelfParam:
7663   case UnqualifiedId::IK_Identifier:
7664   case UnqualifiedId::IK_OperatorFunctionId:
7665   case UnqualifiedId::IK_LiteralOperatorId:
7666   case UnqualifiedId::IK_ConversionFunctionId:
7667     break;
7668 
7669   case UnqualifiedId::IK_ConstructorName:
7670   case UnqualifiedId::IK_ConstructorTemplateId:
7671     // C++11 inheriting constructors.
7672     Diag(Name.getLocStart(),
7673          getLangOpts().CPlusPlus11 ?
7674            diag::warn_cxx98_compat_using_decl_constructor :
7675            diag::err_using_decl_constructor)
7676       << SS.getRange();
7677 
7678     if (getLangOpts().CPlusPlus11) break;
7679 
7680     return nullptr;
7681 
7682   case UnqualifiedId::IK_DestructorName:
7683     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7684       << SS.getRange();
7685     return nullptr;
7686 
7687   case UnqualifiedId::IK_TemplateId:
7688     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7689       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7690     return nullptr;
7691   }
7692 
7693   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7694   DeclarationName TargetName = TargetNameInfo.getName();
7695   if (!TargetName)
7696     return nullptr;
7697 
7698   // Warn about access declarations.
7699   if (!HasUsingKeyword) {
7700     Diag(Name.getLocStart(),
7701          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7702                                    : diag::warn_access_decl_deprecated)
7703       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7704   }
7705 
7706   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7707       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7708     return nullptr;
7709 
7710   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7711                                         TargetNameInfo, AttrList,
7712                                         /* IsInstantiation */ false,
7713                                         HasTypenameKeyword, TypenameLoc);
7714   if (UD)
7715     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7716 
7717   return UD;
7718 }
7719 
7720 /// \brief Determine whether a using declaration considers the given
7721 /// declarations as "equivalent", e.g., if they are redeclarations of
7722 /// the same entity or are both typedefs of the same type.
7723 static bool
7724 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7725   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7726     return true;
7727 
7728   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7729     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7730       return Context.hasSameType(TD1->getUnderlyingType(),
7731                                  TD2->getUnderlyingType());
7732 
7733   return false;
7734 }
7735 
7736 
7737 /// Determines whether to create a using shadow decl for a particular
7738 /// decl, given the set of decls existing prior to this using lookup.
7739 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7740                                 const LookupResult &Previous,
7741                                 UsingShadowDecl *&PrevShadow) {
7742   // Diagnose finding a decl which is not from a base class of the
7743   // current class.  We do this now because there are cases where this
7744   // function will silently decide not to build a shadow decl, which
7745   // will pre-empt further diagnostics.
7746   //
7747   // We don't need to do this in C++0x because we do the check once on
7748   // the qualifier.
7749   //
7750   // FIXME: diagnose the following if we care enough:
7751   //   struct A { int foo; };
7752   //   struct B : A { using A::foo; };
7753   //   template <class T> struct C : A {};
7754   //   template <class T> struct D : C<T> { using B::foo; } // <---
7755   // This is invalid (during instantiation) in C++03 because B::foo
7756   // resolves to the using decl in B, which is not a base class of D<T>.
7757   // We can't diagnose it immediately because C<T> is an unknown
7758   // specialization.  The UsingShadowDecl in D<T> then points directly
7759   // to A::foo, which will look well-formed when we instantiate.
7760   // The right solution is to not collapse the shadow-decl chain.
7761   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7762     DeclContext *OrigDC = Orig->getDeclContext();
7763 
7764     // Handle enums and anonymous structs.
7765     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7766     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7767     while (OrigRec->isAnonymousStructOrUnion())
7768       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7769 
7770     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7771       if (OrigDC == CurContext) {
7772         Diag(Using->getLocation(),
7773              diag::err_using_decl_nested_name_specifier_is_current_class)
7774           << Using->getQualifierLoc().getSourceRange();
7775         Diag(Orig->getLocation(), diag::note_using_decl_target);
7776         return true;
7777       }
7778 
7779       Diag(Using->getQualifierLoc().getBeginLoc(),
7780            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7781         << Using->getQualifier()
7782         << cast<CXXRecordDecl>(CurContext)
7783         << Using->getQualifierLoc().getSourceRange();
7784       Diag(Orig->getLocation(), diag::note_using_decl_target);
7785       return true;
7786     }
7787   }
7788 
7789   if (Previous.empty()) return false;
7790 
7791   NamedDecl *Target = Orig;
7792   if (isa<UsingShadowDecl>(Target))
7793     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7794 
7795   // If the target happens to be one of the previous declarations, we
7796   // don't have a conflict.
7797   //
7798   // FIXME: but we might be increasing its access, in which case we
7799   // should redeclare it.
7800   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7801   bool FoundEquivalentDecl = false;
7802   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7803          I != E; ++I) {
7804     NamedDecl *D = (*I)->getUnderlyingDecl();
7805     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7806       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7807         PrevShadow = Shadow;
7808       FoundEquivalentDecl = true;
7809     }
7810 
7811     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7812   }
7813 
7814   if (FoundEquivalentDecl)
7815     return false;
7816 
7817   if (FunctionDecl *FD = Target->getAsFunction()) {
7818     NamedDecl *OldDecl = nullptr;
7819     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7820                           /*IsForUsingDecl*/ true)) {
7821     case Ovl_Overload:
7822       return false;
7823 
7824     case Ovl_NonFunction:
7825       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7826       break;
7827 
7828     // We found a decl with the exact signature.
7829     case Ovl_Match:
7830       // If we're in a record, we want to hide the target, so we
7831       // return true (without a diagnostic) to tell the caller not to
7832       // build a shadow decl.
7833       if (CurContext->isRecord())
7834         return true;
7835 
7836       // If we're not in a record, this is an error.
7837       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7838       break;
7839     }
7840 
7841     Diag(Target->getLocation(), diag::note_using_decl_target);
7842     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7843     return true;
7844   }
7845 
7846   // Target is not a function.
7847 
7848   if (isa<TagDecl>(Target)) {
7849     // No conflict between a tag and a non-tag.
7850     if (!Tag) return false;
7851 
7852     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7853     Diag(Target->getLocation(), diag::note_using_decl_target);
7854     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7855     return true;
7856   }
7857 
7858   // No conflict between a tag and a non-tag.
7859   if (!NonTag) return false;
7860 
7861   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7862   Diag(Target->getLocation(), diag::note_using_decl_target);
7863   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7864   return true;
7865 }
7866 
7867 /// Builds a shadow declaration corresponding to a 'using' declaration.
7868 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7869                                             UsingDecl *UD,
7870                                             NamedDecl *Orig,
7871                                             UsingShadowDecl *PrevDecl) {
7872 
7873   // If we resolved to another shadow declaration, just coalesce them.
7874   NamedDecl *Target = Orig;
7875   if (isa<UsingShadowDecl>(Target)) {
7876     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7877     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7878   }
7879 
7880   UsingShadowDecl *Shadow
7881     = UsingShadowDecl::Create(Context, CurContext,
7882                               UD->getLocation(), UD, Target);
7883   UD->addShadowDecl(Shadow);
7884 
7885   Shadow->setAccess(UD->getAccess());
7886   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7887     Shadow->setInvalidDecl();
7888 
7889   Shadow->setPreviousDecl(PrevDecl);
7890 
7891   if (S)
7892     PushOnScopeChains(Shadow, S);
7893   else
7894     CurContext->addDecl(Shadow);
7895 
7896 
7897   return Shadow;
7898 }
7899 
7900 /// Hides a using shadow declaration.  This is required by the current
7901 /// using-decl implementation when a resolvable using declaration in a
7902 /// class is followed by a declaration which would hide or override
7903 /// one or more of the using decl's targets; for example:
7904 ///
7905 ///   struct Base { void foo(int); };
7906 ///   struct Derived : Base {
7907 ///     using Base::foo;
7908 ///     void foo(int);
7909 ///   };
7910 ///
7911 /// The governing language is C++03 [namespace.udecl]p12:
7912 ///
7913 ///   When a using-declaration brings names from a base class into a
7914 ///   derived class scope, member functions in the derived class
7915 ///   override and/or hide member functions with the same name and
7916 ///   parameter types in a base class (rather than conflicting).
7917 ///
7918 /// There are two ways to implement this:
7919 ///   (1) optimistically create shadow decls when they're not hidden
7920 ///       by existing declarations, or
7921 ///   (2) don't create any shadow decls (or at least don't make them
7922 ///       visible) until we've fully parsed/instantiated the class.
7923 /// The problem with (1) is that we might have to retroactively remove
7924 /// a shadow decl, which requires several O(n) operations because the
7925 /// decl structures are (very reasonably) not designed for removal.
7926 /// (2) avoids this but is very fiddly and phase-dependent.
7927 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7928   if (Shadow->getDeclName().getNameKind() ==
7929         DeclarationName::CXXConversionFunctionName)
7930     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7931 
7932   // Remove it from the DeclContext...
7933   Shadow->getDeclContext()->removeDecl(Shadow);
7934 
7935   // ...and the scope, if applicable...
7936   if (S) {
7937     S->RemoveDecl(Shadow);
7938     IdResolver.RemoveDecl(Shadow);
7939   }
7940 
7941   // ...and the using decl.
7942   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7943 
7944   // TODO: complain somehow if Shadow was used.  It shouldn't
7945   // be possible for this to happen, because...?
7946 }
7947 
7948 /// Find the base specifier for a base class with the given type.
7949 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7950                                                 QualType DesiredBase,
7951                                                 bool &AnyDependentBases) {
7952   // Check whether the named type is a direct base class.
7953   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7954   for (auto &Base : Derived->bases()) {
7955     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7956     if (CanonicalDesiredBase == BaseType)
7957       return &Base;
7958     if (BaseType->isDependentType())
7959       AnyDependentBases = true;
7960   }
7961   return nullptr;
7962 }
7963 
7964 namespace {
7965 class UsingValidatorCCC : public CorrectionCandidateCallback {
7966 public:
7967   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7968                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7969       : HasTypenameKeyword(HasTypenameKeyword),
7970         IsInstantiation(IsInstantiation), OldNNS(NNS),
7971         RequireMemberOf(RequireMemberOf) {}
7972 
7973   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7974     NamedDecl *ND = Candidate.getCorrectionDecl();
7975 
7976     // Keywords are not valid here.
7977     if (!ND || isa<NamespaceDecl>(ND))
7978       return false;
7979 
7980     // Completely unqualified names are invalid for a 'using' declaration.
7981     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7982       return false;
7983 
7984     if (RequireMemberOf) {
7985       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7986       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7987         // No-one ever wants a using-declaration to name an injected-class-name
7988         // of a base class, unless they're declaring an inheriting constructor.
7989         ASTContext &Ctx = ND->getASTContext();
7990         if (!Ctx.getLangOpts().CPlusPlus11)
7991           return false;
7992         QualType FoundType = Ctx.getRecordType(FoundRecord);
7993 
7994         // Check that the injected-class-name is named as a member of its own
7995         // type; we don't want to suggest 'using Derived::Base;', since that
7996         // means something else.
7997         NestedNameSpecifier *Specifier =
7998             Candidate.WillReplaceSpecifier()
7999                 ? Candidate.getCorrectionSpecifier()
8000                 : OldNNS;
8001         if (!Specifier->getAsType() ||
8002             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8003           return false;
8004 
8005         // Check that this inheriting constructor declaration actually names a
8006         // direct base class of the current class.
8007         bool AnyDependentBases = false;
8008         if (!findDirectBaseWithType(RequireMemberOf,
8009                                     Ctx.getRecordType(FoundRecord),
8010                                     AnyDependentBases) &&
8011             !AnyDependentBases)
8012           return false;
8013       } else {
8014         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8015         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8016           return false;
8017 
8018         // FIXME: Check that the base class member is accessible?
8019       }
8020     }
8021 
8022     if (isa<TypeDecl>(ND))
8023       return HasTypenameKeyword || !IsInstantiation;
8024 
8025     return !HasTypenameKeyword;
8026   }
8027 
8028 private:
8029   bool HasTypenameKeyword;
8030   bool IsInstantiation;
8031   NestedNameSpecifier *OldNNS;
8032   CXXRecordDecl *RequireMemberOf;
8033 };
8034 } // end anonymous namespace
8035 
8036 /// Builds a using declaration.
8037 ///
8038 /// \param IsInstantiation - Whether this call arises from an
8039 ///   instantiation of an unresolved using declaration.  We treat
8040 ///   the lookup differently for these declarations.
8041 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8042                                        SourceLocation UsingLoc,
8043                                        CXXScopeSpec &SS,
8044                                        DeclarationNameInfo NameInfo,
8045                                        AttributeList *AttrList,
8046                                        bool IsInstantiation,
8047                                        bool HasTypenameKeyword,
8048                                        SourceLocation TypenameLoc) {
8049   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8050   SourceLocation IdentLoc = NameInfo.getLoc();
8051   assert(IdentLoc.isValid() && "Invalid TargetName location.");
8052 
8053   // FIXME: We ignore attributes for now.
8054 
8055   if (SS.isEmpty()) {
8056     Diag(IdentLoc, diag::err_using_requires_qualname);
8057     return nullptr;
8058   }
8059 
8060   // Do the redeclaration lookup in the current scope.
8061   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
8062                         ForRedeclaration);
8063   Previous.setHideTags(false);
8064   if (S) {
8065     LookupName(Previous, S);
8066 
8067     // It is really dumb that we have to do this.
8068     LookupResult::Filter F = Previous.makeFilter();
8069     while (F.hasNext()) {
8070       NamedDecl *D = F.next();
8071       if (!isDeclInScope(D, CurContext, S))
8072         F.erase();
8073       // If we found a local extern declaration that's not ordinarily visible,
8074       // and this declaration is being added to a non-block scope, ignore it.
8075       // We're only checking for scope conflicts here, not also for violations
8076       // of the linkage rules.
8077       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8078                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8079         F.erase();
8080     }
8081     F.done();
8082   } else {
8083     assert(IsInstantiation && "no scope in non-instantiation");
8084     assert(CurContext->isRecord() && "scope not record in instantiation");
8085     LookupQualifiedName(Previous, CurContext);
8086   }
8087 
8088   // Check for invalid redeclarations.
8089   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8090                                   SS, IdentLoc, Previous))
8091     return nullptr;
8092 
8093   // Check for bad qualifiers.
8094   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8095     return nullptr;
8096 
8097   DeclContext *LookupContext = computeDeclContext(SS);
8098   NamedDecl *D;
8099   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8100   if (!LookupContext) {
8101     if (HasTypenameKeyword) {
8102       // FIXME: not all declaration name kinds are legal here
8103       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8104                                               UsingLoc, TypenameLoc,
8105                                               QualifierLoc,
8106                                               IdentLoc, NameInfo.getName());
8107     } else {
8108       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8109                                            QualifierLoc, NameInfo);
8110     }
8111     D->setAccess(AS);
8112     CurContext->addDecl(D);
8113     return D;
8114   }
8115 
8116   auto Build = [&](bool Invalid) {
8117     UsingDecl *UD =
8118         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8119                           HasTypenameKeyword);
8120     UD->setAccess(AS);
8121     CurContext->addDecl(UD);
8122     UD->setInvalidDecl(Invalid);
8123     return UD;
8124   };
8125   auto BuildInvalid = [&]{ return Build(true); };
8126   auto BuildValid = [&]{ return Build(false); };
8127 
8128   if (RequireCompleteDeclContext(SS, LookupContext))
8129     return BuildInvalid();
8130 
8131   // Look up the target name.
8132   LookupResult R(*this, NameInfo, LookupOrdinaryName);
8133 
8134   // Unlike most lookups, we don't always want to hide tag
8135   // declarations: tag names are visible through the using declaration
8136   // even if hidden by ordinary names, *except* in a dependent context
8137   // where it's important for the sanity of two-phase lookup.
8138   if (!IsInstantiation)
8139     R.setHideTags(false);
8140 
8141   // For the purposes of this lookup, we have a base object type
8142   // equal to that of the current context.
8143   if (CurContext->isRecord()) {
8144     R.setBaseObjectType(
8145                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8146   }
8147 
8148   LookupQualifiedName(R, LookupContext);
8149 
8150   // Try to correct typos if possible. If constructor name lookup finds no
8151   // results, that means the named class has no explicit constructors, and we
8152   // suppressed declaring implicit ones (probably because it's dependent or
8153   // invalid).
8154   if (R.empty() &&
8155       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
8156     if (TypoCorrection Corrected = CorrectTypo(
8157             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8158             llvm::make_unique<UsingValidatorCCC>(
8159                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8160                 dyn_cast<CXXRecordDecl>(CurContext)),
8161             CTK_ErrorRecovery)) {
8162       // We reject any correction for which ND would be NULL.
8163       NamedDecl *ND = Corrected.getCorrectionDecl();
8164 
8165       // We reject candidates where DroppedSpecifier == true, hence the
8166       // literal '0' below.
8167       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8168                                 << NameInfo.getName() << LookupContext << 0
8169                                 << SS.getRange());
8170 
8171       // If we corrected to an inheriting constructor, handle it as one.
8172       auto *RD = dyn_cast<CXXRecordDecl>(ND);
8173       if (RD && RD->isInjectedClassName()) {
8174         // Fix up the information we'll use to build the using declaration.
8175         if (Corrected.WillReplaceSpecifier()) {
8176           NestedNameSpecifierLocBuilder Builder;
8177           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8178                               QualifierLoc.getSourceRange());
8179           QualifierLoc = Builder.getWithLocInContext(Context);
8180         }
8181 
8182         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8183             Context.getCanonicalType(Context.getRecordType(RD))));
8184         NameInfo.setNamedTypeInfo(nullptr);
8185         for (auto *Ctor : LookupConstructors(RD))
8186           R.addDecl(Ctor);
8187       } else {
8188         // FIXME: Pick up all the declarations if we found an overloaded function.
8189         R.addDecl(ND);
8190       }
8191     } else {
8192       Diag(IdentLoc, diag::err_no_member)
8193         << NameInfo.getName() << LookupContext << SS.getRange();
8194       return BuildInvalid();
8195     }
8196   }
8197 
8198   if (R.isAmbiguous())
8199     return BuildInvalid();
8200 
8201   if (HasTypenameKeyword) {
8202     // If we asked for a typename and got a non-type decl, error out.
8203     if (!R.getAsSingle<TypeDecl>()) {
8204       Diag(IdentLoc, diag::err_using_typename_non_type);
8205       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8206         Diag((*I)->getUnderlyingDecl()->getLocation(),
8207              diag::note_using_decl_target);
8208       return BuildInvalid();
8209     }
8210   } else {
8211     // If we asked for a non-typename and we got a type, error out,
8212     // but only if this is an instantiation of an unresolved using
8213     // decl.  Otherwise just silently find the type name.
8214     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8215       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8216       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8217       return BuildInvalid();
8218     }
8219   }
8220 
8221   // C++0x N2914 [namespace.udecl]p6:
8222   // A using-declaration shall not name a namespace.
8223   if (R.getAsSingle<NamespaceDecl>()) {
8224     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8225       << SS.getRange();
8226     return BuildInvalid();
8227   }
8228 
8229   UsingDecl *UD = BuildValid();
8230 
8231   // The normal rules do not apply to inheriting constructor declarations.
8232   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8233     // Suppress access diagnostics; the access check is instead performed at the
8234     // point of use for an inheriting constructor.
8235     R.suppressDiagnostics();
8236     CheckInheritingConstructorUsingDecl(UD);
8237     return UD;
8238   }
8239 
8240   // Otherwise, look up the target name.
8241 
8242   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8243     UsingShadowDecl *PrevDecl = nullptr;
8244     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8245       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8246   }
8247 
8248   return UD;
8249 }
8250 
8251 /// Additional checks for a using declaration referring to a constructor name.
8252 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8253   assert(!UD->hasTypename() && "expecting a constructor name");
8254 
8255   const Type *SourceType = UD->getQualifier()->getAsType();
8256   assert(SourceType &&
8257          "Using decl naming constructor doesn't have type in scope spec.");
8258   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8259 
8260   // Check whether the named type is a direct base class.
8261   bool AnyDependentBases = false;
8262   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8263                                       AnyDependentBases);
8264   if (!Base && !AnyDependentBases) {
8265     Diag(UD->getUsingLoc(),
8266          diag::err_using_decl_constructor_not_in_direct_base)
8267       << UD->getNameInfo().getSourceRange()
8268       << QualType(SourceType, 0) << TargetClass;
8269     UD->setInvalidDecl();
8270     return true;
8271   }
8272 
8273   if (Base)
8274     Base->setInheritConstructors();
8275 
8276   return false;
8277 }
8278 
8279 /// Checks that the given using declaration is not an invalid
8280 /// redeclaration.  Note that this is checking only for the using decl
8281 /// itself, not for any ill-formedness among the UsingShadowDecls.
8282 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8283                                        bool HasTypenameKeyword,
8284                                        const CXXScopeSpec &SS,
8285                                        SourceLocation NameLoc,
8286                                        const LookupResult &Prev) {
8287   // C++03 [namespace.udecl]p8:
8288   // C++0x [namespace.udecl]p10:
8289   //   A using-declaration is a declaration and can therefore be used
8290   //   repeatedly where (and only where) multiple declarations are
8291   //   allowed.
8292   //
8293   // That's in non-member contexts.
8294   if (!CurContext->getRedeclContext()->isRecord())
8295     return false;
8296 
8297   NestedNameSpecifier *Qual = SS.getScopeRep();
8298 
8299   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8300     NamedDecl *D = *I;
8301 
8302     bool DTypename;
8303     NestedNameSpecifier *DQual;
8304     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8305       DTypename = UD->hasTypename();
8306       DQual = UD->getQualifier();
8307     } else if (UnresolvedUsingValueDecl *UD
8308                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8309       DTypename = false;
8310       DQual = UD->getQualifier();
8311     } else if (UnresolvedUsingTypenameDecl *UD
8312                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8313       DTypename = true;
8314       DQual = UD->getQualifier();
8315     } else continue;
8316 
8317     // using decls differ if one says 'typename' and the other doesn't.
8318     // FIXME: non-dependent using decls?
8319     if (HasTypenameKeyword != DTypename) continue;
8320 
8321     // using decls differ if they name different scopes (but note that
8322     // template instantiation can cause this check to trigger when it
8323     // didn't before instantiation).
8324     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8325         Context.getCanonicalNestedNameSpecifier(DQual))
8326       continue;
8327 
8328     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8329     Diag(D->getLocation(), diag::note_using_decl) << 1;
8330     return true;
8331   }
8332 
8333   return false;
8334 }
8335 
8336 
8337 /// Checks that the given nested-name qualifier used in a using decl
8338 /// in the current context is appropriately related to the current
8339 /// scope.  If an error is found, diagnoses it and returns true.
8340 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8341                                    const CXXScopeSpec &SS,
8342                                    const DeclarationNameInfo &NameInfo,
8343                                    SourceLocation NameLoc) {
8344   DeclContext *NamedContext = computeDeclContext(SS);
8345 
8346   if (!CurContext->isRecord()) {
8347     // C++03 [namespace.udecl]p3:
8348     // C++0x [namespace.udecl]p8:
8349     //   A using-declaration for a class member shall be a member-declaration.
8350 
8351     // If we weren't able to compute a valid scope, it must be a
8352     // dependent class scope.
8353     if (!NamedContext || NamedContext->isRecord()) {
8354       auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
8355       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8356         RD = nullptr;
8357 
8358       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8359         << SS.getRange();
8360 
8361       // If we have a complete, non-dependent source type, try to suggest a
8362       // way to get the same effect.
8363       if (!RD)
8364         return true;
8365 
8366       // Find what this using-declaration was referring to.
8367       LookupResult R(*this, NameInfo, LookupOrdinaryName);
8368       R.setHideTags(false);
8369       R.suppressDiagnostics();
8370       LookupQualifiedName(R, RD);
8371 
8372       if (R.getAsSingle<TypeDecl>()) {
8373         if (getLangOpts().CPlusPlus11) {
8374           // Convert 'using X::Y;' to 'using Y = X::Y;'.
8375           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8376             << 0 // alias declaration
8377             << FixItHint::CreateInsertion(SS.getBeginLoc(),
8378                                           NameInfo.getName().getAsString() +
8379                                               " = ");
8380         } else {
8381           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8382           SourceLocation InsertLoc =
8383               PP.getLocForEndOfToken(NameInfo.getLocEnd());
8384           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8385             << 1 // typedef declaration
8386             << FixItHint::CreateReplacement(UsingLoc, "typedef")
8387             << FixItHint::CreateInsertion(
8388                    InsertLoc, " " + NameInfo.getName().getAsString());
8389         }
8390       } else if (R.getAsSingle<VarDecl>()) {
8391         // Don't provide a fixit outside C++11 mode; we don't want to suggest
8392         // repeating the type of the static data member here.
8393         FixItHint FixIt;
8394         if (getLangOpts().CPlusPlus11) {
8395           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8396           FixIt = FixItHint::CreateReplacement(
8397               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8398         }
8399 
8400         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8401           << 2 // reference declaration
8402           << FixIt;
8403       }
8404       return true;
8405     }
8406 
8407     // Otherwise, everything is known to be fine.
8408     return false;
8409   }
8410 
8411   // The current scope is a record.
8412 
8413   // If the named context is dependent, we can't decide much.
8414   if (!NamedContext) {
8415     // FIXME: in C++0x, we can diagnose if we can prove that the
8416     // nested-name-specifier does not refer to a base class, which is
8417     // still possible in some cases.
8418 
8419     // Otherwise we have to conservatively report that things might be
8420     // okay.
8421     return false;
8422   }
8423 
8424   if (!NamedContext->isRecord()) {
8425     // Ideally this would point at the last name in the specifier,
8426     // but we don't have that level of source info.
8427     Diag(SS.getRange().getBegin(),
8428          diag::err_using_decl_nested_name_specifier_is_not_class)
8429       << SS.getScopeRep() << SS.getRange();
8430     return true;
8431   }
8432 
8433   if (!NamedContext->isDependentContext() &&
8434       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8435     return true;
8436 
8437   if (getLangOpts().CPlusPlus11) {
8438     // C++0x [namespace.udecl]p3:
8439     //   In a using-declaration used as a member-declaration, the
8440     //   nested-name-specifier shall name a base class of the class
8441     //   being defined.
8442 
8443     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8444                                  cast<CXXRecordDecl>(NamedContext))) {
8445       if (CurContext == NamedContext) {
8446         Diag(NameLoc,
8447              diag::err_using_decl_nested_name_specifier_is_current_class)
8448           << SS.getRange();
8449         return true;
8450       }
8451 
8452       Diag(SS.getRange().getBegin(),
8453            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8454         << SS.getScopeRep()
8455         << cast<CXXRecordDecl>(CurContext)
8456         << SS.getRange();
8457       return true;
8458     }
8459 
8460     return false;
8461   }
8462 
8463   // C++03 [namespace.udecl]p4:
8464   //   A using-declaration used as a member-declaration shall refer
8465   //   to a member of a base class of the class being defined [etc.].
8466 
8467   // Salient point: SS doesn't have to name a base class as long as
8468   // lookup only finds members from base classes.  Therefore we can
8469   // diagnose here only if we can prove that that can't happen,
8470   // i.e. if the class hierarchies provably don't intersect.
8471 
8472   // TODO: it would be nice if "definitely valid" results were cached
8473   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8474   // need to be repeated.
8475 
8476   struct UserData {
8477     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8478 
8479     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8480       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8481       Data->Bases.insert(Base);
8482       return true;
8483     }
8484 
8485     bool hasDependentBases(const CXXRecordDecl *Class) {
8486       return !Class->forallBases(collect, this);
8487     }
8488 
8489     /// Returns true if the base is dependent or is one of the
8490     /// accumulated base classes.
8491     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8492       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8493       return !Data->Bases.count(Base);
8494     }
8495 
8496     bool mightShareBases(const CXXRecordDecl *Class) {
8497       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8498     }
8499   };
8500 
8501   UserData Data;
8502 
8503   // Returns false if we find a dependent base.
8504   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8505     return false;
8506 
8507   // Returns false if the class has a dependent base or if it or one
8508   // of its bases is present in the base set of the current context.
8509   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8510     return false;
8511 
8512   Diag(SS.getRange().getBegin(),
8513        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8514     << SS.getScopeRep()
8515     << cast<CXXRecordDecl>(CurContext)
8516     << SS.getRange();
8517 
8518   return true;
8519 }
8520 
8521 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8522                                   AccessSpecifier AS,
8523                                   MultiTemplateParamsArg TemplateParamLists,
8524                                   SourceLocation UsingLoc,
8525                                   UnqualifiedId &Name,
8526                                   AttributeList *AttrList,
8527                                   TypeResult Type,
8528                                   Decl *DeclFromDeclSpec) {
8529   // Skip up to the relevant declaration scope.
8530   while (S->getFlags() & Scope::TemplateParamScope)
8531     S = S->getParent();
8532   assert((S->getFlags() & Scope::DeclScope) &&
8533          "got alias-declaration outside of declaration scope");
8534 
8535   if (Type.isInvalid())
8536     return nullptr;
8537 
8538   bool Invalid = false;
8539   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8540   TypeSourceInfo *TInfo = nullptr;
8541   GetTypeFromParser(Type.get(), &TInfo);
8542 
8543   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8544     return nullptr;
8545 
8546   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8547                                       UPPC_DeclarationType)) {
8548     Invalid = true;
8549     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8550                                              TInfo->getTypeLoc().getBeginLoc());
8551   }
8552 
8553   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8554   LookupName(Previous, S);
8555 
8556   // Warn about shadowing the name of a template parameter.
8557   if (Previous.isSingleResult() &&
8558       Previous.getFoundDecl()->isTemplateParameter()) {
8559     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8560     Previous.clear();
8561   }
8562 
8563   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8564          "name in alias declaration must be an identifier");
8565   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8566                                                Name.StartLocation,
8567                                                Name.Identifier, TInfo);
8568 
8569   NewTD->setAccess(AS);
8570 
8571   if (Invalid)
8572     NewTD->setInvalidDecl();
8573 
8574   ProcessDeclAttributeList(S, NewTD, AttrList);
8575 
8576   CheckTypedefForVariablyModifiedType(S, NewTD);
8577   Invalid |= NewTD->isInvalidDecl();
8578 
8579   bool Redeclaration = false;
8580 
8581   NamedDecl *NewND;
8582   if (TemplateParamLists.size()) {
8583     TypeAliasTemplateDecl *OldDecl = nullptr;
8584     TemplateParameterList *OldTemplateParams = nullptr;
8585 
8586     if (TemplateParamLists.size() != 1) {
8587       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8588         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8589          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8590     }
8591     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8592 
8593     // Only consider previous declarations in the same scope.
8594     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8595                          /*ExplicitInstantiationOrSpecialization*/false);
8596     if (!Previous.empty()) {
8597       Redeclaration = true;
8598 
8599       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8600       if (!OldDecl && !Invalid) {
8601         Diag(UsingLoc, diag::err_redefinition_different_kind)
8602           << Name.Identifier;
8603 
8604         NamedDecl *OldD = Previous.getRepresentativeDecl();
8605         if (OldD->getLocation().isValid())
8606           Diag(OldD->getLocation(), diag::note_previous_definition);
8607 
8608         Invalid = true;
8609       }
8610 
8611       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8612         if (TemplateParameterListsAreEqual(TemplateParams,
8613                                            OldDecl->getTemplateParameters(),
8614                                            /*Complain=*/true,
8615                                            TPL_TemplateMatch))
8616           OldTemplateParams = OldDecl->getTemplateParameters();
8617         else
8618           Invalid = true;
8619 
8620         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8621         if (!Invalid &&
8622             !Context.hasSameType(OldTD->getUnderlyingType(),
8623                                  NewTD->getUnderlyingType())) {
8624           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8625           // but we can't reasonably accept it.
8626           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8627             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8628           if (OldTD->getLocation().isValid())
8629             Diag(OldTD->getLocation(), diag::note_previous_definition);
8630           Invalid = true;
8631         }
8632       }
8633     }
8634 
8635     // Merge any previous default template arguments into our parameters,
8636     // and check the parameter list.
8637     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8638                                    TPC_TypeAliasTemplate))
8639       return nullptr;
8640 
8641     TypeAliasTemplateDecl *NewDecl =
8642       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8643                                     Name.Identifier, TemplateParams,
8644                                     NewTD);
8645     NewTD->setDescribedAliasTemplate(NewDecl);
8646 
8647     NewDecl->setAccess(AS);
8648 
8649     if (Invalid)
8650       NewDecl->setInvalidDecl();
8651     else if (OldDecl)
8652       NewDecl->setPreviousDecl(OldDecl);
8653 
8654     NewND = NewDecl;
8655   } else {
8656     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8657       setTagNameForLinkagePurposes(TD, NewTD);
8658       handleTagNumbering(TD, S);
8659     }
8660     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8661     NewND = NewTD;
8662   }
8663 
8664   if (!Redeclaration)
8665     PushOnScopeChains(NewND, S);
8666 
8667   ActOnDocumentableDecl(NewND);
8668   return NewND;
8669 }
8670 
8671 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8672                                    SourceLocation AliasLoc,
8673                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
8674                                    SourceLocation IdentLoc,
8675                                    IdentifierInfo *Ident) {
8676 
8677   // Lookup the namespace name.
8678   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8679   LookupParsedName(R, S, &SS);
8680 
8681   if (R.isAmbiguous())
8682     return nullptr;
8683 
8684   if (R.empty()) {
8685     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8686       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8687       return nullptr;
8688     }
8689   }
8690   assert(!R.isAmbiguous() && !R.empty());
8691 
8692   // Check if we have a previous declaration with the same name.
8693   NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8694                                          ForRedeclaration);
8695   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8696     PrevDecl = nullptr;
8697 
8698   NamedDecl *ND = R.getFoundDecl();
8699 
8700   if (PrevDecl) {
8701     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8702       // We already have an alias with the same name that points to the same
8703       // namespace; check that it matches.
8704       if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8705         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8706           << Alias;
8707         Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8708           << AD->getNamespace();
8709         return nullptr;
8710       }
8711     } else {
8712       unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8713                             ? diag::err_redefinition
8714                             : diag::err_redefinition_different_kind;
8715       Diag(AliasLoc, DiagID) << Alias;
8716       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8717       return nullptr;
8718     }
8719   }
8720 
8721   // The use of a nested name specifier may trigger deprecation warnings.
8722   DiagnoseUseOfDecl(ND, IdentLoc);
8723 
8724   NamespaceAliasDecl *AliasDecl =
8725     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8726                                Alias, SS.getWithLocInContext(Context),
8727                                IdentLoc, ND);
8728   if (PrevDecl)
8729     AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
8730 
8731   PushOnScopeChains(AliasDecl, S);
8732   return AliasDecl;
8733 }
8734 
8735 Sema::ImplicitExceptionSpecification
8736 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8737                                                CXXMethodDecl *MD) {
8738   CXXRecordDecl *ClassDecl = MD->getParent();
8739 
8740   // C++ [except.spec]p14:
8741   //   An implicitly declared special member function (Clause 12) shall have an
8742   //   exception-specification. [...]
8743   ImplicitExceptionSpecification ExceptSpec(*this);
8744   if (ClassDecl->isInvalidDecl())
8745     return ExceptSpec;
8746 
8747   // Direct base-class constructors.
8748   for (const auto &B : ClassDecl->bases()) {
8749     if (B.isVirtual()) // Handled below.
8750       continue;
8751 
8752     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8753       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8754       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8755       // If this is a deleted function, add it anyway. This might be conformant
8756       // with the standard. This might not. I'm not sure. It might not matter.
8757       if (Constructor)
8758         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8759     }
8760   }
8761 
8762   // Virtual base-class constructors.
8763   for (const auto &B : ClassDecl->vbases()) {
8764     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8765       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8766       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8767       // If this is a deleted function, add it anyway. This might be conformant
8768       // with the standard. This might not. I'm not sure. It might not matter.
8769       if (Constructor)
8770         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8771     }
8772   }
8773 
8774   // Field constructors.
8775   for (const auto *F : ClassDecl->fields()) {
8776     if (F->hasInClassInitializer()) {
8777       if (Expr *E = F->getInClassInitializer())
8778         ExceptSpec.CalledExpr(E);
8779     } else if (const RecordType *RecordTy
8780               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8781       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8782       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8783       // If this is a deleted function, add it anyway. This might be conformant
8784       // with the standard. This might not. I'm not sure. It might not matter.
8785       // In particular, the problem is that this function never gets called. It
8786       // might just be ill-formed because this function attempts to refer to
8787       // a deleted function here.
8788       if (Constructor)
8789         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8790     }
8791   }
8792 
8793   return ExceptSpec;
8794 }
8795 
8796 Sema::ImplicitExceptionSpecification
8797 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8798   CXXRecordDecl *ClassDecl = CD->getParent();
8799 
8800   // C++ [except.spec]p14:
8801   //   An inheriting constructor [...] shall have an exception-specification. [...]
8802   ImplicitExceptionSpecification ExceptSpec(*this);
8803   if (ClassDecl->isInvalidDecl())
8804     return ExceptSpec;
8805 
8806   // Inherited constructor.
8807   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8808   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8809   // FIXME: Copying or moving the parameters could add extra exceptions to the
8810   // set, as could the default arguments for the inherited constructor. This
8811   // will be addressed when we implement the resolution of core issue 1351.
8812   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8813 
8814   // Direct base-class constructors.
8815   for (const auto &B : ClassDecl->bases()) {
8816     if (B.isVirtual()) // Handled below.
8817       continue;
8818 
8819     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8820       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8821       if (BaseClassDecl == InheritedDecl)
8822         continue;
8823       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8824       if (Constructor)
8825         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8826     }
8827   }
8828 
8829   // Virtual base-class constructors.
8830   for (const auto &B : ClassDecl->vbases()) {
8831     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8832       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8833       if (BaseClassDecl == InheritedDecl)
8834         continue;
8835       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8836       if (Constructor)
8837         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8838     }
8839   }
8840 
8841   // Field constructors.
8842   for (const auto *F : ClassDecl->fields()) {
8843     if (F->hasInClassInitializer()) {
8844       if (Expr *E = F->getInClassInitializer())
8845         ExceptSpec.CalledExpr(E);
8846     } else if (const RecordType *RecordTy
8847               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8848       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8849       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8850       if (Constructor)
8851         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8852     }
8853   }
8854 
8855   return ExceptSpec;
8856 }
8857 
8858 namespace {
8859 /// RAII object to register a special member as being currently declared.
8860 struct DeclaringSpecialMember {
8861   Sema &S;
8862   Sema::SpecialMemberDecl D;
8863   bool WasAlreadyBeingDeclared;
8864 
8865   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8866     : S(S), D(RD, CSM) {
8867     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
8868     if (WasAlreadyBeingDeclared)
8869       // This almost never happens, but if it does, ensure that our cache
8870       // doesn't contain a stale result.
8871       S.SpecialMemberCache.clear();
8872 
8873     // FIXME: Register a note to be produced if we encounter an error while
8874     // declaring the special member.
8875   }
8876   ~DeclaringSpecialMember() {
8877     if (!WasAlreadyBeingDeclared)
8878       S.SpecialMembersBeingDeclared.erase(D);
8879   }
8880 
8881   /// \brief Are we already trying to declare this special member?
8882   bool isAlreadyBeingDeclared() const {
8883     return WasAlreadyBeingDeclared;
8884   }
8885 };
8886 } // namespace
8887 
8888 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8889                                                      CXXRecordDecl *ClassDecl) {
8890   // C++ [class.ctor]p5:
8891   //   A default constructor for a class X is a constructor of class X
8892   //   that can be called without an argument. If there is no
8893   //   user-declared constructor for class X, a default constructor is
8894   //   implicitly declared. An implicitly-declared default constructor
8895   //   is an inline public member of its class.
8896   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8897          "Should not build implicit default constructor!");
8898 
8899   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8900   if (DSM.isAlreadyBeingDeclared())
8901     return nullptr;
8902 
8903   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8904                                                      CXXDefaultConstructor,
8905                                                      false);
8906 
8907   // Create the actual constructor declaration.
8908   CanQualType ClassType
8909     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8910   SourceLocation ClassLoc = ClassDecl->getLocation();
8911   DeclarationName Name
8912     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8913   DeclarationNameInfo NameInfo(Name, ClassLoc);
8914   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8915       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8916       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8917       /*isImplicitlyDeclared=*/true, Constexpr);
8918   DefaultCon->setAccess(AS_public);
8919   DefaultCon->setDefaulted();
8920 
8921   if (getLangOpts().CUDA) {
8922     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8923                                             DefaultCon,
8924                                             /* ConstRHS */ false,
8925                                             /* Diagnose */ false);
8926   }
8927 
8928   // Build an exception specification pointing back at this constructor.
8929   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8930   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8931 
8932   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8933   // constructors is easy to compute.
8934   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8935 
8936   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8937     SetDeclDeleted(DefaultCon, ClassLoc);
8938 
8939   // Note that we have declared this constructor.
8940   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8941 
8942   if (Scope *S = getScopeForContext(ClassDecl))
8943     PushOnScopeChains(DefaultCon, S, false);
8944   ClassDecl->addDecl(DefaultCon);
8945 
8946   return DefaultCon;
8947 }
8948 
8949 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8950                                             CXXConstructorDecl *Constructor) {
8951   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8952           !Constructor->doesThisDeclarationHaveABody() &&
8953           !Constructor->isDeleted()) &&
8954     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8955 
8956   CXXRecordDecl *ClassDecl = Constructor->getParent();
8957   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8958 
8959   SynthesizedFunctionScope Scope(*this, Constructor);
8960   DiagnosticErrorTrap Trap(Diags);
8961   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8962       Trap.hasErrorOccurred()) {
8963     Diag(CurrentLocation, diag::note_member_synthesized_at)
8964       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8965     Constructor->setInvalidDecl();
8966     return;
8967   }
8968 
8969   // The exception specification is needed because we are defining the
8970   // function.
8971   ResolveExceptionSpec(CurrentLocation,
8972                        Constructor->getType()->castAs<FunctionProtoType>());
8973 
8974   SourceLocation Loc = Constructor->getLocEnd().isValid()
8975                            ? Constructor->getLocEnd()
8976                            : Constructor->getLocation();
8977   Constructor->setBody(new (Context) CompoundStmt(Loc));
8978 
8979   Constructor->markUsed(Context);
8980   MarkVTableUsed(CurrentLocation, ClassDecl);
8981 
8982   if (ASTMutationListener *L = getASTMutationListener()) {
8983     L->CompletedImplicitDefinition(Constructor);
8984   }
8985 
8986   DiagnoseUninitializedFields(*this, Constructor);
8987 }
8988 
8989 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8990   // Perform any delayed checks on exception specifications.
8991   CheckDelayedMemberExceptionSpecs();
8992 }
8993 
8994 namespace {
8995 /// Information on inheriting constructors to declare.
8996 class InheritingConstructorInfo {
8997 public:
8998   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8999       : SemaRef(SemaRef), Derived(Derived) {
9000     // Mark the constructors that we already have in the derived class.
9001     //
9002     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
9003     //   unless there is a user-declared constructor with the same signature in
9004     //   the class where the using-declaration appears.
9005     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9006   }
9007 
9008   void inheritAll(CXXRecordDecl *RD) {
9009     visitAll(RD, &InheritingConstructorInfo::inherit);
9010   }
9011 
9012 private:
9013   /// Information about an inheriting constructor.
9014   struct InheritingConstructor {
9015     InheritingConstructor()
9016       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
9017 
9018     /// If \c true, a constructor with this signature is already declared
9019     /// in the derived class.
9020     bool DeclaredInDerived;
9021 
9022     /// The constructor which is inherited.
9023     const CXXConstructorDecl *BaseCtor;
9024 
9025     /// The derived constructor we declared.
9026     CXXConstructorDecl *DerivedCtor;
9027   };
9028 
9029   /// Inheriting constructors with a given canonical type. There can be at
9030   /// most one such non-template constructor, and any number of templated
9031   /// constructors.
9032   struct InheritingConstructorsForType {
9033     InheritingConstructor NonTemplate;
9034     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9035         Templates;
9036 
9037     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9038       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9039         TemplateParameterList *ParamList = FTD->getTemplateParameters();
9040         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9041           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9042                                                false, S.TPL_TemplateMatch))
9043             return Templates[I].second;
9044         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9045         return Templates.back().second;
9046       }
9047 
9048       return NonTemplate;
9049     }
9050   };
9051 
9052   /// Get or create the inheriting constructor record for a constructor.
9053   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9054                                   QualType CtorType) {
9055     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9056         .getEntry(SemaRef, Ctor);
9057   }
9058 
9059   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9060 
9061   /// Process all constructors for a class.
9062   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
9063     for (const auto *Ctor : RD->ctors())
9064       (this->*Callback)(Ctor);
9065     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9066              I(RD->decls_begin()), E(RD->decls_end());
9067          I != E; ++I) {
9068       const FunctionDecl *FD = (*I)->getTemplatedDecl();
9069       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9070         (this->*Callback)(CD);
9071     }
9072   }
9073 
9074   /// Note that a constructor (or constructor template) was declared in Derived.
9075   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9076     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9077   }
9078 
9079   /// Inherit a single constructor.
9080   void inherit(const CXXConstructorDecl *Ctor) {
9081     const FunctionProtoType *CtorType =
9082         Ctor->getType()->castAs<FunctionProtoType>();
9083     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
9084     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9085 
9086     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9087 
9088     // Core issue (no number yet): the ellipsis is always discarded.
9089     if (EPI.Variadic) {
9090       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9091       SemaRef.Diag(Ctor->getLocation(),
9092                    diag::note_using_decl_constructor_ellipsis);
9093       EPI.Variadic = false;
9094     }
9095 
9096     // Declare a constructor for each number of parameters.
9097     //
9098     // C++11 [class.inhctor]p1:
9099     //   The candidate set of inherited constructors from the class X named in
9100     //   the using-declaration consists of [... modulo defects ...] for each
9101     //   constructor or constructor template of X, the set of constructors or
9102     //   constructor templates that results from omitting any ellipsis parameter
9103     //   specification and successively omitting parameters with a default
9104     //   argument from the end of the parameter-type-list
9105     unsigned MinParams = minParamsToInherit(Ctor);
9106     unsigned Params = Ctor->getNumParams();
9107     if (Params >= MinParams) {
9108       do
9109         declareCtor(UsingLoc, Ctor,
9110                     SemaRef.Context.getFunctionType(
9111                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
9112       while (Params > MinParams &&
9113              Ctor->getParamDecl(--Params)->hasDefaultArg());
9114     }
9115   }
9116 
9117   /// Find the using-declaration which specified that we should inherit the
9118   /// constructors of \p Base.
9119   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9120     // No fancy lookup required; just look for the base constructor name
9121     // directly within the derived class.
9122     ASTContext &Context = SemaRef.Context;
9123     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9124         Context.getCanonicalType(Context.getRecordType(Base)));
9125     DeclContext::lookup_result Decls = Derived->lookup(Name);
9126     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9127   }
9128 
9129   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9130     // C++11 [class.inhctor]p3:
9131     //   [F]or each constructor template in the candidate set of inherited
9132     //   constructors, a constructor template is implicitly declared
9133     if (Ctor->getDescribedFunctionTemplate())
9134       return 0;
9135 
9136     //   For each non-template constructor in the candidate set of inherited
9137     //   constructors other than a constructor having no parameters or a
9138     //   copy/move constructor having a single parameter, a constructor is
9139     //   implicitly declared [...]
9140     if (Ctor->getNumParams() == 0)
9141       return 1;
9142     if (Ctor->isCopyOrMoveConstructor())
9143       return 2;
9144 
9145     // Per discussion on core reflector, never inherit a constructor which
9146     // would become a default, copy, or move constructor of Derived either.
9147     const ParmVarDecl *PD = Ctor->getParamDecl(0);
9148     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9149     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9150   }
9151 
9152   /// Declare a single inheriting constructor, inheriting the specified
9153   /// constructor, with the given type.
9154   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9155                    QualType DerivedType) {
9156     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9157 
9158     // C++11 [class.inhctor]p3:
9159     //   ... a constructor is implicitly declared with the same constructor
9160     //   characteristics unless there is a user-declared constructor with
9161     //   the same signature in the class where the using-declaration appears
9162     if (Entry.DeclaredInDerived)
9163       return;
9164 
9165     // C++11 [class.inhctor]p7:
9166     //   If two using-declarations declare inheriting constructors with the
9167     //   same signature, the program is ill-formed
9168     if (Entry.DerivedCtor) {
9169       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9170         // Only diagnose this once per constructor.
9171         if (Entry.DerivedCtor->isInvalidDecl())
9172           return;
9173         Entry.DerivedCtor->setInvalidDecl();
9174 
9175         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9176         SemaRef.Diag(BaseCtor->getLocation(),
9177                      diag::note_using_decl_constructor_conflict_current_ctor);
9178         SemaRef.Diag(Entry.BaseCtor->getLocation(),
9179                      diag::note_using_decl_constructor_conflict_previous_ctor);
9180         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9181                      diag::note_using_decl_constructor_conflict_previous_using);
9182       } else {
9183         // Core issue (no number): if the same inheriting constructor is
9184         // produced by multiple base class constructors from the same base
9185         // class, the inheriting constructor is defined as deleted.
9186         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9187       }
9188 
9189       return;
9190     }
9191 
9192     ASTContext &Context = SemaRef.Context;
9193     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9194         Context.getCanonicalType(Context.getRecordType(Derived)));
9195     DeclarationNameInfo NameInfo(Name, UsingLoc);
9196 
9197     TemplateParameterList *TemplateParams = nullptr;
9198     if (const FunctionTemplateDecl *FTD =
9199             BaseCtor->getDescribedFunctionTemplate()) {
9200       TemplateParams = FTD->getTemplateParameters();
9201       // We're reusing template parameters from a different DeclContext. This
9202       // is questionable at best, but works out because the template depth in
9203       // both places is guaranteed to be 0.
9204       // FIXME: Rebuild the template parameters in the new context, and
9205       // transform the function type to refer to them.
9206     }
9207 
9208     // Build type source info pointing at the using-declaration. This is
9209     // required by template instantiation.
9210     TypeSourceInfo *TInfo =
9211         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9212     FunctionProtoTypeLoc ProtoLoc =
9213         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9214 
9215     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9216         Context, Derived, UsingLoc, NameInfo, DerivedType,
9217         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9218         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9219 
9220     // Build an unevaluated exception specification for this constructor.
9221     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9222     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9223     EPI.ExceptionSpec.Type = EST_Unevaluated;
9224     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9225     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9226                                                  FPT->getParamTypes(), EPI));
9227 
9228     // Build the parameter declarations.
9229     SmallVector<ParmVarDecl *, 16> ParamDecls;
9230     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9231       TypeSourceInfo *TInfo =
9232           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9233       ParmVarDecl *PD = ParmVarDecl::Create(
9234           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9235           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9236       PD->setScopeInfo(0, I);
9237       PD->setImplicit();
9238       ParamDecls.push_back(PD);
9239       ProtoLoc.setParam(I, PD);
9240     }
9241 
9242     // Set up the new constructor.
9243     DerivedCtor->setAccess(BaseCtor->getAccess());
9244     DerivedCtor->setParams(ParamDecls);
9245     DerivedCtor->setInheritedConstructor(BaseCtor);
9246     if (BaseCtor->isDeleted())
9247       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9248 
9249     // If this is a constructor template, build the template declaration.
9250     if (TemplateParams) {
9251       FunctionTemplateDecl *DerivedTemplate =
9252           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9253                                        TemplateParams, DerivedCtor);
9254       DerivedTemplate->setAccess(BaseCtor->getAccess());
9255       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9256       Derived->addDecl(DerivedTemplate);
9257     } else {
9258       Derived->addDecl(DerivedCtor);
9259     }
9260 
9261     Entry.BaseCtor = BaseCtor;
9262     Entry.DerivedCtor = DerivedCtor;
9263   }
9264 
9265   Sema &SemaRef;
9266   CXXRecordDecl *Derived;
9267   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9268   MapType Map;
9269 };
9270 } // namespace
9271 
9272 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9273   // Defer declaring the inheriting constructors until the class is
9274   // instantiated.
9275   if (ClassDecl->isDependentContext())
9276     return;
9277 
9278   // Find base classes from which we might inherit constructors.
9279   SmallVector<CXXRecordDecl*, 4> InheritedBases;
9280   for (const auto &BaseIt : ClassDecl->bases())
9281     if (BaseIt.getInheritConstructors())
9282       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9283 
9284   // Go no further if we're not inheriting any constructors.
9285   if (InheritedBases.empty())
9286     return;
9287 
9288   // Declare the inherited constructors.
9289   InheritingConstructorInfo ICI(*this, ClassDecl);
9290   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9291     ICI.inheritAll(InheritedBases[I]);
9292 }
9293 
9294 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9295                                        CXXConstructorDecl *Constructor) {
9296   CXXRecordDecl *ClassDecl = Constructor->getParent();
9297   assert(Constructor->getInheritedConstructor() &&
9298          !Constructor->doesThisDeclarationHaveABody() &&
9299          !Constructor->isDeleted());
9300 
9301   SynthesizedFunctionScope Scope(*this, Constructor);
9302   DiagnosticErrorTrap Trap(Diags);
9303   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9304       Trap.hasErrorOccurred()) {
9305     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9306       << Context.getTagDeclType(ClassDecl);
9307     Constructor->setInvalidDecl();
9308     return;
9309   }
9310 
9311   SourceLocation Loc = Constructor->getLocation();
9312   Constructor->setBody(new (Context) CompoundStmt(Loc));
9313 
9314   Constructor->markUsed(Context);
9315   MarkVTableUsed(CurrentLocation, ClassDecl);
9316 
9317   if (ASTMutationListener *L = getASTMutationListener()) {
9318     L->CompletedImplicitDefinition(Constructor);
9319   }
9320 }
9321 
9322 
9323 Sema::ImplicitExceptionSpecification
9324 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9325   CXXRecordDecl *ClassDecl = MD->getParent();
9326 
9327   // C++ [except.spec]p14:
9328   //   An implicitly declared special member function (Clause 12) shall have
9329   //   an exception-specification.
9330   ImplicitExceptionSpecification ExceptSpec(*this);
9331   if (ClassDecl->isInvalidDecl())
9332     return ExceptSpec;
9333 
9334   // Direct base-class destructors.
9335   for (const auto &B : ClassDecl->bases()) {
9336     if (B.isVirtual()) // Handled below.
9337       continue;
9338 
9339     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9340       ExceptSpec.CalledDecl(B.getLocStart(),
9341                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9342   }
9343 
9344   // Virtual base-class destructors.
9345   for (const auto &B : ClassDecl->vbases()) {
9346     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9347       ExceptSpec.CalledDecl(B.getLocStart(),
9348                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9349   }
9350 
9351   // Field destructors.
9352   for (const auto *F : ClassDecl->fields()) {
9353     if (const RecordType *RecordTy
9354         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9355       ExceptSpec.CalledDecl(F->getLocation(),
9356                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9357   }
9358 
9359   return ExceptSpec;
9360 }
9361 
9362 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9363   // C++ [class.dtor]p2:
9364   //   If a class has no user-declared destructor, a destructor is
9365   //   declared implicitly. An implicitly-declared destructor is an
9366   //   inline public member of its class.
9367   assert(ClassDecl->needsImplicitDestructor());
9368 
9369   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9370   if (DSM.isAlreadyBeingDeclared())
9371     return nullptr;
9372 
9373   // Create the actual destructor declaration.
9374   CanQualType ClassType
9375     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9376   SourceLocation ClassLoc = ClassDecl->getLocation();
9377   DeclarationName Name
9378     = Context.DeclarationNames.getCXXDestructorName(ClassType);
9379   DeclarationNameInfo NameInfo(Name, ClassLoc);
9380   CXXDestructorDecl *Destructor
9381       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9382                                   QualType(), nullptr, /*isInline=*/true,
9383                                   /*isImplicitlyDeclared=*/true);
9384   Destructor->setAccess(AS_public);
9385   Destructor->setDefaulted();
9386 
9387   if (getLangOpts().CUDA) {
9388     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9389                                             Destructor,
9390                                             /* ConstRHS */ false,
9391                                             /* Diagnose */ false);
9392   }
9393 
9394   // Build an exception specification pointing back at this destructor.
9395   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9396   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9397 
9398   AddOverriddenMethods(ClassDecl, Destructor);
9399 
9400   // We don't need to use SpecialMemberIsTrivial here; triviality for
9401   // destructors is easy to compute.
9402   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9403 
9404   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9405     SetDeclDeleted(Destructor, ClassLoc);
9406 
9407   // Note that we have declared this destructor.
9408   ++ASTContext::NumImplicitDestructorsDeclared;
9409 
9410   // Introduce this destructor into its scope.
9411   if (Scope *S = getScopeForContext(ClassDecl))
9412     PushOnScopeChains(Destructor, S, false);
9413   ClassDecl->addDecl(Destructor);
9414 
9415   return Destructor;
9416 }
9417 
9418 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9419                                     CXXDestructorDecl *Destructor) {
9420   assert((Destructor->isDefaulted() &&
9421           !Destructor->doesThisDeclarationHaveABody() &&
9422           !Destructor->isDeleted()) &&
9423          "DefineImplicitDestructor - call it for implicit default dtor");
9424   CXXRecordDecl *ClassDecl = Destructor->getParent();
9425   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9426 
9427   if (Destructor->isInvalidDecl())
9428     return;
9429 
9430   SynthesizedFunctionScope Scope(*this, Destructor);
9431 
9432   DiagnosticErrorTrap Trap(Diags);
9433   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9434                                          Destructor->getParent());
9435 
9436   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9437     Diag(CurrentLocation, diag::note_member_synthesized_at)
9438       << CXXDestructor << Context.getTagDeclType(ClassDecl);
9439 
9440     Destructor->setInvalidDecl();
9441     return;
9442   }
9443 
9444   // The exception specification is needed because we are defining the
9445   // function.
9446   ResolveExceptionSpec(CurrentLocation,
9447                        Destructor->getType()->castAs<FunctionProtoType>());
9448 
9449   SourceLocation Loc = Destructor->getLocEnd().isValid()
9450                            ? Destructor->getLocEnd()
9451                            : Destructor->getLocation();
9452   Destructor->setBody(new (Context) CompoundStmt(Loc));
9453   Destructor->markUsed(Context);
9454   MarkVTableUsed(CurrentLocation, ClassDecl);
9455 
9456   if (ASTMutationListener *L = getASTMutationListener()) {
9457     L->CompletedImplicitDefinition(Destructor);
9458   }
9459 }
9460 
9461 /// \brief Perform any semantic analysis which needs to be delayed until all
9462 /// pending class member declarations have been parsed.
9463 void Sema::ActOnFinishCXXMemberDecls() {
9464   // If the context is an invalid C++ class, just suppress these checks.
9465   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9466     if (Record->isInvalidDecl()) {
9467       DelayedDefaultedMemberExceptionSpecs.clear();
9468       DelayedExceptionSpecChecks.clear();
9469       return;
9470     }
9471   }
9472 }
9473 
9474 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9475   // Don't do anything for template patterns.
9476   if (Class->getDescribedClassTemplate())
9477     return;
9478 
9479   for (Decl *Member : Class->decls()) {
9480     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9481     if (!CD) {
9482       // Recurse on nested classes.
9483       if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9484         getDefaultArgExprsForConstructors(S, NestedRD);
9485       continue;
9486     } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9487       continue;
9488     }
9489 
9490     for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
9491       // Skip any default arguments that we've already instantiated.
9492       if (S.Context.getDefaultArgExprForConstructor(CD, I))
9493         continue;
9494 
9495       Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9496                                                   CD->getParamDecl(I)).get();
9497       S.DiscardCleanupsInEvaluationContext();
9498       S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9499     }
9500   }
9501 }
9502 
9503 void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) {
9504   auto *RD = dyn_cast<CXXRecordDecl>(D);
9505 
9506   // Default constructors that are annotated with __declspec(dllexport) which
9507   // have default arguments or don't use the standard calling convention are
9508   // wrapped with a thunk called the default constructor closure.
9509   if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9510     getDefaultArgExprsForConstructors(*this, RD);
9511 }
9512 
9513 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9514                                          CXXDestructorDecl *Destructor) {
9515   assert(getLangOpts().CPlusPlus11 &&
9516          "adjusting dtor exception specs was introduced in c++11");
9517 
9518   // C++11 [class.dtor]p3:
9519   //   A declaration of a destructor that does not have an exception-
9520   //   specification is implicitly considered to have the same exception-
9521   //   specification as an implicit declaration.
9522   const FunctionProtoType *DtorType = Destructor->getType()->
9523                                         getAs<FunctionProtoType>();
9524   if (DtorType->hasExceptionSpec())
9525     return;
9526 
9527   // Replace the destructor's type, building off the existing one. Fortunately,
9528   // the only thing of interest in the destructor type is its extended info.
9529   // The return and arguments are fixed.
9530   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9531   EPI.ExceptionSpec.Type = EST_Unevaluated;
9532   EPI.ExceptionSpec.SourceDecl = Destructor;
9533   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9534 
9535   // FIXME: If the destructor has a body that could throw, and the newly created
9536   // spec doesn't allow exceptions, we should emit a warning, because this
9537   // change in behavior can break conforming C++03 programs at runtime.
9538   // However, we don't have a body or an exception specification yet, so it
9539   // needs to be done somewhere else.
9540 }
9541 
9542 namespace {
9543 /// \brief An abstract base class for all helper classes used in building the
9544 //  copy/move operators. These classes serve as factory functions and help us
9545 //  avoid using the same Expr* in the AST twice.
9546 class ExprBuilder {
9547   ExprBuilder(const ExprBuilder&) = delete;
9548   ExprBuilder &operator=(const ExprBuilder&) = delete;
9549 
9550 protected:
9551   static Expr *assertNotNull(Expr *E) {
9552     assert(E && "Expression construction must not fail.");
9553     return E;
9554   }
9555 
9556 public:
9557   ExprBuilder() {}
9558   virtual ~ExprBuilder() {}
9559 
9560   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9561 };
9562 
9563 class RefBuilder: public ExprBuilder {
9564   VarDecl *Var;
9565   QualType VarType;
9566 
9567 public:
9568   Expr *build(Sema &S, SourceLocation Loc) const override {
9569     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9570   }
9571 
9572   RefBuilder(VarDecl *Var, QualType VarType)
9573       : Var(Var), VarType(VarType) {}
9574 };
9575 
9576 class ThisBuilder: public ExprBuilder {
9577 public:
9578   Expr *build(Sema &S, SourceLocation Loc) const override {
9579     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9580   }
9581 };
9582 
9583 class CastBuilder: public ExprBuilder {
9584   const ExprBuilder &Builder;
9585   QualType Type;
9586   ExprValueKind Kind;
9587   const CXXCastPath &Path;
9588 
9589 public:
9590   Expr *build(Sema &S, SourceLocation Loc) const override {
9591     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9592                                              CK_UncheckedDerivedToBase, Kind,
9593                                              &Path).get());
9594   }
9595 
9596   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9597               const CXXCastPath &Path)
9598       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9599 };
9600 
9601 class DerefBuilder: public ExprBuilder {
9602   const ExprBuilder &Builder;
9603 
9604 public:
9605   Expr *build(Sema &S, SourceLocation Loc) const override {
9606     return assertNotNull(
9607         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9608   }
9609 
9610   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9611 };
9612 
9613 class MemberBuilder: public ExprBuilder {
9614   const ExprBuilder &Builder;
9615   QualType Type;
9616   CXXScopeSpec SS;
9617   bool IsArrow;
9618   LookupResult &MemberLookup;
9619 
9620 public:
9621   Expr *build(Sema &S, SourceLocation Loc) const override {
9622     return assertNotNull(S.BuildMemberReferenceExpr(
9623         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9624         nullptr, MemberLookup, nullptr).get());
9625   }
9626 
9627   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9628                 LookupResult &MemberLookup)
9629       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9630         MemberLookup(MemberLookup) {}
9631 };
9632 
9633 class MoveCastBuilder: public ExprBuilder {
9634   const ExprBuilder &Builder;
9635 
9636 public:
9637   Expr *build(Sema &S, SourceLocation Loc) const override {
9638     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9639   }
9640 
9641   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9642 };
9643 
9644 class LvalueConvBuilder: public ExprBuilder {
9645   const ExprBuilder &Builder;
9646 
9647 public:
9648   Expr *build(Sema &S, SourceLocation Loc) const override {
9649     return assertNotNull(
9650         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9651   }
9652 
9653   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9654 };
9655 
9656 class SubscriptBuilder: public ExprBuilder {
9657   const ExprBuilder &Base;
9658   const ExprBuilder &Index;
9659 
9660 public:
9661   Expr *build(Sema &S, SourceLocation Loc) const override {
9662     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9663         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9664   }
9665 
9666   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9667       : Base(Base), Index(Index) {}
9668 };
9669 
9670 } // end anonymous namespace
9671 
9672 /// When generating a defaulted copy or move assignment operator, if a field
9673 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9674 /// do so. This optimization only applies for arrays of scalars, and for arrays
9675 /// of class type where the selected copy/move-assignment operator is trivial.
9676 static StmtResult
9677 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9678                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9679   // Compute the size of the memory buffer to be copied.
9680   QualType SizeType = S.Context.getSizeType();
9681   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9682                    S.Context.getTypeSizeInChars(T).getQuantity());
9683 
9684   // Take the address of the field references for "from" and "to". We
9685   // directly construct UnaryOperators here because semantic analysis
9686   // does not permit us to take the address of an xvalue.
9687   Expr *From = FromB.build(S, Loc);
9688   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9689                          S.Context.getPointerType(From->getType()),
9690                          VK_RValue, OK_Ordinary, Loc);
9691   Expr *To = ToB.build(S, Loc);
9692   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9693                        S.Context.getPointerType(To->getType()),
9694                        VK_RValue, OK_Ordinary, Loc);
9695 
9696   const Type *E = T->getBaseElementTypeUnsafe();
9697   bool NeedsCollectableMemCpy =
9698     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9699 
9700   // Create a reference to the __builtin_objc_memmove_collectable function
9701   StringRef MemCpyName = NeedsCollectableMemCpy ?
9702     "__builtin_objc_memmove_collectable" :
9703     "__builtin_memcpy";
9704   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9705                  Sema::LookupOrdinaryName);
9706   S.LookupName(R, S.TUScope, true);
9707 
9708   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9709   if (!MemCpy)
9710     // Something went horribly wrong earlier, and we will have complained
9711     // about it.
9712     return StmtError();
9713 
9714   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9715                                             VK_RValue, Loc, nullptr);
9716   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9717 
9718   Expr *CallArgs[] = {
9719     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9720   };
9721   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9722                                     Loc, CallArgs, Loc);
9723 
9724   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9725   return Call.getAs<Stmt>();
9726 }
9727 
9728 /// \brief Builds a statement that copies/moves the given entity from \p From to
9729 /// \c To.
9730 ///
9731 /// This routine is used to copy/move the members of a class with an
9732 /// implicitly-declared copy/move assignment operator. When the entities being
9733 /// copied are arrays, this routine builds for loops to copy them.
9734 ///
9735 /// \param S The Sema object used for type-checking.
9736 ///
9737 /// \param Loc The location where the implicit copy/move is being generated.
9738 ///
9739 /// \param T The type of the expressions being copied/moved. Both expressions
9740 /// must have this type.
9741 ///
9742 /// \param To The expression we are copying/moving to.
9743 ///
9744 /// \param From The expression we are copying/moving from.
9745 ///
9746 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9747 /// Otherwise, it's a non-static member subobject.
9748 ///
9749 /// \param Copying Whether we're copying or moving.
9750 ///
9751 /// \param Depth Internal parameter recording the depth of the recursion.
9752 ///
9753 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9754 /// if a memcpy should be used instead.
9755 static StmtResult
9756 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9757                                  const ExprBuilder &To, const ExprBuilder &From,
9758                                  bool CopyingBaseSubobject, bool Copying,
9759                                  unsigned Depth = 0) {
9760   // C++11 [class.copy]p28:
9761   //   Each subobject is assigned in the manner appropriate to its type:
9762   //
9763   //     - if the subobject is of class type, as if by a call to operator= with
9764   //       the subobject as the object expression and the corresponding
9765   //       subobject of x as a single function argument (as if by explicit
9766   //       qualification; that is, ignoring any possible virtual overriding
9767   //       functions in more derived classes);
9768   //
9769   // C++03 [class.copy]p13:
9770   //     - if the subobject is of class type, the copy assignment operator for
9771   //       the class is used (as if by explicit qualification; that is,
9772   //       ignoring any possible virtual overriding functions in more derived
9773   //       classes);
9774   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9775     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9776 
9777     // Look for operator=.
9778     DeclarationName Name
9779       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9780     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9781     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9782 
9783     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9784     // operator.
9785     if (!S.getLangOpts().CPlusPlus11) {
9786       LookupResult::Filter F = OpLookup.makeFilter();
9787       while (F.hasNext()) {
9788         NamedDecl *D = F.next();
9789         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9790           if (Method->isCopyAssignmentOperator() ||
9791               (!Copying && Method->isMoveAssignmentOperator()))
9792             continue;
9793 
9794         F.erase();
9795       }
9796       F.done();
9797     }
9798 
9799     // Suppress the protected check (C++ [class.protected]) for each of the
9800     // assignment operators we found. This strange dance is required when
9801     // we're assigning via a base classes's copy-assignment operator. To
9802     // ensure that we're getting the right base class subobject (without
9803     // ambiguities), we need to cast "this" to that subobject type; to
9804     // ensure that we don't go through the virtual call mechanism, we need
9805     // to qualify the operator= name with the base class (see below). However,
9806     // this means that if the base class has a protected copy assignment
9807     // operator, the protected member access check will fail. So, we
9808     // rewrite "protected" access to "public" access in this case, since we
9809     // know by construction that we're calling from a derived class.
9810     if (CopyingBaseSubobject) {
9811       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9812            L != LEnd; ++L) {
9813         if (L.getAccess() == AS_protected)
9814           L.setAccess(AS_public);
9815       }
9816     }
9817 
9818     // Create the nested-name-specifier that will be used to qualify the
9819     // reference to operator=; this is required to suppress the virtual
9820     // call mechanism.
9821     CXXScopeSpec SS;
9822     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9823     SS.MakeTrivial(S.Context,
9824                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9825                                                CanonicalT),
9826                    Loc);
9827 
9828     // Create the reference to operator=.
9829     ExprResult OpEqualRef
9830       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9831                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9832                                    /*FirstQualifierInScope=*/nullptr,
9833                                    OpLookup,
9834                                    /*TemplateArgs=*/nullptr,
9835                                    /*SuppressQualifierCheck=*/true);
9836     if (OpEqualRef.isInvalid())
9837       return StmtError();
9838 
9839     // Build the call to the assignment operator.
9840 
9841     Expr *FromInst = From.build(S, Loc);
9842     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9843                                                   OpEqualRef.getAs<Expr>(),
9844                                                   Loc, FromInst, Loc);
9845     if (Call.isInvalid())
9846       return StmtError();
9847 
9848     // If we built a call to a trivial 'operator=' while copying an array,
9849     // bail out. We'll replace the whole shebang with a memcpy.
9850     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9851     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9852       return StmtResult((Stmt*)nullptr);
9853 
9854     // Convert to an expression-statement, and clean up any produced
9855     // temporaries.
9856     return S.ActOnExprStmt(Call);
9857   }
9858 
9859   //     - if the subobject is of scalar type, the built-in assignment
9860   //       operator is used.
9861   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9862   if (!ArrayTy) {
9863     ExprResult Assignment = S.CreateBuiltinBinOp(
9864         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9865     if (Assignment.isInvalid())
9866       return StmtError();
9867     return S.ActOnExprStmt(Assignment);
9868   }
9869 
9870   //     - if the subobject is an array, each element is assigned, in the
9871   //       manner appropriate to the element type;
9872 
9873   // Construct a loop over the array bounds, e.g.,
9874   //
9875   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9876   //
9877   // that will copy each of the array elements.
9878   QualType SizeType = S.Context.getSizeType();
9879 
9880   // Create the iteration variable.
9881   IdentifierInfo *IterationVarName = nullptr;
9882   {
9883     SmallString<8> Str;
9884     llvm::raw_svector_ostream OS(Str);
9885     OS << "__i" << Depth;
9886     IterationVarName = &S.Context.Idents.get(OS.str());
9887   }
9888   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9889                                           IterationVarName, SizeType,
9890                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9891                                           SC_None);
9892 
9893   // Initialize the iteration variable to zero.
9894   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9895   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9896 
9897   // Creates a reference to the iteration variable.
9898   RefBuilder IterationVarRef(IterationVar, SizeType);
9899   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9900 
9901   // Create the DeclStmt that holds the iteration variable.
9902   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9903 
9904   // Subscript the "from" and "to" expressions with the iteration variable.
9905   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9906   MoveCastBuilder FromIndexMove(FromIndexCopy);
9907   const ExprBuilder *FromIndex;
9908   if (Copying)
9909     FromIndex = &FromIndexCopy;
9910   else
9911     FromIndex = &FromIndexMove;
9912 
9913   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9914 
9915   // Build the copy/move for an individual element of the array.
9916   StmtResult Copy =
9917     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9918                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9919                                      Copying, Depth + 1);
9920   // Bail out if copying fails or if we determined that we should use memcpy.
9921   if (Copy.isInvalid() || !Copy.get())
9922     return Copy;
9923 
9924   // Create the comparison against the array bound.
9925   llvm::APInt Upper
9926     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9927   Expr *Comparison
9928     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9929                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9930                                      BO_NE, S.Context.BoolTy,
9931                                      VK_RValue, OK_Ordinary, Loc, false);
9932 
9933   // Create the pre-increment of the iteration variable.
9934   Expr *Increment
9935     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9936                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9937 
9938   // Construct the loop that copies all elements of this array.
9939   return S.ActOnForStmt(Loc, Loc, InitStmt,
9940                         S.MakeFullExpr(Comparison),
9941                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9942                         Loc, Copy.get());
9943 }
9944 
9945 static StmtResult
9946 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9947                       const ExprBuilder &To, const ExprBuilder &From,
9948                       bool CopyingBaseSubobject, bool Copying) {
9949   // Maybe we should use a memcpy?
9950   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9951       T.isTriviallyCopyableType(S.Context))
9952     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9953 
9954   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9955                                                      CopyingBaseSubobject,
9956                                                      Copying, 0));
9957 
9958   // If we ended up picking a trivial assignment operator for an array of a
9959   // non-trivially-copyable class type, just emit a memcpy.
9960   if (!Result.isInvalid() && !Result.get())
9961     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9962 
9963   return Result;
9964 }
9965 
9966 Sema::ImplicitExceptionSpecification
9967 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9968   CXXRecordDecl *ClassDecl = MD->getParent();
9969 
9970   ImplicitExceptionSpecification ExceptSpec(*this);
9971   if (ClassDecl->isInvalidDecl())
9972     return ExceptSpec;
9973 
9974   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9975   assert(T->getNumParams() == 1 && "not a copy assignment op");
9976   unsigned ArgQuals =
9977       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9978 
9979   // C++ [except.spec]p14:
9980   //   An implicitly declared special member function (Clause 12) shall have an
9981   //   exception-specification. [...]
9982 
9983   // It is unspecified whether or not an implicit copy assignment operator
9984   // attempts to deduplicate calls to assignment operators of virtual bases are
9985   // made. As such, this exception specification is effectively unspecified.
9986   // Based on a similar decision made for constness in C++0x, we're erring on
9987   // the side of assuming such calls to be made regardless of whether they
9988   // actually happen.
9989   for (const auto &Base : ClassDecl->bases()) {
9990     if (Base.isVirtual())
9991       continue;
9992 
9993     CXXRecordDecl *BaseClassDecl
9994       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9995     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9996                                                             ArgQuals, false, 0))
9997       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9998   }
9999 
10000   for (const auto &Base : ClassDecl->vbases()) {
10001     CXXRecordDecl *BaseClassDecl
10002       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10003     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10004                                                             ArgQuals, false, 0))
10005       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10006   }
10007 
10008   for (const auto *Field : ClassDecl->fields()) {
10009     QualType FieldType = Context.getBaseElementType(Field->getType());
10010     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10011       if (CXXMethodDecl *CopyAssign =
10012           LookupCopyingAssignment(FieldClassDecl,
10013                                   ArgQuals | FieldType.getCVRQualifiers(),
10014                                   false, 0))
10015         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10016     }
10017   }
10018 
10019   return ExceptSpec;
10020 }
10021 
10022 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10023   // Note: The following rules are largely analoguous to the copy
10024   // constructor rules. Note that virtual bases are not taken into account
10025   // for determining the argument type of the operator. Note also that
10026   // operators taking an object instead of a reference are allowed.
10027   assert(ClassDecl->needsImplicitCopyAssignment());
10028 
10029   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10030   if (DSM.isAlreadyBeingDeclared())
10031     return nullptr;
10032 
10033   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10034   QualType RetType = Context.getLValueReferenceType(ArgType);
10035   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10036   if (Const)
10037     ArgType = ArgType.withConst();
10038   ArgType = Context.getLValueReferenceType(ArgType);
10039 
10040   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10041                                                      CXXCopyAssignment,
10042                                                      Const);
10043 
10044   //   An implicitly-declared copy assignment operator is an inline public
10045   //   member of its class.
10046   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10047   SourceLocation ClassLoc = ClassDecl->getLocation();
10048   DeclarationNameInfo NameInfo(Name, ClassLoc);
10049   CXXMethodDecl *CopyAssignment =
10050       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10051                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10052                             /*isInline=*/true, Constexpr, SourceLocation());
10053   CopyAssignment->setAccess(AS_public);
10054   CopyAssignment->setDefaulted();
10055   CopyAssignment->setImplicit();
10056 
10057   if (getLangOpts().CUDA) {
10058     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10059                                             CopyAssignment,
10060                                             /* ConstRHS */ Const,
10061                                             /* Diagnose */ false);
10062   }
10063 
10064   // Build an exception specification pointing back at this member.
10065   FunctionProtoType::ExtProtoInfo EPI =
10066       getImplicitMethodEPI(*this, CopyAssignment);
10067   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10068 
10069   // Add the parameter to the operator.
10070   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10071                                                ClassLoc, ClassLoc,
10072                                                /*Id=*/nullptr, ArgType,
10073                                                /*TInfo=*/nullptr, SC_None,
10074                                                nullptr);
10075   CopyAssignment->setParams(FromParam);
10076 
10077   AddOverriddenMethods(ClassDecl, CopyAssignment);
10078 
10079   CopyAssignment->setTrivial(
10080     ClassDecl->needsOverloadResolutionForCopyAssignment()
10081       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10082       : ClassDecl->hasTrivialCopyAssignment());
10083 
10084   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10085     SetDeclDeleted(CopyAssignment, ClassLoc);
10086 
10087   // Note that we have added this copy-assignment operator.
10088   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10089 
10090   if (Scope *S = getScopeForContext(ClassDecl))
10091     PushOnScopeChains(CopyAssignment, S, false);
10092   ClassDecl->addDecl(CopyAssignment);
10093 
10094   return CopyAssignment;
10095 }
10096 
10097 /// Diagnose an implicit copy operation for a class which is odr-used, but
10098 /// which is deprecated because the class has a user-declared copy constructor,
10099 /// copy assignment operator, or destructor.
10100 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10101                                             SourceLocation UseLoc) {
10102   assert(CopyOp->isImplicit());
10103 
10104   CXXRecordDecl *RD = CopyOp->getParent();
10105   CXXMethodDecl *UserDeclaredOperation = nullptr;
10106 
10107   // In Microsoft mode, assignment operations don't affect constructors and
10108   // vice versa.
10109   if (RD->hasUserDeclaredDestructor()) {
10110     UserDeclaredOperation = RD->getDestructor();
10111   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10112              RD->hasUserDeclaredCopyConstructor() &&
10113              !S.getLangOpts().MSVCCompat) {
10114     // Find any user-declared copy constructor.
10115     for (auto *I : RD->ctors()) {
10116       if (I->isCopyConstructor()) {
10117         UserDeclaredOperation = I;
10118         break;
10119       }
10120     }
10121     assert(UserDeclaredOperation);
10122   } else if (isa<CXXConstructorDecl>(CopyOp) &&
10123              RD->hasUserDeclaredCopyAssignment() &&
10124              !S.getLangOpts().MSVCCompat) {
10125     // Find any user-declared move assignment operator.
10126     for (auto *I : RD->methods()) {
10127       if (I->isCopyAssignmentOperator()) {
10128         UserDeclaredOperation = I;
10129         break;
10130       }
10131     }
10132     assert(UserDeclaredOperation);
10133   }
10134 
10135   if (UserDeclaredOperation) {
10136     S.Diag(UserDeclaredOperation->getLocation(),
10137          diag::warn_deprecated_copy_operation)
10138       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10139       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10140     S.Diag(UseLoc, diag::note_member_synthesized_at)
10141       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10142                                           : Sema::CXXCopyAssignment)
10143       << RD;
10144   }
10145 }
10146 
10147 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10148                                         CXXMethodDecl *CopyAssignOperator) {
10149   assert((CopyAssignOperator->isDefaulted() &&
10150           CopyAssignOperator->isOverloadedOperator() &&
10151           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10152           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10153           !CopyAssignOperator->isDeleted()) &&
10154          "DefineImplicitCopyAssignment called for wrong function");
10155 
10156   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10157 
10158   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10159     CopyAssignOperator->setInvalidDecl();
10160     return;
10161   }
10162 
10163   // C++11 [class.copy]p18:
10164   //   The [definition of an implicitly declared copy assignment operator] is
10165   //   deprecated if the class has a user-declared copy constructor or a
10166   //   user-declared destructor.
10167   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10168     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10169 
10170   CopyAssignOperator->markUsed(Context);
10171 
10172   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10173   DiagnosticErrorTrap Trap(Diags);
10174 
10175   // C++0x [class.copy]p30:
10176   //   The implicitly-defined or explicitly-defaulted copy assignment operator
10177   //   for a non-union class X performs memberwise copy assignment of its
10178   //   subobjects. The direct base classes of X are assigned first, in the
10179   //   order of their declaration in the base-specifier-list, and then the
10180   //   immediate non-static data members of X are assigned, in the order in
10181   //   which they were declared in the class definition.
10182 
10183   // The statements that form the synthesized function body.
10184   SmallVector<Stmt*, 8> Statements;
10185 
10186   // The parameter for the "other" object, which we are copying from.
10187   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10188   Qualifiers OtherQuals = Other->getType().getQualifiers();
10189   QualType OtherRefType = Other->getType();
10190   if (const LValueReferenceType *OtherRef
10191                                 = OtherRefType->getAs<LValueReferenceType>()) {
10192     OtherRefType = OtherRef->getPointeeType();
10193     OtherQuals = OtherRefType.getQualifiers();
10194   }
10195 
10196   // Our location for everything implicitly-generated.
10197   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10198                            ? CopyAssignOperator->getLocEnd()
10199                            : CopyAssignOperator->getLocation();
10200 
10201   // Builds a DeclRefExpr for the "other" object.
10202   RefBuilder OtherRef(Other, OtherRefType);
10203 
10204   // Builds the "this" pointer.
10205   ThisBuilder This;
10206 
10207   // Assign base classes.
10208   bool Invalid = false;
10209   for (auto &Base : ClassDecl->bases()) {
10210     // Form the assignment:
10211     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10212     QualType BaseType = Base.getType().getUnqualifiedType();
10213     if (!BaseType->isRecordType()) {
10214       Invalid = true;
10215       continue;
10216     }
10217 
10218     CXXCastPath BasePath;
10219     BasePath.push_back(&Base);
10220 
10221     // Construct the "from" expression, which is an implicit cast to the
10222     // appropriately-qualified base type.
10223     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10224                      VK_LValue, BasePath);
10225 
10226     // Dereference "this".
10227     DerefBuilder DerefThis(This);
10228     CastBuilder To(DerefThis,
10229                    Context.getCVRQualifiedType(
10230                        BaseType, CopyAssignOperator->getTypeQualifiers()),
10231                    VK_LValue, BasePath);
10232 
10233     // Build the copy.
10234     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10235                                             To, From,
10236                                             /*CopyingBaseSubobject=*/true,
10237                                             /*Copying=*/true);
10238     if (Copy.isInvalid()) {
10239       Diag(CurrentLocation, diag::note_member_synthesized_at)
10240         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10241       CopyAssignOperator->setInvalidDecl();
10242       return;
10243     }
10244 
10245     // Success! Record the copy.
10246     Statements.push_back(Copy.getAs<Expr>());
10247   }
10248 
10249   // Assign non-static members.
10250   for (auto *Field : ClassDecl->fields()) {
10251     // FIXME: We should form some kind of AST representation for the implied
10252     // memcpy in a union copy operation.
10253     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10254       continue;
10255 
10256     if (Field->isInvalidDecl()) {
10257       Invalid = true;
10258       continue;
10259     }
10260 
10261     // Check for members of reference type; we can't copy those.
10262     if (Field->getType()->isReferenceType()) {
10263       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10264         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10265       Diag(Field->getLocation(), diag::note_declared_at);
10266       Diag(CurrentLocation, diag::note_member_synthesized_at)
10267         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10268       Invalid = true;
10269       continue;
10270     }
10271 
10272     // Check for members of const-qualified, non-class type.
10273     QualType BaseType = Context.getBaseElementType(Field->getType());
10274     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10275       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10276         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10277       Diag(Field->getLocation(), diag::note_declared_at);
10278       Diag(CurrentLocation, diag::note_member_synthesized_at)
10279         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10280       Invalid = true;
10281       continue;
10282     }
10283 
10284     // Suppress assigning zero-width bitfields.
10285     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10286       continue;
10287 
10288     QualType FieldType = Field->getType().getNonReferenceType();
10289     if (FieldType->isIncompleteArrayType()) {
10290       assert(ClassDecl->hasFlexibleArrayMember() &&
10291              "Incomplete array type is not valid");
10292       continue;
10293     }
10294 
10295     // Build references to the field in the object we're copying from and to.
10296     CXXScopeSpec SS; // Intentionally empty
10297     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10298                               LookupMemberName);
10299     MemberLookup.addDecl(Field);
10300     MemberLookup.resolveKind();
10301 
10302     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10303 
10304     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10305 
10306     // Build the copy of this field.
10307     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10308                                             To, From,
10309                                             /*CopyingBaseSubobject=*/false,
10310                                             /*Copying=*/true);
10311     if (Copy.isInvalid()) {
10312       Diag(CurrentLocation, diag::note_member_synthesized_at)
10313         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10314       CopyAssignOperator->setInvalidDecl();
10315       return;
10316     }
10317 
10318     // Success! Record the copy.
10319     Statements.push_back(Copy.getAs<Stmt>());
10320   }
10321 
10322   if (!Invalid) {
10323     // Add a "return *this;"
10324     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10325 
10326     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10327     if (Return.isInvalid())
10328       Invalid = true;
10329     else {
10330       Statements.push_back(Return.getAs<Stmt>());
10331 
10332       if (Trap.hasErrorOccurred()) {
10333         Diag(CurrentLocation, diag::note_member_synthesized_at)
10334           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10335         Invalid = true;
10336       }
10337     }
10338   }
10339 
10340   // The exception specification is needed because we are defining the
10341   // function.
10342   ResolveExceptionSpec(CurrentLocation,
10343                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10344 
10345   if (Invalid) {
10346     CopyAssignOperator->setInvalidDecl();
10347     return;
10348   }
10349 
10350   StmtResult Body;
10351   {
10352     CompoundScopeRAII CompoundScope(*this);
10353     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10354                              /*isStmtExpr=*/false);
10355     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10356   }
10357   CopyAssignOperator->setBody(Body.getAs<Stmt>());
10358 
10359   if (ASTMutationListener *L = getASTMutationListener()) {
10360     L->CompletedImplicitDefinition(CopyAssignOperator);
10361   }
10362 }
10363 
10364 Sema::ImplicitExceptionSpecification
10365 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10366   CXXRecordDecl *ClassDecl = MD->getParent();
10367 
10368   ImplicitExceptionSpecification ExceptSpec(*this);
10369   if (ClassDecl->isInvalidDecl())
10370     return ExceptSpec;
10371 
10372   // C++0x [except.spec]p14:
10373   //   An implicitly declared special member function (Clause 12) shall have an
10374   //   exception-specification. [...]
10375 
10376   // It is unspecified whether or not an implicit move assignment operator
10377   // attempts to deduplicate calls to assignment operators of virtual bases are
10378   // made. As such, this exception specification is effectively unspecified.
10379   // Based on a similar decision made for constness in C++0x, we're erring on
10380   // the side of assuming such calls to be made regardless of whether they
10381   // actually happen.
10382   // Note that a move constructor is not implicitly declared when there are
10383   // virtual bases, but it can still be user-declared and explicitly defaulted.
10384   for (const auto &Base : ClassDecl->bases()) {
10385     if (Base.isVirtual())
10386       continue;
10387 
10388     CXXRecordDecl *BaseClassDecl
10389       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10390     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10391                                                            0, false, 0))
10392       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10393   }
10394 
10395   for (const auto &Base : ClassDecl->vbases()) {
10396     CXXRecordDecl *BaseClassDecl
10397       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10398     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10399                                                            0, false, 0))
10400       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10401   }
10402 
10403   for (const auto *Field : ClassDecl->fields()) {
10404     QualType FieldType = Context.getBaseElementType(Field->getType());
10405     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10406       if (CXXMethodDecl *MoveAssign =
10407               LookupMovingAssignment(FieldClassDecl,
10408                                      FieldType.getCVRQualifiers(),
10409                                      false, 0))
10410         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10411     }
10412   }
10413 
10414   return ExceptSpec;
10415 }
10416 
10417 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10418   assert(ClassDecl->needsImplicitMoveAssignment());
10419 
10420   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10421   if (DSM.isAlreadyBeingDeclared())
10422     return nullptr;
10423 
10424   // Note: The following rules are largely analoguous to the move
10425   // constructor rules.
10426 
10427   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10428   QualType RetType = Context.getLValueReferenceType(ArgType);
10429   ArgType = Context.getRValueReferenceType(ArgType);
10430 
10431   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10432                                                      CXXMoveAssignment,
10433                                                      false);
10434 
10435   //   An implicitly-declared move assignment operator is an inline public
10436   //   member of its class.
10437   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10438   SourceLocation ClassLoc = ClassDecl->getLocation();
10439   DeclarationNameInfo NameInfo(Name, ClassLoc);
10440   CXXMethodDecl *MoveAssignment =
10441       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10442                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10443                             /*isInline=*/true, Constexpr, SourceLocation());
10444   MoveAssignment->setAccess(AS_public);
10445   MoveAssignment->setDefaulted();
10446   MoveAssignment->setImplicit();
10447 
10448   if (getLangOpts().CUDA) {
10449     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10450                                             MoveAssignment,
10451                                             /* ConstRHS */ false,
10452                                             /* Diagnose */ false);
10453   }
10454 
10455   // Build an exception specification pointing back at this member.
10456   FunctionProtoType::ExtProtoInfo EPI =
10457       getImplicitMethodEPI(*this, MoveAssignment);
10458   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10459 
10460   // Add the parameter to the operator.
10461   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10462                                                ClassLoc, ClassLoc,
10463                                                /*Id=*/nullptr, ArgType,
10464                                                /*TInfo=*/nullptr, SC_None,
10465                                                nullptr);
10466   MoveAssignment->setParams(FromParam);
10467 
10468   AddOverriddenMethods(ClassDecl, MoveAssignment);
10469 
10470   MoveAssignment->setTrivial(
10471     ClassDecl->needsOverloadResolutionForMoveAssignment()
10472       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10473       : ClassDecl->hasTrivialMoveAssignment());
10474 
10475   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10476     ClassDecl->setImplicitMoveAssignmentIsDeleted();
10477     SetDeclDeleted(MoveAssignment, ClassLoc);
10478   }
10479 
10480   // Note that we have added this copy-assignment operator.
10481   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10482 
10483   if (Scope *S = getScopeForContext(ClassDecl))
10484     PushOnScopeChains(MoveAssignment, S, false);
10485   ClassDecl->addDecl(MoveAssignment);
10486 
10487   return MoveAssignment;
10488 }
10489 
10490 /// Check if we're implicitly defining a move assignment operator for a class
10491 /// with virtual bases. Such a move assignment might move-assign the virtual
10492 /// base multiple times.
10493 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10494                                                SourceLocation CurrentLocation) {
10495   assert(!Class->isDependentContext() && "should not define dependent move");
10496 
10497   // Only a virtual base could get implicitly move-assigned multiple times.
10498   // Only a non-trivial move assignment can observe this. We only want to
10499   // diagnose if we implicitly define an assignment operator that assigns
10500   // two base classes, both of which move-assign the same virtual base.
10501   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10502       Class->getNumBases() < 2)
10503     return;
10504 
10505   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10506   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10507   VBaseMap VBases;
10508 
10509   for (auto &BI : Class->bases()) {
10510     Worklist.push_back(&BI);
10511     while (!Worklist.empty()) {
10512       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10513       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10514 
10515       // If the base has no non-trivial move assignment operators,
10516       // we don't care about moves from it.
10517       if (!Base->hasNonTrivialMoveAssignment())
10518         continue;
10519 
10520       // If there's nothing virtual here, skip it.
10521       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10522         continue;
10523 
10524       // If we're not actually going to call a move assignment for this base,
10525       // or the selected move assignment is trivial, skip it.
10526       Sema::SpecialMemberOverloadResult *SMOR =
10527         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10528                               /*ConstArg*/false, /*VolatileArg*/false,
10529                               /*RValueThis*/true, /*ConstThis*/false,
10530                               /*VolatileThis*/false);
10531       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10532           !SMOR->getMethod()->isMoveAssignmentOperator())
10533         continue;
10534 
10535       if (BaseSpec->isVirtual()) {
10536         // We're going to move-assign this virtual base, and its move
10537         // assignment operator is not trivial. If this can happen for
10538         // multiple distinct direct bases of Class, diagnose it. (If it
10539         // only happens in one base, we'll diagnose it when synthesizing
10540         // that base class's move assignment operator.)
10541         CXXBaseSpecifier *&Existing =
10542             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10543                 .first->second;
10544         if (Existing && Existing != &BI) {
10545           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10546             << Class << Base;
10547           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10548             << (Base->getCanonicalDecl() ==
10549                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10550             << Base << Existing->getType() << Existing->getSourceRange();
10551           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10552             << (Base->getCanonicalDecl() ==
10553                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10554             << Base << BI.getType() << BaseSpec->getSourceRange();
10555 
10556           // Only diagnose each vbase once.
10557           Existing = nullptr;
10558         }
10559       } else {
10560         // Only walk over bases that have defaulted move assignment operators.
10561         // We assume that any user-provided move assignment operator handles
10562         // the multiple-moves-of-vbase case itself somehow.
10563         if (!SMOR->getMethod()->isDefaulted())
10564           continue;
10565 
10566         // We're going to move the base classes of Base. Add them to the list.
10567         for (auto &BI : Base->bases())
10568           Worklist.push_back(&BI);
10569       }
10570     }
10571   }
10572 }
10573 
10574 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10575                                         CXXMethodDecl *MoveAssignOperator) {
10576   assert((MoveAssignOperator->isDefaulted() &&
10577           MoveAssignOperator->isOverloadedOperator() &&
10578           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10579           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10580           !MoveAssignOperator->isDeleted()) &&
10581          "DefineImplicitMoveAssignment called for wrong function");
10582 
10583   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10584 
10585   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10586     MoveAssignOperator->setInvalidDecl();
10587     return;
10588   }
10589 
10590   MoveAssignOperator->markUsed(Context);
10591 
10592   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10593   DiagnosticErrorTrap Trap(Diags);
10594 
10595   // C++0x [class.copy]p28:
10596   //   The implicitly-defined or move assignment operator for a non-union class
10597   //   X performs memberwise move assignment of its subobjects. The direct base
10598   //   classes of X are assigned first, in the order of their declaration in the
10599   //   base-specifier-list, and then the immediate non-static data members of X
10600   //   are assigned, in the order in which they were declared in the class
10601   //   definition.
10602 
10603   // Issue a warning if our implicit move assignment operator will move
10604   // from a virtual base more than once.
10605   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10606 
10607   // The statements that form the synthesized function body.
10608   SmallVector<Stmt*, 8> Statements;
10609 
10610   // The parameter for the "other" object, which we are move from.
10611   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10612   QualType OtherRefType = Other->getType()->
10613       getAs<RValueReferenceType>()->getPointeeType();
10614   assert(!OtherRefType.getQualifiers() &&
10615          "Bad argument type of defaulted move assignment");
10616 
10617   // Our location for everything implicitly-generated.
10618   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10619                            ? MoveAssignOperator->getLocEnd()
10620                            : MoveAssignOperator->getLocation();
10621 
10622   // Builds a reference to the "other" object.
10623   RefBuilder OtherRef(Other, OtherRefType);
10624   // Cast to rvalue.
10625   MoveCastBuilder MoveOther(OtherRef);
10626 
10627   // Builds the "this" pointer.
10628   ThisBuilder This;
10629 
10630   // Assign base classes.
10631   bool Invalid = false;
10632   for (auto &Base : ClassDecl->bases()) {
10633     // C++11 [class.copy]p28:
10634     //   It is unspecified whether subobjects representing virtual base classes
10635     //   are assigned more than once by the implicitly-defined copy assignment
10636     //   operator.
10637     // FIXME: Do not assign to a vbase that will be assigned by some other base
10638     // class. For a move-assignment, this can result in the vbase being moved
10639     // multiple times.
10640 
10641     // Form the assignment:
10642     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10643     QualType BaseType = Base.getType().getUnqualifiedType();
10644     if (!BaseType->isRecordType()) {
10645       Invalid = true;
10646       continue;
10647     }
10648 
10649     CXXCastPath BasePath;
10650     BasePath.push_back(&Base);
10651 
10652     // Construct the "from" expression, which is an implicit cast to the
10653     // appropriately-qualified base type.
10654     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10655 
10656     // Dereference "this".
10657     DerefBuilder DerefThis(This);
10658 
10659     // Implicitly cast "this" to the appropriately-qualified base type.
10660     CastBuilder To(DerefThis,
10661                    Context.getCVRQualifiedType(
10662                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10663                    VK_LValue, BasePath);
10664 
10665     // Build the move.
10666     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10667                                             To, From,
10668                                             /*CopyingBaseSubobject=*/true,
10669                                             /*Copying=*/false);
10670     if (Move.isInvalid()) {
10671       Diag(CurrentLocation, diag::note_member_synthesized_at)
10672         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10673       MoveAssignOperator->setInvalidDecl();
10674       return;
10675     }
10676 
10677     // Success! Record the move.
10678     Statements.push_back(Move.getAs<Expr>());
10679   }
10680 
10681   // Assign non-static members.
10682   for (auto *Field : ClassDecl->fields()) {
10683     // FIXME: We should form some kind of AST representation for the implied
10684     // memcpy in a union copy operation.
10685     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10686       continue;
10687 
10688     if (Field->isInvalidDecl()) {
10689       Invalid = true;
10690       continue;
10691     }
10692 
10693     // Check for members of reference type; we can't move those.
10694     if (Field->getType()->isReferenceType()) {
10695       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10696         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10697       Diag(Field->getLocation(), diag::note_declared_at);
10698       Diag(CurrentLocation, diag::note_member_synthesized_at)
10699         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10700       Invalid = true;
10701       continue;
10702     }
10703 
10704     // Check for members of const-qualified, non-class type.
10705     QualType BaseType = Context.getBaseElementType(Field->getType());
10706     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10707       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10708         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10709       Diag(Field->getLocation(), diag::note_declared_at);
10710       Diag(CurrentLocation, diag::note_member_synthesized_at)
10711         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10712       Invalid = true;
10713       continue;
10714     }
10715 
10716     // Suppress assigning zero-width bitfields.
10717     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10718       continue;
10719 
10720     QualType FieldType = Field->getType().getNonReferenceType();
10721     if (FieldType->isIncompleteArrayType()) {
10722       assert(ClassDecl->hasFlexibleArrayMember() &&
10723              "Incomplete array type is not valid");
10724       continue;
10725     }
10726 
10727     // Build references to the field in the object we're copying from and to.
10728     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10729                               LookupMemberName);
10730     MemberLookup.addDecl(Field);
10731     MemberLookup.resolveKind();
10732     MemberBuilder From(MoveOther, OtherRefType,
10733                        /*IsArrow=*/false, MemberLookup);
10734     MemberBuilder To(This, getCurrentThisType(),
10735                      /*IsArrow=*/true, MemberLookup);
10736 
10737     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10738         "Member reference with rvalue base must be rvalue except for reference "
10739         "members, which aren't allowed for move assignment.");
10740 
10741     // Build the move of this field.
10742     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10743                                             To, From,
10744                                             /*CopyingBaseSubobject=*/false,
10745                                             /*Copying=*/false);
10746     if (Move.isInvalid()) {
10747       Diag(CurrentLocation, diag::note_member_synthesized_at)
10748         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10749       MoveAssignOperator->setInvalidDecl();
10750       return;
10751     }
10752 
10753     // Success! Record the copy.
10754     Statements.push_back(Move.getAs<Stmt>());
10755   }
10756 
10757   if (!Invalid) {
10758     // Add a "return *this;"
10759     ExprResult ThisObj =
10760         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10761 
10762     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10763     if (Return.isInvalid())
10764       Invalid = true;
10765     else {
10766       Statements.push_back(Return.getAs<Stmt>());
10767 
10768       if (Trap.hasErrorOccurred()) {
10769         Diag(CurrentLocation, diag::note_member_synthesized_at)
10770           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10771         Invalid = true;
10772       }
10773     }
10774   }
10775 
10776   // The exception specification is needed because we are defining the
10777   // function.
10778   ResolveExceptionSpec(CurrentLocation,
10779                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10780 
10781   if (Invalid) {
10782     MoveAssignOperator->setInvalidDecl();
10783     return;
10784   }
10785 
10786   StmtResult Body;
10787   {
10788     CompoundScopeRAII CompoundScope(*this);
10789     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10790                              /*isStmtExpr=*/false);
10791     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10792   }
10793   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10794 
10795   if (ASTMutationListener *L = getASTMutationListener()) {
10796     L->CompletedImplicitDefinition(MoveAssignOperator);
10797   }
10798 }
10799 
10800 Sema::ImplicitExceptionSpecification
10801 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10802   CXXRecordDecl *ClassDecl = MD->getParent();
10803 
10804   ImplicitExceptionSpecification ExceptSpec(*this);
10805   if (ClassDecl->isInvalidDecl())
10806     return ExceptSpec;
10807 
10808   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10809   assert(T->getNumParams() >= 1 && "not a copy ctor");
10810   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10811 
10812   // C++ [except.spec]p14:
10813   //   An implicitly declared special member function (Clause 12) shall have an
10814   //   exception-specification. [...]
10815   for (const auto &Base : ClassDecl->bases()) {
10816     // Virtual bases are handled below.
10817     if (Base.isVirtual())
10818       continue;
10819 
10820     CXXRecordDecl *BaseClassDecl
10821       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10822     if (CXXConstructorDecl *CopyConstructor =
10823           LookupCopyingConstructor(BaseClassDecl, Quals))
10824       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10825   }
10826   for (const auto &Base : ClassDecl->vbases()) {
10827     CXXRecordDecl *BaseClassDecl
10828       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10829     if (CXXConstructorDecl *CopyConstructor =
10830           LookupCopyingConstructor(BaseClassDecl, Quals))
10831       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10832   }
10833   for (const auto *Field : ClassDecl->fields()) {
10834     QualType FieldType = Context.getBaseElementType(Field->getType());
10835     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10836       if (CXXConstructorDecl *CopyConstructor =
10837               LookupCopyingConstructor(FieldClassDecl,
10838                                        Quals | FieldType.getCVRQualifiers()))
10839       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10840     }
10841   }
10842 
10843   return ExceptSpec;
10844 }
10845 
10846 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10847                                                     CXXRecordDecl *ClassDecl) {
10848   // C++ [class.copy]p4:
10849   //   If the class definition does not explicitly declare a copy
10850   //   constructor, one is declared implicitly.
10851   assert(ClassDecl->needsImplicitCopyConstructor());
10852 
10853   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10854   if (DSM.isAlreadyBeingDeclared())
10855     return nullptr;
10856 
10857   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10858   QualType ArgType = ClassType;
10859   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10860   if (Const)
10861     ArgType = ArgType.withConst();
10862   ArgType = Context.getLValueReferenceType(ArgType);
10863 
10864   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10865                                                      CXXCopyConstructor,
10866                                                      Const);
10867 
10868   DeclarationName Name
10869     = Context.DeclarationNames.getCXXConstructorName(
10870                                            Context.getCanonicalType(ClassType));
10871   SourceLocation ClassLoc = ClassDecl->getLocation();
10872   DeclarationNameInfo NameInfo(Name, ClassLoc);
10873 
10874   //   An implicitly-declared copy constructor is an inline public
10875   //   member of its class.
10876   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10877       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10878       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10879       Constexpr);
10880   CopyConstructor->setAccess(AS_public);
10881   CopyConstructor->setDefaulted();
10882 
10883   if (getLangOpts().CUDA) {
10884     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10885                                             CopyConstructor,
10886                                             /* ConstRHS */ Const,
10887                                             /* Diagnose */ false);
10888   }
10889 
10890   // Build an exception specification pointing back at this member.
10891   FunctionProtoType::ExtProtoInfo EPI =
10892       getImplicitMethodEPI(*this, CopyConstructor);
10893   CopyConstructor->setType(
10894       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10895 
10896   // Add the parameter to the constructor.
10897   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10898                                                ClassLoc, ClassLoc,
10899                                                /*IdentifierInfo=*/nullptr,
10900                                                ArgType, /*TInfo=*/nullptr,
10901                                                SC_None, nullptr);
10902   CopyConstructor->setParams(FromParam);
10903 
10904   CopyConstructor->setTrivial(
10905     ClassDecl->needsOverloadResolutionForCopyConstructor()
10906       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10907       : ClassDecl->hasTrivialCopyConstructor());
10908 
10909   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10910     SetDeclDeleted(CopyConstructor, ClassLoc);
10911 
10912   // Note that we have declared this constructor.
10913   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10914 
10915   if (Scope *S = getScopeForContext(ClassDecl))
10916     PushOnScopeChains(CopyConstructor, S, false);
10917   ClassDecl->addDecl(CopyConstructor);
10918 
10919   return CopyConstructor;
10920 }
10921 
10922 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10923                                    CXXConstructorDecl *CopyConstructor) {
10924   assert((CopyConstructor->isDefaulted() &&
10925           CopyConstructor->isCopyConstructor() &&
10926           !CopyConstructor->doesThisDeclarationHaveABody() &&
10927           !CopyConstructor->isDeleted()) &&
10928          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10929 
10930   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10931   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10932 
10933   // C++11 [class.copy]p7:
10934   //   The [definition of an implicitly declared copy constructor] is
10935   //   deprecated if the class has a user-declared copy assignment operator
10936   //   or a user-declared destructor.
10937   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10938     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10939 
10940   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10941   DiagnosticErrorTrap Trap(Diags);
10942 
10943   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10944       Trap.hasErrorOccurred()) {
10945     Diag(CurrentLocation, diag::note_member_synthesized_at)
10946       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10947     CopyConstructor->setInvalidDecl();
10948   }  else {
10949     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10950                              ? CopyConstructor->getLocEnd()
10951                              : CopyConstructor->getLocation();
10952     Sema::CompoundScopeRAII CompoundScope(*this);
10953     CopyConstructor->setBody(
10954         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10955   }
10956 
10957   // The exception specification is needed because we are defining the
10958   // function.
10959   ResolveExceptionSpec(CurrentLocation,
10960                        CopyConstructor->getType()->castAs<FunctionProtoType>());
10961 
10962   CopyConstructor->markUsed(Context);
10963   MarkVTableUsed(CurrentLocation, ClassDecl);
10964 
10965   if (ASTMutationListener *L = getASTMutationListener()) {
10966     L->CompletedImplicitDefinition(CopyConstructor);
10967   }
10968 }
10969 
10970 Sema::ImplicitExceptionSpecification
10971 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10972   CXXRecordDecl *ClassDecl = MD->getParent();
10973 
10974   // C++ [except.spec]p14:
10975   //   An implicitly declared special member function (Clause 12) shall have an
10976   //   exception-specification. [...]
10977   ImplicitExceptionSpecification ExceptSpec(*this);
10978   if (ClassDecl->isInvalidDecl())
10979     return ExceptSpec;
10980 
10981   // Direct base-class constructors.
10982   for (const auto &B : ClassDecl->bases()) {
10983     if (B.isVirtual()) // Handled below.
10984       continue;
10985 
10986     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10987       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10988       CXXConstructorDecl *Constructor =
10989           LookupMovingConstructor(BaseClassDecl, 0);
10990       // If this is a deleted function, add it anyway. This might be conformant
10991       // with the standard. This might not. I'm not sure. It might not matter.
10992       if (Constructor)
10993         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10994     }
10995   }
10996 
10997   // Virtual base-class constructors.
10998   for (const auto &B : ClassDecl->vbases()) {
10999     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11000       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11001       CXXConstructorDecl *Constructor =
11002           LookupMovingConstructor(BaseClassDecl, 0);
11003       // If this is a deleted function, add it anyway. This might be conformant
11004       // with the standard. This might not. I'm not sure. It might not matter.
11005       if (Constructor)
11006         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11007     }
11008   }
11009 
11010   // Field constructors.
11011   for (const auto *F : ClassDecl->fields()) {
11012     QualType FieldType = Context.getBaseElementType(F->getType());
11013     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11014       CXXConstructorDecl *Constructor =
11015           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11016       // If this is a deleted function, add it anyway. This might be conformant
11017       // with the standard. This might not. I'm not sure. It might not matter.
11018       // In particular, the problem is that this function never gets called. It
11019       // might just be ill-formed because this function attempts to refer to
11020       // a deleted function here.
11021       if (Constructor)
11022         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11023     }
11024   }
11025 
11026   return ExceptSpec;
11027 }
11028 
11029 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11030                                                     CXXRecordDecl *ClassDecl) {
11031   assert(ClassDecl->needsImplicitMoveConstructor());
11032 
11033   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11034   if (DSM.isAlreadyBeingDeclared())
11035     return nullptr;
11036 
11037   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11038   QualType ArgType = Context.getRValueReferenceType(ClassType);
11039 
11040   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11041                                                      CXXMoveConstructor,
11042                                                      false);
11043 
11044   DeclarationName Name
11045     = Context.DeclarationNames.getCXXConstructorName(
11046                                            Context.getCanonicalType(ClassType));
11047   SourceLocation ClassLoc = ClassDecl->getLocation();
11048   DeclarationNameInfo NameInfo(Name, ClassLoc);
11049 
11050   // C++11 [class.copy]p11:
11051   //   An implicitly-declared copy/move constructor is an inline public
11052   //   member of its class.
11053   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11054       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11055       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11056       Constexpr);
11057   MoveConstructor->setAccess(AS_public);
11058   MoveConstructor->setDefaulted();
11059 
11060   if (getLangOpts().CUDA) {
11061     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11062                                             MoveConstructor,
11063                                             /* ConstRHS */ false,
11064                                             /* Diagnose */ false);
11065   }
11066 
11067   // Build an exception specification pointing back at this member.
11068   FunctionProtoType::ExtProtoInfo EPI =
11069       getImplicitMethodEPI(*this, MoveConstructor);
11070   MoveConstructor->setType(
11071       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11072 
11073   // Add the parameter to the constructor.
11074   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11075                                                ClassLoc, ClassLoc,
11076                                                /*IdentifierInfo=*/nullptr,
11077                                                ArgType, /*TInfo=*/nullptr,
11078                                                SC_None, nullptr);
11079   MoveConstructor->setParams(FromParam);
11080 
11081   MoveConstructor->setTrivial(
11082     ClassDecl->needsOverloadResolutionForMoveConstructor()
11083       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11084       : ClassDecl->hasTrivialMoveConstructor());
11085 
11086   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11087     ClassDecl->setImplicitMoveConstructorIsDeleted();
11088     SetDeclDeleted(MoveConstructor, ClassLoc);
11089   }
11090 
11091   // Note that we have declared this constructor.
11092   ++ASTContext::NumImplicitMoveConstructorsDeclared;
11093 
11094   if (Scope *S = getScopeForContext(ClassDecl))
11095     PushOnScopeChains(MoveConstructor, S, false);
11096   ClassDecl->addDecl(MoveConstructor);
11097 
11098   return MoveConstructor;
11099 }
11100 
11101 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11102                                    CXXConstructorDecl *MoveConstructor) {
11103   assert((MoveConstructor->isDefaulted() &&
11104           MoveConstructor->isMoveConstructor() &&
11105           !MoveConstructor->doesThisDeclarationHaveABody() &&
11106           !MoveConstructor->isDeleted()) &&
11107          "DefineImplicitMoveConstructor - call it for implicit move ctor");
11108 
11109   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11110   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11111 
11112   SynthesizedFunctionScope Scope(*this, MoveConstructor);
11113   DiagnosticErrorTrap Trap(Diags);
11114 
11115   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11116       Trap.hasErrorOccurred()) {
11117     Diag(CurrentLocation, diag::note_member_synthesized_at)
11118       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11119     MoveConstructor->setInvalidDecl();
11120   }  else {
11121     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11122                              ? MoveConstructor->getLocEnd()
11123                              : MoveConstructor->getLocation();
11124     Sema::CompoundScopeRAII CompoundScope(*this);
11125     MoveConstructor->setBody(ActOnCompoundStmt(
11126         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11127   }
11128 
11129   // The exception specification is needed because we are defining the
11130   // function.
11131   ResolveExceptionSpec(CurrentLocation,
11132                        MoveConstructor->getType()->castAs<FunctionProtoType>());
11133 
11134   MoveConstructor->markUsed(Context);
11135   MarkVTableUsed(CurrentLocation, ClassDecl);
11136 
11137   if (ASTMutationListener *L = getASTMutationListener()) {
11138     L->CompletedImplicitDefinition(MoveConstructor);
11139   }
11140 }
11141 
11142 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
11143   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11144 }
11145 
11146 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
11147                             SourceLocation CurrentLocation,
11148                             CXXConversionDecl *Conv) {
11149   CXXRecordDecl *Lambda = Conv->getParent();
11150   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11151   // If we are defining a specialization of a conversion to function-ptr
11152   // cache the deduced template arguments for this specialization
11153   // so that we can use them to retrieve the corresponding call-operator
11154   // and static-invoker.
11155   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11156 
11157   // Retrieve the corresponding call-operator specialization.
11158   if (Lambda->isGenericLambda()) {
11159     assert(Conv->isFunctionTemplateSpecialization());
11160     FunctionTemplateDecl *CallOpTemplate =
11161         CallOp->getDescribedFunctionTemplate();
11162     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11163     void *InsertPos = nullptr;
11164     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11165                                                 DeducedTemplateArgs->asArray(),
11166                                                 InsertPos);
11167     assert(CallOpSpec &&
11168           "Conversion operator must have a corresponding call operator");
11169     CallOp = cast<CXXMethodDecl>(CallOpSpec);
11170   }
11171   // Mark the call operator referenced (and add to pending instantiations
11172   // if necessary).
11173   // For both the conversion and static-invoker template specializations
11174   // we construct their body's in this function, so no need to add them
11175   // to the PendingInstantiations.
11176   MarkFunctionReferenced(CurrentLocation, CallOp);
11177 
11178   SynthesizedFunctionScope Scope(*this, Conv);
11179   DiagnosticErrorTrap Trap(Diags);
11180 
11181   // Retrieve the static invoker...
11182   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11183   // ... and get the corresponding specialization for a generic lambda.
11184   if (Lambda->isGenericLambda()) {
11185     assert(DeducedTemplateArgs &&
11186       "Must have deduced template arguments from Conversion Operator");
11187     FunctionTemplateDecl *InvokeTemplate =
11188                           Invoker->getDescribedFunctionTemplate();
11189     void *InsertPos = nullptr;
11190     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11191                                                 DeducedTemplateArgs->asArray(),
11192                                                 InsertPos);
11193     assert(InvokeSpec &&
11194       "Must have a corresponding static invoker specialization");
11195     Invoker = cast<CXXMethodDecl>(InvokeSpec);
11196   }
11197   // Construct the body of the conversion function { return __invoke; }.
11198   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11199                                         VK_LValue, Conv->getLocation()).get();
11200    assert(FunctionRef && "Can't refer to __invoke function?");
11201    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11202    Conv->setBody(new (Context) CompoundStmt(Context, Return,
11203                                             Conv->getLocation(),
11204                                             Conv->getLocation()));
11205 
11206   Conv->markUsed(Context);
11207   Conv->setReferenced();
11208 
11209   // Fill in the __invoke function with a dummy implementation. IR generation
11210   // will fill in the actual details.
11211   Invoker->markUsed(Context);
11212   Invoker->setReferenced();
11213   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11214 
11215   if (ASTMutationListener *L = getASTMutationListener()) {
11216     L->CompletedImplicitDefinition(Conv);
11217     L->CompletedImplicitDefinition(Invoker);
11218    }
11219 }
11220 
11221 
11222 
11223 void Sema::DefineImplicitLambdaToBlockPointerConversion(
11224        SourceLocation CurrentLocation,
11225        CXXConversionDecl *Conv)
11226 {
11227   assert(!Conv->getParent()->isGenericLambda());
11228 
11229   Conv->markUsed(Context);
11230 
11231   SynthesizedFunctionScope Scope(*this, Conv);
11232   DiagnosticErrorTrap Trap(Diags);
11233 
11234   // Copy-initialize the lambda object as needed to capture it.
11235   Expr *This = ActOnCXXThis(CurrentLocation).get();
11236   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11237 
11238   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11239                                                         Conv->getLocation(),
11240                                                         Conv, DerefThis);
11241 
11242   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11243   // behavior.  Note that only the general conversion function does this
11244   // (since it's unusable otherwise); in the case where we inline the
11245   // block literal, it has block literal lifetime semantics.
11246   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11247     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11248                                           CK_CopyAndAutoreleaseBlockObject,
11249                                           BuildBlock.get(), nullptr, VK_RValue);
11250 
11251   if (BuildBlock.isInvalid()) {
11252     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11253     Conv->setInvalidDecl();
11254     return;
11255   }
11256 
11257   // Create the return statement that returns the block from the conversion
11258   // function.
11259   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11260   if (Return.isInvalid()) {
11261     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11262     Conv->setInvalidDecl();
11263     return;
11264   }
11265 
11266   // Set the body of the conversion function.
11267   Stmt *ReturnS = Return.get();
11268   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11269                                            Conv->getLocation(),
11270                                            Conv->getLocation()));
11271 
11272   // We're done; notify the mutation listener, if any.
11273   if (ASTMutationListener *L = getASTMutationListener()) {
11274     L->CompletedImplicitDefinition(Conv);
11275   }
11276 }
11277 
11278 /// \brief Determine whether the given list arguments contains exactly one
11279 /// "real" (non-default) argument.
11280 static bool hasOneRealArgument(MultiExprArg Args) {
11281   switch (Args.size()) {
11282   case 0:
11283     return false;
11284 
11285   default:
11286     if (!Args[1]->isDefaultArgument())
11287       return false;
11288 
11289     // fall through
11290   case 1:
11291     return !Args[0]->isDefaultArgument();
11292   }
11293 
11294   return false;
11295 }
11296 
11297 ExprResult
11298 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11299                             CXXConstructorDecl *Constructor,
11300                             MultiExprArg ExprArgs,
11301                             bool HadMultipleCandidates,
11302                             bool IsListInitialization,
11303                             bool IsStdInitListInitialization,
11304                             bool RequiresZeroInit,
11305                             unsigned ConstructKind,
11306                             SourceRange ParenRange) {
11307   bool Elidable = false;
11308 
11309   // C++0x [class.copy]p34:
11310   //   When certain criteria are met, an implementation is allowed to
11311   //   omit the copy/move construction of a class object, even if the
11312   //   copy/move constructor and/or destructor for the object have
11313   //   side effects. [...]
11314   //     - when a temporary class object that has not been bound to a
11315   //       reference (12.2) would be copied/moved to a class object
11316   //       with the same cv-unqualified type, the copy/move operation
11317   //       can be omitted by constructing the temporary object
11318   //       directly into the target of the omitted copy/move
11319   if (ConstructKind == CXXConstructExpr::CK_Complete &&
11320       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11321     Expr *SubExpr = ExprArgs[0];
11322     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11323   }
11324 
11325   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11326                                Elidable, ExprArgs, HadMultipleCandidates,
11327                                IsListInitialization,
11328                                IsStdInitListInitialization, RequiresZeroInit,
11329                                ConstructKind, ParenRange);
11330 }
11331 
11332 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11333 /// including handling of its default argument expressions.
11334 ExprResult
11335 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11336                             CXXConstructorDecl *Constructor, bool Elidable,
11337                             MultiExprArg ExprArgs,
11338                             bool HadMultipleCandidates,
11339                             bool IsListInitialization,
11340                             bool IsStdInitListInitialization,
11341                             bool RequiresZeroInit,
11342                             unsigned ConstructKind,
11343                             SourceRange ParenRange) {
11344   MarkFunctionReferenced(ConstructLoc, Constructor);
11345   return CXXConstructExpr::Create(
11346       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11347       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11348       RequiresZeroInit,
11349       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11350       ParenRange);
11351 }
11352 
11353 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11354   assert(Field->hasInClassInitializer());
11355 
11356   // If we already have the in-class initializer nothing needs to be done.
11357   if (Field->getInClassInitializer())
11358     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11359 
11360   // Maybe we haven't instantiated the in-class initializer. Go check the
11361   // pattern FieldDecl to see if it has one.
11362   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11363 
11364   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11365     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11366     DeclContext::lookup_result Lookup =
11367         ClassPattern->lookup(Field->getDeclName());
11368     assert(Lookup.size() == 1);
11369     FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11370     if (InstantiateInClassInitializer(Loc, Field, Pattern,
11371                                       getTemplateInstantiationArgs(Field)))
11372       return ExprError();
11373     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11374   }
11375 
11376   // DR1351:
11377   //   If the brace-or-equal-initializer of a non-static data member
11378   //   invokes a defaulted default constructor of its class or of an
11379   //   enclosing class in a potentially evaluated subexpression, the
11380   //   program is ill-formed.
11381   //
11382   // This resolution is unworkable: the exception specification of the
11383   // default constructor can be needed in an unevaluated context, in
11384   // particular, in the operand of a noexcept-expression, and we can be
11385   // unable to compute an exception specification for an enclosed class.
11386   //
11387   // Any attempt to resolve the exception specification of a defaulted default
11388   // constructor before the initializer is lexically complete will ultimately
11389   // come here at which point we can diagnose it.
11390   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11391   if (OutermostClass == ParentRD) {
11392     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11393         << ParentRD << Field;
11394   } else {
11395     Diag(Field->getLocEnd(),
11396          diag::err_in_class_initializer_not_yet_parsed_outer_class)
11397         << ParentRD << OutermostClass << Field;
11398   }
11399 
11400   return ExprError();
11401 }
11402 
11403 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11404   if (VD->isInvalidDecl()) return;
11405 
11406   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11407   if (ClassDecl->isInvalidDecl()) return;
11408   if (ClassDecl->hasIrrelevantDestructor()) return;
11409   if (ClassDecl->isDependentContext()) return;
11410 
11411   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11412   MarkFunctionReferenced(VD->getLocation(), Destructor);
11413   CheckDestructorAccess(VD->getLocation(), Destructor,
11414                         PDiag(diag::err_access_dtor_var)
11415                         << VD->getDeclName()
11416                         << VD->getType());
11417   DiagnoseUseOfDecl(Destructor, VD->getLocation());
11418 
11419   if (Destructor->isTrivial()) return;
11420   if (!VD->hasGlobalStorage()) return;
11421 
11422   // Emit warning for non-trivial dtor in global scope (a real global,
11423   // class-static, function-static).
11424   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11425 
11426   // TODO: this should be re-enabled for static locals by !CXAAtExit
11427   if (!VD->isStaticLocal())
11428     Diag(VD->getLocation(), diag::warn_global_destructor);
11429 }
11430 
11431 /// \brief Given a constructor and the set of arguments provided for the
11432 /// constructor, convert the arguments and add any required default arguments
11433 /// to form a proper call to this constructor.
11434 ///
11435 /// \returns true if an error occurred, false otherwise.
11436 bool
11437 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11438                               MultiExprArg ArgsPtr,
11439                               SourceLocation Loc,
11440                               SmallVectorImpl<Expr*> &ConvertedArgs,
11441                               bool AllowExplicit,
11442                               bool IsListInitialization) {
11443   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11444   unsigned NumArgs = ArgsPtr.size();
11445   Expr **Args = ArgsPtr.data();
11446 
11447   const FunctionProtoType *Proto
11448     = Constructor->getType()->getAs<FunctionProtoType>();
11449   assert(Proto && "Constructor without a prototype?");
11450   unsigned NumParams = Proto->getNumParams();
11451 
11452   // If too few arguments are available, we'll fill in the rest with defaults.
11453   if (NumArgs < NumParams)
11454     ConvertedArgs.reserve(NumParams);
11455   else
11456     ConvertedArgs.reserve(NumArgs);
11457 
11458   VariadicCallType CallType =
11459     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11460   SmallVector<Expr *, 8> AllArgs;
11461   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11462                                         Proto, 0,
11463                                         llvm::makeArrayRef(Args, NumArgs),
11464                                         AllArgs,
11465                                         CallType, AllowExplicit,
11466                                         IsListInitialization);
11467   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11468 
11469   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11470 
11471   CheckConstructorCall(Constructor,
11472                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11473                        Proto, Loc);
11474 
11475   return Invalid;
11476 }
11477 
11478 static inline bool
11479 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11480                                        const FunctionDecl *FnDecl) {
11481   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11482   if (isa<NamespaceDecl>(DC)) {
11483     return SemaRef.Diag(FnDecl->getLocation(),
11484                         diag::err_operator_new_delete_declared_in_namespace)
11485       << FnDecl->getDeclName();
11486   }
11487 
11488   if (isa<TranslationUnitDecl>(DC) &&
11489       FnDecl->getStorageClass() == SC_Static) {
11490     return SemaRef.Diag(FnDecl->getLocation(),
11491                         diag::err_operator_new_delete_declared_static)
11492       << FnDecl->getDeclName();
11493   }
11494 
11495   return false;
11496 }
11497 
11498 static inline bool
11499 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11500                             CanQualType ExpectedResultType,
11501                             CanQualType ExpectedFirstParamType,
11502                             unsigned DependentParamTypeDiag,
11503                             unsigned InvalidParamTypeDiag) {
11504   QualType ResultType =
11505       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11506 
11507   // Check that the result type is not dependent.
11508   if (ResultType->isDependentType())
11509     return SemaRef.Diag(FnDecl->getLocation(),
11510                         diag::err_operator_new_delete_dependent_result_type)
11511     << FnDecl->getDeclName() << ExpectedResultType;
11512 
11513   // Check that the result type is what we expect.
11514   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11515     return SemaRef.Diag(FnDecl->getLocation(),
11516                         diag::err_operator_new_delete_invalid_result_type)
11517     << FnDecl->getDeclName() << ExpectedResultType;
11518 
11519   // A function template must have at least 2 parameters.
11520   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11521     return SemaRef.Diag(FnDecl->getLocation(),
11522                       diag::err_operator_new_delete_template_too_few_parameters)
11523         << FnDecl->getDeclName();
11524 
11525   // The function decl must have at least 1 parameter.
11526   if (FnDecl->getNumParams() == 0)
11527     return SemaRef.Diag(FnDecl->getLocation(),
11528                         diag::err_operator_new_delete_too_few_parameters)
11529       << FnDecl->getDeclName();
11530 
11531   // Check the first parameter type is not dependent.
11532   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11533   if (FirstParamType->isDependentType())
11534     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11535       << FnDecl->getDeclName() << ExpectedFirstParamType;
11536 
11537   // Check that the first parameter type is what we expect.
11538   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11539       ExpectedFirstParamType)
11540     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11541     << FnDecl->getDeclName() << ExpectedFirstParamType;
11542 
11543   return false;
11544 }
11545 
11546 static bool
11547 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11548   // C++ [basic.stc.dynamic.allocation]p1:
11549   //   A program is ill-formed if an allocation function is declared in a
11550   //   namespace scope other than global scope or declared static in global
11551   //   scope.
11552   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11553     return true;
11554 
11555   CanQualType SizeTy =
11556     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11557 
11558   // C++ [basic.stc.dynamic.allocation]p1:
11559   //  The return type shall be void*. The first parameter shall have type
11560   //  std::size_t.
11561   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11562                                   SizeTy,
11563                                   diag::err_operator_new_dependent_param_type,
11564                                   diag::err_operator_new_param_type))
11565     return true;
11566 
11567   // C++ [basic.stc.dynamic.allocation]p1:
11568   //  The first parameter shall not have an associated default argument.
11569   if (FnDecl->getParamDecl(0)->hasDefaultArg())
11570     return SemaRef.Diag(FnDecl->getLocation(),
11571                         diag::err_operator_new_default_arg)
11572       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11573 
11574   return false;
11575 }
11576 
11577 static bool
11578 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11579   // C++ [basic.stc.dynamic.deallocation]p1:
11580   //   A program is ill-formed if deallocation functions are declared in a
11581   //   namespace scope other than global scope or declared static in global
11582   //   scope.
11583   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11584     return true;
11585 
11586   // C++ [basic.stc.dynamic.deallocation]p2:
11587   //   Each deallocation function shall return void and its first parameter
11588   //   shall be void*.
11589   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11590                                   SemaRef.Context.VoidPtrTy,
11591                                  diag::err_operator_delete_dependent_param_type,
11592                                  diag::err_operator_delete_param_type))
11593     return true;
11594 
11595   return false;
11596 }
11597 
11598 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11599 /// of this overloaded operator is well-formed. If so, returns false;
11600 /// otherwise, emits appropriate diagnostics and returns true.
11601 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11602   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11603          "Expected an overloaded operator declaration");
11604 
11605   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11606 
11607   // C++ [over.oper]p5:
11608   //   The allocation and deallocation functions, operator new,
11609   //   operator new[], operator delete and operator delete[], are
11610   //   described completely in 3.7.3. The attributes and restrictions
11611   //   found in the rest of this subclause do not apply to them unless
11612   //   explicitly stated in 3.7.3.
11613   if (Op == OO_Delete || Op == OO_Array_Delete)
11614     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11615 
11616   if (Op == OO_New || Op == OO_Array_New)
11617     return CheckOperatorNewDeclaration(*this, FnDecl);
11618 
11619   // C++ [over.oper]p6:
11620   //   An operator function shall either be a non-static member
11621   //   function or be a non-member function and have at least one
11622   //   parameter whose type is a class, a reference to a class, an
11623   //   enumeration, or a reference to an enumeration.
11624   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11625     if (MethodDecl->isStatic())
11626       return Diag(FnDecl->getLocation(),
11627                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11628   } else {
11629     bool ClassOrEnumParam = false;
11630     for (auto Param : FnDecl->params()) {
11631       QualType ParamType = Param->getType().getNonReferenceType();
11632       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11633           ParamType->isEnumeralType()) {
11634         ClassOrEnumParam = true;
11635         break;
11636       }
11637     }
11638 
11639     if (!ClassOrEnumParam)
11640       return Diag(FnDecl->getLocation(),
11641                   diag::err_operator_overload_needs_class_or_enum)
11642         << FnDecl->getDeclName();
11643   }
11644 
11645   // C++ [over.oper]p8:
11646   //   An operator function cannot have default arguments (8.3.6),
11647   //   except where explicitly stated below.
11648   //
11649   // Only the function-call operator allows default arguments
11650   // (C++ [over.call]p1).
11651   if (Op != OO_Call) {
11652     for (auto Param : FnDecl->params()) {
11653       if (Param->hasDefaultArg())
11654         return Diag(Param->getLocation(),
11655                     diag::err_operator_overload_default_arg)
11656           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11657     }
11658   }
11659 
11660   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11661     { false, false, false }
11662 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11663     , { Unary, Binary, MemberOnly }
11664 #include "clang/Basic/OperatorKinds.def"
11665   };
11666 
11667   bool CanBeUnaryOperator = OperatorUses[Op][0];
11668   bool CanBeBinaryOperator = OperatorUses[Op][1];
11669   bool MustBeMemberOperator = OperatorUses[Op][2];
11670 
11671   // C++ [over.oper]p8:
11672   //   [...] Operator functions cannot have more or fewer parameters
11673   //   than the number required for the corresponding operator, as
11674   //   described in the rest of this subclause.
11675   unsigned NumParams = FnDecl->getNumParams()
11676                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11677   if (Op != OO_Call &&
11678       ((NumParams == 1 && !CanBeUnaryOperator) ||
11679        (NumParams == 2 && !CanBeBinaryOperator) ||
11680        (NumParams < 1) || (NumParams > 2))) {
11681     // We have the wrong number of parameters.
11682     unsigned ErrorKind;
11683     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11684       ErrorKind = 2;  // 2 -> unary or binary.
11685     } else if (CanBeUnaryOperator) {
11686       ErrorKind = 0;  // 0 -> unary
11687     } else {
11688       assert(CanBeBinaryOperator &&
11689              "All non-call overloaded operators are unary or binary!");
11690       ErrorKind = 1;  // 1 -> binary
11691     }
11692 
11693     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11694       << FnDecl->getDeclName() << NumParams << ErrorKind;
11695   }
11696 
11697   // Overloaded operators other than operator() cannot be variadic.
11698   if (Op != OO_Call &&
11699       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11700     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11701       << FnDecl->getDeclName();
11702   }
11703 
11704   // Some operators must be non-static member functions.
11705   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11706     return Diag(FnDecl->getLocation(),
11707                 diag::err_operator_overload_must_be_member)
11708       << FnDecl->getDeclName();
11709   }
11710 
11711   // C++ [over.inc]p1:
11712   //   The user-defined function called operator++ implements the
11713   //   prefix and postfix ++ operator. If this function is a member
11714   //   function with no parameters, or a non-member function with one
11715   //   parameter of class or enumeration type, it defines the prefix
11716   //   increment operator ++ for objects of that type. If the function
11717   //   is a member function with one parameter (which shall be of type
11718   //   int) or a non-member function with two parameters (the second
11719   //   of which shall be of type int), it defines the postfix
11720   //   increment operator ++ for objects of that type.
11721   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11722     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11723     QualType ParamType = LastParam->getType();
11724 
11725     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11726         !ParamType->isDependentType())
11727       return Diag(LastParam->getLocation(),
11728                   diag::err_operator_overload_post_incdec_must_be_int)
11729         << LastParam->getType() << (Op == OO_MinusMinus);
11730   }
11731 
11732   return false;
11733 }
11734 
11735 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11736 /// of this literal operator function is well-formed. If so, returns
11737 /// false; otherwise, emits appropriate diagnostics and returns true.
11738 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11739   if (isa<CXXMethodDecl>(FnDecl)) {
11740     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11741       << FnDecl->getDeclName();
11742     return true;
11743   }
11744 
11745   if (FnDecl->isExternC()) {
11746     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11747     return true;
11748   }
11749 
11750   bool Valid = false;
11751 
11752   // This might be the definition of a literal operator template.
11753   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11754   // This might be a specialization of a literal operator template.
11755   if (!TpDecl)
11756     TpDecl = FnDecl->getPrimaryTemplate();
11757 
11758   // template <char...> type operator "" name() and
11759   // template <class T, T...> type operator "" name() are the only valid
11760   // template signatures, and the only valid signatures with no parameters.
11761   if (TpDecl) {
11762     if (FnDecl->param_size() == 0) {
11763       // Must have one or two template parameters
11764       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11765       if (Params->size() == 1) {
11766         NonTypeTemplateParmDecl *PmDecl =
11767           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11768 
11769         // The template parameter must be a char parameter pack.
11770         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11771             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11772           Valid = true;
11773       } else if (Params->size() == 2) {
11774         TemplateTypeParmDecl *PmType =
11775           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11776         NonTypeTemplateParmDecl *PmArgs =
11777           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11778 
11779         // The second template parameter must be a parameter pack with the
11780         // first template parameter as its type.
11781         if (PmType && PmArgs &&
11782             !PmType->isTemplateParameterPack() &&
11783             PmArgs->isTemplateParameterPack()) {
11784           const TemplateTypeParmType *TArgs =
11785             PmArgs->getType()->getAs<TemplateTypeParmType>();
11786           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11787               TArgs->getIndex() == PmType->getIndex()) {
11788             Valid = true;
11789             if (ActiveTemplateInstantiations.empty())
11790               Diag(FnDecl->getLocation(),
11791                    diag::ext_string_literal_operator_template);
11792           }
11793         }
11794       }
11795     }
11796   } else if (FnDecl->param_size()) {
11797     // Check the first parameter
11798     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11799 
11800     QualType T = (*Param)->getType().getUnqualifiedType();
11801 
11802     // unsigned long long int, long double, and any character type are allowed
11803     // as the only parameters.
11804     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11805         Context.hasSameType(T, Context.LongDoubleTy) ||
11806         Context.hasSameType(T, Context.CharTy) ||
11807         Context.hasSameType(T, Context.WideCharTy) ||
11808         Context.hasSameType(T, Context.Char16Ty) ||
11809         Context.hasSameType(T, Context.Char32Ty)) {
11810       if (++Param == FnDecl->param_end())
11811         Valid = true;
11812       goto FinishedParams;
11813     }
11814 
11815     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11816     const PointerType *PT = T->getAs<PointerType>();
11817     if (!PT)
11818       goto FinishedParams;
11819     T = PT->getPointeeType();
11820     if (!T.isConstQualified() || T.isVolatileQualified())
11821       goto FinishedParams;
11822     T = T.getUnqualifiedType();
11823 
11824     // Move on to the second parameter;
11825     ++Param;
11826 
11827     // If there is no second parameter, the first must be a const char *
11828     if (Param == FnDecl->param_end()) {
11829       if (Context.hasSameType(T, Context.CharTy))
11830         Valid = true;
11831       goto FinishedParams;
11832     }
11833 
11834     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11835     // are allowed as the first parameter to a two-parameter function
11836     if (!(Context.hasSameType(T, Context.CharTy) ||
11837           Context.hasSameType(T, Context.WideCharTy) ||
11838           Context.hasSameType(T, Context.Char16Ty) ||
11839           Context.hasSameType(T, Context.Char32Ty)))
11840       goto FinishedParams;
11841 
11842     // The second and final parameter must be an std::size_t
11843     T = (*Param)->getType().getUnqualifiedType();
11844     if (Context.hasSameType(T, Context.getSizeType()) &&
11845         ++Param == FnDecl->param_end())
11846       Valid = true;
11847   }
11848 
11849   // FIXME: This diagnostic is absolutely terrible.
11850 FinishedParams:
11851   if (!Valid) {
11852     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11853       << FnDecl->getDeclName();
11854     return true;
11855   }
11856 
11857   // A parameter-declaration-clause containing a default argument is not
11858   // equivalent to any of the permitted forms.
11859   for (auto Param : FnDecl->params()) {
11860     if (Param->hasDefaultArg()) {
11861       Diag(Param->getDefaultArgRange().getBegin(),
11862            diag::err_literal_operator_default_argument)
11863         << Param->getDefaultArgRange();
11864       break;
11865     }
11866   }
11867 
11868   StringRef LiteralName
11869     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11870   if (LiteralName[0] != '_') {
11871     // C++11 [usrlit.suffix]p1:
11872     //   Literal suffix identifiers that do not start with an underscore
11873     //   are reserved for future standardization.
11874     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11875       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11876   }
11877 
11878   return false;
11879 }
11880 
11881 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11882 /// linkage specification, including the language and (if present)
11883 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11884 /// language string literal. LBraceLoc, if valid, provides the location of
11885 /// the '{' brace. Otherwise, this linkage specification does not
11886 /// have any braces.
11887 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11888                                            Expr *LangStr,
11889                                            SourceLocation LBraceLoc) {
11890   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11891   if (!Lit->isAscii()) {
11892     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11893       << LangStr->getSourceRange();
11894     return nullptr;
11895   }
11896 
11897   StringRef Lang = Lit->getString();
11898   LinkageSpecDecl::LanguageIDs Language;
11899   if (Lang == "C")
11900     Language = LinkageSpecDecl::lang_c;
11901   else if (Lang == "C++")
11902     Language = LinkageSpecDecl::lang_cxx;
11903   else {
11904     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11905       << LangStr->getSourceRange();
11906     return nullptr;
11907   }
11908 
11909   // FIXME: Add all the various semantics of linkage specifications
11910 
11911   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11912                                                LangStr->getExprLoc(), Language,
11913                                                LBraceLoc.isValid());
11914   CurContext->addDecl(D);
11915   PushDeclContext(S, D);
11916   return D;
11917 }
11918 
11919 /// ActOnFinishLinkageSpecification - Complete the definition of
11920 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11921 /// valid, it's the position of the closing '}' brace in a linkage
11922 /// specification that uses braces.
11923 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11924                                             Decl *LinkageSpec,
11925                                             SourceLocation RBraceLoc) {
11926   if (RBraceLoc.isValid()) {
11927     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11928     LSDecl->setRBraceLoc(RBraceLoc);
11929   }
11930   PopDeclContext();
11931   return LinkageSpec;
11932 }
11933 
11934 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11935                                   AttributeList *AttrList,
11936                                   SourceLocation SemiLoc) {
11937   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11938   // Attribute declarations appertain to empty declaration so we handle
11939   // them here.
11940   if (AttrList)
11941     ProcessDeclAttributeList(S, ED, AttrList);
11942 
11943   CurContext->addDecl(ED);
11944   return ED;
11945 }
11946 
11947 /// \brief Perform semantic analysis for the variable declaration that
11948 /// occurs within a C++ catch clause, returning the newly-created
11949 /// variable.
11950 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11951                                          TypeSourceInfo *TInfo,
11952                                          SourceLocation StartLoc,
11953                                          SourceLocation Loc,
11954                                          IdentifierInfo *Name) {
11955   bool Invalid = false;
11956   QualType ExDeclType = TInfo->getType();
11957 
11958   // Arrays and functions decay.
11959   if (ExDeclType->isArrayType())
11960     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11961   else if (ExDeclType->isFunctionType())
11962     ExDeclType = Context.getPointerType(ExDeclType);
11963 
11964   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11965   // The exception-declaration shall not denote a pointer or reference to an
11966   // incomplete type, other than [cv] void*.
11967   // N2844 forbids rvalue references.
11968   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11969     Diag(Loc, diag::err_catch_rvalue_ref);
11970     Invalid = true;
11971   }
11972 
11973   QualType BaseType = ExDeclType;
11974   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11975   unsigned DK = diag::err_catch_incomplete;
11976   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11977     BaseType = Ptr->getPointeeType();
11978     Mode = 1;
11979     DK = diag::err_catch_incomplete_ptr;
11980   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11981     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11982     BaseType = Ref->getPointeeType();
11983     Mode = 2;
11984     DK = diag::err_catch_incomplete_ref;
11985   }
11986   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11987       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11988     Invalid = true;
11989 
11990   if (!Invalid && !ExDeclType->isDependentType() &&
11991       RequireNonAbstractType(Loc, ExDeclType,
11992                              diag::err_abstract_type_in_decl,
11993                              AbstractVariableType))
11994     Invalid = true;
11995 
11996   // Only the non-fragile NeXT runtime currently supports C++ catches
11997   // of ObjC types, and no runtime supports catching ObjC types by value.
11998   if (!Invalid && getLangOpts().ObjC1) {
11999     QualType T = ExDeclType;
12000     if (const ReferenceType *RT = T->getAs<ReferenceType>())
12001       T = RT->getPointeeType();
12002 
12003     if (T->isObjCObjectType()) {
12004       Diag(Loc, diag::err_objc_object_catch);
12005       Invalid = true;
12006     } else if (T->isObjCObjectPointerType()) {
12007       // FIXME: should this be a test for macosx-fragile specifically?
12008       if (getLangOpts().ObjCRuntime.isFragile())
12009         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12010     }
12011   }
12012 
12013   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
12014                                     ExDeclType, TInfo, SC_None);
12015   ExDecl->setExceptionVariable(true);
12016 
12017   // In ARC, infer 'retaining' for variables of retainable type.
12018   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
12019     Invalid = true;
12020 
12021   if (!Invalid && !ExDeclType->isDependentType()) {
12022     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
12023       // Insulate this from anything else we might currently be parsing.
12024       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12025 
12026       // C++ [except.handle]p16:
12027       //   The object declared in an exception-declaration or, if the
12028       //   exception-declaration does not specify a name, a temporary (12.2) is
12029       //   copy-initialized (8.5) from the exception object. [...]
12030       //   The object is destroyed when the handler exits, after the destruction
12031       //   of any automatic objects initialized within the handler.
12032       //
12033       // We just pretend to initialize the object with itself, then make sure
12034       // it can be destroyed later.
12035       QualType initType = Context.getExceptionObjectType(ExDeclType);
12036 
12037       InitializedEntity entity =
12038         InitializedEntity::InitializeVariable(ExDecl);
12039       InitializationKind initKind =
12040         InitializationKind::CreateCopy(Loc, SourceLocation());
12041 
12042       Expr *opaqueValue =
12043         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
12044       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12045       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
12046       if (result.isInvalid())
12047         Invalid = true;
12048       else {
12049         // If the constructor used was non-trivial, set this as the
12050         // "initializer".
12051         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
12052         if (!construct->getConstructor()->isTrivial()) {
12053           Expr *init = MaybeCreateExprWithCleanups(construct);
12054           ExDecl->setInit(init);
12055         }
12056 
12057         // And make sure it's destructable.
12058         FinalizeVarWithDestructor(ExDecl, recordType);
12059       }
12060     }
12061   }
12062 
12063   if (Invalid)
12064     ExDecl->setInvalidDecl();
12065 
12066   return ExDecl;
12067 }
12068 
12069 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12070 /// handler.
12071 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
12072   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12073   bool Invalid = D.isInvalidType();
12074 
12075   // Check for unexpanded parameter packs.
12076   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12077                                       UPPC_ExceptionType)) {
12078     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12079                                              D.getIdentifierLoc());
12080     Invalid = true;
12081   }
12082 
12083   IdentifierInfo *II = D.getIdentifier();
12084   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
12085                                              LookupOrdinaryName,
12086                                              ForRedeclaration)) {
12087     // The scope should be freshly made just for us. There is just no way
12088     // it contains any previous declaration, except for function parameters in
12089     // a function-try-block's catch statement.
12090     assert(!S->isDeclScope(PrevDecl));
12091     if (isDeclInScope(PrevDecl, CurContext, S)) {
12092       Diag(D.getIdentifierLoc(), diag::err_redefinition)
12093         << D.getIdentifier();
12094       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12095       Invalid = true;
12096     } else if (PrevDecl->isTemplateParameter())
12097       // Maybe we will complain about the shadowed template parameter.
12098       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12099   }
12100 
12101   if (D.getCXXScopeSpec().isSet() && !Invalid) {
12102     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12103       << D.getCXXScopeSpec().getRange();
12104     Invalid = true;
12105   }
12106 
12107   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12108                                               D.getLocStart(),
12109                                               D.getIdentifierLoc(),
12110                                               D.getIdentifier());
12111   if (Invalid)
12112     ExDecl->setInvalidDecl();
12113 
12114   // Add the exception declaration into this scope.
12115   if (II)
12116     PushOnScopeChains(ExDecl, S);
12117   else
12118     CurContext->addDecl(ExDecl);
12119 
12120   ProcessDeclAttributes(S, ExDecl, D);
12121   return ExDecl;
12122 }
12123 
12124 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12125                                          Expr *AssertExpr,
12126                                          Expr *AssertMessageExpr,
12127                                          SourceLocation RParenLoc) {
12128   StringLiteral *AssertMessage =
12129       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12130 
12131   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
12132     return nullptr;
12133 
12134   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12135                                       AssertMessage, RParenLoc, false);
12136 }
12137 
12138 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12139                                          Expr *AssertExpr,
12140                                          StringLiteral *AssertMessage,
12141                                          SourceLocation RParenLoc,
12142                                          bool Failed) {
12143   assert(AssertExpr != nullptr && "Expected non-null condition");
12144   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12145       !Failed) {
12146     // In a static_assert-declaration, the constant-expression shall be a
12147     // constant expression that can be contextually converted to bool.
12148     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12149     if (Converted.isInvalid())
12150       Failed = true;
12151 
12152     llvm::APSInt Cond;
12153     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12154           diag::err_static_assert_expression_is_not_constant,
12155           /*AllowFold=*/false).isInvalid())
12156       Failed = true;
12157 
12158     if (!Failed && !Cond) {
12159       SmallString<256> MsgBuffer;
12160       llvm::raw_svector_ostream Msg(MsgBuffer);
12161       if (AssertMessage)
12162         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12163       Diag(StaticAssertLoc, diag::err_static_assert_failed)
12164         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12165       Failed = true;
12166     }
12167   }
12168 
12169   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12170                                         AssertExpr, AssertMessage, RParenLoc,
12171                                         Failed);
12172 
12173   CurContext->addDecl(Decl);
12174   return Decl;
12175 }
12176 
12177 /// \brief Perform semantic analysis of the given friend type declaration.
12178 ///
12179 /// \returns A friend declaration that.
12180 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12181                                       SourceLocation FriendLoc,
12182                                       TypeSourceInfo *TSInfo) {
12183   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12184 
12185   QualType T = TSInfo->getType();
12186   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12187 
12188   // C++03 [class.friend]p2:
12189   //   An elaborated-type-specifier shall be used in a friend declaration
12190   //   for a class.*
12191   //
12192   //   * The class-key of the elaborated-type-specifier is required.
12193   if (!ActiveTemplateInstantiations.empty()) {
12194     // Do not complain about the form of friend template types during
12195     // template instantiation; we will already have complained when the
12196     // template was declared.
12197   } else {
12198     if (!T->isElaboratedTypeSpecifier()) {
12199       // If we evaluated the type to a record type, suggest putting
12200       // a tag in front.
12201       if (const RecordType *RT = T->getAs<RecordType>()) {
12202         RecordDecl *RD = RT->getDecl();
12203 
12204         SmallString<16> InsertionText(" ");
12205         InsertionText += RD->getKindName();
12206 
12207         Diag(TypeRange.getBegin(),
12208              getLangOpts().CPlusPlus11 ?
12209                diag::warn_cxx98_compat_unelaborated_friend_type :
12210                diag::ext_unelaborated_friend_type)
12211           << (unsigned) RD->getTagKind()
12212           << T
12213           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12214                                         InsertionText);
12215       } else {
12216         Diag(FriendLoc,
12217              getLangOpts().CPlusPlus11 ?
12218                diag::warn_cxx98_compat_nonclass_type_friend :
12219                diag::ext_nonclass_type_friend)
12220           << T
12221           << TypeRange;
12222       }
12223     } else if (T->getAs<EnumType>()) {
12224       Diag(FriendLoc,
12225            getLangOpts().CPlusPlus11 ?
12226              diag::warn_cxx98_compat_enum_friend :
12227              diag::ext_enum_friend)
12228         << T
12229         << TypeRange;
12230     }
12231 
12232     // C++11 [class.friend]p3:
12233     //   A friend declaration that does not declare a function shall have one
12234     //   of the following forms:
12235     //     friend elaborated-type-specifier ;
12236     //     friend simple-type-specifier ;
12237     //     friend typename-specifier ;
12238     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12239       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12240   }
12241 
12242   //   If the type specifier in a friend declaration designates a (possibly
12243   //   cv-qualified) class type, that class is declared as a friend; otherwise,
12244   //   the friend declaration is ignored.
12245   return FriendDecl::Create(Context, CurContext,
12246                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
12247                             FriendLoc);
12248 }
12249 
12250 /// Handle a friend tag declaration where the scope specifier was
12251 /// templated.
12252 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12253                                     unsigned TagSpec, SourceLocation TagLoc,
12254                                     CXXScopeSpec &SS,
12255                                     IdentifierInfo *Name,
12256                                     SourceLocation NameLoc,
12257                                     AttributeList *Attr,
12258                                     MultiTemplateParamsArg TempParamLists) {
12259   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12260 
12261   bool isExplicitSpecialization = false;
12262   bool Invalid = false;
12263 
12264   if (TemplateParameterList *TemplateParams =
12265           MatchTemplateParametersToScopeSpecifier(
12266               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12267               isExplicitSpecialization, Invalid)) {
12268     if (TemplateParams->size() > 0) {
12269       // This is a declaration of a class template.
12270       if (Invalid)
12271         return nullptr;
12272 
12273       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12274                                 NameLoc, Attr, TemplateParams, AS_public,
12275                                 /*ModulePrivateLoc=*/SourceLocation(),
12276                                 FriendLoc, TempParamLists.size() - 1,
12277                                 TempParamLists.data()).get();
12278     } else {
12279       // The "template<>" header is extraneous.
12280       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12281         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12282       isExplicitSpecialization = true;
12283     }
12284   }
12285 
12286   if (Invalid) return nullptr;
12287 
12288   bool isAllExplicitSpecializations = true;
12289   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12290     if (TempParamLists[I]->size()) {
12291       isAllExplicitSpecializations = false;
12292       break;
12293     }
12294   }
12295 
12296   // FIXME: don't ignore attributes.
12297 
12298   // If it's explicit specializations all the way down, just forget
12299   // about the template header and build an appropriate non-templated
12300   // friend.  TODO: for source fidelity, remember the headers.
12301   if (isAllExplicitSpecializations) {
12302     if (SS.isEmpty()) {
12303       bool Owned = false;
12304       bool IsDependent = false;
12305       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12306                       Attr, AS_public,
12307                       /*ModulePrivateLoc=*/SourceLocation(),
12308                       MultiTemplateParamsArg(), Owned, IsDependent,
12309                       /*ScopedEnumKWLoc=*/SourceLocation(),
12310                       /*ScopedEnumUsesClassTag=*/false,
12311                       /*UnderlyingType=*/TypeResult(),
12312                       /*IsTypeSpecifier=*/false);
12313     }
12314 
12315     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12316     ElaboratedTypeKeyword Keyword
12317       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12318     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12319                                    *Name, NameLoc);
12320     if (T.isNull())
12321       return nullptr;
12322 
12323     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12324     if (isa<DependentNameType>(T)) {
12325       DependentNameTypeLoc TL =
12326           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12327       TL.setElaboratedKeywordLoc(TagLoc);
12328       TL.setQualifierLoc(QualifierLoc);
12329       TL.setNameLoc(NameLoc);
12330     } else {
12331       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12332       TL.setElaboratedKeywordLoc(TagLoc);
12333       TL.setQualifierLoc(QualifierLoc);
12334       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12335     }
12336 
12337     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12338                                             TSI, FriendLoc, TempParamLists);
12339     Friend->setAccess(AS_public);
12340     CurContext->addDecl(Friend);
12341     return Friend;
12342   }
12343 
12344   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12345 
12346 
12347 
12348   // Handle the case of a templated-scope friend class.  e.g.
12349   //   template <class T> class A<T>::B;
12350   // FIXME: we don't support these right now.
12351   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12352     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12353   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12354   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12355   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12356   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12357   TL.setElaboratedKeywordLoc(TagLoc);
12358   TL.setQualifierLoc(SS.getWithLocInContext(Context));
12359   TL.setNameLoc(NameLoc);
12360 
12361   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12362                                           TSI, FriendLoc, TempParamLists);
12363   Friend->setAccess(AS_public);
12364   Friend->setUnsupportedFriend(true);
12365   CurContext->addDecl(Friend);
12366   return Friend;
12367 }
12368 
12369 
12370 /// Handle a friend type declaration.  This works in tandem with
12371 /// ActOnTag.
12372 ///
12373 /// Notes on friend class templates:
12374 ///
12375 /// We generally treat friend class declarations as if they were
12376 /// declaring a class.  So, for example, the elaborated type specifier
12377 /// in a friend declaration is required to obey the restrictions of a
12378 /// class-head (i.e. no typedefs in the scope chain), template
12379 /// parameters are required to match up with simple template-ids, &c.
12380 /// However, unlike when declaring a template specialization, it's
12381 /// okay to refer to a template specialization without an empty
12382 /// template parameter declaration, e.g.
12383 ///   friend class A<T>::B<unsigned>;
12384 /// We permit this as a special case; if there are any template
12385 /// parameters present at all, require proper matching, i.e.
12386 ///   template <> template \<class T> friend class A<int>::B;
12387 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12388                                 MultiTemplateParamsArg TempParams) {
12389   SourceLocation Loc = DS.getLocStart();
12390 
12391   assert(DS.isFriendSpecified());
12392   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12393 
12394   // Try to convert the decl specifier to a type.  This works for
12395   // friend templates because ActOnTag never produces a ClassTemplateDecl
12396   // for a TUK_Friend.
12397   Declarator TheDeclarator(DS, Declarator::MemberContext);
12398   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12399   QualType T = TSI->getType();
12400   if (TheDeclarator.isInvalidType())
12401     return nullptr;
12402 
12403   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12404     return nullptr;
12405 
12406   // This is definitely an error in C++98.  It's probably meant to
12407   // be forbidden in C++0x, too, but the specification is just
12408   // poorly written.
12409   //
12410   // The problem is with declarations like the following:
12411   //   template <T> friend A<T>::foo;
12412   // where deciding whether a class C is a friend or not now hinges
12413   // on whether there exists an instantiation of A that causes
12414   // 'foo' to equal C.  There are restrictions on class-heads
12415   // (which we declare (by fiat) elaborated friend declarations to
12416   // be) that makes this tractable.
12417   //
12418   // FIXME: handle "template <> friend class A<T>;", which
12419   // is possibly well-formed?  Who even knows?
12420   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12421     Diag(Loc, diag::err_tagless_friend_type_template)
12422       << DS.getSourceRange();
12423     return nullptr;
12424   }
12425 
12426   // C++98 [class.friend]p1: A friend of a class is a function
12427   //   or class that is not a member of the class . . .
12428   // This is fixed in DR77, which just barely didn't make the C++03
12429   // deadline.  It's also a very silly restriction that seriously
12430   // affects inner classes and which nobody else seems to implement;
12431   // thus we never diagnose it, not even in -pedantic.
12432   //
12433   // But note that we could warn about it: it's always useless to
12434   // friend one of your own members (it's not, however, worthless to
12435   // friend a member of an arbitrary specialization of your template).
12436 
12437   Decl *D;
12438   if (unsigned NumTempParamLists = TempParams.size())
12439     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12440                                    NumTempParamLists,
12441                                    TempParams.data(),
12442                                    TSI,
12443                                    DS.getFriendSpecLoc());
12444   else
12445     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12446 
12447   if (!D)
12448     return nullptr;
12449 
12450   D->setAccess(AS_public);
12451   CurContext->addDecl(D);
12452 
12453   return D;
12454 }
12455 
12456 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12457                                         MultiTemplateParamsArg TemplateParams) {
12458   const DeclSpec &DS = D.getDeclSpec();
12459 
12460   assert(DS.isFriendSpecified());
12461   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12462 
12463   SourceLocation Loc = D.getIdentifierLoc();
12464   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12465 
12466   // C++ [class.friend]p1
12467   //   A friend of a class is a function or class....
12468   // Note that this sees through typedefs, which is intended.
12469   // It *doesn't* see through dependent types, which is correct
12470   // according to [temp.arg.type]p3:
12471   //   If a declaration acquires a function type through a
12472   //   type dependent on a template-parameter and this causes
12473   //   a declaration that does not use the syntactic form of a
12474   //   function declarator to have a function type, the program
12475   //   is ill-formed.
12476   if (!TInfo->getType()->isFunctionType()) {
12477     Diag(Loc, diag::err_unexpected_friend);
12478 
12479     // It might be worthwhile to try to recover by creating an
12480     // appropriate declaration.
12481     return nullptr;
12482   }
12483 
12484   // C++ [namespace.memdef]p3
12485   //  - If a friend declaration in a non-local class first declares a
12486   //    class or function, the friend class or function is a member
12487   //    of the innermost enclosing namespace.
12488   //  - The name of the friend is not found by simple name lookup
12489   //    until a matching declaration is provided in that namespace
12490   //    scope (either before or after the class declaration granting
12491   //    friendship).
12492   //  - If a friend function is called, its name may be found by the
12493   //    name lookup that considers functions from namespaces and
12494   //    classes associated with the types of the function arguments.
12495   //  - When looking for a prior declaration of a class or a function
12496   //    declared as a friend, scopes outside the innermost enclosing
12497   //    namespace scope are not considered.
12498 
12499   CXXScopeSpec &SS = D.getCXXScopeSpec();
12500   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12501   DeclarationName Name = NameInfo.getName();
12502   assert(Name);
12503 
12504   // Check for unexpanded parameter packs.
12505   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12506       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12507       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12508     return nullptr;
12509 
12510   // The context we found the declaration in, or in which we should
12511   // create the declaration.
12512   DeclContext *DC;
12513   Scope *DCScope = S;
12514   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12515                         ForRedeclaration);
12516 
12517   // There are five cases here.
12518   //   - There's no scope specifier and we're in a local class. Only look
12519   //     for functions declared in the immediately-enclosing block scope.
12520   // We recover from invalid scope qualifiers as if they just weren't there.
12521   FunctionDecl *FunctionContainingLocalClass = nullptr;
12522   if ((SS.isInvalid() || !SS.isSet()) &&
12523       (FunctionContainingLocalClass =
12524            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12525     // C++11 [class.friend]p11:
12526     //   If a friend declaration appears in a local class and the name
12527     //   specified is an unqualified name, a prior declaration is
12528     //   looked up without considering scopes that are outside the
12529     //   innermost enclosing non-class scope. For a friend function
12530     //   declaration, if there is no prior declaration, the program is
12531     //   ill-formed.
12532 
12533     // Find the innermost enclosing non-class scope. This is the block
12534     // scope containing the local class definition (or for a nested class,
12535     // the outer local class).
12536     DCScope = S->getFnParent();
12537 
12538     // Look up the function name in the scope.
12539     Previous.clear(LookupLocalFriendName);
12540     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12541 
12542     if (!Previous.empty()) {
12543       // All possible previous declarations must have the same context:
12544       // either they were declared at block scope or they are members of
12545       // one of the enclosing local classes.
12546       DC = Previous.getRepresentativeDecl()->getDeclContext();
12547     } else {
12548       // This is ill-formed, but provide the context that we would have
12549       // declared the function in, if we were permitted to, for error recovery.
12550       DC = FunctionContainingLocalClass;
12551     }
12552     adjustContextForLocalExternDecl(DC);
12553 
12554     // C++ [class.friend]p6:
12555     //   A function can be defined in a friend declaration of a class if and
12556     //   only if the class is a non-local class (9.8), the function name is
12557     //   unqualified, and the function has namespace scope.
12558     if (D.isFunctionDefinition()) {
12559       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12560     }
12561 
12562   //   - There's no scope specifier, in which case we just go to the
12563   //     appropriate scope and look for a function or function template
12564   //     there as appropriate.
12565   } else if (SS.isInvalid() || !SS.isSet()) {
12566     // C++11 [namespace.memdef]p3:
12567     //   If the name in a friend declaration is neither qualified nor
12568     //   a template-id and the declaration is a function or an
12569     //   elaborated-type-specifier, the lookup to determine whether
12570     //   the entity has been previously declared shall not consider
12571     //   any scopes outside the innermost enclosing namespace.
12572     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12573 
12574     // Find the appropriate context according to the above.
12575     DC = CurContext;
12576 
12577     // Skip class contexts.  If someone can cite chapter and verse
12578     // for this behavior, that would be nice --- it's what GCC and
12579     // EDG do, and it seems like a reasonable intent, but the spec
12580     // really only says that checks for unqualified existing
12581     // declarations should stop at the nearest enclosing namespace,
12582     // not that they should only consider the nearest enclosing
12583     // namespace.
12584     while (DC->isRecord())
12585       DC = DC->getParent();
12586 
12587     DeclContext *LookupDC = DC;
12588     while (LookupDC->isTransparentContext())
12589       LookupDC = LookupDC->getParent();
12590 
12591     while (true) {
12592       LookupQualifiedName(Previous, LookupDC);
12593 
12594       if (!Previous.empty()) {
12595         DC = LookupDC;
12596         break;
12597       }
12598 
12599       if (isTemplateId) {
12600         if (isa<TranslationUnitDecl>(LookupDC)) break;
12601       } else {
12602         if (LookupDC->isFileContext()) break;
12603       }
12604       LookupDC = LookupDC->getParent();
12605     }
12606 
12607     DCScope = getScopeForDeclContext(S, DC);
12608 
12609   //   - There's a non-dependent scope specifier, in which case we
12610   //     compute it and do a previous lookup there for a function
12611   //     or function template.
12612   } else if (!SS.getScopeRep()->isDependent()) {
12613     DC = computeDeclContext(SS);
12614     if (!DC) return nullptr;
12615 
12616     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12617 
12618     LookupQualifiedName(Previous, DC);
12619 
12620     // Ignore things found implicitly in the wrong scope.
12621     // TODO: better diagnostics for this case.  Suggesting the right
12622     // qualified scope would be nice...
12623     LookupResult::Filter F = Previous.makeFilter();
12624     while (F.hasNext()) {
12625       NamedDecl *D = F.next();
12626       if (!DC->InEnclosingNamespaceSetOf(
12627               D->getDeclContext()->getRedeclContext()))
12628         F.erase();
12629     }
12630     F.done();
12631 
12632     if (Previous.empty()) {
12633       D.setInvalidType();
12634       Diag(Loc, diag::err_qualified_friend_not_found)
12635           << Name << TInfo->getType();
12636       return nullptr;
12637     }
12638 
12639     // C++ [class.friend]p1: A friend of a class is a function or
12640     //   class that is not a member of the class . . .
12641     if (DC->Equals(CurContext))
12642       Diag(DS.getFriendSpecLoc(),
12643            getLangOpts().CPlusPlus11 ?
12644              diag::warn_cxx98_compat_friend_is_member :
12645              diag::err_friend_is_member);
12646 
12647     if (D.isFunctionDefinition()) {
12648       // C++ [class.friend]p6:
12649       //   A function can be defined in a friend declaration of a class if and
12650       //   only if the class is a non-local class (9.8), the function name is
12651       //   unqualified, and the function has namespace scope.
12652       SemaDiagnosticBuilder DB
12653         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12654 
12655       DB << SS.getScopeRep();
12656       if (DC->isFileContext())
12657         DB << FixItHint::CreateRemoval(SS.getRange());
12658       SS.clear();
12659     }
12660 
12661   //   - There's a scope specifier that does not match any template
12662   //     parameter lists, in which case we use some arbitrary context,
12663   //     create a method or method template, and wait for instantiation.
12664   //   - There's a scope specifier that does match some template
12665   //     parameter lists, which we don't handle right now.
12666   } else {
12667     if (D.isFunctionDefinition()) {
12668       // C++ [class.friend]p6:
12669       //   A function can be defined in a friend declaration of a class if and
12670       //   only if the class is a non-local class (9.8), the function name is
12671       //   unqualified, and the function has namespace scope.
12672       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12673         << SS.getScopeRep();
12674     }
12675 
12676     DC = CurContext;
12677     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12678   }
12679 
12680   if (!DC->isRecord()) {
12681     // This implies that it has to be an operator or function.
12682     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12683         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12684         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12685       Diag(Loc, diag::err_introducing_special_friend) <<
12686         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12687          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12688       return nullptr;
12689     }
12690   }
12691 
12692   // FIXME: This is an egregious hack to cope with cases where the scope stack
12693   // does not contain the declaration context, i.e., in an out-of-line
12694   // definition of a class.
12695   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12696   if (!DCScope) {
12697     FakeDCScope.setEntity(DC);
12698     DCScope = &FakeDCScope;
12699   }
12700 
12701   bool AddToScope = true;
12702   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12703                                           TemplateParams, AddToScope);
12704   if (!ND) return nullptr;
12705 
12706   assert(ND->getLexicalDeclContext() == CurContext);
12707 
12708   // If we performed typo correction, we might have added a scope specifier
12709   // and changed the decl context.
12710   DC = ND->getDeclContext();
12711 
12712   // Add the function declaration to the appropriate lookup tables,
12713   // adjusting the redeclarations list as necessary.  We don't
12714   // want to do this yet if the friending class is dependent.
12715   //
12716   // Also update the scope-based lookup if the target context's
12717   // lookup context is in lexical scope.
12718   if (!CurContext->isDependentContext()) {
12719     DC = DC->getRedeclContext();
12720     DC->makeDeclVisibleInContext(ND);
12721     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12722       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12723   }
12724 
12725   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12726                                        D.getIdentifierLoc(), ND,
12727                                        DS.getFriendSpecLoc());
12728   FrD->setAccess(AS_public);
12729   CurContext->addDecl(FrD);
12730 
12731   if (ND->isInvalidDecl()) {
12732     FrD->setInvalidDecl();
12733   } else {
12734     if (DC->isRecord()) CheckFriendAccess(ND);
12735 
12736     FunctionDecl *FD;
12737     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12738       FD = FTD->getTemplatedDecl();
12739     else
12740       FD = cast<FunctionDecl>(ND);
12741 
12742     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12743     // default argument expression, that declaration shall be a definition
12744     // and shall be the only declaration of the function or function
12745     // template in the translation unit.
12746     if (functionDeclHasDefaultArgument(FD)) {
12747       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12748         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12749         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12750       } else if (!D.isFunctionDefinition())
12751         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12752     }
12753 
12754     // Mark templated-scope function declarations as unsupported.
12755     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12756       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12757         << SS.getScopeRep() << SS.getRange()
12758         << cast<CXXRecordDecl>(CurContext);
12759       FrD->setUnsupportedFriend(true);
12760     }
12761   }
12762 
12763   return ND;
12764 }
12765 
12766 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12767   AdjustDeclIfTemplate(Dcl);
12768 
12769   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12770   if (!Fn) {
12771     Diag(DelLoc, diag::err_deleted_non_function);
12772     return;
12773   }
12774 
12775   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12776     // Don't consider the implicit declaration we generate for explicit
12777     // specializations. FIXME: Do not generate these implicit declarations.
12778     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12779          Prev->getPreviousDecl()) &&
12780         !Prev->isDefined()) {
12781       Diag(DelLoc, diag::err_deleted_decl_not_first);
12782       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12783            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12784                               : diag::note_previous_declaration);
12785     }
12786     // If the declaration wasn't the first, we delete the function anyway for
12787     // recovery.
12788     Fn = Fn->getCanonicalDecl();
12789   }
12790 
12791   // dllimport/dllexport cannot be deleted.
12792   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12793     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12794     Fn->setInvalidDecl();
12795   }
12796 
12797   if (Fn->isDeleted())
12798     return;
12799 
12800   // See if we're deleting a function which is already known to override a
12801   // non-deleted virtual function.
12802   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12803     bool IssuedDiagnostic = false;
12804     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12805                                         E = MD->end_overridden_methods();
12806          I != E; ++I) {
12807       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12808         if (!IssuedDiagnostic) {
12809           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12810           IssuedDiagnostic = true;
12811         }
12812         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12813       }
12814     }
12815   }
12816 
12817   // C++11 [basic.start.main]p3:
12818   //   A program that defines main as deleted [...] is ill-formed.
12819   if (Fn->isMain())
12820     Diag(DelLoc, diag::err_deleted_main);
12821 
12822   Fn->setDeletedAsWritten();
12823 }
12824 
12825 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12826   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12827 
12828   if (MD) {
12829     if (MD->getParent()->isDependentType()) {
12830       MD->setDefaulted();
12831       MD->setExplicitlyDefaulted();
12832       return;
12833     }
12834 
12835     CXXSpecialMember Member = getSpecialMember(MD);
12836     if (Member == CXXInvalid) {
12837       if (!MD->isInvalidDecl())
12838         Diag(DefaultLoc, diag::err_default_special_members);
12839       return;
12840     }
12841 
12842     MD->setDefaulted();
12843     MD->setExplicitlyDefaulted();
12844 
12845     // If this definition appears within the record, do the checking when
12846     // the record is complete.
12847     const FunctionDecl *Primary = MD;
12848     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12849       // Find the uninstantiated declaration that actually had the '= default'
12850       // on it.
12851       Pattern->isDefined(Primary);
12852 
12853     // If the method was defaulted on its first declaration, we will have
12854     // already performed the checking in CheckCompletedCXXClass. Such a
12855     // declaration doesn't trigger an implicit definition.
12856     if (Primary == Primary->getCanonicalDecl())
12857       return;
12858 
12859     CheckExplicitlyDefaultedSpecialMember(MD);
12860 
12861     if (MD->isInvalidDecl())
12862       return;
12863 
12864     switch (Member) {
12865     case CXXDefaultConstructor:
12866       DefineImplicitDefaultConstructor(DefaultLoc,
12867                                        cast<CXXConstructorDecl>(MD));
12868       break;
12869     case CXXCopyConstructor:
12870       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12871       break;
12872     case CXXCopyAssignment:
12873       DefineImplicitCopyAssignment(DefaultLoc, MD);
12874       break;
12875     case CXXDestructor:
12876       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12877       break;
12878     case CXXMoveConstructor:
12879       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12880       break;
12881     case CXXMoveAssignment:
12882       DefineImplicitMoveAssignment(DefaultLoc, MD);
12883       break;
12884     case CXXInvalid:
12885       llvm_unreachable("Invalid special member.");
12886     }
12887   } else {
12888     Diag(DefaultLoc, diag::err_default_special_members);
12889   }
12890 }
12891 
12892 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12893   for (Stmt::child_range CI = S->children(); CI; ++CI) {
12894     Stmt *SubStmt = *CI;
12895     if (!SubStmt)
12896       continue;
12897     if (isa<ReturnStmt>(SubStmt))
12898       Self.Diag(SubStmt->getLocStart(),
12899            diag::err_return_in_constructor_handler);
12900     if (!isa<Expr>(SubStmt))
12901       SearchForReturnInStmt(Self, SubStmt);
12902   }
12903 }
12904 
12905 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12906   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12907     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12908     SearchForReturnInStmt(*this, Handler);
12909   }
12910 }
12911 
12912 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12913                                              const CXXMethodDecl *Old) {
12914   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12915   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12916 
12917   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12918 
12919   // If the calling conventions match, everything is fine
12920   if (NewCC == OldCC)
12921     return false;
12922 
12923   // If the calling conventions mismatch because the new function is static,
12924   // suppress the calling convention mismatch error; the error about static
12925   // function override (err_static_overrides_virtual from
12926   // Sema::CheckFunctionDeclaration) is more clear.
12927   if (New->getStorageClass() == SC_Static)
12928     return false;
12929 
12930   Diag(New->getLocation(),
12931        diag::err_conflicting_overriding_cc_attributes)
12932     << New->getDeclName() << New->getType() << Old->getType();
12933   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12934   return true;
12935 }
12936 
12937 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12938                                              const CXXMethodDecl *Old) {
12939   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12940   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12941 
12942   if (Context.hasSameType(NewTy, OldTy) ||
12943       NewTy->isDependentType() || OldTy->isDependentType())
12944     return false;
12945 
12946   // Check if the return types are covariant
12947   QualType NewClassTy, OldClassTy;
12948 
12949   /// Both types must be pointers or references to classes.
12950   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12951     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12952       NewClassTy = NewPT->getPointeeType();
12953       OldClassTy = OldPT->getPointeeType();
12954     }
12955   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12956     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12957       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12958         NewClassTy = NewRT->getPointeeType();
12959         OldClassTy = OldRT->getPointeeType();
12960       }
12961     }
12962   }
12963 
12964   // The return types aren't either both pointers or references to a class type.
12965   if (NewClassTy.isNull()) {
12966     Diag(New->getLocation(),
12967          diag::err_different_return_type_for_overriding_virtual_function)
12968         << New->getDeclName() << NewTy << OldTy
12969         << New->getReturnTypeSourceRange();
12970     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12971         << Old->getReturnTypeSourceRange();
12972 
12973     return true;
12974   }
12975 
12976   // C++ [class.virtual]p6:
12977   //   If the return type of D::f differs from the return type of B::f, the
12978   //   class type in the return type of D::f shall be complete at the point of
12979   //   declaration of D::f or shall be the class type D.
12980   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12981     if (!RT->isBeingDefined() &&
12982         RequireCompleteType(New->getLocation(), NewClassTy,
12983                             diag::err_covariant_return_incomplete,
12984                             New->getDeclName()))
12985     return true;
12986   }
12987 
12988   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12989     // Check if the new class derives from the old class.
12990     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12991       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12992           << New->getDeclName() << NewTy << OldTy
12993           << New->getReturnTypeSourceRange();
12994       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12995           << Old->getReturnTypeSourceRange();
12996       return true;
12997     }
12998 
12999     // Check if we the conversion from derived to base is valid.
13000     if (CheckDerivedToBaseConversion(
13001             NewClassTy, OldClassTy,
13002             diag::err_covariant_return_inaccessible_base,
13003             diag::err_covariant_return_ambiguous_derived_to_base_conv,
13004             New->getLocation(), New->getReturnTypeSourceRange(),
13005             New->getDeclName(), nullptr)) {
13006       // FIXME: this note won't trigger for delayed access control
13007       // diagnostics, and it's impossible to get an undelayed error
13008       // here from access control during the original parse because
13009       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13010       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13011           << Old->getReturnTypeSourceRange();
13012       return true;
13013     }
13014   }
13015 
13016   // The qualifiers of the return types must be the same.
13017   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13018     Diag(New->getLocation(),
13019          diag::err_covariant_return_type_different_qualifications)
13020         << New->getDeclName() << NewTy << OldTy
13021         << New->getReturnTypeSourceRange();
13022     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13023         << Old->getReturnTypeSourceRange();
13024     return true;
13025   };
13026 
13027 
13028   // The new class type must have the same or less qualifiers as the old type.
13029   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13030     Diag(New->getLocation(),
13031          diag::err_covariant_return_type_class_type_more_qualified)
13032         << New->getDeclName() << NewTy << OldTy
13033         << New->getReturnTypeSourceRange();
13034     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13035         << Old->getReturnTypeSourceRange();
13036     return true;
13037   };
13038 
13039   return false;
13040 }
13041 
13042 /// \brief Mark the given method pure.
13043 ///
13044 /// \param Method the method to be marked pure.
13045 ///
13046 /// \param InitRange the source range that covers the "0" initializer.
13047 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
13048   SourceLocation EndLoc = InitRange.getEnd();
13049   if (EndLoc.isValid())
13050     Method->setRangeEnd(EndLoc);
13051 
13052   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13053     Method->setPure();
13054     return false;
13055   }
13056 
13057   if (!Method->isInvalidDecl())
13058     Diag(Method->getLocation(), diag::err_non_virtual_pure)
13059       << Method->getDeclName() << InitRange;
13060   return true;
13061 }
13062 
13063 /// \brief Determine whether the given declaration is a static data member.
13064 static bool isStaticDataMember(const Decl *D) {
13065   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13066     return Var->isStaticDataMember();
13067 
13068   return false;
13069 }
13070 
13071 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13072 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
13073 /// is a fresh scope pushed for just this purpose.
13074 ///
13075 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13076 /// static data member of class X, names should be looked up in the scope of
13077 /// class X.
13078 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
13079   // If there is no declaration, there was an error parsing it.
13080   if (!D || D->isInvalidDecl())
13081     return;
13082 
13083   // We will always have a nested name specifier here, but this declaration
13084   // might not be out of line if the specifier names the current namespace:
13085   //   extern int n;
13086   //   int ::n = 0;
13087   if (D->isOutOfLine())
13088     EnterDeclaratorContext(S, D->getDeclContext());
13089 
13090   // If we are parsing the initializer for a static data member, push a
13091   // new expression evaluation context that is associated with this static
13092   // data member.
13093   if (isStaticDataMember(D))
13094     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
13095 }
13096 
13097 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
13098 /// initializer for the out-of-line declaration 'D'.
13099 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
13100   // If there is no declaration, there was an error parsing it.
13101   if (!D || D->isInvalidDecl())
13102     return;
13103 
13104   if (isStaticDataMember(D))
13105     PopExpressionEvaluationContext();
13106 
13107   if (D->isOutOfLine())
13108     ExitDeclaratorContext(S);
13109 }
13110 
13111 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13112 /// C++ if/switch/while/for statement.
13113 /// e.g: "if (int x = f()) {...}"
13114 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
13115   // C++ 6.4p2:
13116   // The declarator shall not specify a function or an array.
13117   // The type-specifier-seq shall not contain typedef and shall not declare a
13118   // new class or enumeration.
13119   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13120          "Parser allowed 'typedef' as storage class of condition decl.");
13121 
13122   Decl *Dcl = ActOnDeclarator(S, D);
13123   if (!Dcl)
13124     return true;
13125 
13126   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13127     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13128       << D.getSourceRange();
13129     return true;
13130   }
13131 
13132   return Dcl;
13133 }
13134 
13135 void Sema::LoadExternalVTableUses() {
13136   if (!ExternalSource)
13137     return;
13138 
13139   SmallVector<ExternalVTableUse, 4> VTables;
13140   ExternalSource->ReadUsedVTables(VTables);
13141   SmallVector<VTableUse, 4> NewUses;
13142   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13143     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13144       = VTablesUsed.find(VTables[I].Record);
13145     // Even if a definition wasn't required before, it may be required now.
13146     if (Pos != VTablesUsed.end()) {
13147       if (!Pos->second && VTables[I].DefinitionRequired)
13148         Pos->second = true;
13149       continue;
13150     }
13151 
13152     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13153     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13154   }
13155 
13156   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13157 }
13158 
13159 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13160                           bool DefinitionRequired) {
13161   // Ignore any vtable uses in unevaluated operands or for classes that do
13162   // not have a vtable.
13163   if (!Class->isDynamicClass() || Class->isDependentContext() ||
13164       CurContext->isDependentContext() || isUnevaluatedContext())
13165     return;
13166 
13167   // Try to insert this class into the map.
13168   LoadExternalVTableUses();
13169   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13170   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13171     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13172   if (!Pos.second) {
13173     // If we already had an entry, check to see if we are promoting this vtable
13174     // to require a definition. If so, we need to reappend to the VTableUses
13175     // list, since we may have already processed the first entry.
13176     if (DefinitionRequired && !Pos.first->second) {
13177       Pos.first->second = true;
13178     } else {
13179       // Otherwise, we can early exit.
13180       return;
13181     }
13182   } else {
13183     // The Microsoft ABI requires that we perform the destructor body
13184     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13185     // the deleting destructor is emitted with the vtable, not with the
13186     // destructor definition as in the Itanium ABI.
13187     // If it has a definition, we do the check at that point instead.
13188     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13189         Class->hasUserDeclaredDestructor() &&
13190         !Class->getDestructor()->isDefined() &&
13191         !Class->getDestructor()->isDeleted()) {
13192       CXXDestructorDecl *DD = Class->getDestructor();
13193       ContextRAII SavedContext(*this, DD);
13194       CheckDestructor(DD);
13195     }
13196   }
13197 
13198   // Local classes need to have their virtual members marked
13199   // immediately. For all other classes, we mark their virtual members
13200   // at the end of the translation unit.
13201   if (Class->isLocalClass())
13202     MarkVirtualMembersReferenced(Loc, Class);
13203   else
13204     VTableUses.push_back(std::make_pair(Class, Loc));
13205 }
13206 
13207 bool Sema::DefineUsedVTables() {
13208   LoadExternalVTableUses();
13209   if (VTableUses.empty())
13210     return false;
13211 
13212   // Note: The VTableUses vector could grow as a result of marking
13213   // the members of a class as "used", so we check the size each
13214   // time through the loop and prefer indices (which are stable) to
13215   // iterators (which are not).
13216   bool DefinedAnything = false;
13217   for (unsigned I = 0; I != VTableUses.size(); ++I) {
13218     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13219     if (!Class)
13220       continue;
13221 
13222     SourceLocation Loc = VTableUses[I].second;
13223 
13224     bool DefineVTable = true;
13225 
13226     // If this class has a key function, but that key function is
13227     // defined in another translation unit, we don't need to emit the
13228     // vtable even though we're using it.
13229     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13230     if (KeyFunction && !KeyFunction->hasBody()) {
13231       // The key function is in another translation unit.
13232       DefineVTable = false;
13233       TemplateSpecializationKind TSK =
13234           KeyFunction->getTemplateSpecializationKind();
13235       assert(TSK != TSK_ExplicitInstantiationDefinition &&
13236              TSK != TSK_ImplicitInstantiation &&
13237              "Instantiations don't have key functions");
13238       (void)TSK;
13239     } else if (!KeyFunction) {
13240       // If we have a class with no key function that is the subject
13241       // of an explicit instantiation declaration, suppress the
13242       // vtable; it will live with the explicit instantiation
13243       // definition.
13244       bool IsExplicitInstantiationDeclaration
13245         = Class->getTemplateSpecializationKind()
13246                                       == TSK_ExplicitInstantiationDeclaration;
13247       for (auto R : Class->redecls()) {
13248         TemplateSpecializationKind TSK
13249           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13250         if (TSK == TSK_ExplicitInstantiationDeclaration)
13251           IsExplicitInstantiationDeclaration = true;
13252         else if (TSK == TSK_ExplicitInstantiationDefinition) {
13253           IsExplicitInstantiationDeclaration = false;
13254           break;
13255         }
13256       }
13257 
13258       if (IsExplicitInstantiationDeclaration)
13259         DefineVTable = false;
13260     }
13261 
13262     // The exception specifications for all virtual members may be needed even
13263     // if we are not providing an authoritative form of the vtable in this TU.
13264     // We may choose to emit it available_externally anyway.
13265     if (!DefineVTable) {
13266       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13267       continue;
13268     }
13269 
13270     // Mark all of the virtual members of this class as referenced, so
13271     // that we can build a vtable. Then, tell the AST consumer that a
13272     // vtable for this class is required.
13273     DefinedAnything = true;
13274     MarkVirtualMembersReferenced(Loc, Class);
13275     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13276     if (VTablesUsed[Canonical])
13277       Consumer.HandleVTable(Class);
13278 
13279     // Optionally warn if we're emitting a weak vtable.
13280     if (Class->isExternallyVisible() &&
13281         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13282       const FunctionDecl *KeyFunctionDef = nullptr;
13283       if (!KeyFunction ||
13284           (KeyFunction->hasBody(KeyFunctionDef) &&
13285            KeyFunctionDef->isInlined()))
13286         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13287              TSK_ExplicitInstantiationDefinition
13288              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13289           << Class;
13290     }
13291   }
13292   VTableUses.clear();
13293 
13294   return DefinedAnything;
13295 }
13296 
13297 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13298                                                  const CXXRecordDecl *RD) {
13299   for (const auto *I : RD->methods())
13300     if (I->isVirtual() && !I->isPure())
13301       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13302 }
13303 
13304 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13305                                         const CXXRecordDecl *RD) {
13306   // Mark all functions which will appear in RD's vtable as used.
13307   CXXFinalOverriderMap FinalOverriders;
13308   RD->getFinalOverriders(FinalOverriders);
13309   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13310                                             E = FinalOverriders.end();
13311        I != E; ++I) {
13312     for (OverridingMethods::const_iterator OI = I->second.begin(),
13313                                            OE = I->second.end();
13314          OI != OE; ++OI) {
13315       assert(OI->second.size() > 0 && "no final overrider");
13316       CXXMethodDecl *Overrider = OI->second.front().Method;
13317 
13318       // C++ [basic.def.odr]p2:
13319       //   [...] A virtual member function is used if it is not pure. [...]
13320       if (!Overrider->isPure())
13321         MarkFunctionReferenced(Loc, Overrider);
13322     }
13323   }
13324 
13325   // Only classes that have virtual bases need a VTT.
13326   if (RD->getNumVBases() == 0)
13327     return;
13328 
13329   for (const auto &I : RD->bases()) {
13330     const CXXRecordDecl *Base =
13331         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13332     if (Base->getNumVBases() == 0)
13333       continue;
13334     MarkVirtualMembersReferenced(Loc, Base);
13335   }
13336 }
13337 
13338 /// SetIvarInitializers - This routine builds initialization ASTs for the
13339 /// Objective-C implementation whose ivars need be initialized.
13340 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13341   if (!getLangOpts().CPlusPlus)
13342     return;
13343   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13344     SmallVector<ObjCIvarDecl*, 8> ivars;
13345     CollectIvarsToConstructOrDestruct(OID, ivars);
13346     if (ivars.empty())
13347       return;
13348     SmallVector<CXXCtorInitializer*, 32> AllToInit;
13349     for (unsigned i = 0; i < ivars.size(); i++) {
13350       FieldDecl *Field = ivars[i];
13351       if (Field->isInvalidDecl())
13352         continue;
13353 
13354       CXXCtorInitializer *Member;
13355       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13356       InitializationKind InitKind =
13357         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13358 
13359       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13360       ExprResult MemberInit =
13361         InitSeq.Perform(*this, InitEntity, InitKind, None);
13362       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13363       // Note, MemberInit could actually come back empty if no initialization
13364       // is required (e.g., because it would call a trivial default constructor)
13365       if (!MemberInit.get() || MemberInit.isInvalid())
13366         continue;
13367 
13368       Member =
13369         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13370                                          SourceLocation(),
13371                                          MemberInit.getAs<Expr>(),
13372                                          SourceLocation());
13373       AllToInit.push_back(Member);
13374 
13375       // Be sure that the destructor is accessible and is marked as referenced.
13376       if (const RecordType *RecordTy =
13377               Context.getBaseElementType(Field->getType())
13378                   ->getAs<RecordType>()) {
13379         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13380         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13381           MarkFunctionReferenced(Field->getLocation(), Destructor);
13382           CheckDestructorAccess(Field->getLocation(), Destructor,
13383                             PDiag(diag::err_access_dtor_ivar)
13384                               << Context.getBaseElementType(Field->getType()));
13385         }
13386       }
13387     }
13388     ObjCImplementation->setIvarInitializers(Context,
13389                                             AllToInit.data(), AllToInit.size());
13390   }
13391 }
13392 
13393 static
13394 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13395                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13396                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13397                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13398                            Sema &S) {
13399   if (Ctor->isInvalidDecl())
13400     return;
13401 
13402   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13403 
13404   // Target may not be determinable yet, for instance if this is a dependent
13405   // call in an uninstantiated template.
13406   if (Target) {
13407     const FunctionDecl *FNTarget = nullptr;
13408     (void)Target->hasBody(FNTarget);
13409     Target = const_cast<CXXConstructorDecl*>(
13410       cast_or_null<CXXConstructorDecl>(FNTarget));
13411   }
13412 
13413   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13414                      // Avoid dereferencing a null pointer here.
13415                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13416 
13417   if (!Current.insert(Canonical).second)
13418     return;
13419 
13420   // We know that beyond here, we aren't chaining into a cycle.
13421   if (!Target || !Target->isDelegatingConstructor() ||
13422       Target->isInvalidDecl() || Valid.count(TCanonical)) {
13423     Valid.insert(Current.begin(), Current.end());
13424     Current.clear();
13425   // We've hit a cycle.
13426   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13427              Current.count(TCanonical)) {
13428     // If we haven't diagnosed this cycle yet, do so now.
13429     if (!Invalid.count(TCanonical)) {
13430       S.Diag((*Ctor->init_begin())->getSourceLocation(),
13431              diag::warn_delegating_ctor_cycle)
13432         << Ctor;
13433 
13434       // Don't add a note for a function delegating directly to itself.
13435       if (TCanonical != Canonical)
13436         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13437 
13438       CXXConstructorDecl *C = Target;
13439       while (C->getCanonicalDecl() != Canonical) {
13440         const FunctionDecl *FNTarget = nullptr;
13441         (void)C->getTargetConstructor()->hasBody(FNTarget);
13442         assert(FNTarget && "Ctor cycle through bodiless function");
13443 
13444         C = const_cast<CXXConstructorDecl*>(
13445           cast<CXXConstructorDecl>(FNTarget));
13446         S.Diag(C->getLocation(), diag::note_which_delegates_to);
13447       }
13448     }
13449 
13450     Invalid.insert(Current.begin(), Current.end());
13451     Current.clear();
13452   } else {
13453     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13454   }
13455 }
13456 
13457 
13458 void Sema::CheckDelegatingCtorCycles() {
13459   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13460 
13461   for (DelegatingCtorDeclsType::iterator
13462          I = DelegatingCtorDecls.begin(ExternalSource),
13463          E = DelegatingCtorDecls.end();
13464        I != E; ++I)
13465     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13466 
13467   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13468                                                          CE = Invalid.end();
13469        CI != CE; ++CI)
13470     (*CI)->setInvalidDecl();
13471 }
13472 
13473 namespace {
13474   /// \brief AST visitor that finds references to the 'this' expression.
13475   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13476     Sema &S;
13477 
13478   public:
13479     explicit FindCXXThisExpr(Sema &S) : S(S) { }
13480 
13481     bool VisitCXXThisExpr(CXXThisExpr *E) {
13482       S.Diag(E->getLocation(), diag::err_this_static_member_func)
13483         << E->isImplicit();
13484       return false;
13485     }
13486   };
13487 } // namespace
13488 
13489 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13490   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13491   if (!TSInfo)
13492     return false;
13493 
13494   TypeLoc TL = TSInfo->getTypeLoc();
13495   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13496   if (!ProtoTL)
13497     return false;
13498 
13499   // C++11 [expr.prim.general]p3:
13500   //   [The expression this] shall not appear before the optional
13501   //   cv-qualifier-seq and it shall not appear within the declaration of a
13502   //   static member function (although its type and value category are defined
13503   //   within a static member function as they are within a non-static member
13504   //   function). [ Note: this is because declaration matching does not occur
13505   //  until the complete declarator is known. - end note ]
13506   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13507   FindCXXThisExpr Finder(*this);
13508 
13509   // If the return type came after the cv-qualifier-seq, check it now.
13510   if (Proto->hasTrailingReturn() &&
13511       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13512     return true;
13513 
13514   // Check the exception specification.
13515   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13516     return true;
13517 
13518   return checkThisInStaticMemberFunctionAttributes(Method);
13519 }
13520 
13521 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13522   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13523   if (!TSInfo)
13524     return false;
13525 
13526   TypeLoc TL = TSInfo->getTypeLoc();
13527   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13528   if (!ProtoTL)
13529     return false;
13530 
13531   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13532   FindCXXThisExpr Finder(*this);
13533 
13534   switch (Proto->getExceptionSpecType()) {
13535   case EST_Unparsed:
13536   case EST_Uninstantiated:
13537   case EST_Unevaluated:
13538   case EST_BasicNoexcept:
13539   case EST_DynamicNone:
13540   case EST_MSAny:
13541   case EST_None:
13542     break;
13543 
13544   case EST_ComputedNoexcept:
13545     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13546       return true;
13547 
13548   case EST_Dynamic:
13549     for (const auto &E : Proto->exceptions()) {
13550       if (!Finder.TraverseType(E))
13551         return true;
13552     }
13553     break;
13554   }
13555 
13556   return false;
13557 }
13558 
13559 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13560   FindCXXThisExpr Finder(*this);
13561 
13562   // Check attributes.
13563   for (const auto *A : Method->attrs()) {
13564     // FIXME: This should be emitted by tblgen.
13565     Expr *Arg = nullptr;
13566     ArrayRef<Expr *> Args;
13567     if (const auto *G = dyn_cast<GuardedByAttr>(A))
13568       Arg = G->getArg();
13569     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13570       Arg = G->getArg();
13571     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13572       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13573     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13574       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13575     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13576       Arg = ETLF->getSuccessValue();
13577       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13578     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13579       Arg = STLF->getSuccessValue();
13580       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13581     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13582       Arg = LR->getArg();
13583     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13584       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13585     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13586       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13587     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13588       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13589     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13590       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13591     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13592       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13593 
13594     if (Arg && !Finder.TraverseStmt(Arg))
13595       return true;
13596 
13597     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13598       if (!Finder.TraverseStmt(Args[I]))
13599         return true;
13600     }
13601   }
13602 
13603   return false;
13604 }
13605 
13606 void Sema::checkExceptionSpecification(
13607     bool IsTopLevel, ExceptionSpecificationType EST,
13608     ArrayRef<ParsedType> DynamicExceptions,
13609     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13610     SmallVectorImpl<QualType> &Exceptions,
13611     FunctionProtoType::ExceptionSpecInfo &ESI) {
13612   Exceptions.clear();
13613   ESI.Type = EST;
13614   if (EST == EST_Dynamic) {
13615     Exceptions.reserve(DynamicExceptions.size());
13616     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13617       // FIXME: Preserve type source info.
13618       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13619 
13620       if (IsTopLevel) {
13621         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13622         collectUnexpandedParameterPacks(ET, Unexpanded);
13623         if (!Unexpanded.empty()) {
13624           DiagnoseUnexpandedParameterPacks(
13625               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13626               Unexpanded);
13627           continue;
13628         }
13629       }
13630 
13631       // Check that the type is valid for an exception spec, and
13632       // drop it if not.
13633       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13634         Exceptions.push_back(ET);
13635     }
13636     ESI.Exceptions = Exceptions;
13637     return;
13638   }
13639 
13640   if (EST == EST_ComputedNoexcept) {
13641     // If an error occurred, there's no expression here.
13642     if (NoexceptExpr) {
13643       assert((NoexceptExpr->isTypeDependent() ||
13644               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13645               Context.BoolTy) &&
13646              "Parser should have made sure that the expression is boolean");
13647       if (IsTopLevel && NoexceptExpr &&
13648           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13649         ESI.Type = EST_BasicNoexcept;
13650         return;
13651       }
13652 
13653       if (!NoexceptExpr->isValueDependent())
13654         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13655                          diag::err_noexcept_needs_constant_expression,
13656                          /*AllowFold*/ false).get();
13657       ESI.NoexceptExpr = NoexceptExpr;
13658     }
13659     return;
13660   }
13661 }
13662 
13663 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13664              ExceptionSpecificationType EST,
13665              SourceRange SpecificationRange,
13666              ArrayRef<ParsedType> DynamicExceptions,
13667              ArrayRef<SourceRange> DynamicExceptionRanges,
13668              Expr *NoexceptExpr) {
13669   if (!MethodD)
13670     return;
13671 
13672   // Dig out the method we're referring to.
13673   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13674     MethodD = FunTmpl->getTemplatedDecl();
13675 
13676   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13677   if (!Method)
13678     return;
13679 
13680   // Check the exception specification.
13681   llvm::SmallVector<QualType, 4> Exceptions;
13682   FunctionProtoType::ExceptionSpecInfo ESI;
13683   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13684                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
13685                               ESI);
13686 
13687   // Update the exception specification on the function type.
13688   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13689 
13690   if (Method->isStatic())
13691     checkThisInStaticMemberFunctionExceptionSpec(Method);
13692 
13693   if (Method->isVirtual()) {
13694     // Check overrides, which we previously had to delay.
13695     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13696                                      OEnd = Method->end_overridden_methods();
13697          O != OEnd; ++O)
13698       CheckOverridingFunctionExceptionSpec(Method, *O);
13699   }
13700 }
13701 
13702 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13703 ///
13704 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13705                                        SourceLocation DeclStart,
13706                                        Declarator &D, Expr *BitWidth,
13707                                        InClassInitStyle InitStyle,
13708                                        AccessSpecifier AS,
13709                                        AttributeList *MSPropertyAttr) {
13710   IdentifierInfo *II = D.getIdentifier();
13711   if (!II) {
13712     Diag(DeclStart, diag::err_anonymous_property);
13713     return nullptr;
13714   }
13715   SourceLocation Loc = D.getIdentifierLoc();
13716 
13717   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13718   QualType T = TInfo->getType();
13719   if (getLangOpts().CPlusPlus) {
13720     CheckExtraCXXDefaultArguments(D);
13721 
13722     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13723                                         UPPC_DataMemberType)) {
13724       D.setInvalidType();
13725       T = Context.IntTy;
13726       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13727     }
13728   }
13729 
13730   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13731 
13732   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13733     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13734          diag::err_invalid_thread)
13735       << DeclSpec::getSpecifierName(TSCS);
13736 
13737   // Check to see if this name was declared as a member previously
13738   NamedDecl *PrevDecl = nullptr;
13739   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13740   LookupName(Previous, S);
13741   switch (Previous.getResultKind()) {
13742   case LookupResult::Found:
13743   case LookupResult::FoundUnresolvedValue:
13744     PrevDecl = Previous.getAsSingle<NamedDecl>();
13745     break;
13746 
13747   case LookupResult::FoundOverloaded:
13748     PrevDecl = Previous.getRepresentativeDecl();
13749     break;
13750 
13751   case LookupResult::NotFound:
13752   case LookupResult::NotFoundInCurrentInstantiation:
13753   case LookupResult::Ambiguous:
13754     break;
13755   }
13756 
13757   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13758     // Maybe we will complain about the shadowed template parameter.
13759     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13760     // Just pretend that we didn't see the previous declaration.
13761     PrevDecl = nullptr;
13762   }
13763 
13764   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13765     PrevDecl = nullptr;
13766 
13767   SourceLocation TSSL = D.getLocStart();
13768   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13769   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13770       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13771   ProcessDeclAttributes(TUScope, NewPD, D);
13772   NewPD->setAccess(AS);
13773 
13774   if (NewPD->isInvalidDecl())
13775     Record->setInvalidDecl();
13776 
13777   if (D.getDeclSpec().isModulePrivateSpecified())
13778     NewPD->setModulePrivate();
13779 
13780   if (NewPD->isInvalidDecl() && PrevDecl) {
13781     // Don't introduce NewFD into scope; there's already something
13782     // with the same name in the same scope.
13783   } else if (II) {
13784     PushOnScopeChains(NewPD, S);
13785   } else
13786     Record->addDecl(NewPD);
13787 
13788   return NewPD;
13789 }
13790