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 }
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   // Check that the default argument is well-formed
322   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323   if (DefaultArgChecker.Visit(DefaultArg)) {
324     Param->setInvalidDecl();
325     return;
326   }
327 
328   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
329 }
330 
331 /// ActOnParamUnparsedDefaultArgument - We've seen a default
332 /// argument for a function parameter, but we can't parse it yet
333 /// because we're inside a class definition. Note that this default
334 /// argument will be parsed later.
335 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
336                                              SourceLocation EqualLoc,
337                                              SourceLocation ArgLoc) {
338   if (!param)
339     return;
340 
341   ParmVarDecl *Param = cast<ParmVarDecl>(param);
342   Param->setUnparsedDefaultArg();
343   UnparsedDefaultArgLocs[Param] = ArgLoc;
344 }
345 
346 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347 /// the default argument for the parameter param failed.
348 void Sema::ActOnParamDefaultArgumentError(Decl *param,
349                                           SourceLocation EqualLoc) {
350   if (!param)
351     return;
352 
353   ParmVarDecl *Param = cast<ParmVarDecl>(param);
354   Param->setInvalidDecl();
355   UnparsedDefaultArgLocs.erase(Param);
356   Param->setDefaultArg(new(Context)
357                        OpaqueValueExpr(EqualLoc,
358                                        Param->getType().getNonReferenceType(),
359                                        VK_RValue));
360 }
361 
362 /// CheckExtraCXXDefaultArguments - Check for any extra default
363 /// arguments in the declarator, which is not a function declaration
364 /// or definition and therefore is not permitted to have default
365 /// arguments. This routine should be invoked for every declarator
366 /// that is not a function declaration or definition.
367 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
368   // C++ [dcl.fct.default]p3
369   //   A default argument expression shall be specified only in the
370   //   parameter-declaration-clause of a function declaration or in a
371   //   template-parameter (14.1). It shall not be specified for a
372   //   parameter pack. If it is specified in a
373   //   parameter-declaration-clause, it shall not occur within a
374   //   declarator or abstract-declarator of a parameter-declaration.
375   bool MightBeFunction = D.isFunctionDeclarationContext();
376   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
377     DeclaratorChunk &chunk = D.getTypeObject(i);
378     if (chunk.Kind == DeclaratorChunk::Function) {
379       if (MightBeFunction) {
380         // This is a function declaration. It can have default arguments, but
381         // keep looking in case its return type is a function type with default
382         // arguments.
383         MightBeFunction = false;
384         continue;
385       }
386       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
387            ++argIdx) {
388         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
389         if (Param->hasUnparsedDefaultArg()) {
390           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
391           SourceRange SR;
392           if (Toks->size() > 1)
393             SR = SourceRange((*Toks)[1].getLocation(),
394                              Toks->back().getLocation());
395           else
396             SR = UnparsedDefaultArgLocs[Param];
397           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
398             << SR;
399           delete Toks;
400           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
401         } else if (Param->getDefaultArg()) {
402           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
403             << Param->getDefaultArg()->getSourceRange();
404           Param->setDefaultArg(nullptr);
405         }
406       }
407     } else if (chunk.Kind != DeclaratorChunk::Paren) {
408       MightBeFunction = false;
409     }
410   }
411 }
412 
413 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
414   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
415     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
416     if (!PVD->hasDefaultArg())
417       return false;
418     if (!PVD->hasInheritedDefaultArg())
419       return true;
420   }
421   return false;
422 }
423 
424 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
425 /// function, once we already know that they have the same
426 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
427 /// error, false otherwise.
428 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
429                                 Scope *S) {
430   bool Invalid = false;
431 
432   // C++ [dcl.fct.default]p4:
433   //   For non-template functions, default arguments can be added in
434   //   later declarations of a function in the same
435   //   scope. Declarations in different scopes have completely
436   //   distinct sets of default arguments. That is, declarations in
437   //   inner scopes do not acquire default arguments from
438   //   declarations in outer scopes, and vice versa. In a given
439   //   function declaration, all parameters subsequent to a
440   //   parameter with a default argument shall have default
441   //   arguments supplied in this or previous declarations. A
442   //   default argument shall not be redefined by a later
443   //   declaration (not even to the same value).
444   //
445   // C++ [dcl.fct.default]p6:
446   //   Except for member functions of class templates, the default arguments
447   //   in a member function definition that appears outside of the class
448   //   definition are added to the set of default arguments provided by the
449   //   member function declaration in the class definition.
450   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
451     ParmVarDecl *OldParam = Old->getParamDecl(p);
452     ParmVarDecl *NewParam = New->getParamDecl(p);
453 
454     bool OldParamHasDfl = OldParam->hasDefaultArg();
455     bool NewParamHasDfl = NewParam->hasDefaultArg();
456 
457     // The declaration context corresponding to the scope is the semantic
458     // parent, unless this is a local function declaration, in which case
459     // it is that surrounding function.
460     DeclContext *ScopeDC = New->isLocalExternDecl()
461                                ? New->getLexicalDeclContext()
462                                : New->getDeclContext();
463     if (S && !isDeclInScope(Old, ScopeDC, S) &&
464         !New->getDeclContext()->isRecord())
465       // Ignore default parameters of old decl if they are not in
466       // the same scope and this is not an out-of-line definition of
467       // a member function.
468       OldParamHasDfl = false;
469     if (New->isLocalExternDecl() != Old->isLocalExternDecl())
470       // If only one of these is a local function declaration, then they are
471       // declared in different scopes, even though isDeclInScope may think
472       // they're in the same scope. (If both are local, the scope check is
473       // sufficent, and if neither is local, then they are in the same scope.)
474       OldParamHasDfl = false;
475 
476     if (OldParamHasDfl && NewParamHasDfl) {
477 
478       unsigned DiagDefaultParamID =
479         diag::err_param_default_argument_redefinition;
480 
481       // MSVC accepts that default parameters be redefined for member functions
482       // of template class. The new default parameter's value is ignored.
483       Invalid = true;
484       if (getLangOpts().MicrosoftExt) {
485         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
486         if (MD && MD->getParent()->getDescribedClassTemplate()) {
487           // Merge the old default argument into the new parameter.
488           NewParam->setHasInheritedDefaultArg();
489           if (OldParam->hasUninstantiatedDefaultArg())
490             NewParam->setUninstantiatedDefaultArg(
491                                       OldParam->getUninstantiatedDefaultArg());
492           else
493             NewParam->setDefaultArg(OldParam->getInit());
494           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
495           Invalid = false;
496         }
497       }
498 
499       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
500       // hint here. Alternatively, we could walk the type-source information
501       // for NewParam to find the last source location in the type... but it
502       // isn't worth the effort right now. This is the kind of test case that
503       // is hard to get right:
504       //   int f(int);
505       //   void g(int (*fp)(int) = f);
506       //   void g(int (*fp)(int) = &f);
507       Diag(NewParam->getLocation(), DiagDefaultParamID)
508         << NewParam->getDefaultArgRange();
509 
510       // Look for the function declaration where the default argument was
511       // actually written, which may be a declaration prior to Old.
512       for (FunctionDecl *Older = Old->getPreviousDecl();
513            Older; Older = Older->getPreviousDecl()) {
514         if (!Older->getParamDecl(p)->hasDefaultArg())
515           break;
516 
517         OldParam = Older->getParamDecl(p);
518       }
519 
520       Diag(OldParam->getLocation(), diag::note_previous_definition)
521         << OldParam->getDefaultArgRange();
522     } else if (OldParamHasDfl) {
523       // Merge the old default argument into the new parameter.
524       // It's important to use getInit() here;  getDefaultArg()
525       // strips off any top-level ExprWithCleanups.
526       NewParam->setHasInheritedDefaultArg();
527       if (OldParam->hasUninstantiatedDefaultArg())
528         NewParam->setUninstantiatedDefaultArg(
529                                       OldParam->getUninstantiatedDefaultArg());
530       else
531         NewParam->setDefaultArg(OldParam->getInit());
532     } else if (NewParamHasDfl) {
533       if (New->getDescribedFunctionTemplate()) {
534         // Paragraph 4, quoted above, only applies to non-template functions.
535         Diag(NewParam->getLocation(),
536              diag::err_param_default_argument_template_redecl)
537           << NewParam->getDefaultArgRange();
538         Diag(Old->getLocation(), diag::note_template_prev_declaration)
539           << false;
540       } else if (New->getTemplateSpecializationKind()
541                    != TSK_ImplicitInstantiation &&
542                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
543         // C++ [temp.expr.spec]p21:
544         //   Default function arguments shall not be specified in a declaration
545         //   or a definition for one of the following explicit specializations:
546         //     - the explicit specialization of a function template;
547         //     - the explicit specialization of a member function template;
548         //     - the explicit specialization of a member function of a class
549         //       template where the class template specialization to which the
550         //       member function specialization belongs is implicitly
551         //       instantiated.
552         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
553           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
554           << New->getDeclName()
555           << NewParam->getDefaultArgRange();
556       } else if (New->getDeclContext()->isDependentContext()) {
557         // C++ [dcl.fct.default]p6 (DR217):
558         //   Default arguments for a member function of a class template shall
559         //   be specified on the initial declaration of the member function
560         //   within the class template.
561         //
562         // Reading the tea leaves a bit in DR217 and its reference to DR205
563         // leads me to the conclusion that one cannot add default function
564         // arguments for an out-of-line definition of a member function of a
565         // dependent type.
566         int WhichKind = 2;
567         if (CXXRecordDecl *Record
568               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
569           if (Record->getDescribedClassTemplate())
570             WhichKind = 0;
571           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
572             WhichKind = 1;
573           else
574             WhichKind = 2;
575         }
576 
577         Diag(NewParam->getLocation(),
578              diag::err_param_default_argument_member_template_redecl)
579           << WhichKind
580           << NewParam->getDefaultArgRange();
581       }
582     }
583   }
584 
585   // DR1344: If a default argument is added outside a class definition and that
586   // default argument makes the function a special member function, the program
587   // is ill-formed. This can only happen for constructors.
588   if (isa<CXXConstructorDecl>(New) &&
589       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
590     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
591                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
592     if (NewSM != OldSM) {
593       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
594       assert(NewParam->hasDefaultArg());
595       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
596         << NewParam->getDefaultArgRange() << NewSM;
597       Diag(Old->getLocation(), diag::note_previous_declaration);
598     }
599   }
600 
601   const FunctionDecl *Def;
602   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
603   // template has a constexpr specifier then all its declarations shall
604   // contain the constexpr specifier.
605   if (New->isConstexpr() != Old->isConstexpr()) {
606     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
607       << New << New->isConstexpr();
608     Diag(Old->getLocation(), diag::note_previous_declaration);
609     Invalid = true;
610   } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
611     // C++11 [dcl.fcn.spec]p4:
612     //   If the definition of a function appears in a translation unit before its
613     //   first declaration as inline, the program is ill-formed.
614     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
615     Diag(Def->getLocation(), diag::note_previous_definition);
616     Invalid = true;
617   }
618 
619   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
620   // argument expression, that declaration shall be a definition and shall be
621   // the only declaration of the function or function template in the
622   // translation unit.
623   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
624       functionDeclHasDefaultArgument(Old)) {
625     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
626     Diag(Old->getLocation(), diag::note_previous_declaration);
627     Invalid = true;
628   }
629 
630   if (CheckEquivalentExceptionSpec(Old, New))
631     Invalid = true;
632 
633   return Invalid;
634 }
635 
636 /// \brief Merge the exception specifications of two variable declarations.
637 ///
638 /// This is called when there's a redeclaration of a VarDecl. The function
639 /// checks if the redeclaration might have an exception specification and
640 /// validates compatibility and merges the specs if necessary.
641 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
642   // Shortcut if exceptions are disabled.
643   if (!getLangOpts().CXXExceptions)
644     return;
645 
646   assert(Context.hasSameType(New->getType(), Old->getType()) &&
647          "Should only be called if types are otherwise the same.");
648 
649   QualType NewType = New->getType();
650   QualType OldType = Old->getType();
651 
652   // We're only interested in pointers and references to functions, as well
653   // as pointers to member functions.
654   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
655     NewType = R->getPointeeType();
656     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
657   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
658     NewType = P->getPointeeType();
659     OldType = OldType->getAs<PointerType>()->getPointeeType();
660   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
661     NewType = M->getPointeeType();
662     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
663   }
664 
665   if (!NewType->isFunctionProtoType())
666     return;
667 
668   // There's lots of special cases for functions. For function pointers, system
669   // libraries are hopefully not as broken so that we don't need these
670   // workarounds.
671   if (CheckEquivalentExceptionSpec(
672         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
673         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
674     New->setInvalidDecl();
675   }
676 }
677 
678 /// CheckCXXDefaultArguments - Verify that the default arguments for a
679 /// function declaration are well-formed according to C++
680 /// [dcl.fct.default].
681 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
682   unsigned NumParams = FD->getNumParams();
683   unsigned p;
684 
685   // Find first parameter with a default argument
686   for (p = 0; p < NumParams; ++p) {
687     ParmVarDecl *Param = FD->getParamDecl(p);
688     if (Param->hasDefaultArg())
689       break;
690   }
691 
692   // C++ [dcl.fct.default]p4:
693   //   In a given function declaration, all parameters
694   //   subsequent to a parameter with a default argument shall
695   //   have default arguments supplied in this or previous
696   //   declarations. A default argument shall not be redefined
697   //   by a later declaration (not even to the same value).
698   unsigned LastMissingDefaultArg = 0;
699   for (; p < NumParams; ++p) {
700     ParmVarDecl *Param = FD->getParamDecl(p);
701     if (!Param->hasDefaultArg()) {
702       if (Param->isInvalidDecl())
703         /* We already complained about this parameter. */;
704       else if (Param->getIdentifier())
705         Diag(Param->getLocation(),
706              diag::err_param_default_argument_missing_name)
707           << Param->getIdentifier();
708       else
709         Diag(Param->getLocation(),
710              diag::err_param_default_argument_missing);
711 
712       LastMissingDefaultArg = p;
713     }
714   }
715 
716   if (LastMissingDefaultArg > 0) {
717     // Some default arguments were missing. Clear out all of the
718     // default arguments up to (and including) the last missing
719     // default argument, so that we leave the function parameters
720     // in a semantically valid state.
721     for (p = 0; p <= LastMissingDefaultArg; ++p) {
722       ParmVarDecl *Param = FD->getParamDecl(p);
723       if (Param->hasDefaultArg()) {
724         Param->setDefaultArg(nullptr);
725       }
726     }
727   }
728 }
729 
730 // CheckConstexprParameterTypes - Check whether a function's parameter types
731 // are all literal types. If so, return true. If not, produce a suitable
732 // diagnostic and return false.
733 static bool CheckConstexprParameterTypes(Sema &SemaRef,
734                                          const FunctionDecl *FD) {
735   unsigned ArgIndex = 0;
736   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
737   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
738                                               e = FT->param_type_end();
739        i != e; ++i, ++ArgIndex) {
740     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
741     SourceLocation ParamLoc = PD->getLocation();
742     if (!(*i)->isDependentType() &&
743         SemaRef.RequireLiteralType(ParamLoc, *i,
744                                    diag::err_constexpr_non_literal_param,
745                                    ArgIndex+1, PD->getSourceRange(),
746                                    isa<CXXConstructorDecl>(FD)))
747       return false;
748   }
749   return true;
750 }
751 
752 /// \brief Get diagnostic %select index for tag kind for
753 /// record diagnostic message.
754 /// WARNING: Indexes apply to particular diagnostics only!
755 ///
756 /// \returns diagnostic %select index.
757 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
758   switch (Tag) {
759   case TTK_Struct: return 0;
760   case TTK_Interface: return 1;
761   case TTK_Class:  return 2;
762   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
763   }
764 }
765 
766 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
767 // the requirements of a constexpr function definition or a constexpr
768 // constructor definition. If so, return true. If not, produce appropriate
769 // diagnostics and return false.
770 //
771 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
772 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
773   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
774   if (MD && MD->isInstance()) {
775     // C++11 [dcl.constexpr]p4:
776     //  The definition of a constexpr constructor shall satisfy the following
777     //  constraints:
778     //  - the class shall not have any virtual base classes;
779     const CXXRecordDecl *RD = MD->getParent();
780     if (RD->getNumVBases()) {
781       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
782         << isa<CXXConstructorDecl>(NewFD)
783         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
784       for (const auto &I : RD->vbases())
785         Diag(I.getLocStart(),
786              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
787       return false;
788     }
789   }
790 
791   if (!isa<CXXConstructorDecl>(NewFD)) {
792     // C++11 [dcl.constexpr]p3:
793     //  The definition of a constexpr function shall satisfy the following
794     //  constraints:
795     // - it shall not be virtual;
796     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
797     if (Method && Method->isVirtual()) {
798       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
799 
800       // If it's not obvious why this function is virtual, find an overridden
801       // function which uses the 'virtual' keyword.
802       const CXXMethodDecl *WrittenVirtual = Method;
803       while (!WrittenVirtual->isVirtualAsWritten())
804         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
805       if (WrittenVirtual != Method)
806         Diag(WrittenVirtual->getLocation(),
807              diag::note_overridden_virtual_function);
808       return false;
809     }
810 
811     // - its return type shall be a literal type;
812     QualType RT = NewFD->getReturnType();
813     if (!RT->isDependentType() &&
814         RequireLiteralType(NewFD->getLocation(), RT,
815                            diag::err_constexpr_non_literal_return))
816       return false;
817   }
818 
819   // - each of its parameter types shall be a literal type;
820   if (!CheckConstexprParameterTypes(*this, NewFD))
821     return false;
822 
823   return true;
824 }
825 
826 /// Check the given declaration statement is legal within a constexpr function
827 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
828 ///
829 /// \return true if the body is OK (maybe only as an extension), false if we
830 ///         have diagnosed a problem.
831 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
832                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
833   // C++11 [dcl.constexpr]p3 and p4:
834   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
835   //  contain only
836   for (const auto *DclIt : DS->decls()) {
837     switch (DclIt->getKind()) {
838     case Decl::StaticAssert:
839     case Decl::Using:
840     case Decl::UsingShadow:
841     case Decl::UsingDirective:
842     case Decl::UnresolvedUsingTypename:
843     case Decl::UnresolvedUsingValue:
844       //   - static_assert-declarations
845       //   - using-declarations,
846       //   - using-directives,
847       continue;
848 
849     case Decl::Typedef:
850     case Decl::TypeAlias: {
851       //   - typedef declarations and alias-declarations that do not define
852       //     classes or enumerations,
853       const auto *TN = cast<TypedefNameDecl>(DclIt);
854       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
855         // Don't allow variably-modified types in constexpr functions.
856         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
857         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
858           << TL.getSourceRange() << TL.getType()
859           << isa<CXXConstructorDecl>(Dcl);
860         return false;
861       }
862       continue;
863     }
864 
865     case Decl::Enum:
866     case Decl::CXXRecord:
867       // C++1y allows types to be defined, not just declared.
868       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
869         SemaRef.Diag(DS->getLocStart(),
870                      SemaRef.getLangOpts().CPlusPlus14
871                        ? diag::warn_cxx11_compat_constexpr_type_definition
872                        : diag::ext_constexpr_type_definition)
873           << isa<CXXConstructorDecl>(Dcl);
874       continue;
875 
876     case Decl::EnumConstant:
877     case Decl::IndirectField:
878     case Decl::ParmVar:
879       // These can only appear with other declarations which are banned in
880       // C++11 and permitted in C++1y, so ignore them.
881       continue;
882 
883     case Decl::Var: {
884       // C++1y [dcl.constexpr]p3 allows anything except:
885       //   a definition of a variable of non-literal type or of static or
886       //   thread storage duration or for which no initialization is performed.
887       const auto *VD = cast<VarDecl>(DclIt);
888       if (VD->isThisDeclarationADefinition()) {
889         if (VD->isStaticLocal()) {
890           SemaRef.Diag(VD->getLocation(),
891                        diag::err_constexpr_local_var_static)
892             << isa<CXXConstructorDecl>(Dcl)
893             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
894           return false;
895         }
896         if (!VD->getType()->isDependentType() &&
897             SemaRef.RequireLiteralType(
898               VD->getLocation(), VD->getType(),
899               diag::err_constexpr_local_var_non_literal_type,
900               isa<CXXConstructorDecl>(Dcl)))
901           return false;
902         if (!VD->getType()->isDependentType() &&
903             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
904           SemaRef.Diag(VD->getLocation(),
905                        diag::err_constexpr_local_var_no_init)
906             << isa<CXXConstructorDecl>(Dcl);
907           return false;
908         }
909       }
910       SemaRef.Diag(VD->getLocation(),
911                    SemaRef.getLangOpts().CPlusPlus14
912                     ? diag::warn_cxx11_compat_constexpr_local_var
913                     : diag::ext_constexpr_local_var)
914         << isa<CXXConstructorDecl>(Dcl);
915       continue;
916     }
917 
918     case Decl::NamespaceAlias:
919     case Decl::Function:
920       // These are disallowed in C++11 and permitted in C++1y. Allow them
921       // everywhere as an extension.
922       if (!Cxx1yLoc.isValid())
923         Cxx1yLoc = DS->getLocStart();
924       continue;
925 
926     default:
927       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
928         << isa<CXXConstructorDecl>(Dcl);
929       return false;
930     }
931   }
932 
933   return true;
934 }
935 
936 /// Check that the given field is initialized within a constexpr constructor.
937 ///
938 /// \param Dcl The constexpr constructor being checked.
939 /// \param Field The field being checked. This may be a member of an anonymous
940 ///        struct or union nested within the class being checked.
941 /// \param Inits All declarations, including anonymous struct/union members and
942 ///        indirect members, for which any initialization was provided.
943 /// \param Diagnosed Set to true if an error is produced.
944 static void CheckConstexprCtorInitializer(Sema &SemaRef,
945                                           const FunctionDecl *Dcl,
946                                           FieldDecl *Field,
947                                           llvm::SmallSet<Decl*, 16> &Inits,
948                                           bool &Diagnosed) {
949   if (Field->isInvalidDecl())
950     return;
951 
952   if (Field->isUnnamedBitfield())
953     return;
954 
955   // Anonymous unions with no variant members and empty anonymous structs do not
956   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
957   // indirect fields don't need initializing.
958   if (Field->isAnonymousStructOrUnion() &&
959       (Field->getType()->isUnionType()
960            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
961            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
962     return;
963 
964   if (!Inits.count(Field)) {
965     if (!Diagnosed) {
966       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
967       Diagnosed = true;
968     }
969     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
970   } else if (Field->isAnonymousStructOrUnion()) {
971     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
972     for (auto *I : RD->fields())
973       // If an anonymous union contains an anonymous struct of which any member
974       // is initialized, all members must be initialized.
975       if (!RD->isUnion() || Inits.count(I))
976         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
977   }
978 }
979 
980 /// Check the provided statement is allowed in a constexpr function
981 /// definition.
982 static bool
983 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
984                            SmallVectorImpl<SourceLocation> &ReturnStmts,
985                            SourceLocation &Cxx1yLoc) {
986   // - its function-body shall be [...] a compound-statement that contains only
987   switch (S->getStmtClass()) {
988   case Stmt::NullStmtClass:
989     //   - null statements,
990     return true;
991 
992   case Stmt::DeclStmtClass:
993     //   - static_assert-declarations
994     //   - using-declarations,
995     //   - using-directives,
996     //   - typedef declarations and alias-declarations that do not define
997     //     classes or enumerations,
998     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
999       return false;
1000     return true;
1001 
1002   case Stmt::ReturnStmtClass:
1003     //   - and exactly one return statement;
1004     if (isa<CXXConstructorDecl>(Dcl)) {
1005       // C++1y allows return statements in constexpr constructors.
1006       if (!Cxx1yLoc.isValid())
1007         Cxx1yLoc = S->getLocStart();
1008       return true;
1009     }
1010 
1011     ReturnStmts.push_back(S->getLocStart());
1012     return true;
1013 
1014   case Stmt::CompoundStmtClass: {
1015     // C++1y allows compound-statements.
1016     if (!Cxx1yLoc.isValid())
1017       Cxx1yLoc = S->getLocStart();
1018 
1019     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1020     for (auto *BodyIt : CompStmt->body()) {
1021       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1022                                       Cxx1yLoc))
1023         return false;
1024     }
1025     return true;
1026   }
1027 
1028   case Stmt::AttributedStmtClass:
1029     if (!Cxx1yLoc.isValid())
1030       Cxx1yLoc = S->getLocStart();
1031     return true;
1032 
1033   case Stmt::IfStmtClass: {
1034     // C++1y allows if-statements.
1035     if (!Cxx1yLoc.isValid())
1036       Cxx1yLoc = S->getLocStart();
1037 
1038     IfStmt *If = cast<IfStmt>(S);
1039     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1040                                     Cxx1yLoc))
1041       return false;
1042     if (If->getElse() &&
1043         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1044                                     Cxx1yLoc))
1045       return false;
1046     return true;
1047   }
1048 
1049   case Stmt::WhileStmtClass:
1050   case Stmt::DoStmtClass:
1051   case Stmt::ForStmtClass:
1052   case Stmt::CXXForRangeStmtClass:
1053   case Stmt::ContinueStmtClass:
1054     // C++1y allows all of these. We don't allow them as extensions in C++11,
1055     // because they don't make sense without variable mutation.
1056     if (!SemaRef.getLangOpts().CPlusPlus14)
1057       break;
1058     if (!Cxx1yLoc.isValid())
1059       Cxx1yLoc = S->getLocStart();
1060     for (Stmt::child_range Children = S->children(); Children; ++Children)
1061       if (*Children &&
1062           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1063                                       Cxx1yLoc))
1064         return false;
1065     return true;
1066 
1067   case Stmt::SwitchStmtClass:
1068   case Stmt::CaseStmtClass:
1069   case Stmt::DefaultStmtClass:
1070   case Stmt::BreakStmtClass:
1071     // C++1y allows switch-statements, and since they don't need variable
1072     // mutation, we can reasonably allow them in C++11 as an extension.
1073     if (!Cxx1yLoc.isValid())
1074       Cxx1yLoc = S->getLocStart();
1075     for (Stmt::child_range Children = S->children(); Children; ++Children)
1076       if (*Children &&
1077           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1078                                       Cxx1yLoc))
1079         return false;
1080     return true;
1081 
1082   default:
1083     if (!isa<Expr>(S))
1084       break;
1085 
1086     // C++1y allows expression-statements.
1087     if (!Cxx1yLoc.isValid())
1088       Cxx1yLoc = S->getLocStart();
1089     return true;
1090   }
1091 
1092   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1093     << isa<CXXConstructorDecl>(Dcl);
1094   return false;
1095 }
1096 
1097 /// Check the body for the given constexpr function declaration only contains
1098 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1099 ///
1100 /// \return true if the body is OK, false if we have diagnosed a problem.
1101 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1102   if (isa<CXXTryStmt>(Body)) {
1103     // C++11 [dcl.constexpr]p3:
1104     //  The definition of a constexpr function shall satisfy the following
1105     //  constraints: [...]
1106     // - its function-body shall be = delete, = default, or a
1107     //   compound-statement
1108     //
1109     // C++11 [dcl.constexpr]p4:
1110     //  In the definition of a constexpr constructor, [...]
1111     // - its function-body shall not be a function-try-block;
1112     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1113       << isa<CXXConstructorDecl>(Dcl);
1114     return false;
1115   }
1116 
1117   SmallVector<SourceLocation, 4> ReturnStmts;
1118 
1119   // - its function-body shall be [...] a compound-statement that contains only
1120   //   [... list of cases ...]
1121   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1122   SourceLocation Cxx1yLoc;
1123   for (auto *BodyIt : CompBody->body()) {
1124     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1125       return false;
1126   }
1127 
1128   if (Cxx1yLoc.isValid())
1129     Diag(Cxx1yLoc,
1130          getLangOpts().CPlusPlus14
1131            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1132            : diag::ext_constexpr_body_invalid_stmt)
1133       << isa<CXXConstructorDecl>(Dcl);
1134 
1135   if (const CXXConstructorDecl *Constructor
1136         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1137     const CXXRecordDecl *RD = Constructor->getParent();
1138     // DR1359:
1139     // - every non-variant non-static data member and base class sub-object
1140     //   shall be initialized;
1141     // DR1460:
1142     // - if the class is a union having variant members, exactly one of them
1143     //   shall be initialized;
1144     if (RD->isUnion()) {
1145       if (Constructor->getNumCtorInitializers() == 0 &&
1146           RD->hasVariantMembers()) {
1147         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1148         return false;
1149       }
1150     } else if (!Constructor->isDependentContext() &&
1151                !Constructor->isDelegatingConstructor()) {
1152       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1153 
1154       // Skip detailed checking if we have enough initializers, and we would
1155       // allow at most one initializer per member.
1156       bool AnyAnonStructUnionMembers = false;
1157       unsigned Fields = 0;
1158       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1159            E = RD->field_end(); I != E; ++I, ++Fields) {
1160         if (I->isAnonymousStructOrUnion()) {
1161           AnyAnonStructUnionMembers = true;
1162           break;
1163         }
1164       }
1165       // DR1460:
1166       // - if the class is a union-like class, but is not a union, for each of
1167       //   its anonymous union members having variant members, exactly one of
1168       //   them shall be initialized;
1169       if (AnyAnonStructUnionMembers ||
1170           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1171         // Check initialization of non-static data members. Base classes are
1172         // always initialized so do not need to be checked. Dependent bases
1173         // might not have initializers in the member initializer list.
1174         llvm::SmallSet<Decl*, 16> Inits;
1175         for (const auto *I: Constructor->inits()) {
1176           if (FieldDecl *FD = I->getMember())
1177             Inits.insert(FD);
1178           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1179             Inits.insert(ID->chain_begin(), ID->chain_end());
1180         }
1181 
1182         bool Diagnosed = false;
1183         for (auto *I : RD->fields())
1184           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1185         if (Diagnosed)
1186           return false;
1187       }
1188     }
1189   } else {
1190     if (ReturnStmts.empty()) {
1191       // C++1y doesn't require constexpr functions to contain a 'return'
1192       // statement. We still do, unless the return type might be void, because
1193       // otherwise if there's no return statement, the function cannot
1194       // be used in a core constant expression.
1195       bool OK = getLangOpts().CPlusPlus14 &&
1196                 (Dcl->getReturnType()->isVoidType() ||
1197                  Dcl->getReturnType()->isDependentType());
1198       Diag(Dcl->getLocation(),
1199            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1200               : diag::err_constexpr_body_no_return);
1201       return OK;
1202     }
1203     if (ReturnStmts.size() > 1) {
1204       Diag(ReturnStmts.back(),
1205            getLangOpts().CPlusPlus14
1206              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1207              : diag::ext_constexpr_body_multiple_return);
1208       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1209         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1210     }
1211   }
1212 
1213   // C++11 [dcl.constexpr]p5:
1214   //   if no function argument values exist such that the function invocation
1215   //   substitution would produce a constant expression, the program is
1216   //   ill-formed; no diagnostic required.
1217   // C++11 [dcl.constexpr]p3:
1218   //   - every constructor call and implicit conversion used in initializing the
1219   //     return value shall be one of those allowed in a constant expression.
1220   // C++11 [dcl.constexpr]p4:
1221   //   - every constructor involved in initializing non-static data members and
1222   //     base class sub-objects shall be a constexpr constructor.
1223   SmallVector<PartialDiagnosticAt, 8> Diags;
1224   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1225     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1226       << isa<CXXConstructorDecl>(Dcl);
1227     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1228       Diag(Diags[I].first, Diags[I].second);
1229     // Don't return false here: we allow this for compatibility in
1230     // system headers.
1231   }
1232 
1233   return true;
1234 }
1235 
1236 /// isCurrentClassName - Determine whether the identifier II is the
1237 /// name of the class type currently being defined. In the case of
1238 /// nested classes, this will only return true if II is the name of
1239 /// the innermost class.
1240 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1241                               const CXXScopeSpec *SS) {
1242   assert(getLangOpts().CPlusPlus && "No class names in C!");
1243 
1244   CXXRecordDecl *CurDecl;
1245   if (SS && SS->isSet() && !SS->isInvalid()) {
1246     DeclContext *DC = computeDeclContext(*SS, true);
1247     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1248   } else
1249     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1250 
1251   if (CurDecl && CurDecl->getIdentifier())
1252     return &II == CurDecl->getIdentifier();
1253   return false;
1254 }
1255 
1256 /// \brief Determine whether the identifier II is a typo for the name of
1257 /// the class type currently being defined. If so, update it to the identifier
1258 /// that should have been used.
1259 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1260   assert(getLangOpts().CPlusPlus && "No class names in C!");
1261 
1262   if (!getLangOpts().SpellChecking)
1263     return false;
1264 
1265   CXXRecordDecl *CurDecl;
1266   if (SS && SS->isSet() && !SS->isInvalid()) {
1267     DeclContext *DC = computeDeclContext(*SS, true);
1268     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1269   } else
1270     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1271 
1272   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1273       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1274           < II->getLength()) {
1275     II = CurDecl->getIdentifier();
1276     return true;
1277   }
1278 
1279   return false;
1280 }
1281 
1282 /// \brief Determine whether the given class is a base class of the given
1283 /// class, including looking at dependent bases.
1284 static bool findCircularInheritance(const CXXRecordDecl *Class,
1285                                     const CXXRecordDecl *Current) {
1286   SmallVector<const CXXRecordDecl*, 8> Queue;
1287 
1288   Class = Class->getCanonicalDecl();
1289   while (true) {
1290     for (const auto &I : Current->bases()) {
1291       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1292       if (!Base)
1293         continue;
1294 
1295       Base = Base->getDefinition();
1296       if (!Base)
1297         continue;
1298 
1299       if (Base->getCanonicalDecl() == Class)
1300         return true;
1301 
1302       Queue.push_back(Base);
1303     }
1304 
1305     if (Queue.empty())
1306       return false;
1307 
1308     Current = Queue.pop_back_val();
1309   }
1310 
1311   return false;
1312 }
1313 
1314 /// \brief Perform propagation of DLL attributes from a derived class to a
1315 /// templated base class for MS compatibility.
1316 static void propagateDLLAttrToBaseClassTemplate(
1317     Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1318     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1319   if (getDLLAttr(
1320           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1321     // If the base class template has a DLL attribute, don't try to change it.
1322     return;
1323   }
1324 
1325   if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1326     // If the base class is not already specialized, we can do the propagation.
1327     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1328     NewAttr->setInherited(true);
1329     BaseTemplateSpec->addAttr(NewAttr);
1330     return;
1331   }
1332 
1333   bool DifferentAttribute = false;
1334   if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1335     if (!SpecializationAttr->isInherited()) {
1336       // The template has previously been specialized or instantiated with an
1337       // explicit attribute. We should not try to change it.
1338       return;
1339     }
1340     if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1341       // The specialization already has the right attribute.
1342       return;
1343     }
1344     DifferentAttribute = true;
1345   }
1346 
1347   // The template was previously instantiated or explicitly specialized without
1348   // a dll attribute, or the template was previously instantiated with a
1349   // different inherited attribute. It's too late for us to change the
1350   // attribute, so warn that this is unsupported.
1351   S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1352       << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1353   S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1354   if (BaseTemplateSpec->isExplicitSpecialization()) {
1355     S.Diag(BaseTemplateSpec->getLocation(),
1356            diag::note_template_class_explicit_specialization_was_here)
1357         << BaseTemplateSpec;
1358   } else {
1359     S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1360            diag::note_template_class_instantiation_was_here)
1361         << BaseTemplateSpec;
1362   }
1363 }
1364 
1365 /// \brief Check the validity of a C++ base class specifier.
1366 ///
1367 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1368 /// and returns NULL otherwise.
1369 CXXBaseSpecifier *
1370 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1371                          SourceRange SpecifierRange,
1372                          bool Virtual, AccessSpecifier Access,
1373                          TypeSourceInfo *TInfo,
1374                          SourceLocation EllipsisLoc) {
1375   QualType BaseType = TInfo->getType();
1376 
1377   // C++ [class.union]p1:
1378   //   A union shall not have base classes.
1379   if (Class->isUnion()) {
1380     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1381       << SpecifierRange;
1382     return nullptr;
1383   }
1384 
1385   if (EllipsisLoc.isValid() &&
1386       !TInfo->getType()->containsUnexpandedParameterPack()) {
1387     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1388       << TInfo->getTypeLoc().getSourceRange();
1389     EllipsisLoc = SourceLocation();
1390   }
1391 
1392   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1393 
1394   if (BaseType->isDependentType()) {
1395     // Make sure that we don't have circular inheritance among our dependent
1396     // bases. For non-dependent bases, the check for completeness below handles
1397     // this.
1398     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1399       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1400           ((BaseDecl = BaseDecl->getDefinition()) &&
1401            findCircularInheritance(Class, BaseDecl))) {
1402         Diag(BaseLoc, diag::err_circular_inheritance)
1403           << BaseType << Context.getTypeDeclType(Class);
1404 
1405         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1406           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1407             << BaseType;
1408 
1409         return nullptr;
1410       }
1411     }
1412 
1413     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1414                                           Class->getTagKind() == TTK_Class,
1415                                           Access, TInfo, EllipsisLoc);
1416   }
1417 
1418   // Base specifiers must be record types.
1419   if (!BaseType->isRecordType()) {
1420     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1421     return nullptr;
1422   }
1423 
1424   // C++ [class.union]p1:
1425   //   A union shall not be used as a base class.
1426   if (BaseType->isUnionType()) {
1427     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1428     return nullptr;
1429   }
1430 
1431   // For the MS ABI, propagate DLL attributes to base class templates.
1432   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1433     if (Attr *ClassAttr = getDLLAttr(Class)) {
1434       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1435               BaseType->getAsCXXRecordDecl())) {
1436         propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1437                                             BaseTemplate, BaseLoc);
1438       }
1439     }
1440   }
1441 
1442   // C++ [class.derived]p2:
1443   //   The class-name in a base-specifier shall not be an incompletely
1444   //   defined class.
1445   if (RequireCompleteType(BaseLoc, BaseType,
1446                           diag::err_incomplete_base_class, SpecifierRange)) {
1447     Class->setInvalidDecl();
1448     return nullptr;
1449   }
1450 
1451   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1452   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1453   assert(BaseDecl && "Record type has no declaration");
1454   BaseDecl = BaseDecl->getDefinition();
1455   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1456   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1457   assert(CXXBaseDecl && "Base type is not a C++ type");
1458 
1459   // A class which contains a flexible array member is not suitable for use as a
1460   // base class:
1461   //   - If the layout determines that a base comes before another base,
1462   //     the flexible array member would index into the subsequent base.
1463   //   - If the layout determines that base comes before the derived class,
1464   //     the flexible array member would index into the derived class.
1465   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1466     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1467       << CXXBaseDecl->getDeclName();
1468     return nullptr;
1469   }
1470 
1471   // C++ [class]p3:
1472   //   If a class is marked final and it appears as a base-type-specifier in
1473   //   base-clause, the program is ill-formed.
1474   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1475     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1476       << CXXBaseDecl->getDeclName()
1477       << FA->isSpelledAsSealed();
1478     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1479         << CXXBaseDecl->getDeclName() << FA->getRange();
1480     return nullptr;
1481   }
1482 
1483   if (BaseDecl->isInvalidDecl())
1484     Class->setInvalidDecl();
1485 
1486   // Create the base specifier.
1487   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1488                                         Class->getTagKind() == TTK_Class,
1489                                         Access, TInfo, EllipsisLoc);
1490 }
1491 
1492 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1493 /// one entry in the base class list of a class specifier, for
1494 /// example:
1495 ///    class foo : public bar, virtual private baz {
1496 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1497 BaseResult
1498 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1499                          ParsedAttributes &Attributes,
1500                          bool Virtual, AccessSpecifier Access,
1501                          ParsedType basetype, SourceLocation BaseLoc,
1502                          SourceLocation EllipsisLoc) {
1503   if (!classdecl)
1504     return true;
1505 
1506   AdjustDeclIfTemplate(classdecl);
1507   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1508   if (!Class)
1509     return true;
1510 
1511   // We haven't yet attached the base specifiers.
1512   Class->setIsParsingBaseSpecifiers();
1513 
1514   // We do not support any C++11 attributes on base-specifiers yet.
1515   // Diagnose any attributes we see.
1516   if (!Attributes.empty()) {
1517     for (AttributeList *Attr = Attributes.getList(); Attr;
1518          Attr = Attr->getNext()) {
1519       if (Attr->isInvalid() ||
1520           Attr->getKind() == AttributeList::IgnoredAttribute)
1521         continue;
1522       Diag(Attr->getLoc(),
1523            Attr->getKind() == AttributeList::UnknownAttribute
1524              ? diag::warn_unknown_attribute_ignored
1525              : diag::err_base_specifier_attribute)
1526         << Attr->getName();
1527     }
1528   }
1529 
1530   TypeSourceInfo *TInfo = nullptr;
1531   GetTypeFromParser(basetype, &TInfo);
1532 
1533   if (EllipsisLoc.isInvalid() &&
1534       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1535                                       UPPC_BaseType))
1536     return true;
1537 
1538   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1539                                                       Virtual, Access, TInfo,
1540                                                       EllipsisLoc))
1541     return BaseSpec;
1542   else
1543     Class->setInvalidDecl();
1544 
1545   return true;
1546 }
1547 
1548 /// Use small set to collect indirect bases.  As this is only used
1549 /// locally, there's no need to abstract the small size parameter.
1550 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1551 
1552 /// \brief Recursively add the bases of Type.  Don't add Type itself.
1553 static void
1554 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1555                   const QualType &Type)
1556 {
1557   // Even though the incoming type is a base, it might not be
1558   // a class -- it could be a template parm, for instance.
1559   if (auto Rec = Type->getAs<RecordType>()) {
1560     auto Decl = Rec->getAsCXXRecordDecl();
1561 
1562     // Iterate over its bases.
1563     for (const auto &BaseSpec : Decl->bases()) {
1564       QualType Base = Context.getCanonicalType(BaseSpec.getType())
1565         .getUnqualifiedType();
1566       if (Set.insert(Base).second)
1567         // If we've not already seen it, recurse.
1568         NoteIndirectBases(Context, Set, Base);
1569     }
1570   }
1571 }
1572 
1573 /// \brief Performs the actual work of attaching the given base class
1574 /// specifiers to a C++ class.
1575 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1576                                 unsigned NumBases) {
1577  if (NumBases == 0)
1578     return false;
1579 
1580   // Used to keep track of which base types we have already seen, so
1581   // that we can properly diagnose redundant direct base types. Note
1582   // that the key is always the unqualified canonical type of the base
1583   // class.
1584   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1585 
1586   // Used to track indirect bases so we can see if a direct base is
1587   // ambiguous.
1588   IndirectBaseSet IndirectBaseTypes;
1589 
1590   // Copy non-redundant base specifiers into permanent storage.
1591   unsigned NumGoodBases = 0;
1592   bool Invalid = false;
1593   for (unsigned idx = 0; idx < NumBases; ++idx) {
1594     QualType NewBaseType
1595       = Context.getCanonicalType(Bases[idx]->getType());
1596     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1597 
1598     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1599     if (KnownBase) {
1600       // C++ [class.mi]p3:
1601       //   A class shall not be specified as a direct base class of a
1602       //   derived class more than once.
1603       Diag(Bases[idx]->getLocStart(),
1604            diag::err_duplicate_base_class)
1605         << KnownBase->getType()
1606         << Bases[idx]->getSourceRange();
1607 
1608       // Delete the duplicate base class specifier; we're going to
1609       // overwrite its pointer later.
1610       Context.Deallocate(Bases[idx]);
1611 
1612       Invalid = true;
1613     } else {
1614       // Okay, add this new base class.
1615       KnownBase = Bases[idx];
1616       Bases[NumGoodBases++] = Bases[idx];
1617 
1618       // Note this base's direct & indirect bases, if there could be ambiguity.
1619       if (NumBases > 1)
1620         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1621 
1622       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1623         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1624         if (Class->isInterface() &&
1625               (!RD->isInterface() ||
1626                KnownBase->getAccessSpecifier() != AS_public)) {
1627           // The Microsoft extension __interface does not permit bases that
1628           // are not themselves public interfaces.
1629           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1630             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1631             << RD->getSourceRange();
1632           Invalid = true;
1633         }
1634         if (RD->hasAttr<WeakAttr>())
1635           Class->addAttr(WeakAttr::CreateImplicit(Context));
1636       }
1637     }
1638   }
1639 
1640   // Attach the remaining base class specifiers to the derived class.
1641   Class->setBases(Bases, NumGoodBases);
1642 
1643   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1644     // Check whether this direct base is inaccessible due to ambiguity.
1645     QualType BaseType = Bases[idx]->getType();
1646     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1647       .getUnqualifiedType();
1648 
1649     if (IndirectBaseTypes.count(CanonicalBase)) {
1650       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1651                          /*DetectVirtual=*/true);
1652       bool found
1653         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1654       assert(found);
1655       (void)found;
1656 
1657       if (Paths.isAmbiguous(CanonicalBase))
1658         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1659           << BaseType << getAmbiguousPathsDisplayString(Paths)
1660           << Bases[idx]->getSourceRange();
1661       else
1662         assert(Bases[idx]->isVirtual());
1663     }
1664 
1665     // Delete the base class specifier, since its data has been copied
1666     // into the CXXRecordDecl.
1667     Context.Deallocate(Bases[idx]);
1668   }
1669 
1670   return Invalid;
1671 }
1672 
1673 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1674 /// class, after checking whether there are any duplicate base
1675 /// classes.
1676 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1677                                unsigned NumBases) {
1678   if (!ClassDecl || !Bases || !NumBases)
1679     return;
1680 
1681   AdjustDeclIfTemplate(ClassDecl);
1682   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1683 }
1684 
1685 /// \brief Determine whether the type \p Derived is a C++ class that is
1686 /// derived from the type \p Base.
1687 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1688   if (!getLangOpts().CPlusPlus)
1689     return false;
1690 
1691   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1692   if (!DerivedRD)
1693     return false;
1694 
1695   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1696   if (!BaseRD)
1697     return false;
1698 
1699   // If either the base or the derived type is invalid, don't try to
1700   // check whether one is derived from the other.
1701   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1702     return false;
1703 
1704   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1705   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1706 }
1707 
1708 /// \brief Determine whether the type \p Derived is a C++ class that is
1709 /// derived from the type \p Base.
1710 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1711   if (!getLangOpts().CPlusPlus)
1712     return false;
1713 
1714   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1715   if (!DerivedRD)
1716     return false;
1717 
1718   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1719   if (!BaseRD)
1720     return false;
1721 
1722   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1723 }
1724 
1725 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1726                               CXXCastPath &BasePathArray) {
1727   assert(BasePathArray.empty() && "Base path array must be empty!");
1728   assert(Paths.isRecordingPaths() && "Must record paths!");
1729 
1730   const CXXBasePath &Path = Paths.front();
1731 
1732   // We first go backward and check if we have a virtual base.
1733   // FIXME: It would be better if CXXBasePath had the base specifier for
1734   // the nearest virtual base.
1735   unsigned Start = 0;
1736   for (unsigned I = Path.size(); I != 0; --I) {
1737     if (Path[I - 1].Base->isVirtual()) {
1738       Start = I - 1;
1739       break;
1740     }
1741   }
1742 
1743   // Now add all bases.
1744   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1745     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1746 }
1747 
1748 /// \brief Determine whether the given base path includes a virtual
1749 /// base class.
1750 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1751   for (CXXCastPath::const_iterator B = BasePath.begin(),
1752                                 BEnd = BasePath.end();
1753        B != BEnd; ++B)
1754     if ((*B)->isVirtual())
1755       return true;
1756 
1757   return false;
1758 }
1759 
1760 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1761 /// conversion (where Derived and Base are class types) is
1762 /// well-formed, meaning that the conversion is unambiguous (and
1763 /// that all of the base classes are accessible). Returns true
1764 /// and emits a diagnostic if the code is ill-formed, returns false
1765 /// otherwise. Loc is the location where this routine should point to
1766 /// if there is an error, and Range is the source range to highlight
1767 /// if there is an error.
1768 bool
1769 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1770                                    unsigned InaccessibleBaseID,
1771                                    unsigned AmbigiousBaseConvID,
1772                                    SourceLocation Loc, SourceRange Range,
1773                                    DeclarationName Name,
1774                                    CXXCastPath *BasePath) {
1775   // First, determine whether the path from Derived to Base is
1776   // ambiguous. This is slightly more expensive than checking whether
1777   // the Derived to Base conversion exists, because here we need to
1778   // explore multiple paths to determine if there is an ambiguity.
1779   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1780                      /*DetectVirtual=*/false);
1781   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1782   assert(DerivationOkay &&
1783          "Can only be used with a derived-to-base conversion");
1784   (void)DerivationOkay;
1785 
1786   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1787     if (InaccessibleBaseID) {
1788       // Check that the base class can be accessed.
1789       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1790                                    InaccessibleBaseID)) {
1791         case AR_inaccessible:
1792           return true;
1793         case AR_accessible:
1794         case AR_dependent:
1795         case AR_delayed:
1796           break;
1797       }
1798     }
1799 
1800     // Build a base path if necessary.
1801     if (BasePath)
1802       BuildBasePathArray(Paths, *BasePath);
1803     return false;
1804   }
1805 
1806   if (AmbigiousBaseConvID) {
1807     // We know that the derived-to-base conversion is ambiguous, and
1808     // we're going to produce a diagnostic. Perform the derived-to-base
1809     // search just one more time to compute all of the possible paths so
1810     // that we can print them out. This is more expensive than any of
1811     // the previous derived-to-base checks we've done, but at this point
1812     // performance isn't as much of an issue.
1813     Paths.clear();
1814     Paths.setRecordingPaths(true);
1815     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1816     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1817     (void)StillOkay;
1818 
1819     // Build up a textual representation of the ambiguous paths, e.g.,
1820     // D -> B -> A, that will be used to illustrate the ambiguous
1821     // conversions in the diagnostic. We only print one of the paths
1822     // to each base class subobject.
1823     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1824 
1825     Diag(Loc, AmbigiousBaseConvID)
1826     << Derived << Base << PathDisplayStr << Range << Name;
1827   }
1828   return true;
1829 }
1830 
1831 bool
1832 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1833                                    SourceLocation Loc, SourceRange Range,
1834                                    CXXCastPath *BasePath,
1835                                    bool IgnoreAccess) {
1836   return CheckDerivedToBaseConversion(Derived, Base,
1837                                       IgnoreAccess ? 0
1838                                        : diag::err_upcast_to_inaccessible_base,
1839                                       diag::err_ambiguous_derived_to_base_conv,
1840                                       Loc, Range, DeclarationName(),
1841                                       BasePath);
1842 }
1843 
1844 
1845 /// @brief Builds a string representing ambiguous paths from a
1846 /// specific derived class to different subobjects of the same base
1847 /// class.
1848 ///
1849 /// This function builds a string that can be used in error messages
1850 /// to show the different paths that one can take through the
1851 /// inheritance hierarchy to go from the derived class to different
1852 /// subobjects of a base class. The result looks something like this:
1853 /// @code
1854 /// struct D -> struct B -> struct A
1855 /// struct D -> struct C -> struct A
1856 /// @endcode
1857 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1858   std::string PathDisplayStr;
1859   std::set<unsigned> DisplayedPaths;
1860   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1861        Path != Paths.end(); ++Path) {
1862     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1863       // We haven't displayed a path to this particular base
1864       // class subobject yet.
1865       PathDisplayStr += "\n    ";
1866       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1867       for (CXXBasePath::const_iterator Element = Path->begin();
1868            Element != Path->end(); ++Element)
1869         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1870     }
1871   }
1872 
1873   return PathDisplayStr;
1874 }
1875 
1876 //===----------------------------------------------------------------------===//
1877 // C++ class member Handling
1878 //===----------------------------------------------------------------------===//
1879 
1880 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1881 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1882                                 SourceLocation ASLoc,
1883                                 SourceLocation ColonLoc,
1884                                 AttributeList *Attrs) {
1885   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1886   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1887                                                   ASLoc, ColonLoc);
1888   CurContext->addHiddenDecl(ASDecl);
1889   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1890 }
1891 
1892 /// CheckOverrideControl - Check C++11 override control semantics.
1893 void Sema::CheckOverrideControl(NamedDecl *D) {
1894   if (D->isInvalidDecl())
1895     return;
1896 
1897   // We only care about "override" and "final" declarations.
1898   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1899     return;
1900 
1901   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1902 
1903   // We can't check dependent instance methods.
1904   if (MD && MD->isInstance() &&
1905       (MD->getParent()->hasAnyDependentBases() ||
1906        MD->getType()->isDependentType()))
1907     return;
1908 
1909   if (MD && !MD->isVirtual()) {
1910     // If we have a non-virtual method, check if if hides a virtual method.
1911     // (In that case, it's most likely the method has the wrong type.)
1912     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1913     FindHiddenVirtualMethods(MD, OverloadedMethods);
1914 
1915     if (!OverloadedMethods.empty()) {
1916       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1917         Diag(OA->getLocation(),
1918              diag::override_keyword_hides_virtual_member_function)
1919           << "override" << (OverloadedMethods.size() > 1);
1920       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1921         Diag(FA->getLocation(),
1922              diag::override_keyword_hides_virtual_member_function)
1923           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1924           << (OverloadedMethods.size() > 1);
1925       }
1926       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1927       MD->setInvalidDecl();
1928       return;
1929     }
1930     // Fall through into the general case diagnostic.
1931     // FIXME: We might want to attempt typo correction here.
1932   }
1933 
1934   if (!MD || !MD->isVirtual()) {
1935     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1936       Diag(OA->getLocation(),
1937            diag::override_keyword_only_allowed_on_virtual_member_functions)
1938         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1939       D->dropAttr<OverrideAttr>();
1940     }
1941     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1942       Diag(FA->getLocation(),
1943            diag::override_keyword_only_allowed_on_virtual_member_functions)
1944         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1945         << FixItHint::CreateRemoval(FA->getLocation());
1946       D->dropAttr<FinalAttr>();
1947     }
1948     return;
1949   }
1950 
1951   // C++11 [class.virtual]p5:
1952   //   If a function is marked with the virt-specifier override and
1953   //   does not override a member function of a base class, the program is
1954   //   ill-formed.
1955   bool HasOverriddenMethods =
1956     MD->begin_overridden_methods() != MD->end_overridden_methods();
1957   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1958     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1959       << MD->getDeclName();
1960 }
1961 
1962 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1963   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1964     return;
1965   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1966   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1967       isa<CXXDestructorDecl>(MD))
1968     return;
1969 
1970   SourceLocation Loc = MD->getLocation();
1971   SourceLocation SpellingLoc = Loc;
1972   if (getSourceManager().isMacroArgExpansion(Loc))
1973     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1974   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1975   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1976       return;
1977 
1978   if (MD->size_overridden_methods() > 0) {
1979     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1980       << MD->getDeclName();
1981     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1982     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1983   }
1984 }
1985 
1986 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1987 /// function overrides a virtual member function marked 'final', according to
1988 /// C++11 [class.virtual]p4.
1989 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1990                                                   const CXXMethodDecl *Old) {
1991   FinalAttr *FA = Old->getAttr<FinalAttr>();
1992   if (!FA)
1993     return false;
1994 
1995   Diag(New->getLocation(), diag::err_final_function_overridden)
1996     << New->getDeclName()
1997     << FA->isSpelledAsSealed();
1998   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1999   return true;
2000 }
2001 
2002 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2003   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2004   // FIXME: Destruction of ObjC lifetime types has side-effects.
2005   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2006     return !RD->isCompleteDefinition() ||
2007            !RD->hasTrivialDefaultConstructor() ||
2008            !RD->hasTrivialDestructor();
2009   return false;
2010 }
2011 
2012 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2013   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2014     if (it->isDeclspecPropertyAttribute())
2015       return it;
2016   return nullptr;
2017 }
2018 
2019 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2020 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2021 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2022 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2023 /// present (but parsing it has been deferred).
2024 NamedDecl *
2025 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2026                                MultiTemplateParamsArg TemplateParameterLists,
2027                                Expr *BW, const VirtSpecifiers &VS,
2028                                InClassInitStyle InitStyle) {
2029   const DeclSpec &DS = D.getDeclSpec();
2030   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2031   DeclarationName Name = NameInfo.getName();
2032   SourceLocation Loc = NameInfo.getLoc();
2033 
2034   // For anonymous bitfields, the location should point to the type.
2035   if (Loc.isInvalid())
2036     Loc = D.getLocStart();
2037 
2038   Expr *BitWidth = static_cast<Expr*>(BW);
2039 
2040   assert(isa<CXXRecordDecl>(CurContext));
2041   assert(!DS.isFriendSpecified());
2042 
2043   bool isFunc = D.isDeclarationOfFunction();
2044 
2045   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2046     // The Microsoft extension __interface only permits public member functions
2047     // and prohibits constructors, destructors, operators, non-public member
2048     // functions, static methods and data members.
2049     unsigned InvalidDecl;
2050     bool ShowDeclName = true;
2051     if (!isFunc)
2052       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2053     else if (AS != AS_public)
2054       InvalidDecl = 2;
2055     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2056       InvalidDecl = 3;
2057     else switch (Name.getNameKind()) {
2058       case DeclarationName::CXXConstructorName:
2059         InvalidDecl = 4;
2060         ShowDeclName = false;
2061         break;
2062 
2063       case DeclarationName::CXXDestructorName:
2064         InvalidDecl = 5;
2065         ShowDeclName = false;
2066         break;
2067 
2068       case DeclarationName::CXXOperatorName:
2069       case DeclarationName::CXXConversionFunctionName:
2070         InvalidDecl = 6;
2071         break;
2072 
2073       default:
2074         InvalidDecl = 0;
2075         break;
2076     }
2077 
2078     if (InvalidDecl) {
2079       if (ShowDeclName)
2080         Diag(Loc, diag::err_invalid_member_in_interface)
2081           << (InvalidDecl-1) << Name;
2082       else
2083         Diag(Loc, diag::err_invalid_member_in_interface)
2084           << (InvalidDecl-1) << "";
2085       return nullptr;
2086     }
2087   }
2088 
2089   // C++ 9.2p6: A member shall not be declared to have automatic storage
2090   // duration (auto, register) or with the extern storage-class-specifier.
2091   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2092   // data members and cannot be applied to names declared const or static,
2093   // and cannot be applied to reference members.
2094   switch (DS.getStorageClassSpec()) {
2095   case DeclSpec::SCS_unspecified:
2096   case DeclSpec::SCS_typedef:
2097   case DeclSpec::SCS_static:
2098     break;
2099   case DeclSpec::SCS_mutable:
2100     if (isFunc) {
2101       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2102 
2103       // FIXME: It would be nicer if the keyword was ignored only for this
2104       // declarator. Otherwise we could get follow-up errors.
2105       D.getMutableDeclSpec().ClearStorageClassSpecs();
2106     }
2107     break;
2108   default:
2109     Diag(DS.getStorageClassSpecLoc(),
2110          diag::err_storageclass_invalid_for_member);
2111     D.getMutableDeclSpec().ClearStorageClassSpecs();
2112     break;
2113   }
2114 
2115   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2116                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2117                       !isFunc);
2118 
2119   if (DS.isConstexprSpecified() && isInstField) {
2120     SemaDiagnosticBuilder B =
2121         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2122     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2123     if (InitStyle == ICIS_NoInit) {
2124       B << 0 << 0;
2125       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2126         B << FixItHint::CreateRemoval(ConstexprLoc);
2127       else {
2128         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2129         D.getMutableDeclSpec().ClearConstexprSpec();
2130         const char *PrevSpec;
2131         unsigned DiagID;
2132         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2133             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2134         (void)Failed;
2135         assert(!Failed && "Making a constexpr member const shouldn't fail");
2136       }
2137     } else {
2138       B << 1;
2139       const char *PrevSpec;
2140       unsigned DiagID;
2141       if (D.getMutableDeclSpec().SetStorageClassSpec(
2142           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2143           Context.getPrintingPolicy())) {
2144         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2145                "This is the only DeclSpec that should fail to be applied");
2146         B << 1;
2147       } else {
2148         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2149         isInstField = false;
2150       }
2151     }
2152   }
2153 
2154   NamedDecl *Member;
2155   if (isInstField) {
2156     CXXScopeSpec &SS = D.getCXXScopeSpec();
2157 
2158     // Data members must have identifiers for names.
2159     if (!Name.isIdentifier()) {
2160       Diag(Loc, diag::err_bad_variable_name)
2161         << Name;
2162       return nullptr;
2163     }
2164 
2165     IdentifierInfo *II = Name.getAsIdentifierInfo();
2166 
2167     // Member field could not be with "template" keyword.
2168     // So TemplateParameterLists should be empty in this case.
2169     if (TemplateParameterLists.size()) {
2170       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2171       if (TemplateParams->size()) {
2172         // There is no such thing as a member field template.
2173         Diag(D.getIdentifierLoc(), diag::err_template_member)
2174             << II
2175             << SourceRange(TemplateParams->getTemplateLoc(),
2176                 TemplateParams->getRAngleLoc());
2177       } else {
2178         // There is an extraneous 'template<>' for this member.
2179         Diag(TemplateParams->getTemplateLoc(),
2180             diag::err_template_member_noparams)
2181             << II
2182             << SourceRange(TemplateParams->getTemplateLoc(),
2183                 TemplateParams->getRAngleLoc());
2184       }
2185       return nullptr;
2186     }
2187 
2188     if (SS.isSet() && !SS.isInvalid()) {
2189       // The user provided a superfluous scope specifier inside a class
2190       // definition:
2191       //
2192       // class X {
2193       //   int X::member;
2194       // };
2195       if (DeclContext *DC = computeDeclContext(SS, false))
2196         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2197       else
2198         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2199           << Name << SS.getRange();
2200 
2201       SS.clear();
2202     }
2203 
2204     AttributeList *MSPropertyAttr =
2205       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2206     if (MSPropertyAttr) {
2207       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2208                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2209       if (!Member)
2210         return nullptr;
2211       isInstField = false;
2212     } else {
2213       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2214                                 BitWidth, InitStyle, AS);
2215       assert(Member && "HandleField never returns null");
2216     }
2217   } else {
2218     assert(InitStyle == ICIS_NoInit ||
2219            D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2220 
2221     Member = HandleDeclarator(S, D, TemplateParameterLists);
2222     if (!Member)
2223       return nullptr;
2224 
2225     // Non-instance-fields can't have a bitfield.
2226     if (BitWidth) {
2227       if (Member->isInvalidDecl()) {
2228         // don't emit another diagnostic.
2229       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2230         // C++ 9.6p3: A bit-field shall not be a static member.
2231         // "static member 'A' cannot be a bit-field"
2232         Diag(Loc, diag::err_static_not_bitfield)
2233           << Name << BitWidth->getSourceRange();
2234       } else if (isa<TypedefDecl>(Member)) {
2235         // "typedef member 'x' cannot be a bit-field"
2236         Diag(Loc, diag::err_typedef_not_bitfield)
2237           << Name << BitWidth->getSourceRange();
2238       } else {
2239         // A function typedef ("typedef int f(); f a;").
2240         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2241         Diag(Loc, diag::err_not_integral_type_bitfield)
2242           << Name << cast<ValueDecl>(Member)->getType()
2243           << BitWidth->getSourceRange();
2244       }
2245 
2246       BitWidth = nullptr;
2247       Member->setInvalidDecl();
2248     }
2249 
2250     Member->setAccess(AS);
2251 
2252     // If we have declared a member function template or static data member
2253     // template, set the access of the templated declaration as well.
2254     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2255       FunTmpl->getTemplatedDecl()->setAccess(AS);
2256     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2257       VarTmpl->getTemplatedDecl()->setAccess(AS);
2258   }
2259 
2260   if (VS.isOverrideSpecified())
2261     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2262   if (VS.isFinalSpecified())
2263     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2264                                             VS.isFinalSpelledSealed()));
2265 
2266   if (VS.getLastLocation().isValid()) {
2267     // Update the end location of a method that has a virt-specifiers.
2268     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2269       MD->setRangeEnd(VS.getLastLocation());
2270   }
2271 
2272   CheckOverrideControl(Member);
2273 
2274   assert((Name || isInstField) && "No identifier for non-field ?");
2275 
2276   if (isInstField) {
2277     FieldDecl *FD = cast<FieldDecl>(Member);
2278     FieldCollector->Add(FD);
2279 
2280     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2281       // Remember all explicit private FieldDecls that have a name, no side
2282       // effects and are not part of a dependent type declaration.
2283       if (!FD->isImplicit() && FD->getDeclName() &&
2284           FD->getAccess() == AS_private &&
2285           !FD->hasAttr<UnusedAttr>() &&
2286           !FD->getParent()->isDependentContext() &&
2287           !InitializationHasSideEffects(*FD))
2288         UnusedPrivateFields.insert(FD);
2289     }
2290   }
2291 
2292   return Member;
2293 }
2294 
2295 namespace {
2296   class UninitializedFieldVisitor
2297       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2298     Sema &S;
2299     // List of Decls to generate a warning on.  Also remove Decls that become
2300     // initialized.
2301     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2302     // List of base classes of the record.  Classes are removed after their
2303     // initializers.
2304     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2305     // Vector of decls to be removed from the Decl set prior to visiting the
2306     // nodes.  These Decls may have been initialized in the prior initializer.
2307     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2308     // If non-null, add a note to the warning pointing back to the constructor.
2309     const CXXConstructorDecl *Constructor;
2310     // Variables to hold state when processing an initializer list.  When
2311     // InitList is true, special case initialization of FieldDecls matching
2312     // InitListFieldDecl.
2313     bool InitList;
2314     FieldDecl *InitListFieldDecl;
2315     llvm::SmallVector<unsigned, 4> InitFieldIndex;
2316 
2317   public:
2318     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2319     UninitializedFieldVisitor(Sema &S,
2320                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2321                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2322       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2323         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2324 
2325     // Returns true if the use of ME is not an uninitialized use.
2326     bool IsInitListMemberExprInitialized(MemberExpr *ME,
2327                                          bool CheckReferenceOnly) {
2328       llvm::SmallVector<FieldDecl*, 4> Fields;
2329       bool ReferenceField = false;
2330       while (ME) {
2331         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2332         if (!FD)
2333           return false;
2334         Fields.push_back(FD);
2335         if (FD->getType()->isReferenceType())
2336           ReferenceField = true;
2337         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2338       }
2339 
2340       // Binding a reference to an unintialized field is not an
2341       // uninitialized use.
2342       if (CheckReferenceOnly && !ReferenceField)
2343         return true;
2344 
2345       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2346       // Discard the first field since it is the field decl that is being
2347       // initialized.
2348       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2349         UsedFieldIndex.push_back((*I)->getFieldIndex());
2350       }
2351 
2352       for (auto UsedIter = UsedFieldIndex.begin(),
2353                 UsedEnd = UsedFieldIndex.end(),
2354                 OrigIter = InitFieldIndex.begin(),
2355                 OrigEnd = InitFieldIndex.end();
2356            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2357         if (*UsedIter < *OrigIter)
2358           return true;
2359         if (*UsedIter > *OrigIter)
2360           break;
2361       }
2362 
2363       return false;
2364     }
2365 
2366     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2367                           bool AddressOf) {
2368       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2369         return;
2370 
2371       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2372       // or union.
2373       MemberExpr *FieldME = ME;
2374 
2375       bool AllPODFields = FieldME->getType().isPODType(S.Context);
2376 
2377       Expr *Base = ME;
2378       while (MemberExpr *SubME =
2379                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2380 
2381         if (isa<VarDecl>(SubME->getMemberDecl()))
2382           return;
2383 
2384         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2385           if (!FD->isAnonymousStructOrUnion())
2386             FieldME = SubME;
2387 
2388         if (!FieldME->getType().isPODType(S.Context))
2389           AllPODFields = false;
2390 
2391         Base = SubME->getBase();
2392       }
2393 
2394       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2395         return;
2396 
2397       if (AddressOf && AllPODFields)
2398         return;
2399 
2400       ValueDecl* FoundVD = FieldME->getMemberDecl();
2401 
2402       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2403         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2404           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2405         }
2406 
2407         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2408           QualType T = BaseCast->getType();
2409           if (T->isPointerType() &&
2410               BaseClasses.count(T->getPointeeType())) {
2411             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2412                 << T->getPointeeType() << FoundVD;
2413           }
2414         }
2415       }
2416 
2417       if (!Decls.count(FoundVD))
2418         return;
2419 
2420       const bool IsReference = FoundVD->getType()->isReferenceType();
2421 
2422       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2423         // Special checking for initializer lists.
2424         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2425           return;
2426         }
2427       } else {
2428         // Prevent double warnings on use of unbounded references.
2429         if (CheckReferenceOnly && !IsReference)
2430           return;
2431       }
2432 
2433       unsigned diag = IsReference
2434           ? diag::warn_reference_field_is_uninit
2435           : diag::warn_field_is_uninit;
2436       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2437       if (Constructor)
2438         S.Diag(Constructor->getLocation(),
2439                diag::note_uninit_in_this_constructor)
2440           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2441 
2442     }
2443 
2444     void HandleValue(Expr *E, bool AddressOf) {
2445       E = E->IgnoreParens();
2446 
2447       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2448         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2449                          AddressOf /*AddressOf*/);
2450         return;
2451       }
2452 
2453       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2454         Visit(CO->getCond());
2455         HandleValue(CO->getTrueExpr(), AddressOf);
2456         HandleValue(CO->getFalseExpr(), AddressOf);
2457         return;
2458       }
2459 
2460       if (BinaryConditionalOperator *BCO =
2461               dyn_cast<BinaryConditionalOperator>(E)) {
2462         Visit(BCO->getCond());
2463         HandleValue(BCO->getFalseExpr(), AddressOf);
2464         return;
2465       }
2466 
2467       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2468         HandleValue(OVE->getSourceExpr(), AddressOf);
2469         return;
2470       }
2471 
2472       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2473         switch (BO->getOpcode()) {
2474         default:
2475           break;
2476         case(BO_PtrMemD):
2477         case(BO_PtrMemI):
2478           HandleValue(BO->getLHS(), AddressOf);
2479           Visit(BO->getRHS());
2480           return;
2481         case(BO_Comma):
2482           Visit(BO->getLHS());
2483           HandleValue(BO->getRHS(), AddressOf);
2484           return;
2485         }
2486       }
2487 
2488       Visit(E);
2489     }
2490 
2491     void CheckInitListExpr(InitListExpr *ILE) {
2492       InitFieldIndex.push_back(0);
2493       for (auto Child : ILE->children()) {
2494         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2495           CheckInitListExpr(SubList);
2496         } else {
2497           Visit(Child);
2498         }
2499         ++InitFieldIndex.back();
2500       }
2501       InitFieldIndex.pop_back();
2502     }
2503 
2504     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2505                           FieldDecl *Field, const Type *BaseClass) {
2506       // Remove Decls that may have been initialized in the previous
2507       // initializer.
2508       for (ValueDecl* VD : DeclsToRemove)
2509         Decls.erase(VD);
2510       DeclsToRemove.clear();
2511 
2512       Constructor = FieldConstructor;
2513       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2514 
2515       if (ILE && Field) {
2516         InitList = true;
2517         InitListFieldDecl = Field;
2518         InitFieldIndex.clear();
2519         CheckInitListExpr(ILE);
2520       } else {
2521         InitList = false;
2522         Visit(E);
2523       }
2524 
2525       if (Field)
2526         Decls.erase(Field);
2527       if (BaseClass)
2528         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2529     }
2530 
2531     void VisitMemberExpr(MemberExpr *ME) {
2532       // All uses of unbounded reference fields will warn.
2533       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2534     }
2535 
2536     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2537       if (E->getCastKind() == CK_LValueToRValue) {
2538         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2539         return;
2540       }
2541 
2542       Inherited::VisitImplicitCastExpr(E);
2543     }
2544 
2545     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2546       if (E->getConstructor()->isCopyConstructor()) {
2547         Expr *ArgExpr = E->getArg(0);
2548         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2549           if (ILE->getNumInits() == 1)
2550             ArgExpr = ILE->getInit(0);
2551         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2552           if (ICE->getCastKind() == CK_NoOp)
2553             ArgExpr = ICE->getSubExpr();
2554         HandleValue(ArgExpr, false /*AddressOf*/);
2555         return;
2556       }
2557       Inherited::VisitCXXConstructExpr(E);
2558     }
2559 
2560     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2561       Expr *Callee = E->getCallee();
2562       if (isa<MemberExpr>(Callee)) {
2563         HandleValue(Callee, false /*AddressOf*/);
2564         for (auto Arg : E->arguments())
2565           Visit(Arg);
2566         return;
2567       }
2568 
2569       Inherited::VisitCXXMemberCallExpr(E);
2570     }
2571 
2572     void VisitCallExpr(CallExpr *E) {
2573       // Treat std::move as a use.
2574       if (E->getNumArgs() == 1) {
2575         if (FunctionDecl *FD = E->getDirectCallee()) {
2576           if (FD->isInStdNamespace() && FD->getIdentifier() &&
2577               FD->getIdentifier()->isStr("move")) {
2578             HandleValue(E->getArg(0), false /*AddressOf*/);
2579             return;
2580           }
2581         }
2582       }
2583 
2584       Inherited::VisitCallExpr(E);
2585     }
2586 
2587     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2588       Expr *Callee = E->getCallee();
2589 
2590       if (isa<UnresolvedLookupExpr>(Callee))
2591         return Inherited::VisitCXXOperatorCallExpr(E);
2592 
2593       Visit(Callee);
2594       for (auto Arg : E->arguments())
2595         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2596     }
2597 
2598     void VisitBinaryOperator(BinaryOperator *E) {
2599       // If a field assignment is detected, remove the field from the
2600       // uninitiailized field set.
2601       if (E->getOpcode() == BO_Assign)
2602         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2603           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2604             if (!FD->getType()->isReferenceType())
2605               DeclsToRemove.push_back(FD);
2606 
2607       if (E->isCompoundAssignmentOp()) {
2608         HandleValue(E->getLHS(), false /*AddressOf*/);
2609         Visit(E->getRHS());
2610         return;
2611       }
2612 
2613       Inherited::VisitBinaryOperator(E);
2614     }
2615 
2616     void VisitUnaryOperator(UnaryOperator *E) {
2617       if (E->isIncrementDecrementOp()) {
2618         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2619         return;
2620       }
2621       if (E->getOpcode() == UO_AddrOf) {
2622         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2623           HandleValue(ME->getBase(), true /*AddressOf*/);
2624           return;
2625         }
2626       }
2627 
2628       Inherited::VisitUnaryOperator(E);
2629     }
2630   };
2631 
2632   // Diagnose value-uses of fields to initialize themselves, e.g.
2633   //   foo(foo)
2634   // where foo is not also a parameter to the constructor.
2635   // Also diagnose across field uninitialized use such as
2636   //   x(y), y(x)
2637   // TODO: implement -Wuninitialized and fold this into that framework.
2638   static void DiagnoseUninitializedFields(
2639       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2640 
2641     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2642                                            Constructor->getLocation())) {
2643       return;
2644     }
2645 
2646     if (Constructor->isInvalidDecl())
2647       return;
2648 
2649     const CXXRecordDecl *RD = Constructor->getParent();
2650 
2651     if (RD->getDescribedClassTemplate())
2652       return;
2653 
2654     // Holds fields that are uninitialized.
2655     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2656 
2657     // At the beginning, all fields are uninitialized.
2658     for (auto *I : RD->decls()) {
2659       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2660         UninitializedFields.insert(FD);
2661       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2662         UninitializedFields.insert(IFD->getAnonField());
2663       }
2664     }
2665 
2666     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2667     for (auto I : RD->bases())
2668       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2669 
2670     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2671       return;
2672 
2673     UninitializedFieldVisitor UninitializedChecker(SemaRef,
2674                                                    UninitializedFields,
2675                                                    UninitializedBaseClasses);
2676 
2677     for (const auto *FieldInit : Constructor->inits()) {
2678       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2679         break;
2680 
2681       Expr *InitExpr = FieldInit->getInit();
2682       if (!InitExpr)
2683         continue;
2684 
2685       if (CXXDefaultInitExpr *Default =
2686               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2687         InitExpr = Default->getExpr();
2688         if (!InitExpr)
2689           continue;
2690         // In class initializers will point to the constructor.
2691         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2692                                               FieldInit->getAnyMember(),
2693                                               FieldInit->getBaseClass());
2694       } else {
2695         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2696                                               FieldInit->getAnyMember(),
2697                                               FieldInit->getBaseClass());
2698       }
2699     }
2700   }
2701 } // namespace
2702 
2703 /// \brief Enter a new C++ default initializer scope. After calling this, the
2704 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2705 /// parsing or instantiating the initializer failed.
2706 void Sema::ActOnStartCXXInClassMemberInitializer() {
2707   // Create a synthetic function scope to represent the call to the constructor
2708   // that notionally surrounds a use of this initializer.
2709   PushFunctionScope();
2710 }
2711 
2712 /// \brief This is invoked after parsing an in-class initializer for a
2713 /// non-static C++ class member, and after instantiating an in-class initializer
2714 /// in a class template. Such actions are deferred until the class is complete.
2715 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2716                                                   SourceLocation InitLoc,
2717                                                   Expr *InitExpr) {
2718   // Pop the notional constructor scope we created earlier.
2719   PopFunctionScopeInfo(nullptr, D);
2720 
2721   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2722   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2723          "must set init style when field is created");
2724 
2725   if (!InitExpr) {
2726     D->setInvalidDecl();
2727     if (FD)
2728       FD->removeInClassInitializer();
2729     return;
2730   }
2731 
2732   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2733     FD->setInvalidDecl();
2734     FD->removeInClassInitializer();
2735     return;
2736   }
2737 
2738   ExprResult Init = InitExpr;
2739   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2740     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2741     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2742         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2743         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2744     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2745     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2746     if (Init.isInvalid()) {
2747       FD->setInvalidDecl();
2748       return;
2749     }
2750   }
2751 
2752   // C++11 [class.base.init]p7:
2753   //   The initialization of each base and member constitutes a
2754   //   full-expression.
2755   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2756   if (Init.isInvalid()) {
2757     FD->setInvalidDecl();
2758     return;
2759   }
2760 
2761   InitExpr = Init.get();
2762 
2763   FD->setInClassInitializer(InitExpr);
2764 }
2765 
2766 /// \brief Find the direct and/or virtual base specifiers that
2767 /// correspond to the given base type, for use in base initialization
2768 /// within a constructor.
2769 static bool FindBaseInitializer(Sema &SemaRef,
2770                                 CXXRecordDecl *ClassDecl,
2771                                 QualType BaseType,
2772                                 const CXXBaseSpecifier *&DirectBaseSpec,
2773                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2774   // First, check for a direct base class.
2775   DirectBaseSpec = nullptr;
2776   for (const auto &Base : ClassDecl->bases()) {
2777     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2778       // We found a direct base of this type. That's what we're
2779       // initializing.
2780       DirectBaseSpec = &Base;
2781       break;
2782     }
2783   }
2784 
2785   // Check for a virtual base class.
2786   // FIXME: We might be able to short-circuit this if we know in advance that
2787   // there are no virtual bases.
2788   VirtualBaseSpec = nullptr;
2789   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2790     // We haven't found a base yet; search the class hierarchy for a
2791     // virtual base class.
2792     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2793                        /*DetectVirtual=*/false);
2794     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2795                               BaseType, Paths)) {
2796       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2797            Path != Paths.end(); ++Path) {
2798         if (Path->back().Base->isVirtual()) {
2799           VirtualBaseSpec = Path->back().Base;
2800           break;
2801         }
2802       }
2803     }
2804   }
2805 
2806   return DirectBaseSpec || VirtualBaseSpec;
2807 }
2808 
2809 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2810 MemInitResult
2811 Sema::ActOnMemInitializer(Decl *ConstructorD,
2812                           Scope *S,
2813                           CXXScopeSpec &SS,
2814                           IdentifierInfo *MemberOrBase,
2815                           ParsedType TemplateTypeTy,
2816                           const DeclSpec &DS,
2817                           SourceLocation IdLoc,
2818                           Expr *InitList,
2819                           SourceLocation EllipsisLoc) {
2820   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2821                              DS, IdLoc, InitList,
2822                              EllipsisLoc);
2823 }
2824 
2825 /// \brief Handle a C++ member initializer using parentheses syntax.
2826 MemInitResult
2827 Sema::ActOnMemInitializer(Decl *ConstructorD,
2828                           Scope *S,
2829                           CXXScopeSpec &SS,
2830                           IdentifierInfo *MemberOrBase,
2831                           ParsedType TemplateTypeTy,
2832                           const DeclSpec &DS,
2833                           SourceLocation IdLoc,
2834                           SourceLocation LParenLoc,
2835                           ArrayRef<Expr *> Args,
2836                           SourceLocation RParenLoc,
2837                           SourceLocation EllipsisLoc) {
2838   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2839                                            Args, RParenLoc);
2840   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2841                              DS, IdLoc, List, EllipsisLoc);
2842 }
2843 
2844 namespace {
2845 
2846 // Callback to only accept typo corrections that can be a valid C++ member
2847 // intializer: either a non-static field member or a base class.
2848 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2849 public:
2850   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2851       : ClassDecl(ClassDecl) {}
2852 
2853   bool ValidateCandidate(const TypoCorrection &candidate) override {
2854     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2855       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2856         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2857       return isa<TypeDecl>(ND);
2858     }
2859     return false;
2860   }
2861 
2862 private:
2863   CXXRecordDecl *ClassDecl;
2864 };
2865 
2866 }
2867 
2868 /// \brief Handle a C++ member initializer.
2869 MemInitResult
2870 Sema::BuildMemInitializer(Decl *ConstructorD,
2871                           Scope *S,
2872                           CXXScopeSpec &SS,
2873                           IdentifierInfo *MemberOrBase,
2874                           ParsedType TemplateTypeTy,
2875                           const DeclSpec &DS,
2876                           SourceLocation IdLoc,
2877                           Expr *Init,
2878                           SourceLocation EllipsisLoc) {
2879   ExprResult Res = CorrectDelayedTyposInExpr(Init);
2880   if (!Res.isUsable())
2881     return true;
2882   Init = Res.get();
2883 
2884   if (!ConstructorD)
2885     return true;
2886 
2887   AdjustDeclIfTemplate(ConstructorD);
2888 
2889   CXXConstructorDecl *Constructor
2890     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2891   if (!Constructor) {
2892     // The user wrote a constructor initializer on a function that is
2893     // not a C++ constructor. Ignore the error for now, because we may
2894     // have more member initializers coming; we'll diagnose it just
2895     // once in ActOnMemInitializers.
2896     return true;
2897   }
2898 
2899   CXXRecordDecl *ClassDecl = Constructor->getParent();
2900 
2901   // C++ [class.base.init]p2:
2902   //   Names in a mem-initializer-id are looked up in the scope of the
2903   //   constructor's class and, if not found in that scope, are looked
2904   //   up in the scope containing the constructor's definition.
2905   //   [Note: if the constructor's class contains a member with the
2906   //   same name as a direct or virtual base class of the class, a
2907   //   mem-initializer-id naming the member or base class and composed
2908   //   of a single identifier refers to the class member. A
2909   //   mem-initializer-id for the hidden base class may be specified
2910   //   using a qualified name. ]
2911   if (!SS.getScopeRep() && !TemplateTypeTy) {
2912     // Look for a member, first.
2913     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2914     if (!Result.empty()) {
2915       ValueDecl *Member;
2916       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2917           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2918         if (EllipsisLoc.isValid())
2919           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2920             << MemberOrBase
2921             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2922 
2923         return BuildMemberInitializer(Member, Init, IdLoc);
2924       }
2925     }
2926   }
2927   // It didn't name a member, so see if it names a class.
2928   QualType BaseType;
2929   TypeSourceInfo *TInfo = nullptr;
2930 
2931   if (TemplateTypeTy) {
2932     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2933   } else if (DS.getTypeSpecType() == TST_decltype) {
2934     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2935   } else {
2936     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2937     LookupParsedName(R, S, &SS);
2938 
2939     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2940     if (!TyD) {
2941       if (R.isAmbiguous()) return true;
2942 
2943       // We don't want access-control diagnostics here.
2944       R.suppressDiagnostics();
2945 
2946       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2947         bool NotUnknownSpecialization = false;
2948         DeclContext *DC = computeDeclContext(SS, false);
2949         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2950           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2951 
2952         if (!NotUnknownSpecialization) {
2953           // When the scope specifier can refer to a member of an unknown
2954           // specialization, we take it as a type name.
2955           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2956                                        SS.getWithLocInContext(Context),
2957                                        *MemberOrBase, IdLoc);
2958           if (BaseType.isNull())
2959             return true;
2960 
2961           R.clear();
2962           R.setLookupName(MemberOrBase);
2963         }
2964       }
2965 
2966       // If no results were found, try to correct typos.
2967       TypoCorrection Corr;
2968       if (R.empty() && BaseType.isNull() &&
2969           (Corr = CorrectTypo(
2970                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2971                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2972                CTK_ErrorRecovery, ClassDecl))) {
2973         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2974           // We have found a non-static data member with a similar
2975           // name to what was typed; complain and initialize that
2976           // member.
2977           diagnoseTypo(Corr,
2978                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2979                          << MemberOrBase << true);
2980           return BuildMemberInitializer(Member, Init, IdLoc);
2981         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2982           const CXXBaseSpecifier *DirectBaseSpec;
2983           const CXXBaseSpecifier *VirtualBaseSpec;
2984           if (FindBaseInitializer(*this, ClassDecl,
2985                                   Context.getTypeDeclType(Type),
2986                                   DirectBaseSpec, VirtualBaseSpec)) {
2987             // We have found a direct or virtual base class with a
2988             // similar name to what was typed; complain and initialize
2989             // that base class.
2990             diagnoseTypo(Corr,
2991                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2992                            << MemberOrBase << false,
2993                          PDiag() /*Suppress note, we provide our own.*/);
2994 
2995             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2996                                                               : VirtualBaseSpec;
2997             Diag(BaseSpec->getLocStart(),
2998                  diag::note_base_class_specified_here)
2999               << BaseSpec->getType()
3000               << BaseSpec->getSourceRange();
3001 
3002             TyD = Type;
3003           }
3004         }
3005       }
3006 
3007       if (!TyD && BaseType.isNull()) {
3008         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3009           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3010         return true;
3011       }
3012     }
3013 
3014     if (BaseType.isNull()) {
3015       BaseType = Context.getTypeDeclType(TyD);
3016       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3017       if (SS.isSet())
3018         // FIXME: preserve source range information
3019         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3020                                              BaseType);
3021     }
3022   }
3023 
3024   if (!TInfo)
3025     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3026 
3027   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3028 }
3029 
3030 /// Checks a member initializer expression for cases where reference (or
3031 /// pointer) members are bound to by-value parameters (or their addresses).
3032 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3033                                                Expr *Init,
3034                                                SourceLocation IdLoc) {
3035   QualType MemberTy = Member->getType();
3036 
3037   // We only handle pointers and references currently.
3038   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3039   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3040     return;
3041 
3042   const bool IsPointer = MemberTy->isPointerType();
3043   if (IsPointer) {
3044     if (const UnaryOperator *Op
3045           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3046       // The only case we're worried about with pointers requires taking the
3047       // address.
3048       if (Op->getOpcode() != UO_AddrOf)
3049         return;
3050 
3051       Init = Op->getSubExpr();
3052     } else {
3053       // We only handle address-of expression initializers for pointers.
3054       return;
3055     }
3056   }
3057 
3058   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3059     // We only warn when referring to a non-reference parameter declaration.
3060     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3061     if (!Parameter || Parameter->getType()->isReferenceType())
3062       return;
3063 
3064     S.Diag(Init->getExprLoc(),
3065            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3066                      : diag::warn_bind_ref_member_to_parameter)
3067       << Member << Parameter << Init->getSourceRange();
3068   } else {
3069     // Other initializers are fine.
3070     return;
3071   }
3072 
3073   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3074     << (unsigned)IsPointer;
3075 }
3076 
3077 MemInitResult
3078 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3079                              SourceLocation IdLoc) {
3080   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3081   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3082   assert((DirectMember || IndirectMember) &&
3083          "Member must be a FieldDecl or IndirectFieldDecl");
3084 
3085   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3086     return true;
3087 
3088   if (Member->isInvalidDecl())
3089     return true;
3090 
3091   MultiExprArg Args;
3092   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3093     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3094   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3095     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3096   } else {
3097     // Template instantiation doesn't reconstruct ParenListExprs for us.
3098     Args = Init;
3099   }
3100 
3101   SourceRange InitRange = Init->getSourceRange();
3102 
3103   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3104     // Can't check initialization for a member of dependent type or when
3105     // any of the arguments are type-dependent expressions.
3106     DiscardCleanupsInEvaluationContext();
3107   } else {
3108     bool InitList = false;
3109     if (isa<InitListExpr>(Init)) {
3110       InitList = true;
3111       Args = Init;
3112     }
3113 
3114     // Initialize the member.
3115     InitializedEntity MemberEntity =
3116       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3117                    : InitializedEntity::InitializeMember(IndirectMember,
3118                                                          nullptr);
3119     InitializationKind Kind =
3120       InitList ? InitializationKind::CreateDirectList(IdLoc)
3121                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3122                                                   InitRange.getEnd());
3123 
3124     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3125     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3126                                             nullptr);
3127     if (MemberInit.isInvalid())
3128       return true;
3129 
3130     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3131 
3132     // C++11 [class.base.init]p7:
3133     //   The initialization of each base and member constitutes a
3134     //   full-expression.
3135     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3136     if (MemberInit.isInvalid())
3137       return true;
3138 
3139     Init = MemberInit.get();
3140   }
3141 
3142   if (DirectMember) {
3143     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3144                                             InitRange.getBegin(), Init,
3145                                             InitRange.getEnd());
3146   } else {
3147     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3148                                             InitRange.getBegin(), Init,
3149                                             InitRange.getEnd());
3150   }
3151 }
3152 
3153 MemInitResult
3154 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3155                                  CXXRecordDecl *ClassDecl) {
3156   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3157   if (!LangOpts.CPlusPlus11)
3158     return Diag(NameLoc, diag::err_delegating_ctor)
3159       << TInfo->getTypeLoc().getLocalSourceRange();
3160   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3161 
3162   bool InitList = true;
3163   MultiExprArg Args = Init;
3164   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3165     InitList = false;
3166     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3167   }
3168 
3169   SourceRange InitRange = Init->getSourceRange();
3170   // Initialize the object.
3171   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3172                                      QualType(ClassDecl->getTypeForDecl(), 0));
3173   InitializationKind Kind =
3174     InitList ? InitializationKind::CreateDirectList(NameLoc)
3175              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3176                                                 InitRange.getEnd());
3177   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3178   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3179                                               Args, nullptr);
3180   if (DelegationInit.isInvalid())
3181     return true;
3182 
3183   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3184          "Delegating constructor with no target?");
3185 
3186   // C++11 [class.base.init]p7:
3187   //   The initialization of each base and member constitutes a
3188   //   full-expression.
3189   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3190                                        InitRange.getBegin());
3191   if (DelegationInit.isInvalid())
3192     return true;
3193 
3194   // If we are in a dependent context, template instantiation will
3195   // perform this type-checking again. Just save the arguments that we
3196   // received in a ParenListExpr.
3197   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3198   // of the information that we have about the base
3199   // initializer. However, deconstructing the ASTs is a dicey process,
3200   // and this approach is far more likely to get the corner cases right.
3201   if (CurContext->isDependentContext())
3202     DelegationInit = Init;
3203 
3204   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3205                                           DelegationInit.getAs<Expr>(),
3206                                           InitRange.getEnd());
3207 }
3208 
3209 MemInitResult
3210 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3211                            Expr *Init, CXXRecordDecl *ClassDecl,
3212                            SourceLocation EllipsisLoc) {
3213   SourceLocation BaseLoc
3214     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3215 
3216   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3217     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3218              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3219 
3220   // C++ [class.base.init]p2:
3221   //   [...] Unless the mem-initializer-id names a nonstatic data
3222   //   member of the constructor's class or a direct or virtual base
3223   //   of that class, the mem-initializer is ill-formed. A
3224   //   mem-initializer-list can initialize a base class using any
3225   //   name that denotes that base class type.
3226   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3227 
3228   SourceRange InitRange = Init->getSourceRange();
3229   if (EllipsisLoc.isValid()) {
3230     // This is a pack expansion.
3231     if (!BaseType->containsUnexpandedParameterPack())  {
3232       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3233         << SourceRange(BaseLoc, InitRange.getEnd());
3234 
3235       EllipsisLoc = SourceLocation();
3236     }
3237   } else {
3238     // Check for any unexpanded parameter packs.
3239     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3240       return true;
3241 
3242     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3243       return true;
3244   }
3245 
3246   // Check for direct and virtual base classes.
3247   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3248   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3249   if (!Dependent) {
3250     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3251                                        BaseType))
3252       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3253 
3254     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3255                         VirtualBaseSpec);
3256 
3257     // C++ [base.class.init]p2:
3258     // Unless the mem-initializer-id names a nonstatic data member of the
3259     // constructor's class or a direct or virtual base of that class, the
3260     // mem-initializer is ill-formed.
3261     if (!DirectBaseSpec && !VirtualBaseSpec) {
3262       // If the class has any dependent bases, then it's possible that
3263       // one of those types will resolve to the same type as
3264       // BaseType. Therefore, just treat this as a dependent base
3265       // class initialization.  FIXME: Should we try to check the
3266       // initialization anyway? It seems odd.
3267       if (ClassDecl->hasAnyDependentBases())
3268         Dependent = true;
3269       else
3270         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3271           << BaseType << Context.getTypeDeclType(ClassDecl)
3272           << BaseTInfo->getTypeLoc().getLocalSourceRange();
3273     }
3274   }
3275 
3276   if (Dependent) {
3277     DiscardCleanupsInEvaluationContext();
3278 
3279     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3280                                             /*IsVirtual=*/false,
3281                                             InitRange.getBegin(), Init,
3282                                             InitRange.getEnd(), EllipsisLoc);
3283   }
3284 
3285   // C++ [base.class.init]p2:
3286   //   If a mem-initializer-id is ambiguous because it designates both
3287   //   a direct non-virtual base class and an inherited virtual base
3288   //   class, the mem-initializer is ill-formed.
3289   if (DirectBaseSpec && VirtualBaseSpec)
3290     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3291       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3292 
3293   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3294   if (!BaseSpec)
3295     BaseSpec = VirtualBaseSpec;
3296 
3297   // Initialize the base.
3298   bool InitList = true;
3299   MultiExprArg Args = Init;
3300   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3301     InitList = false;
3302     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3303   }
3304 
3305   InitializedEntity BaseEntity =
3306     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3307   InitializationKind Kind =
3308     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3309              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3310                                                 InitRange.getEnd());
3311   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3312   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3313   if (BaseInit.isInvalid())
3314     return true;
3315 
3316   // C++11 [class.base.init]p7:
3317   //   The initialization of each base and member constitutes a
3318   //   full-expression.
3319   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3320   if (BaseInit.isInvalid())
3321     return true;
3322 
3323   // If we are in a dependent context, template instantiation will
3324   // perform this type-checking again. Just save the arguments that we
3325   // received in a ParenListExpr.
3326   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3327   // of the information that we have about the base
3328   // initializer. However, deconstructing the ASTs is a dicey process,
3329   // and this approach is far more likely to get the corner cases right.
3330   if (CurContext->isDependentContext())
3331     BaseInit = Init;
3332 
3333   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3334                                           BaseSpec->isVirtual(),
3335                                           InitRange.getBegin(),
3336                                           BaseInit.getAs<Expr>(),
3337                                           InitRange.getEnd(), EllipsisLoc);
3338 }
3339 
3340 // Create a static_cast\<T&&>(expr).
3341 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3342   if (T.isNull()) T = E->getType();
3343   QualType TargetType = SemaRef.BuildReferenceType(
3344       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3345   SourceLocation ExprLoc = E->getLocStart();
3346   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3347       TargetType, ExprLoc);
3348 
3349   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3350                                    SourceRange(ExprLoc, ExprLoc),
3351                                    E->getSourceRange()).get();
3352 }
3353 
3354 /// ImplicitInitializerKind - How an implicit base or member initializer should
3355 /// initialize its base or member.
3356 enum ImplicitInitializerKind {
3357   IIK_Default,
3358   IIK_Copy,
3359   IIK_Move,
3360   IIK_Inherit
3361 };
3362 
3363 static bool
3364 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3365                              ImplicitInitializerKind ImplicitInitKind,
3366                              CXXBaseSpecifier *BaseSpec,
3367                              bool IsInheritedVirtualBase,
3368                              CXXCtorInitializer *&CXXBaseInit) {
3369   InitializedEntity InitEntity
3370     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3371                                         IsInheritedVirtualBase);
3372 
3373   ExprResult BaseInit;
3374 
3375   switch (ImplicitInitKind) {
3376   case IIK_Inherit: {
3377     const CXXRecordDecl *Inherited =
3378         Constructor->getInheritedConstructor()->getParent();
3379     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3380     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3381       // C++11 [class.inhctor]p8:
3382       //   Each expression in the expression-list is of the form
3383       //   static_cast<T&&>(p), where p is the name of the corresponding
3384       //   constructor parameter and T is the declared type of p.
3385       SmallVector<Expr*, 16> Args;
3386       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3387         ParmVarDecl *PD = Constructor->getParamDecl(I);
3388         ExprResult ArgExpr =
3389             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3390                                      VK_LValue, SourceLocation());
3391         if (ArgExpr.isInvalid())
3392           return true;
3393         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3394       }
3395 
3396       InitializationKind InitKind = InitializationKind::CreateDirect(
3397           Constructor->getLocation(), SourceLocation(), SourceLocation());
3398       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3399       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3400       break;
3401     }
3402   }
3403   // Fall through.
3404   case IIK_Default: {
3405     InitializationKind InitKind
3406       = InitializationKind::CreateDefault(Constructor->getLocation());
3407     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3408     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3409     break;
3410   }
3411 
3412   case IIK_Move:
3413   case IIK_Copy: {
3414     bool Moving = ImplicitInitKind == IIK_Move;
3415     ParmVarDecl *Param = Constructor->getParamDecl(0);
3416     QualType ParamType = Param->getType().getNonReferenceType();
3417 
3418     Expr *CopyCtorArg =
3419       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3420                           SourceLocation(), Param, false,
3421                           Constructor->getLocation(), ParamType,
3422                           VK_LValue, nullptr);
3423 
3424     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3425 
3426     // Cast to the base class to avoid ambiguities.
3427     QualType ArgTy =
3428       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3429                                        ParamType.getQualifiers());
3430 
3431     if (Moving) {
3432       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3433     }
3434 
3435     CXXCastPath BasePath;
3436     BasePath.push_back(BaseSpec);
3437     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3438                                             CK_UncheckedDerivedToBase,
3439                                             Moving ? VK_XValue : VK_LValue,
3440                                             &BasePath).get();
3441 
3442     InitializationKind InitKind
3443       = InitializationKind::CreateDirect(Constructor->getLocation(),
3444                                          SourceLocation(), SourceLocation());
3445     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3446     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3447     break;
3448   }
3449   }
3450 
3451   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3452   if (BaseInit.isInvalid())
3453     return true;
3454 
3455   CXXBaseInit =
3456     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3457                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3458                                                         SourceLocation()),
3459                                              BaseSpec->isVirtual(),
3460                                              SourceLocation(),
3461                                              BaseInit.getAs<Expr>(),
3462                                              SourceLocation(),
3463                                              SourceLocation());
3464 
3465   return false;
3466 }
3467 
3468 static bool RefersToRValueRef(Expr *MemRef) {
3469   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3470   return Referenced->getType()->isRValueReferenceType();
3471 }
3472 
3473 static bool
3474 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3475                                ImplicitInitializerKind ImplicitInitKind,
3476                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3477                                CXXCtorInitializer *&CXXMemberInit) {
3478   if (Field->isInvalidDecl())
3479     return true;
3480 
3481   SourceLocation Loc = Constructor->getLocation();
3482 
3483   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3484     bool Moving = ImplicitInitKind == IIK_Move;
3485     ParmVarDecl *Param = Constructor->getParamDecl(0);
3486     QualType ParamType = Param->getType().getNonReferenceType();
3487 
3488     // Suppress copying zero-width bitfields.
3489     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3490       return false;
3491 
3492     Expr *MemberExprBase =
3493       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3494                           SourceLocation(), Param, false,
3495                           Loc, ParamType, VK_LValue, nullptr);
3496 
3497     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3498 
3499     if (Moving) {
3500       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3501     }
3502 
3503     // Build a reference to this field within the parameter.
3504     CXXScopeSpec SS;
3505     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3506                               Sema::LookupMemberName);
3507     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3508                                   : cast<ValueDecl>(Field), AS_public);
3509     MemberLookup.resolveKind();
3510     ExprResult CtorArg
3511       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3512                                          ParamType, Loc,
3513                                          /*IsArrow=*/false,
3514                                          SS,
3515                                          /*TemplateKWLoc=*/SourceLocation(),
3516                                          /*FirstQualifierInScope=*/nullptr,
3517                                          MemberLookup,
3518                                          /*TemplateArgs=*/nullptr);
3519     if (CtorArg.isInvalid())
3520       return true;
3521 
3522     // C++11 [class.copy]p15:
3523     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3524     //     with static_cast<T&&>(x.m);
3525     if (RefersToRValueRef(CtorArg.get())) {
3526       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3527     }
3528 
3529     // When the field we are copying is an array, create index variables for
3530     // each dimension of the array. We use these index variables to subscript
3531     // the source array, and other clients (e.g., CodeGen) will perform the
3532     // necessary iteration with these index variables.
3533     SmallVector<VarDecl *, 4> IndexVariables;
3534     QualType BaseType = Field->getType();
3535     QualType SizeType = SemaRef.Context.getSizeType();
3536     bool InitializingArray = false;
3537     while (const ConstantArrayType *Array
3538                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3539       InitializingArray = true;
3540       // Create the iteration variable for this array index.
3541       IdentifierInfo *IterationVarName = nullptr;
3542       {
3543         SmallString<8> Str;
3544         llvm::raw_svector_ostream OS(Str);
3545         OS << "__i" << IndexVariables.size();
3546         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3547       }
3548       VarDecl *IterationVar
3549         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3550                           IterationVarName, SizeType,
3551                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3552                           SC_None);
3553       IndexVariables.push_back(IterationVar);
3554 
3555       // Create a reference to the iteration variable.
3556       ExprResult IterationVarRef
3557         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3558       assert(!IterationVarRef.isInvalid() &&
3559              "Reference to invented variable cannot fail!");
3560       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3561       assert(!IterationVarRef.isInvalid() &&
3562              "Conversion of invented variable cannot fail!");
3563 
3564       // Subscript the array with this iteration variable.
3565       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3566                                                         IterationVarRef.get(),
3567                                                         Loc);
3568       if (CtorArg.isInvalid())
3569         return true;
3570 
3571       BaseType = Array->getElementType();
3572     }
3573 
3574     // The array subscript expression is an lvalue, which is wrong for moving.
3575     if (Moving && InitializingArray)
3576       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3577 
3578     // Construct the entity that we will be initializing. For an array, this
3579     // will be first element in the array, which may require several levels
3580     // of array-subscript entities.
3581     SmallVector<InitializedEntity, 4> Entities;
3582     Entities.reserve(1 + IndexVariables.size());
3583     if (Indirect)
3584       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3585     else
3586       Entities.push_back(InitializedEntity::InitializeMember(Field));
3587     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3588       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3589                                                               0,
3590                                                               Entities.back()));
3591 
3592     // Direct-initialize to use the copy constructor.
3593     InitializationKind InitKind =
3594       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3595 
3596     Expr *CtorArgE = CtorArg.getAs<Expr>();
3597     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3598 
3599     ExprResult MemberInit
3600       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3601                         MultiExprArg(&CtorArgE, 1));
3602     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3603     if (MemberInit.isInvalid())
3604       return true;
3605 
3606     if (Indirect) {
3607       assert(IndexVariables.size() == 0 &&
3608              "Indirect field improperly initialized");
3609       CXXMemberInit
3610         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3611                                                    Loc, Loc,
3612                                                    MemberInit.getAs<Expr>(),
3613                                                    Loc);
3614     } else
3615       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3616                                                  Loc, MemberInit.getAs<Expr>(),
3617                                                  Loc,
3618                                                  IndexVariables.data(),
3619                                                  IndexVariables.size());
3620     return false;
3621   }
3622 
3623   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3624          "Unhandled implicit init kind!");
3625 
3626   QualType FieldBaseElementType =
3627     SemaRef.Context.getBaseElementType(Field->getType());
3628 
3629   if (FieldBaseElementType->isRecordType()) {
3630     InitializedEntity InitEntity
3631       = Indirect? InitializedEntity::InitializeMember(Indirect)
3632                 : InitializedEntity::InitializeMember(Field);
3633     InitializationKind InitKind =
3634       InitializationKind::CreateDefault(Loc);
3635 
3636     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3637     ExprResult MemberInit =
3638       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3639 
3640     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3641     if (MemberInit.isInvalid())
3642       return true;
3643 
3644     if (Indirect)
3645       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3646                                                                Indirect, Loc,
3647                                                                Loc,
3648                                                                MemberInit.get(),
3649                                                                Loc);
3650     else
3651       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3652                                                                Field, Loc, Loc,
3653                                                                MemberInit.get(),
3654                                                                Loc);
3655     return false;
3656   }
3657 
3658   if (!Field->getParent()->isUnion()) {
3659     if (FieldBaseElementType->isReferenceType()) {
3660       SemaRef.Diag(Constructor->getLocation(),
3661                    diag::err_uninitialized_member_in_ctor)
3662       << (int)Constructor->isImplicit()
3663       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3664       << 0 << Field->getDeclName();
3665       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3666       return true;
3667     }
3668 
3669     if (FieldBaseElementType.isConstQualified()) {
3670       SemaRef.Diag(Constructor->getLocation(),
3671                    diag::err_uninitialized_member_in_ctor)
3672       << (int)Constructor->isImplicit()
3673       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3674       << 1 << Field->getDeclName();
3675       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3676       return true;
3677     }
3678   }
3679 
3680   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3681       FieldBaseElementType->isObjCRetainableType() &&
3682       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3683       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3684     // ARC:
3685     //   Default-initialize Objective-C pointers to NULL.
3686     CXXMemberInit
3687       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3688                                                  Loc, Loc,
3689                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3690                                                  Loc);
3691     return false;
3692   }
3693 
3694   // Nothing to initialize.
3695   CXXMemberInit = nullptr;
3696   return false;
3697 }
3698 
3699 namespace {
3700 struct BaseAndFieldInfo {
3701   Sema &S;
3702   CXXConstructorDecl *Ctor;
3703   bool AnyErrorsInInits;
3704   ImplicitInitializerKind IIK;
3705   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3706   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3707   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3708 
3709   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3710     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3711     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3712     if (Generated && Ctor->isCopyConstructor())
3713       IIK = IIK_Copy;
3714     else if (Generated && Ctor->isMoveConstructor())
3715       IIK = IIK_Move;
3716     else if (Ctor->getInheritedConstructor())
3717       IIK = IIK_Inherit;
3718     else
3719       IIK = IIK_Default;
3720   }
3721 
3722   bool isImplicitCopyOrMove() const {
3723     switch (IIK) {
3724     case IIK_Copy:
3725     case IIK_Move:
3726       return true;
3727 
3728     case IIK_Default:
3729     case IIK_Inherit:
3730       return false;
3731     }
3732 
3733     llvm_unreachable("Invalid ImplicitInitializerKind!");
3734   }
3735 
3736   bool addFieldInitializer(CXXCtorInitializer *Init) {
3737     AllToInit.push_back(Init);
3738 
3739     // Check whether this initializer makes the field "used".
3740     if (Init->getInit()->HasSideEffects(S.Context))
3741       S.UnusedPrivateFields.remove(Init->getAnyMember());
3742 
3743     return false;
3744   }
3745 
3746   bool isInactiveUnionMember(FieldDecl *Field) {
3747     RecordDecl *Record = Field->getParent();
3748     if (!Record->isUnion())
3749       return false;
3750 
3751     if (FieldDecl *Active =
3752             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3753       return Active != Field->getCanonicalDecl();
3754 
3755     // In an implicit copy or move constructor, ignore any in-class initializer.
3756     if (isImplicitCopyOrMove())
3757       return true;
3758 
3759     // If there's no explicit initialization, the field is active only if it
3760     // has an in-class initializer...
3761     if (Field->hasInClassInitializer())
3762       return false;
3763     // ... or it's an anonymous struct or union whose class has an in-class
3764     // initializer.
3765     if (!Field->isAnonymousStructOrUnion())
3766       return true;
3767     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3768     return !FieldRD->hasInClassInitializer();
3769   }
3770 
3771   /// \brief Determine whether the given field is, or is within, a union member
3772   /// that is inactive (because there was an initializer given for a different
3773   /// member of the union, or because the union was not initialized at all).
3774   bool isWithinInactiveUnionMember(FieldDecl *Field,
3775                                    IndirectFieldDecl *Indirect) {
3776     if (!Indirect)
3777       return isInactiveUnionMember(Field);
3778 
3779     for (auto *C : Indirect->chain()) {
3780       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3781       if (Field && isInactiveUnionMember(Field))
3782         return true;
3783     }
3784     return false;
3785   }
3786 };
3787 }
3788 
3789 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3790 /// array type.
3791 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3792   if (T->isIncompleteArrayType())
3793     return true;
3794 
3795   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3796     if (!ArrayT->getSize())
3797       return true;
3798 
3799     T = ArrayT->getElementType();
3800   }
3801 
3802   return false;
3803 }
3804 
3805 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3806                                     FieldDecl *Field,
3807                                     IndirectFieldDecl *Indirect = nullptr) {
3808   if (Field->isInvalidDecl())
3809     return false;
3810 
3811   // Overwhelmingly common case: we have a direct initializer for this field.
3812   if (CXXCtorInitializer *Init =
3813           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3814     return Info.addFieldInitializer(Init);
3815 
3816   // C++11 [class.base.init]p8:
3817   //   if the entity is a non-static data member that has a
3818   //   brace-or-equal-initializer and either
3819   //   -- the constructor's class is a union and no other variant member of that
3820   //      union is designated by a mem-initializer-id or
3821   //   -- the constructor's class is not a union, and, if the entity is a member
3822   //      of an anonymous union, no other member of that union is designated by
3823   //      a mem-initializer-id,
3824   //   the entity is initialized as specified in [dcl.init].
3825   //
3826   // We also apply the same rules to handle anonymous structs within anonymous
3827   // unions.
3828   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3829     return false;
3830 
3831   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3832     ExprResult DIE =
3833         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3834     if (DIE.isInvalid())
3835       return true;
3836     CXXCtorInitializer *Init;
3837     if (Indirect)
3838       Init = new (SemaRef.Context)
3839           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3840                              SourceLocation(), DIE.get(), SourceLocation());
3841     else
3842       Init = new (SemaRef.Context)
3843           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3844                              SourceLocation(), DIE.get(), SourceLocation());
3845     return Info.addFieldInitializer(Init);
3846   }
3847 
3848   // Don't initialize incomplete or zero-length arrays.
3849   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3850     return false;
3851 
3852   // Don't try to build an implicit initializer if there were semantic
3853   // errors in any of the initializers (and therefore we might be
3854   // missing some that the user actually wrote).
3855   if (Info.AnyErrorsInInits)
3856     return false;
3857 
3858   CXXCtorInitializer *Init = nullptr;
3859   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3860                                      Indirect, Init))
3861     return true;
3862 
3863   if (!Init)
3864     return false;
3865 
3866   return Info.addFieldInitializer(Init);
3867 }
3868 
3869 bool
3870 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3871                                CXXCtorInitializer *Initializer) {
3872   assert(Initializer->isDelegatingInitializer());
3873   Constructor->setNumCtorInitializers(1);
3874   CXXCtorInitializer **initializer =
3875     new (Context) CXXCtorInitializer*[1];
3876   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3877   Constructor->setCtorInitializers(initializer);
3878 
3879   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3880     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3881     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3882   }
3883 
3884   DelegatingCtorDecls.push_back(Constructor);
3885 
3886   DiagnoseUninitializedFields(*this, Constructor);
3887 
3888   return false;
3889 }
3890 
3891 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3892                                ArrayRef<CXXCtorInitializer *> Initializers) {
3893   if (Constructor->isDependentContext()) {
3894     // Just store the initializers as written, they will be checked during
3895     // instantiation.
3896     if (!Initializers.empty()) {
3897       Constructor->setNumCtorInitializers(Initializers.size());
3898       CXXCtorInitializer **baseOrMemberInitializers =
3899         new (Context) CXXCtorInitializer*[Initializers.size()];
3900       memcpy(baseOrMemberInitializers, Initializers.data(),
3901              Initializers.size() * sizeof(CXXCtorInitializer*));
3902       Constructor->setCtorInitializers(baseOrMemberInitializers);
3903     }
3904 
3905     // Let template instantiation know whether we had errors.
3906     if (AnyErrors)
3907       Constructor->setInvalidDecl();
3908 
3909     return false;
3910   }
3911 
3912   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3913 
3914   // We need to build the initializer AST according to order of construction
3915   // and not what user specified in the Initializers list.
3916   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3917   if (!ClassDecl)
3918     return true;
3919 
3920   bool HadError = false;
3921 
3922   for (unsigned i = 0; i < Initializers.size(); i++) {
3923     CXXCtorInitializer *Member = Initializers[i];
3924 
3925     if (Member->isBaseInitializer())
3926       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3927     else {
3928       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3929 
3930       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3931         for (auto *C : F->chain()) {
3932           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3933           if (FD && FD->getParent()->isUnion())
3934             Info.ActiveUnionMember.insert(std::make_pair(
3935                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3936         }
3937       } else if (FieldDecl *FD = Member->getMember()) {
3938         if (FD->getParent()->isUnion())
3939           Info.ActiveUnionMember.insert(std::make_pair(
3940               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3941       }
3942     }
3943   }
3944 
3945   // Keep track of the direct virtual bases.
3946   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3947   for (auto &I : ClassDecl->bases()) {
3948     if (I.isVirtual())
3949       DirectVBases.insert(&I);
3950   }
3951 
3952   // Push virtual bases before others.
3953   for (auto &VBase : ClassDecl->vbases()) {
3954     if (CXXCtorInitializer *Value
3955         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3956       // [class.base.init]p7, per DR257:
3957       //   A mem-initializer where the mem-initializer-id names a virtual base
3958       //   class is ignored during execution of a constructor of any class that
3959       //   is not the most derived class.
3960       if (ClassDecl->isAbstract()) {
3961         // FIXME: Provide a fixit to remove the base specifier. This requires
3962         // tracking the location of the associated comma for a base specifier.
3963         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3964           << VBase.getType() << ClassDecl;
3965         DiagnoseAbstractType(ClassDecl);
3966       }
3967 
3968       Info.AllToInit.push_back(Value);
3969     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3970       // [class.base.init]p8, per DR257:
3971       //   If a given [...] base class is not named by a mem-initializer-id
3972       //   [...] and the entity is not a virtual base class of an abstract
3973       //   class, then [...] the entity is default-initialized.
3974       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3975       CXXCtorInitializer *CXXBaseInit;
3976       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3977                                        &VBase, IsInheritedVirtualBase,
3978                                        CXXBaseInit)) {
3979         HadError = true;
3980         continue;
3981       }
3982 
3983       Info.AllToInit.push_back(CXXBaseInit);
3984     }
3985   }
3986 
3987   // Non-virtual bases.
3988   for (auto &Base : ClassDecl->bases()) {
3989     // Virtuals are in the virtual base list and already constructed.
3990     if (Base.isVirtual())
3991       continue;
3992 
3993     if (CXXCtorInitializer *Value
3994           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3995       Info.AllToInit.push_back(Value);
3996     } else if (!AnyErrors) {
3997       CXXCtorInitializer *CXXBaseInit;
3998       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3999                                        &Base, /*IsInheritedVirtualBase=*/false,
4000                                        CXXBaseInit)) {
4001         HadError = true;
4002         continue;
4003       }
4004 
4005       Info.AllToInit.push_back(CXXBaseInit);
4006     }
4007   }
4008 
4009   // Fields.
4010   for (auto *Mem : ClassDecl->decls()) {
4011     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4012       // C++ [class.bit]p2:
4013       //   A declaration for a bit-field that omits the identifier declares an
4014       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4015       //   initialized.
4016       if (F->isUnnamedBitfield())
4017         continue;
4018 
4019       // If we're not generating the implicit copy/move constructor, then we'll
4020       // handle anonymous struct/union fields based on their individual
4021       // indirect fields.
4022       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4023         continue;
4024 
4025       if (CollectFieldInitializer(*this, Info, F))
4026         HadError = true;
4027       continue;
4028     }
4029 
4030     // Beyond this point, we only consider default initialization.
4031     if (Info.isImplicitCopyOrMove())
4032       continue;
4033 
4034     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4035       if (F->getType()->isIncompleteArrayType()) {
4036         assert(ClassDecl->hasFlexibleArrayMember() &&
4037                "Incomplete array type is not valid");
4038         continue;
4039       }
4040 
4041       // Initialize each field of an anonymous struct individually.
4042       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4043         HadError = true;
4044 
4045       continue;
4046     }
4047   }
4048 
4049   unsigned NumInitializers = Info.AllToInit.size();
4050   if (NumInitializers > 0) {
4051     Constructor->setNumCtorInitializers(NumInitializers);
4052     CXXCtorInitializer **baseOrMemberInitializers =
4053       new (Context) CXXCtorInitializer*[NumInitializers];
4054     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4055            NumInitializers * sizeof(CXXCtorInitializer*));
4056     Constructor->setCtorInitializers(baseOrMemberInitializers);
4057 
4058     // Constructors implicitly reference the base and member
4059     // destructors.
4060     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4061                                            Constructor->getParent());
4062   }
4063 
4064   return HadError;
4065 }
4066 
4067 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4068   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4069     const RecordDecl *RD = RT->getDecl();
4070     if (RD->isAnonymousStructOrUnion()) {
4071       for (auto *Field : RD->fields())
4072         PopulateKeysForFields(Field, IdealInits);
4073       return;
4074     }
4075   }
4076   IdealInits.push_back(Field->getCanonicalDecl());
4077 }
4078 
4079 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4080   return Context.getCanonicalType(BaseType).getTypePtr();
4081 }
4082 
4083 static const void *GetKeyForMember(ASTContext &Context,
4084                                    CXXCtorInitializer *Member) {
4085   if (!Member->isAnyMemberInitializer())
4086     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4087 
4088   return Member->getAnyMember()->getCanonicalDecl();
4089 }
4090 
4091 static void DiagnoseBaseOrMemInitializerOrder(
4092     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4093     ArrayRef<CXXCtorInitializer *> Inits) {
4094   if (Constructor->getDeclContext()->isDependentContext())
4095     return;
4096 
4097   // Don't check initializers order unless the warning is enabled at the
4098   // location of at least one initializer.
4099   bool ShouldCheckOrder = false;
4100   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4101     CXXCtorInitializer *Init = Inits[InitIndex];
4102     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4103                                  Init->getSourceLocation())) {
4104       ShouldCheckOrder = true;
4105       break;
4106     }
4107   }
4108   if (!ShouldCheckOrder)
4109     return;
4110 
4111   // Build the list of bases and members in the order that they'll
4112   // actually be initialized.  The explicit initializers should be in
4113   // this same order but may be missing things.
4114   SmallVector<const void*, 32> IdealInitKeys;
4115 
4116   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4117 
4118   // 1. Virtual bases.
4119   for (const auto &VBase : ClassDecl->vbases())
4120     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4121 
4122   // 2. Non-virtual bases.
4123   for (const auto &Base : ClassDecl->bases()) {
4124     if (Base.isVirtual())
4125       continue;
4126     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4127   }
4128 
4129   // 3. Direct fields.
4130   for (auto *Field : ClassDecl->fields()) {
4131     if (Field->isUnnamedBitfield())
4132       continue;
4133 
4134     PopulateKeysForFields(Field, IdealInitKeys);
4135   }
4136 
4137   unsigned NumIdealInits = IdealInitKeys.size();
4138   unsigned IdealIndex = 0;
4139 
4140   CXXCtorInitializer *PrevInit = nullptr;
4141   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4142     CXXCtorInitializer *Init = Inits[InitIndex];
4143     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4144 
4145     // Scan forward to try to find this initializer in the idealized
4146     // initializers list.
4147     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4148       if (InitKey == IdealInitKeys[IdealIndex])
4149         break;
4150 
4151     // If we didn't find this initializer, it must be because we
4152     // scanned past it on a previous iteration.  That can only
4153     // happen if we're out of order;  emit a warning.
4154     if (IdealIndex == NumIdealInits && PrevInit) {
4155       Sema::SemaDiagnosticBuilder D =
4156         SemaRef.Diag(PrevInit->getSourceLocation(),
4157                      diag::warn_initializer_out_of_order);
4158 
4159       if (PrevInit->isAnyMemberInitializer())
4160         D << 0 << PrevInit->getAnyMember()->getDeclName();
4161       else
4162         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4163 
4164       if (Init->isAnyMemberInitializer())
4165         D << 0 << Init->getAnyMember()->getDeclName();
4166       else
4167         D << 1 << Init->getTypeSourceInfo()->getType();
4168 
4169       // Move back to the initializer's location in the ideal list.
4170       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4171         if (InitKey == IdealInitKeys[IdealIndex])
4172           break;
4173 
4174       assert(IdealIndex != NumIdealInits &&
4175              "initializer not found in initializer list");
4176     }
4177 
4178     PrevInit = Init;
4179   }
4180 }
4181 
4182 namespace {
4183 bool CheckRedundantInit(Sema &S,
4184                         CXXCtorInitializer *Init,
4185                         CXXCtorInitializer *&PrevInit) {
4186   if (!PrevInit) {
4187     PrevInit = Init;
4188     return false;
4189   }
4190 
4191   if (FieldDecl *Field = Init->getAnyMember())
4192     S.Diag(Init->getSourceLocation(),
4193            diag::err_multiple_mem_initialization)
4194       << Field->getDeclName()
4195       << Init->getSourceRange();
4196   else {
4197     const Type *BaseClass = Init->getBaseClass();
4198     assert(BaseClass && "neither field nor base");
4199     S.Diag(Init->getSourceLocation(),
4200            diag::err_multiple_base_initialization)
4201       << QualType(BaseClass, 0)
4202       << Init->getSourceRange();
4203   }
4204   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4205     << 0 << PrevInit->getSourceRange();
4206 
4207   return true;
4208 }
4209 
4210 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4211 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4212 
4213 bool CheckRedundantUnionInit(Sema &S,
4214                              CXXCtorInitializer *Init,
4215                              RedundantUnionMap &Unions) {
4216   FieldDecl *Field = Init->getAnyMember();
4217   RecordDecl *Parent = Field->getParent();
4218   NamedDecl *Child = Field;
4219 
4220   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4221     if (Parent->isUnion()) {
4222       UnionEntry &En = Unions[Parent];
4223       if (En.first && En.first != Child) {
4224         S.Diag(Init->getSourceLocation(),
4225                diag::err_multiple_mem_union_initialization)
4226           << Field->getDeclName()
4227           << Init->getSourceRange();
4228         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4229           << 0 << En.second->getSourceRange();
4230         return true;
4231       }
4232       if (!En.first) {
4233         En.first = Child;
4234         En.second = Init;
4235       }
4236       if (!Parent->isAnonymousStructOrUnion())
4237         return false;
4238     }
4239 
4240     Child = Parent;
4241     Parent = cast<RecordDecl>(Parent->getDeclContext());
4242   }
4243 
4244   return false;
4245 }
4246 }
4247 
4248 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4249 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4250                                 SourceLocation ColonLoc,
4251                                 ArrayRef<CXXCtorInitializer*> MemInits,
4252                                 bool AnyErrors) {
4253   if (!ConstructorDecl)
4254     return;
4255 
4256   AdjustDeclIfTemplate(ConstructorDecl);
4257 
4258   CXXConstructorDecl *Constructor
4259     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4260 
4261   if (!Constructor) {
4262     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4263     return;
4264   }
4265 
4266   // Mapping for the duplicate initializers check.
4267   // For member initializers, this is keyed with a FieldDecl*.
4268   // For base initializers, this is keyed with a Type*.
4269   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4270 
4271   // Mapping for the inconsistent anonymous-union initializers check.
4272   RedundantUnionMap MemberUnions;
4273 
4274   bool HadError = false;
4275   for (unsigned i = 0; i < MemInits.size(); i++) {
4276     CXXCtorInitializer *Init = MemInits[i];
4277 
4278     // Set the source order index.
4279     Init->setSourceOrder(i);
4280 
4281     if (Init->isAnyMemberInitializer()) {
4282       const void *Key = GetKeyForMember(Context, Init);
4283       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4284           CheckRedundantUnionInit(*this, Init, MemberUnions))
4285         HadError = true;
4286     } else if (Init->isBaseInitializer()) {
4287       const void *Key = GetKeyForMember(Context, Init);
4288       if (CheckRedundantInit(*this, Init, Members[Key]))
4289         HadError = true;
4290     } else {
4291       assert(Init->isDelegatingInitializer());
4292       // This must be the only initializer
4293       if (MemInits.size() != 1) {
4294         Diag(Init->getSourceLocation(),
4295              diag::err_delegating_initializer_alone)
4296           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4297         // We will treat this as being the only initializer.
4298       }
4299       SetDelegatingInitializer(Constructor, MemInits[i]);
4300       // Return immediately as the initializer is set.
4301       return;
4302     }
4303   }
4304 
4305   if (HadError)
4306     return;
4307 
4308   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4309 
4310   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4311 
4312   DiagnoseUninitializedFields(*this, Constructor);
4313 }
4314 
4315 void
4316 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4317                                              CXXRecordDecl *ClassDecl) {
4318   // Ignore dependent contexts. Also ignore unions, since their members never
4319   // have destructors implicitly called.
4320   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4321     return;
4322 
4323   // FIXME: all the access-control diagnostics are positioned on the
4324   // field/base declaration.  That's probably good; that said, the
4325   // user might reasonably want to know why the destructor is being
4326   // emitted, and we currently don't say.
4327 
4328   // Non-static data members.
4329   for (auto *Field : ClassDecl->fields()) {
4330     if (Field->isInvalidDecl())
4331       continue;
4332 
4333     // Don't destroy incomplete or zero-length arrays.
4334     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4335       continue;
4336 
4337     QualType FieldType = Context.getBaseElementType(Field->getType());
4338 
4339     const RecordType* RT = FieldType->getAs<RecordType>();
4340     if (!RT)
4341       continue;
4342 
4343     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4344     if (FieldClassDecl->isInvalidDecl())
4345       continue;
4346     if (FieldClassDecl->hasIrrelevantDestructor())
4347       continue;
4348     // The destructor for an implicit anonymous union member is never invoked.
4349     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4350       continue;
4351 
4352     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4353     assert(Dtor && "No dtor found for FieldClassDecl!");
4354     CheckDestructorAccess(Field->getLocation(), Dtor,
4355                           PDiag(diag::err_access_dtor_field)
4356                             << Field->getDeclName()
4357                             << FieldType);
4358 
4359     MarkFunctionReferenced(Location, Dtor);
4360     DiagnoseUseOfDecl(Dtor, Location);
4361   }
4362 
4363   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4364 
4365   // Bases.
4366   for (const auto &Base : ClassDecl->bases()) {
4367     // Bases are always records in a well-formed non-dependent class.
4368     const RecordType *RT = Base.getType()->getAs<RecordType>();
4369 
4370     // Remember direct virtual bases.
4371     if (Base.isVirtual())
4372       DirectVirtualBases.insert(RT);
4373 
4374     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4375     // If our base class is invalid, we probably can't get its dtor anyway.
4376     if (BaseClassDecl->isInvalidDecl())
4377       continue;
4378     if (BaseClassDecl->hasIrrelevantDestructor())
4379       continue;
4380 
4381     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4382     assert(Dtor && "No dtor found for BaseClassDecl!");
4383 
4384     // FIXME: caret should be on the start of the class name
4385     CheckDestructorAccess(Base.getLocStart(), Dtor,
4386                           PDiag(diag::err_access_dtor_base)
4387                             << Base.getType()
4388                             << Base.getSourceRange(),
4389                           Context.getTypeDeclType(ClassDecl));
4390 
4391     MarkFunctionReferenced(Location, Dtor);
4392     DiagnoseUseOfDecl(Dtor, Location);
4393   }
4394 
4395   // Virtual bases.
4396   for (const auto &VBase : ClassDecl->vbases()) {
4397     // Bases are always records in a well-formed non-dependent class.
4398     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4399 
4400     // Ignore direct virtual bases.
4401     if (DirectVirtualBases.count(RT))
4402       continue;
4403 
4404     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4405     // If our base class is invalid, we probably can't get its dtor anyway.
4406     if (BaseClassDecl->isInvalidDecl())
4407       continue;
4408     if (BaseClassDecl->hasIrrelevantDestructor())
4409       continue;
4410 
4411     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4412     assert(Dtor && "No dtor found for BaseClassDecl!");
4413     if (CheckDestructorAccess(
4414             ClassDecl->getLocation(), Dtor,
4415             PDiag(diag::err_access_dtor_vbase)
4416                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4417             Context.getTypeDeclType(ClassDecl)) ==
4418         AR_accessible) {
4419       CheckDerivedToBaseConversion(
4420           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4421           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4422           SourceRange(), DeclarationName(), nullptr);
4423     }
4424 
4425     MarkFunctionReferenced(Location, Dtor);
4426     DiagnoseUseOfDecl(Dtor, Location);
4427   }
4428 }
4429 
4430 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4431   if (!CDtorDecl)
4432     return;
4433 
4434   if (CXXConstructorDecl *Constructor
4435       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4436     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4437     DiagnoseUninitializedFields(*this, Constructor);
4438   }
4439 }
4440 
4441 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4442                                   unsigned DiagID, AbstractDiagSelID SelID) {
4443   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4444     unsigned DiagID;
4445     AbstractDiagSelID SelID;
4446 
4447   public:
4448     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4449       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4450 
4451     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4452       if (Suppressed) return;
4453       if (SelID == -1)
4454         S.Diag(Loc, DiagID) << T;
4455       else
4456         S.Diag(Loc, DiagID) << SelID << T;
4457     }
4458   } Diagnoser(DiagID, SelID);
4459 
4460   return RequireNonAbstractType(Loc, T, Diagnoser);
4461 }
4462 
4463 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4464                                   TypeDiagnoser &Diagnoser) {
4465   if (!getLangOpts().CPlusPlus)
4466     return false;
4467 
4468   if (const ArrayType *AT = Context.getAsArrayType(T))
4469     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4470 
4471   if (const PointerType *PT = T->getAs<PointerType>()) {
4472     // Find the innermost pointer type.
4473     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4474       PT = T;
4475 
4476     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4477       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4478   }
4479 
4480   const RecordType *RT = T->getAs<RecordType>();
4481   if (!RT)
4482     return false;
4483 
4484   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4485 
4486   // We can't answer whether something is abstract until it has a
4487   // definition.  If it's currently being defined, we'll walk back
4488   // over all the declarations when we have a full definition.
4489   const CXXRecordDecl *Def = RD->getDefinition();
4490   if (!Def || Def->isBeingDefined())
4491     return false;
4492 
4493   if (!RD->isAbstract())
4494     return false;
4495 
4496   Diagnoser.diagnose(*this, Loc, T);
4497   DiagnoseAbstractType(RD);
4498 
4499   return true;
4500 }
4501 
4502 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4503   // Check if we've already emitted the list of pure virtual functions
4504   // for this class.
4505   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4506     return;
4507 
4508   // If the diagnostic is suppressed, don't emit the notes. We're only
4509   // going to emit them once, so try to attach them to a diagnostic we're
4510   // actually going to show.
4511   if (Diags.isLastDiagnosticIgnored())
4512     return;
4513 
4514   CXXFinalOverriderMap FinalOverriders;
4515   RD->getFinalOverriders(FinalOverriders);
4516 
4517   // Keep a set of seen pure methods so we won't diagnose the same method
4518   // more than once.
4519   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4520 
4521   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4522                                    MEnd = FinalOverriders.end();
4523        M != MEnd;
4524        ++M) {
4525     for (OverridingMethods::iterator SO = M->second.begin(),
4526                                   SOEnd = M->second.end();
4527          SO != SOEnd; ++SO) {
4528       // C++ [class.abstract]p4:
4529       //   A class is abstract if it contains or inherits at least one
4530       //   pure virtual function for which the final overrider is pure
4531       //   virtual.
4532 
4533       //
4534       if (SO->second.size() != 1)
4535         continue;
4536 
4537       if (!SO->second.front().Method->isPure())
4538         continue;
4539 
4540       if (!SeenPureMethods.insert(SO->second.front().Method).second)
4541         continue;
4542 
4543       Diag(SO->second.front().Method->getLocation(),
4544            diag::note_pure_virtual_function)
4545         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4546     }
4547   }
4548 
4549   if (!PureVirtualClassDiagSet)
4550     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4551   PureVirtualClassDiagSet->insert(RD);
4552 }
4553 
4554 namespace {
4555 struct AbstractUsageInfo {
4556   Sema &S;
4557   CXXRecordDecl *Record;
4558   CanQualType AbstractType;
4559   bool Invalid;
4560 
4561   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4562     : S(S), Record(Record),
4563       AbstractType(S.Context.getCanonicalType(
4564                    S.Context.getTypeDeclType(Record))),
4565       Invalid(false) {}
4566 
4567   void DiagnoseAbstractType() {
4568     if (Invalid) return;
4569     S.DiagnoseAbstractType(Record);
4570     Invalid = true;
4571   }
4572 
4573   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4574 };
4575 
4576 struct CheckAbstractUsage {
4577   AbstractUsageInfo &Info;
4578   const NamedDecl *Ctx;
4579 
4580   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4581     : Info(Info), Ctx(Ctx) {}
4582 
4583   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4584     switch (TL.getTypeLocClass()) {
4585 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4586 #define TYPELOC(CLASS, PARENT) \
4587     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4588 #include "clang/AST/TypeLocNodes.def"
4589     }
4590   }
4591 
4592   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4593     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4594     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4595       if (!TL.getParam(I))
4596         continue;
4597 
4598       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4599       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4600     }
4601   }
4602 
4603   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4604     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4605   }
4606 
4607   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4608     // Visit the type parameters from a permissive context.
4609     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4610       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4611       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4612         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4613           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4614       // TODO: other template argument types?
4615     }
4616   }
4617 
4618   // Visit pointee types from a permissive context.
4619 #define CheckPolymorphic(Type) \
4620   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4621     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4622   }
4623   CheckPolymorphic(PointerTypeLoc)
4624   CheckPolymorphic(ReferenceTypeLoc)
4625   CheckPolymorphic(MemberPointerTypeLoc)
4626   CheckPolymorphic(BlockPointerTypeLoc)
4627   CheckPolymorphic(AtomicTypeLoc)
4628 
4629   /// Handle all the types we haven't given a more specific
4630   /// implementation for above.
4631   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4632     // Every other kind of type that we haven't called out already
4633     // that has an inner type is either (1) sugar or (2) contains that
4634     // inner type in some way as a subobject.
4635     if (TypeLoc Next = TL.getNextTypeLoc())
4636       return Visit(Next, Sel);
4637 
4638     // If there's no inner type and we're in a permissive context,
4639     // don't diagnose.
4640     if (Sel == Sema::AbstractNone) return;
4641 
4642     // Check whether the type matches the abstract type.
4643     QualType T = TL.getType();
4644     if (T->isArrayType()) {
4645       Sel = Sema::AbstractArrayType;
4646       T = Info.S.Context.getBaseElementType(T);
4647     }
4648     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4649     if (CT != Info.AbstractType) return;
4650 
4651     // It matched; do some magic.
4652     if (Sel == Sema::AbstractArrayType) {
4653       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4654         << T << TL.getSourceRange();
4655     } else {
4656       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4657         << Sel << T << TL.getSourceRange();
4658     }
4659     Info.DiagnoseAbstractType();
4660   }
4661 };
4662 
4663 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4664                                   Sema::AbstractDiagSelID Sel) {
4665   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4666 }
4667 
4668 }
4669 
4670 /// Check for invalid uses of an abstract type in a method declaration.
4671 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4672                                     CXXMethodDecl *MD) {
4673   // No need to do the check on definitions, which require that
4674   // the return/param types be complete.
4675   if (MD->doesThisDeclarationHaveABody())
4676     return;
4677 
4678   // For safety's sake, just ignore it if we don't have type source
4679   // information.  This should never happen for non-implicit methods,
4680   // but...
4681   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4682     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4683 }
4684 
4685 /// Check for invalid uses of an abstract type within a class definition.
4686 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4687                                     CXXRecordDecl *RD) {
4688   for (auto *D : RD->decls()) {
4689     if (D->isImplicit()) continue;
4690 
4691     // Methods and method templates.
4692     if (isa<CXXMethodDecl>(D)) {
4693       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4694     } else if (isa<FunctionTemplateDecl>(D)) {
4695       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4696       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4697 
4698     // Fields and static variables.
4699     } else if (isa<FieldDecl>(D)) {
4700       FieldDecl *FD = cast<FieldDecl>(D);
4701       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4702         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4703     } else if (isa<VarDecl>(D)) {
4704       VarDecl *VD = cast<VarDecl>(D);
4705       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4706         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4707 
4708     // Nested classes and class templates.
4709     } else if (isa<CXXRecordDecl>(D)) {
4710       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4711     } else if (isa<ClassTemplateDecl>(D)) {
4712       CheckAbstractClassUsage(Info,
4713                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4714     }
4715   }
4716 }
4717 
4718 /// \brief Check class-level dllimport/dllexport attribute.
4719 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4720   Attr *ClassAttr = getDLLAttr(Class);
4721 
4722   // MSVC inherits DLL attributes to partial class template specializations.
4723   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4724     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4725       if (Attr *TemplateAttr =
4726               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4727         auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4728         A->setInherited(true);
4729         ClassAttr = A;
4730       }
4731     }
4732   }
4733 
4734   if (!ClassAttr)
4735     return;
4736 
4737   if (!Class->isExternallyVisible()) {
4738     S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4739         << Class << ClassAttr;
4740     return;
4741   }
4742 
4743   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4744       !ClassAttr->isInherited()) {
4745     // Diagnose dll attributes on members of class with dll attribute.
4746     for (Decl *Member : Class->decls()) {
4747       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4748         continue;
4749       InheritableAttr *MemberAttr = getDLLAttr(Member);
4750       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4751         continue;
4752 
4753       S.Diag(MemberAttr->getLocation(),
4754              diag::err_attribute_dll_member_of_dll_class)
4755           << MemberAttr << ClassAttr;
4756       S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4757       Member->setInvalidDecl();
4758     }
4759   }
4760 
4761   if (Class->getDescribedClassTemplate())
4762     // Don't inherit dll attribute until the template is instantiated.
4763     return;
4764 
4765   // The class is either imported or exported.
4766   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4767   const bool ClassImported = !ClassExported;
4768 
4769   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4770 
4771   // Don't dllexport explicit class template instantiation declarations.
4772   if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) {
4773     Class->dropAttr<DLLExportAttr>();
4774     return;
4775   }
4776 
4777   // Force declaration of implicit members so they can inherit the attribute.
4778   S.ForceDeclarationOfImplicitMembers(Class);
4779 
4780   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4781   // seem to be true in practice?
4782 
4783   for (Decl *Member : Class->decls()) {
4784     VarDecl *VD = dyn_cast<VarDecl>(Member);
4785     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4786 
4787     // Only methods and static fields inherit the attributes.
4788     if (!VD && !MD)
4789       continue;
4790 
4791     if (MD) {
4792       // Don't process deleted methods.
4793       if (MD->isDeleted())
4794         continue;
4795 
4796       if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) {
4797         // Current MSVC versions don't export the move assignment operators, so
4798         // don't attempt to import them if we have a definition.
4799         continue;
4800       }
4801 
4802       if (MD->isInlined() && ClassImported &&
4803           !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4804         // MinGW does not import inline functions.
4805         continue;
4806       }
4807     }
4808 
4809     if (!getDLLAttr(Member)) {
4810       auto *NewAttr =
4811           cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4812       NewAttr->setInherited(true);
4813       Member->addAttr(NewAttr);
4814     }
4815 
4816     if (MD && ClassExported) {
4817       if (MD->isUserProvided()) {
4818         // Instantiate non-default class member functions ...
4819 
4820         // .. except for certain kinds of template specializations.
4821         if (TSK == TSK_ExplicitInstantiationDeclaration)
4822           continue;
4823         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4824           continue;
4825 
4826         S.MarkFunctionReferenced(Class->getLocation(), MD);
4827 
4828         // The function will be passed to the consumer when its definition is
4829         // encountered.
4830       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4831                  MD->isCopyAssignmentOperator() ||
4832                  MD->isMoveAssignmentOperator()) {
4833         // Synthesize and instantiate non-trivial implicit methods, explicitly
4834         // defaulted methods, and the copy and move assignment operators. The
4835         // latter are exported even if they are trivial, because the address of
4836         // an operator can be taken and should compare equal accross libraries.
4837         S.MarkFunctionReferenced(Class->getLocation(), MD);
4838 
4839         // There is no later point when we will see the definition of this
4840         // function, so pass it to the consumer now.
4841         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4842       }
4843     }
4844   }
4845 }
4846 
4847 /// \brief Perform semantic checks on a class definition that has been
4848 /// completing, introducing implicitly-declared members, checking for
4849 /// abstract types, etc.
4850 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4851   if (!Record)
4852     return;
4853 
4854   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4855     AbstractUsageInfo Info(*this, Record);
4856     CheckAbstractClassUsage(Info, Record);
4857   }
4858 
4859   // If this is not an aggregate type and has no user-declared constructor,
4860   // complain about any non-static data members of reference or const scalar
4861   // type, since they will never get initializers.
4862   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4863       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4864       !Record->isLambda()) {
4865     bool Complained = false;
4866     for (const auto *F : Record->fields()) {
4867       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4868         continue;
4869 
4870       if (F->getType()->isReferenceType() ||
4871           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4872         if (!Complained) {
4873           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4874             << Record->getTagKind() << Record;
4875           Complained = true;
4876         }
4877 
4878         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4879           << F->getType()->isReferenceType()
4880           << F->getDeclName();
4881       }
4882     }
4883   }
4884 
4885   if (Record->isDynamicClass() && !Record->isDependentType())
4886     DynamicClasses.push_back(Record);
4887 
4888   if (Record->getIdentifier()) {
4889     // C++ [class.mem]p13:
4890     //   If T is the name of a class, then each of the following shall have a
4891     //   name different from T:
4892     //     - every member of every anonymous union that is a member of class T.
4893     //
4894     // C++ [class.mem]p14:
4895     //   In addition, if class T has a user-declared constructor (12.1), every
4896     //   non-static data member of class T shall have a name different from T.
4897     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4898     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4899          ++I) {
4900       NamedDecl *D = *I;
4901       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4902           isa<IndirectFieldDecl>(D)) {
4903         Diag(D->getLocation(), diag::err_member_name_of_class)
4904           << D->getDeclName();
4905         break;
4906       }
4907     }
4908   }
4909 
4910   // Warn if the class has virtual methods but non-virtual public destructor.
4911   if (Record->isPolymorphic() && !Record->isDependentType()) {
4912     CXXDestructorDecl *dtor = Record->getDestructor();
4913     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4914         !Record->hasAttr<FinalAttr>())
4915       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4916            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4917   }
4918 
4919   if (Record->isAbstract()) {
4920     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4921       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4922         << FA->isSpelledAsSealed();
4923       DiagnoseAbstractType(Record);
4924     }
4925   }
4926 
4927   bool HasMethodWithOverrideControl = false,
4928        HasOverridingMethodWithoutOverrideControl = false;
4929   if (!Record->isDependentType()) {
4930     for (auto *M : Record->methods()) {
4931       // See if a method overloads virtual methods in a base
4932       // class without overriding any.
4933       if (!M->isStatic())
4934         DiagnoseHiddenVirtualMethods(M);
4935       if (M->hasAttr<OverrideAttr>())
4936         HasMethodWithOverrideControl = true;
4937       else if (M->size_overridden_methods() > 0)
4938         HasOverridingMethodWithoutOverrideControl = true;
4939       // Check whether the explicitly-defaulted special members are valid.
4940       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4941         CheckExplicitlyDefaultedSpecialMember(M);
4942 
4943       // For an explicitly defaulted or deleted special member, we defer
4944       // determining triviality until the class is complete. That time is now!
4945       if (!M->isImplicit() && !M->isUserProvided()) {
4946         CXXSpecialMember CSM = getSpecialMember(M);
4947         if (CSM != CXXInvalid) {
4948           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4949 
4950           // Inform the class that we've finished declaring this member.
4951           Record->finishedDefaultedOrDeletedMember(M);
4952         }
4953       }
4954     }
4955   }
4956 
4957   if (HasMethodWithOverrideControl &&
4958       HasOverridingMethodWithoutOverrideControl) {
4959     // At least one method has the 'override' control declared.
4960     // Diagnose all other overridden methods which do not have 'override' specified on them.
4961     for (auto *M : Record->methods())
4962       DiagnoseAbsenceOfOverrideControl(M);
4963   }
4964 
4965   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4966   // whether this class uses any C++ features that are implemented
4967   // completely differently in MSVC, and if so, emit a diagnostic.
4968   // That diagnostic defaults to an error, but we allow projects to
4969   // map it down to a warning (or ignore it).  It's a fairly common
4970   // practice among users of the ms_struct pragma to mass-annotate
4971   // headers, sweeping up a bunch of types that the project doesn't
4972   // really rely on MSVC-compatible layout for.  We must therefore
4973   // support "ms_struct except for C++ stuff" as a secondary ABI.
4974   if (Record->isMsStruct(Context) &&
4975       (Record->isPolymorphic() || Record->getNumBases())) {
4976     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4977   }
4978 
4979   // Declare inheriting constructors. We do this eagerly here because:
4980   // - The standard requires an eager diagnostic for conflicting inheriting
4981   //   constructors from different classes.
4982   // - The lazy declaration of the other implicit constructors is so as to not
4983   //   waste space and performance on classes that are not meant to be
4984   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4985   //   have inheriting constructors.
4986   DeclareInheritingConstructors(Record);
4987 
4988   checkDLLAttribute(*this, Record);
4989 }
4990 
4991 /// Look up the special member function that would be called by a special
4992 /// member function for a subobject of class type.
4993 ///
4994 /// \param Class The class type of the subobject.
4995 /// \param CSM The kind of special member function.
4996 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4997 /// \param ConstRHS True if this is a copy operation with a const object
4998 ///        on its RHS, that is, if the argument to the outer special member
4999 ///        function is 'const' and this is not a field marked 'mutable'.
5000 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5001     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5002     unsigned FieldQuals, bool ConstRHS) {
5003   unsigned LHSQuals = 0;
5004   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5005     LHSQuals = FieldQuals;
5006 
5007   unsigned RHSQuals = FieldQuals;
5008   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5009     RHSQuals = 0;
5010   else if (ConstRHS)
5011     RHSQuals |= Qualifiers::Const;
5012 
5013   return S.LookupSpecialMember(Class, CSM,
5014                                RHSQuals & Qualifiers::Const,
5015                                RHSQuals & Qualifiers::Volatile,
5016                                false,
5017                                LHSQuals & Qualifiers::Const,
5018                                LHSQuals & Qualifiers::Volatile);
5019 }
5020 
5021 /// Is the special member function which would be selected to perform the
5022 /// specified operation on the specified class type a constexpr constructor?
5023 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5024                                      Sema::CXXSpecialMember CSM,
5025                                      unsigned Quals, bool ConstRHS) {
5026   Sema::SpecialMemberOverloadResult *SMOR =
5027       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5028   if (!SMOR || !SMOR->getMethod())
5029     // A constructor we wouldn't select can't be "involved in initializing"
5030     // anything.
5031     return true;
5032   return SMOR->getMethod()->isConstexpr();
5033 }
5034 
5035 /// Determine whether the specified special member function would be constexpr
5036 /// if it were implicitly defined.
5037 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5038                                               Sema::CXXSpecialMember CSM,
5039                                               bool ConstArg) {
5040   if (!S.getLangOpts().CPlusPlus11)
5041     return false;
5042 
5043   // C++11 [dcl.constexpr]p4:
5044   // In the definition of a constexpr constructor [...]
5045   bool Ctor = true;
5046   switch (CSM) {
5047   case Sema::CXXDefaultConstructor:
5048     // Since default constructor lookup is essentially trivial (and cannot
5049     // involve, for instance, template instantiation), we compute whether a
5050     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5051     //
5052     // This is important for performance; we need to know whether the default
5053     // constructor is constexpr to determine whether the type is a literal type.
5054     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5055 
5056   case Sema::CXXCopyConstructor:
5057   case Sema::CXXMoveConstructor:
5058     // For copy or move constructors, we need to perform overload resolution.
5059     break;
5060 
5061   case Sema::CXXCopyAssignment:
5062   case Sema::CXXMoveAssignment:
5063     if (!S.getLangOpts().CPlusPlus14)
5064       return false;
5065     // In C++1y, we need to perform overload resolution.
5066     Ctor = false;
5067     break;
5068 
5069   case Sema::CXXDestructor:
5070   case Sema::CXXInvalid:
5071     return false;
5072   }
5073 
5074   //   -- if the class is a non-empty union, or for each non-empty anonymous
5075   //      union member of a non-union class, exactly one non-static data member
5076   //      shall be initialized; [DR1359]
5077   //
5078   // If we squint, this is guaranteed, since exactly one non-static data member
5079   // will be initialized (if the constructor isn't deleted), we just don't know
5080   // which one.
5081   if (Ctor && ClassDecl->isUnion())
5082     return true;
5083 
5084   //   -- the class shall not have any virtual base classes;
5085   if (Ctor && ClassDecl->getNumVBases())
5086     return false;
5087 
5088   // C++1y [class.copy]p26:
5089   //   -- [the class] is a literal type, and
5090   if (!Ctor && !ClassDecl->isLiteral())
5091     return false;
5092 
5093   //   -- every constructor involved in initializing [...] base class
5094   //      sub-objects shall be a constexpr constructor;
5095   //   -- the assignment operator selected to copy/move each direct base
5096   //      class is a constexpr function, and
5097   for (const auto &B : ClassDecl->bases()) {
5098     const RecordType *BaseType = B.getType()->getAs<RecordType>();
5099     if (!BaseType) continue;
5100 
5101     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5102     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
5103       return false;
5104   }
5105 
5106   //   -- every constructor involved in initializing non-static data members
5107   //      [...] shall be a constexpr constructor;
5108   //   -- every non-static data member and base class sub-object shall be
5109   //      initialized
5110   //   -- for each non-static data member of X that is of class type (or array
5111   //      thereof), the assignment operator selected to copy/move that member is
5112   //      a constexpr function
5113   for (const auto *F : ClassDecl->fields()) {
5114     if (F->isInvalidDecl())
5115       continue;
5116     QualType BaseType = S.Context.getBaseElementType(F->getType());
5117     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5118       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5119       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5120                                     BaseType.getCVRQualifiers(),
5121                                     ConstArg && !F->isMutable()))
5122         return false;
5123     }
5124   }
5125 
5126   // All OK, it's constexpr!
5127   return true;
5128 }
5129 
5130 static Sema::ImplicitExceptionSpecification
5131 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5132   switch (S.getSpecialMember(MD)) {
5133   case Sema::CXXDefaultConstructor:
5134     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5135   case Sema::CXXCopyConstructor:
5136     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5137   case Sema::CXXCopyAssignment:
5138     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5139   case Sema::CXXMoveConstructor:
5140     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5141   case Sema::CXXMoveAssignment:
5142     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5143   case Sema::CXXDestructor:
5144     return S.ComputeDefaultedDtorExceptionSpec(MD);
5145   case Sema::CXXInvalid:
5146     break;
5147   }
5148   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5149          "only special members have implicit exception specs");
5150   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5151 }
5152 
5153 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5154                                                             CXXMethodDecl *MD) {
5155   FunctionProtoType::ExtProtoInfo EPI;
5156 
5157   // Build an exception specification pointing back at this member.
5158   EPI.ExceptionSpec.Type = EST_Unevaluated;
5159   EPI.ExceptionSpec.SourceDecl = MD;
5160 
5161   // Set the calling convention to the default for C++ instance methods.
5162   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5163       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5164                                             /*IsCXXMethod=*/true));
5165   return EPI;
5166 }
5167 
5168 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5169   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5170   if (FPT->getExceptionSpecType() != EST_Unevaluated)
5171     return;
5172 
5173   // Evaluate the exception specification.
5174   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5175 
5176   // Update the type of the special member to use it.
5177   UpdateExceptionSpec(MD, ESI);
5178 
5179   // A user-provided destructor can be defined outside the class. When that
5180   // happens, be sure to update the exception specification on both
5181   // declarations.
5182   const FunctionProtoType *CanonicalFPT =
5183     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5184   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5185     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5186 }
5187 
5188 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5189   CXXRecordDecl *RD = MD->getParent();
5190   CXXSpecialMember CSM = getSpecialMember(MD);
5191 
5192   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5193          "not an explicitly-defaulted special member");
5194 
5195   // Whether this was the first-declared instance of the constructor.
5196   // This affects whether we implicitly add an exception spec and constexpr.
5197   bool First = MD == MD->getCanonicalDecl();
5198 
5199   bool HadError = false;
5200 
5201   // C++11 [dcl.fct.def.default]p1:
5202   //   A function that is explicitly defaulted shall
5203   //     -- be a special member function (checked elsewhere),
5204   //     -- have the same type (except for ref-qualifiers, and except that a
5205   //        copy operation can take a non-const reference) as an implicit
5206   //        declaration, and
5207   //     -- not have default arguments.
5208   unsigned ExpectedParams = 1;
5209   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5210     ExpectedParams = 0;
5211   if (MD->getNumParams() != ExpectedParams) {
5212     // This also checks for default arguments: a copy or move constructor with a
5213     // default argument is classified as a default constructor, and assignment
5214     // operations and destructors can't have default arguments.
5215     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5216       << CSM << MD->getSourceRange();
5217     HadError = true;
5218   } else if (MD->isVariadic()) {
5219     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5220       << CSM << MD->getSourceRange();
5221     HadError = true;
5222   }
5223 
5224   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5225 
5226   bool CanHaveConstParam = false;
5227   if (CSM == CXXCopyConstructor)
5228     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5229   else if (CSM == CXXCopyAssignment)
5230     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5231 
5232   QualType ReturnType = Context.VoidTy;
5233   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5234     // Check for return type matching.
5235     ReturnType = Type->getReturnType();
5236     QualType ExpectedReturnType =
5237         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5238     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5239       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5240         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5241       HadError = true;
5242     }
5243 
5244     // A defaulted special member cannot have cv-qualifiers.
5245     if (Type->getTypeQuals()) {
5246       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5247         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5248       HadError = true;
5249     }
5250   }
5251 
5252   // Check for parameter type matching.
5253   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5254   bool HasConstParam = false;
5255   if (ExpectedParams && ArgType->isReferenceType()) {
5256     // Argument must be reference to possibly-const T.
5257     QualType ReferentType = ArgType->getPointeeType();
5258     HasConstParam = ReferentType.isConstQualified();
5259 
5260     if (ReferentType.isVolatileQualified()) {
5261       Diag(MD->getLocation(),
5262            diag::err_defaulted_special_member_volatile_param) << CSM;
5263       HadError = true;
5264     }
5265 
5266     if (HasConstParam && !CanHaveConstParam) {
5267       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5268         Diag(MD->getLocation(),
5269              diag::err_defaulted_special_member_copy_const_param)
5270           << (CSM == CXXCopyAssignment);
5271         // FIXME: Explain why this special member can't be const.
5272       } else {
5273         Diag(MD->getLocation(),
5274              diag::err_defaulted_special_member_move_const_param)
5275           << (CSM == CXXMoveAssignment);
5276       }
5277       HadError = true;
5278     }
5279   } else if (ExpectedParams) {
5280     // A copy assignment operator can take its argument by value, but a
5281     // defaulted one cannot.
5282     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5283     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5284     HadError = true;
5285   }
5286 
5287   // C++11 [dcl.fct.def.default]p2:
5288   //   An explicitly-defaulted function may be declared constexpr only if it
5289   //   would have been implicitly declared as constexpr,
5290   // Do not apply this rule to members of class templates, since core issue 1358
5291   // makes such functions always instantiate to constexpr functions. For
5292   // functions which cannot be constexpr (for non-constructors in C++11 and for
5293   // destructors in C++1y), this is checked elsewhere.
5294   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5295                                                      HasConstParam);
5296   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5297                                  : isa<CXXConstructorDecl>(MD)) &&
5298       MD->isConstexpr() && !Constexpr &&
5299       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5300     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5301     // FIXME: Explain why the special member can't be constexpr.
5302     HadError = true;
5303   }
5304 
5305   //   and may have an explicit exception-specification only if it is compatible
5306   //   with the exception-specification on the implicit declaration.
5307   if (Type->hasExceptionSpec()) {
5308     // Delay the check if this is the first declaration of the special member,
5309     // since we may not have parsed some necessary in-class initializers yet.
5310     if (First) {
5311       // If the exception specification needs to be instantiated, do so now,
5312       // before we clobber it with an EST_Unevaluated specification below.
5313       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5314         InstantiateExceptionSpec(MD->getLocStart(), MD);
5315         Type = MD->getType()->getAs<FunctionProtoType>();
5316       }
5317       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5318     } else
5319       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5320   }
5321 
5322   //   If a function is explicitly defaulted on its first declaration,
5323   if (First) {
5324     //  -- it is implicitly considered to be constexpr if the implicit
5325     //     definition would be,
5326     MD->setConstexpr(Constexpr);
5327 
5328     //  -- it is implicitly considered to have the same exception-specification
5329     //     as if it had been implicitly declared,
5330     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5331     EPI.ExceptionSpec.Type = EST_Unevaluated;
5332     EPI.ExceptionSpec.SourceDecl = MD;
5333     MD->setType(Context.getFunctionType(ReturnType,
5334                                         llvm::makeArrayRef(&ArgType,
5335                                                            ExpectedParams),
5336                                         EPI));
5337   }
5338 
5339   if (ShouldDeleteSpecialMember(MD, CSM)) {
5340     if (First) {
5341       SetDeclDeleted(MD, MD->getLocation());
5342     } else {
5343       // C++11 [dcl.fct.def.default]p4:
5344       //   [For a] user-provided explicitly-defaulted function [...] if such a
5345       //   function is implicitly defined as deleted, the program is ill-formed.
5346       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5347       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5348       HadError = true;
5349     }
5350   }
5351 
5352   if (HadError)
5353     MD->setInvalidDecl();
5354 }
5355 
5356 /// Check whether the exception specification provided for an
5357 /// explicitly-defaulted special member matches the exception specification
5358 /// that would have been generated for an implicit special member, per
5359 /// C++11 [dcl.fct.def.default]p2.
5360 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5361     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5362   // If the exception specification was explicitly specified but hadn't been
5363   // parsed when the method was defaulted, grab it now.
5364   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5365     SpecifiedType =
5366         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5367 
5368   // Compute the implicit exception specification.
5369   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5370                                                        /*IsCXXMethod=*/true);
5371   FunctionProtoType::ExtProtoInfo EPI(CC);
5372   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5373                           .getExceptionSpec();
5374   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5375     Context.getFunctionType(Context.VoidTy, None, EPI));
5376 
5377   // Ensure that it matches.
5378   CheckEquivalentExceptionSpec(
5379     PDiag(diag::err_incorrect_defaulted_exception_spec)
5380       << getSpecialMember(MD), PDiag(),
5381     ImplicitType, SourceLocation(),
5382     SpecifiedType, MD->getLocation());
5383 }
5384 
5385 void Sema::CheckDelayedMemberExceptionSpecs() {
5386   decltype(DelayedExceptionSpecChecks) Checks;
5387   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5388 
5389   std::swap(Checks, DelayedExceptionSpecChecks);
5390   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5391 
5392   // Perform any deferred checking of exception specifications for virtual
5393   // destructors.
5394   for (auto &Check : Checks)
5395     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5396 
5397   // Check that any explicitly-defaulted methods have exception specifications
5398   // compatible with their implicit exception specifications.
5399   for (auto &Spec : Specs)
5400     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5401 }
5402 
5403 namespace {
5404 struct SpecialMemberDeletionInfo {
5405   Sema &S;
5406   CXXMethodDecl *MD;
5407   Sema::CXXSpecialMember CSM;
5408   bool Diagnose;
5409 
5410   // Properties of the special member, computed for convenience.
5411   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5412   SourceLocation Loc;
5413 
5414   bool AllFieldsAreConst;
5415 
5416   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5417                             Sema::CXXSpecialMember CSM, bool Diagnose)
5418     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5419       IsConstructor(false), IsAssignment(false), IsMove(false),
5420       ConstArg(false), Loc(MD->getLocation()),
5421       AllFieldsAreConst(true) {
5422     switch (CSM) {
5423       case Sema::CXXDefaultConstructor:
5424       case Sema::CXXCopyConstructor:
5425         IsConstructor = true;
5426         break;
5427       case Sema::CXXMoveConstructor:
5428         IsConstructor = true;
5429         IsMove = true;
5430         break;
5431       case Sema::CXXCopyAssignment:
5432         IsAssignment = true;
5433         break;
5434       case Sema::CXXMoveAssignment:
5435         IsAssignment = true;
5436         IsMove = true;
5437         break;
5438       case Sema::CXXDestructor:
5439         break;
5440       case Sema::CXXInvalid:
5441         llvm_unreachable("invalid special member kind");
5442     }
5443 
5444     if (MD->getNumParams()) {
5445       if (const ReferenceType *RT =
5446               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5447         ConstArg = RT->getPointeeType().isConstQualified();
5448     }
5449   }
5450 
5451   bool inUnion() const { return MD->getParent()->isUnion(); }
5452 
5453   /// Look up the corresponding special member in the given class.
5454   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5455                                               unsigned Quals, bool IsMutable) {
5456     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5457                                        ConstArg && !IsMutable);
5458   }
5459 
5460   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5461 
5462   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5463   bool shouldDeleteForField(FieldDecl *FD);
5464   bool shouldDeleteForAllConstMembers();
5465 
5466   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5467                                      unsigned Quals);
5468   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5469                                     Sema::SpecialMemberOverloadResult *SMOR,
5470                                     bool IsDtorCallInCtor);
5471 
5472   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5473 };
5474 }
5475 
5476 /// Is the given special member inaccessible when used on the given
5477 /// sub-object.
5478 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5479                                              CXXMethodDecl *target) {
5480   /// If we're operating on a base class, the object type is the
5481   /// type of this special member.
5482   QualType objectTy;
5483   AccessSpecifier access = target->getAccess();
5484   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5485     objectTy = S.Context.getTypeDeclType(MD->getParent());
5486     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5487 
5488   // If we're operating on a field, the object type is the type of the field.
5489   } else {
5490     objectTy = S.Context.getTypeDeclType(target->getParent());
5491   }
5492 
5493   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5494 }
5495 
5496 /// Check whether we should delete a special member due to the implicit
5497 /// definition containing a call to a special member of a subobject.
5498 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5499     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5500     bool IsDtorCallInCtor) {
5501   CXXMethodDecl *Decl = SMOR->getMethod();
5502   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5503 
5504   int DiagKind = -1;
5505 
5506   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5507     DiagKind = !Decl ? 0 : 1;
5508   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5509     DiagKind = 2;
5510   else if (!isAccessible(Subobj, Decl))
5511     DiagKind = 3;
5512   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5513            !Decl->isTrivial()) {
5514     // A member of a union must have a trivial corresponding special member.
5515     // As a weird special case, a destructor call from a union's constructor
5516     // must be accessible and non-deleted, but need not be trivial. Such a
5517     // destructor is never actually called, but is semantically checked as
5518     // if it were.
5519     DiagKind = 4;
5520   }
5521 
5522   if (DiagKind == -1)
5523     return false;
5524 
5525   if (Diagnose) {
5526     if (Field) {
5527       S.Diag(Field->getLocation(),
5528              diag::note_deleted_special_member_class_subobject)
5529         << CSM << MD->getParent() << /*IsField*/true
5530         << Field << DiagKind << IsDtorCallInCtor;
5531     } else {
5532       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5533       S.Diag(Base->getLocStart(),
5534              diag::note_deleted_special_member_class_subobject)
5535         << CSM << MD->getParent() << /*IsField*/false
5536         << Base->getType() << DiagKind << IsDtorCallInCtor;
5537     }
5538 
5539     if (DiagKind == 1)
5540       S.NoteDeletedFunction(Decl);
5541     // FIXME: Explain inaccessibility if DiagKind == 3.
5542   }
5543 
5544   return true;
5545 }
5546 
5547 /// Check whether we should delete a special member function due to having a
5548 /// direct or virtual base class or non-static data member of class type M.
5549 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5550     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5551   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5552   bool IsMutable = Field && Field->isMutable();
5553 
5554   // C++11 [class.ctor]p5:
5555   // -- any direct or virtual base class, or non-static data member with no
5556   //    brace-or-equal-initializer, has class type M (or array thereof) and
5557   //    either M has no default constructor or overload resolution as applied
5558   //    to M's default constructor results in an ambiguity or in a function
5559   //    that is deleted or inaccessible
5560   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5561   // -- a direct or virtual base class B that cannot be copied/moved because
5562   //    overload resolution, as applied to B's corresponding special member,
5563   //    results in an ambiguity or a function that is deleted or inaccessible
5564   //    from the defaulted special member
5565   // C++11 [class.dtor]p5:
5566   // -- any direct or virtual base class [...] has a type with a destructor
5567   //    that is deleted or inaccessible
5568   if (!(CSM == Sema::CXXDefaultConstructor &&
5569         Field && Field->hasInClassInitializer()) &&
5570       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5571                                    false))
5572     return true;
5573 
5574   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5575   // -- any direct or virtual base class or non-static data member has a
5576   //    type with a destructor that is deleted or inaccessible
5577   if (IsConstructor) {
5578     Sema::SpecialMemberOverloadResult *SMOR =
5579         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5580                               false, false, false, false, false);
5581     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5582       return true;
5583   }
5584 
5585   return false;
5586 }
5587 
5588 /// Check whether we should delete a special member function due to the class
5589 /// having a particular direct or virtual base class.
5590 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5591   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5592   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5593 }
5594 
5595 /// Check whether we should delete a special member function due to the class
5596 /// having a particular non-static data member.
5597 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5598   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5599   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5600 
5601   if (CSM == Sema::CXXDefaultConstructor) {
5602     // For a default constructor, all references must be initialized in-class
5603     // and, if a union, it must have a non-const member.
5604     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5605       if (Diagnose)
5606         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5607           << MD->getParent() << FD << FieldType << /*Reference*/0;
5608       return true;
5609     }
5610     // C++11 [class.ctor]p5: any non-variant non-static data member of
5611     // const-qualified type (or array thereof) with no
5612     // brace-or-equal-initializer does not have a user-provided default
5613     // constructor.
5614     if (!inUnion() && FieldType.isConstQualified() &&
5615         !FD->hasInClassInitializer() &&
5616         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5617       if (Diagnose)
5618         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5619           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5620       return true;
5621     }
5622 
5623     if (inUnion() && !FieldType.isConstQualified())
5624       AllFieldsAreConst = false;
5625   } else if (CSM == Sema::CXXCopyConstructor) {
5626     // For a copy constructor, data members must not be of rvalue reference
5627     // type.
5628     if (FieldType->isRValueReferenceType()) {
5629       if (Diagnose)
5630         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5631           << MD->getParent() << FD << FieldType;
5632       return true;
5633     }
5634   } else if (IsAssignment) {
5635     // For an assignment operator, data members must not be of reference type.
5636     if (FieldType->isReferenceType()) {
5637       if (Diagnose)
5638         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5639           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5640       return true;
5641     }
5642     if (!FieldRecord && FieldType.isConstQualified()) {
5643       // C++11 [class.copy]p23:
5644       // -- a non-static data member of const non-class type (or array thereof)
5645       if (Diagnose)
5646         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5647           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5648       return true;
5649     }
5650   }
5651 
5652   if (FieldRecord) {
5653     // Some additional restrictions exist on the variant members.
5654     if (!inUnion() && FieldRecord->isUnion() &&
5655         FieldRecord->isAnonymousStructOrUnion()) {
5656       bool AllVariantFieldsAreConst = true;
5657 
5658       // FIXME: Handle anonymous unions declared within anonymous unions.
5659       for (auto *UI : FieldRecord->fields()) {
5660         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5661 
5662         if (!UnionFieldType.isConstQualified())
5663           AllVariantFieldsAreConst = false;
5664 
5665         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5666         if (UnionFieldRecord &&
5667             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5668                                           UnionFieldType.getCVRQualifiers()))
5669           return true;
5670       }
5671 
5672       // At least one member in each anonymous union must be non-const
5673       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5674           !FieldRecord->field_empty()) {
5675         if (Diagnose)
5676           S.Diag(FieldRecord->getLocation(),
5677                  diag::note_deleted_default_ctor_all_const)
5678             << MD->getParent() << /*anonymous union*/1;
5679         return true;
5680       }
5681 
5682       // Don't check the implicit member of the anonymous union type.
5683       // This is technically non-conformant, but sanity demands it.
5684       return false;
5685     }
5686 
5687     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5688                                       FieldType.getCVRQualifiers()))
5689       return true;
5690   }
5691 
5692   return false;
5693 }
5694 
5695 /// C++11 [class.ctor] p5:
5696 ///   A defaulted default constructor for a class X is defined as deleted if
5697 /// X is a union and all of its variant members are of const-qualified type.
5698 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5699   // This is a silly definition, because it gives an empty union a deleted
5700   // default constructor. Don't do that.
5701   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5702       !MD->getParent()->field_empty()) {
5703     if (Diagnose)
5704       S.Diag(MD->getParent()->getLocation(),
5705              diag::note_deleted_default_ctor_all_const)
5706         << MD->getParent() << /*not anonymous union*/0;
5707     return true;
5708   }
5709   return false;
5710 }
5711 
5712 /// Determine whether a defaulted special member function should be defined as
5713 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5714 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5715 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5716                                      bool Diagnose) {
5717   if (MD->isInvalidDecl())
5718     return false;
5719   CXXRecordDecl *RD = MD->getParent();
5720   assert(!RD->isDependentType() && "do deletion after instantiation");
5721   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5722     return false;
5723 
5724   // C++11 [expr.lambda.prim]p19:
5725   //   The closure type associated with a lambda-expression has a
5726   //   deleted (8.4.3) default constructor and a deleted copy
5727   //   assignment operator.
5728   if (RD->isLambda() &&
5729       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5730     if (Diagnose)
5731       Diag(RD->getLocation(), diag::note_lambda_decl);
5732     return true;
5733   }
5734 
5735   // For an anonymous struct or union, the copy and assignment special members
5736   // will never be used, so skip the check. For an anonymous union declared at
5737   // namespace scope, the constructor and destructor are used.
5738   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5739       RD->isAnonymousStructOrUnion())
5740     return false;
5741 
5742   // C++11 [class.copy]p7, p18:
5743   //   If the class definition declares a move constructor or move assignment
5744   //   operator, an implicitly declared copy constructor or copy assignment
5745   //   operator is defined as deleted.
5746   if (MD->isImplicit() &&
5747       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5748     CXXMethodDecl *UserDeclaredMove = nullptr;
5749 
5750     // In Microsoft mode, a user-declared move only causes the deletion of the
5751     // corresponding copy operation, not both copy operations.
5752     if (RD->hasUserDeclaredMoveConstructor() &&
5753         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5754       if (!Diagnose) return true;
5755 
5756       // Find any user-declared move constructor.
5757       for (auto *I : RD->ctors()) {
5758         if (I->isMoveConstructor()) {
5759           UserDeclaredMove = I;
5760           break;
5761         }
5762       }
5763       assert(UserDeclaredMove);
5764     } else if (RD->hasUserDeclaredMoveAssignment() &&
5765                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5766       if (!Diagnose) return true;
5767 
5768       // Find any user-declared move assignment operator.
5769       for (auto *I : RD->methods()) {
5770         if (I->isMoveAssignmentOperator()) {
5771           UserDeclaredMove = I;
5772           break;
5773         }
5774       }
5775       assert(UserDeclaredMove);
5776     }
5777 
5778     if (UserDeclaredMove) {
5779       Diag(UserDeclaredMove->getLocation(),
5780            diag::note_deleted_copy_user_declared_move)
5781         << (CSM == CXXCopyAssignment) << RD
5782         << UserDeclaredMove->isMoveAssignmentOperator();
5783       return true;
5784     }
5785   }
5786 
5787   // Do access control from the special member function
5788   ContextRAII MethodContext(*this, MD);
5789 
5790   // C++11 [class.dtor]p5:
5791   // -- for a virtual destructor, lookup of the non-array deallocation function
5792   //    results in an ambiguity or in a function that is deleted or inaccessible
5793   if (CSM == CXXDestructor && MD->isVirtual()) {
5794     FunctionDecl *OperatorDelete = nullptr;
5795     DeclarationName Name =
5796       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5797     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5798                                  OperatorDelete, false)) {
5799       if (Diagnose)
5800         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5801       return true;
5802     }
5803   }
5804 
5805   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5806 
5807   for (auto &BI : RD->bases())
5808     if (!BI.isVirtual() &&
5809         SMI.shouldDeleteForBase(&BI))
5810       return true;
5811 
5812   // Per DR1611, do not consider virtual bases of constructors of abstract
5813   // classes, since we are not going to construct them.
5814   if (!RD->isAbstract() || !SMI.IsConstructor) {
5815     for (auto &BI : RD->vbases())
5816       if (SMI.shouldDeleteForBase(&BI))
5817         return true;
5818   }
5819 
5820   for (auto *FI : RD->fields())
5821     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5822         SMI.shouldDeleteForField(FI))
5823       return true;
5824 
5825   if (SMI.shouldDeleteForAllConstMembers())
5826     return true;
5827 
5828   if (getLangOpts().CUDA) {
5829     // We should delete the special member in CUDA mode if target inference
5830     // failed.
5831     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5832                                                    Diagnose);
5833   }
5834 
5835   return false;
5836 }
5837 
5838 /// Perform lookup for a special member of the specified kind, and determine
5839 /// whether it is trivial. If the triviality can be determined without the
5840 /// lookup, skip it. This is intended for use when determining whether a
5841 /// special member of a containing object is trivial, and thus does not ever
5842 /// perform overload resolution for default constructors.
5843 ///
5844 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5845 /// member that was most likely to be intended to be trivial, if any.
5846 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5847                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5848                                      bool ConstRHS, CXXMethodDecl **Selected) {
5849   if (Selected)
5850     *Selected = nullptr;
5851 
5852   switch (CSM) {
5853   case Sema::CXXInvalid:
5854     llvm_unreachable("not a special member");
5855 
5856   case Sema::CXXDefaultConstructor:
5857     // C++11 [class.ctor]p5:
5858     //   A default constructor is trivial if:
5859     //    - all the [direct subobjects] have trivial default constructors
5860     //
5861     // Note, no overload resolution is performed in this case.
5862     if (RD->hasTrivialDefaultConstructor())
5863       return true;
5864 
5865     if (Selected) {
5866       // If there's a default constructor which could have been trivial, dig it
5867       // out. Otherwise, if there's any user-provided default constructor, point
5868       // to that as an example of why there's not a trivial one.
5869       CXXConstructorDecl *DefCtor = nullptr;
5870       if (RD->needsImplicitDefaultConstructor())
5871         S.DeclareImplicitDefaultConstructor(RD);
5872       for (auto *CI : RD->ctors()) {
5873         if (!CI->isDefaultConstructor())
5874           continue;
5875         DefCtor = CI;
5876         if (!DefCtor->isUserProvided())
5877           break;
5878       }
5879 
5880       *Selected = DefCtor;
5881     }
5882 
5883     return false;
5884 
5885   case Sema::CXXDestructor:
5886     // C++11 [class.dtor]p5:
5887     //   A destructor is trivial if:
5888     //    - all the direct [subobjects] have trivial destructors
5889     if (RD->hasTrivialDestructor())
5890       return true;
5891 
5892     if (Selected) {
5893       if (RD->needsImplicitDestructor())
5894         S.DeclareImplicitDestructor(RD);
5895       *Selected = RD->getDestructor();
5896     }
5897 
5898     return false;
5899 
5900   case Sema::CXXCopyConstructor:
5901     // C++11 [class.copy]p12:
5902     //   A copy constructor is trivial if:
5903     //    - the constructor selected to copy each direct [subobject] is trivial
5904     if (RD->hasTrivialCopyConstructor()) {
5905       if (Quals == Qualifiers::Const)
5906         // We must either select the trivial copy constructor or reach an
5907         // ambiguity; no need to actually perform overload resolution.
5908         return true;
5909     } else if (!Selected) {
5910       return false;
5911     }
5912     // In C++98, we are not supposed to perform overload resolution here, but we
5913     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5914     // cases like B as having a non-trivial copy constructor:
5915     //   struct A { template<typename T> A(T&); };
5916     //   struct B { mutable A a; };
5917     goto NeedOverloadResolution;
5918 
5919   case Sema::CXXCopyAssignment:
5920     // C++11 [class.copy]p25:
5921     //   A copy assignment operator is trivial if:
5922     //    - the assignment operator selected to copy each direct [subobject] is
5923     //      trivial
5924     if (RD->hasTrivialCopyAssignment()) {
5925       if (Quals == Qualifiers::Const)
5926         return true;
5927     } else if (!Selected) {
5928       return false;
5929     }
5930     // In C++98, we are not supposed to perform overload resolution here, but we
5931     // treat that as a language defect.
5932     goto NeedOverloadResolution;
5933 
5934   case Sema::CXXMoveConstructor:
5935   case Sema::CXXMoveAssignment:
5936   NeedOverloadResolution:
5937     Sema::SpecialMemberOverloadResult *SMOR =
5938         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5939 
5940     // The standard doesn't describe how to behave if the lookup is ambiguous.
5941     // We treat it as not making the member non-trivial, just like the standard
5942     // mandates for the default constructor. This should rarely matter, because
5943     // the member will also be deleted.
5944     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5945       return true;
5946 
5947     if (!SMOR->getMethod()) {
5948       assert(SMOR->getKind() ==
5949              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5950       return false;
5951     }
5952 
5953     // We deliberately don't check if we found a deleted special member. We're
5954     // not supposed to!
5955     if (Selected)
5956       *Selected = SMOR->getMethod();
5957     return SMOR->getMethod()->isTrivial();
5958   }
5959 
5960   llvm_unreachable("unknown special method kind");
5961 }
5962 
5963 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5964   for (auto *CI : RD->ctors())
5965     if (!CI->isImplicit())
5966       return CI;
5967 
5968   // Look for constructor templates.
5969   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5970   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5971     if (CXXConstructorDecl *CD =
5972           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5973       return CD;
5974   }
5975 
5976   return nullptr;
5977 }
5978 
5979 /// The kind of subobject we are checking for triviality. The values of this
5980 /// enumeration are used in diagnostics.
5981 enum TrivialSubobjectKind {
5982   /// The subobject is a base class.
5983   TSK_BaseClass,
5984   /// The subobject is a non-static data member.
5985   TSK_Field,
5986   /// The object is actually the complete object.
5987   TSK_CompleteObject
5988 };
5989 
5990 /// Check whether the special member selected for a given type would be trivial.
5991 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5992                                       QualType SubType, bool ConstRHS,
5993                                       Sema::CXXSpecialMember CSM,
5994                                       TrivialSubobjectKind Kind,
5995                                       bool Diagnose) {
5996   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5997   if (!SubRD)
5998     return true;
5999 
6000   CXXMethodDecl *Selected;
6001   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6002                                ConstRHS, Diagnose ? &Selected : nullptr))
6003     return true;
6004 
6005   if (Diagnose) {
6006     if (ConstRHS)
6007       SubType.addConst();
6008 
6009     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6010       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6011         << Kind << SubType.getUnqualifiedType();
6012       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6013         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6014     } else if (!Selected)
6015       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6016         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6017     else if (Selected->isUserProvided()) {
6018       if (Kind == TSK_CompleteObject)
6019         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6020           << Kind << SubType.getUnqualifiedType() << CSM;
6021       else {
6022         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6023           << Kind << SubType.getUnqualifiedType() << CSM;
6024         S.Diag(Selected->getLocation(), diag::note_declared_at);
6025       }
6026     } else {
6027       if (Kind != TSK_CompleteObject)
6028         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6029           << Kind << SubType.getUnqualifiedType() << CSM;
6030 
6031       // Explain why the defaulted or deleted special member isn't trivial.
6032       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6033     }
6034   }
6035 
6036   return false;
6037 }
6038 
6039 /// Check whether the members of a class type allow a special member to be
6040 /// trivial.
6041 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6042                                      Sema::CXXSpecialMember CSM,
6043                                      bool ConstArg, bool Diagnose) {
6044   for (const auto *FI : RD->fields()) {
6045     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6046       continue;
6047 
6048     QualType FieldType = S.Context.getBaseElementType(FI->getType());
6049 
6050     // Pretend anonymous struct or union members are members of this class.
6051     if (FI->isAnonymousStructOrUnion()) {
6052       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6053                                     CSM, ConstArg, Diagnose))
6054         return false;
6055       continue;
6056     }
6057 
6058     // C++11 [class.ctor]p5:
6059     //   A default constructor is trivial if [...]
6060     //    -- no non-static data member of its class has a
6061     //       brace-or-equal-initializer
6062     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6063       if (Diagnose)
6064         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6065       return false;
6066     }
6067 
6068     // Objective C ARC 4.3.5:
6069     //   [...] nontrivally ownership-qualified types are [...] not trivially
6070     //   default constructible, copy constructible, move constructible, copy
6071     //   assignable, move assignable, or destructible [...]
6072     if (S.getLangOpts().ObjCAutoRefCount &&
6073         FieldType.hasNonTrivialObjCLifetime()) {
6074       if (Diagnose)
6075         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6076           << RD << FieldType.getObjCLifetime();
6077       return false;
6078     }
6079 
6080     bool ConstRHS = ConstArg && !FI->isMutable();
6081     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6082                                    CSM, TSK_Field, Diagnose))
6083       return false;
6084   }
6085 
6086   return true;
6087 }
6088 
6089 /// Diagnose why the specified class does not have a trivial special member of
6090 /// the given kind.
6091 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6092   QualType Ty = Context.getRecordType(RD);
6093 
6094   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6095   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6096                             TSK_CompleteObject, /*Diagnose*/true);
6097 }
6098 
6099 /// Determine whether a defaulted or deleted special member function is trivial,
6100 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6101 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6102 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6103                                   bool Diagnose) {
6104   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6105 
6106   CXXRecordDecl *RD = MD->getParent();
6107 
6108   bool ConstArg = false;
6109 
6110   // C++11 [class.copy]p12, p25: [DR1593]
6111   //   A [special member] is trivial if [...] its parameter-type-list is
6112   //   equivalent to the parameter-type-list of an implicit declaration [...]
6113   switch (CSM) {
6114   case CXXDefaultConstructor:
6115   case CXXDestructor:
6116     // Trivial default constructors and destructors cannot have parameters.
6117     break;
6118 
6119   case CXXCopyConstructor:
6120   case CXXCopyAssignment: {
6121     // Trivial copy operations always have const, non-volatile parameter types.
6122     ConstArg = true;
6123     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6124     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6125     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6126       if (Diagnose)
6127         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6128           << Param0->getSourceRange() << Param0->getType()
6129           << Context.getLValueReferenceType(
6130                Context.getRecordType(RD).withConst());
6131       return false;
6132     }
6133     break;
6134   }
6135 
6136   case CXXMoveConstructor:
6137   case CXXMoveAssignment: {
6138     // Trivial move operations always have non-cv-qualified parameters.
6139     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6140     const RValueReferenceType *RT =
6141       Param0->getType()->getAs<RValueReferenceType>();
6142     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6143       if (Diagnose)
6144         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6145           << Param0->getSourceRange() << Param0->getType()
6146           << Context.getRValueReferenceType(Context.getRecordType(RD));
6147       return false;
6148     }
6149     break;
6150   }
6151 
6152   case CXXInvalid:
6153     llvm_unreachable("not a special member");
6154   }
6155 
6156   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6157     if (Diagnose)
6158       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6159            diag::note_nontrivial_default_arg)
6160         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6161     return false;
6162   }
6163   if (MD->isVariadic()) {
6164     if (Diagnose)
6165       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6166     return false;
6167   }
6168 
6169   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6170   //   A copy/move [constructor or assignment operator] is trivial if
6171   //    -- the [member] selected to copy/move each direct base class subobject
6172   //       is trivial
6173   //
6174   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6175   //   A [default constructor or destructor] is trivial if
6176   //    -- all the direct base classes have trivial [default constructors or
6177   //       destructors]
6178   for (const auto &BI : RD->bases())
6179     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6180                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
6181       return false;
6182 
6183   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6184   //   A copy/move [constructor or assignment operator] for a class X is
6185   //   trivial if
6186   //    -- for each non-static data member of X that is of class type (or array
6187   //       thereof), the constructor selected to copy/move that member is
6188   //       trivial
6189   //
6190   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6191   //   A [default constructor or destructor] is trivial if
6192   //    -- for all of the non-static data members of its class that are of class
6193   //       type (or array thereof), each such class has a trivial [default
6194   //       constructor or destructor]
6195   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6196     return false;
6197 
6198   // C++11 [class.dtor]p5:
6199   //   A destructor is trivial if [...]
6200   //    -- the destructor is not virtual
6201   if (CSM == CXXDestructor && MD->isVirtual()) {
6202     if (Diagnose)
6203       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6204     return false;
6205   }
6206 
6207   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6208   //   A [special member] for class X is trivial if [...]
6209   //    -- class X has no virtual functions and no virtual base classes
6210   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6211     if (!Diagnose)
6212       return false;
6213 
6214     if (RD->getNumVBases()) {
6215       // Check for virtual bases. We already know that the corresponding
6216       // member in all bases is trivial, so vbases must all be direct.
6217       CXXBaseSpecifier &BS = *RD->vbases_begin();
6218       assert(BS.isVirtual());
6219       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6220       return false;
6221     }
6222 
6223     // Must have a virtual method.
6224     for (const auto *MI : RD->methods()) {
6225       if (MI->isVirtual()) {
6226         SourceLocation MLoc = MI->getLocStart();
6227         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6228         return false;
6229       }
6230     }
6231 
6232     llvm_unreachable("dynamic class with no vbases and no virtual functions");
6233   }
6234 
6235   // Looks like it's trivial!
6236   return true;
6237 }
6238 
6239 /// \brief Data used with FindHiddenVirtualMethod
6240 namespace {
6241   struct FindHiddenVirtualMethodData {
6242     Sema *S;
6243     CXXMethodDecl *Method;
6244     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6245     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6246   };
6247 }
6248 
6249 /// \brief Check whether any most overriden method from MD in Methods
6250 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
6251                   const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6252   if (MD->size_overridden_methods() == 0)
6253     return Methods.count(MD->getCanonicalDecl());
6254   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6255                                       E = MD->end_overridden_methods();
6256        I != E; ++I)
6257     if (CheckMostOverridenMethods(*I, Methods))
6258       return true;
6259   return false;
6260 }
6261 
6262 /// \brief Member lookup function that determines whether a given C++
6263 /// method overloads virtual methods in a base class without overriding any,
6264 /// to be used with CXXRecordDecl::lookupInBases().
6265 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6266                                     CXXBasePath &Path,
6267                                     void *UserData) {
6268   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6269 
6270   FindHiddenVirtualMethodData &Data
6271     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6272 
6273   DeclarationName Name = Data.Method->getDeclName();
6274   assert(Name.getNameKind() == DeclarationName::Identifier);
6275 
6276   bool foundSameNameMethod = false;
6277   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6278   for (Path.Decls = BaseRecord->lookup(Name);
6279        !Path.Decls.empty();
6280        Path.Decls = Path.Decls.slice(1)) {
6281     NamedDecl *D = Path.Decls.front();
6282     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6283       MD = MD->getCanonicalDecl();
6284       foundSameNameMethod = true;
6285       // Interested only in hidden virtual methods.
6286       if (!MD->isVirtual())
6287         continue;
6288       // If the method we are checking overrides a method from its base
6289       // don't warn about the other overloaded methods. Clang deviates from GCC
6290       // by only diagnosing overloads of inherited virtual functions that do not
6291       // override any other virtual functions in the base. GCC's
6292       // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6293       // function from a base class. These cases may be better served by a
6294       // warning (not specific to virtual functions) on call sites when the call
6295       // would select a different function from the base class, were it visible.
6296       // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6297       if (!Data.S->IsOverload(Data.Method, MD, false))
6298         return true;
6299       // Collect the overload only if its hidden.
6300       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
6301         overloadedMethods.push_back(MD);
6302     }
6303   }
6304 
6305   if (foundSameNameMethod)
6306     Data.OverloadedMethods.append(overloadedMethods.begin(),
6307                                    overloadedMethods.end());
6308   return foundSameNameMethod;
6309 }
6310 
6311 /// \brief Add the most overriden methods from MD to Methods
6312 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6313                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6314   if (MD->size_overridden_methods() == 0)
6315     Methods.insert(MD->getCanonicalDecl());
6316   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6317                                       E = MD->end_overridden_methods();
6318        I != E; ++I)
6319     AddMostOverridenMethods(*I, Methods);
6320 }
6321 
6322 /// \brief Check if a method overloads virtual methods in a base class without
6323 /// overriding any.
6324 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6325                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6326   if (!MD->getDeclName().isIdentifier())
6327     return;
6328 
6329   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6330                      /*bool RecordPaths=*/false,
6331                      /*bool DetectVirtual=*/false);
6332   FindHiddenVirtualMethodData Data;
6333   Data.Method = MD;
6334   Data.S = this;
6335 
6336   // Keep the base methods that were overriden or introduced in the subclass
6337   // by 'using' in a set. A base method not in this set is hidden.
6338   CXXRecordDecl *DC = MD->getParent();
6339   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6340   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6341     NamedDecl *ND = *I;
6342     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6343       ND = shad->getTargetDecl();
6344     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6345       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
6346   }
6347 
6348   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6349     OverloadedMethods = Data.OverloadedMethods;
6350 }
6351 
6352 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6353                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6354   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6355     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6356     PartialDiagnostic PD = PDiag(
6357          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6358     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6359     Diag(overloadedMD->getLocation(), PD);
6360   }
6361 }
6362 
6363 /// \brief Diagnose methods which overload virtual methods in a base class
6364 /// without overriding any.
6365 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6366   if (MD->isInvalidDecl())
6367     return;
6368 
6369   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6370     return;
6371 
6372   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6373   FindHiddenVirtualMethods(MD, OverloadedMethods);
6374   if (!OverloadedMethods.empty()) {
6375     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6376       << MD << (OverloadedMethods.size() > 1);
6377 
6378     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6379   }
6380 }
6381 
6382 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6383                                              Decl *TagDecl,
6384                                              SourceLocation LBrac,
6385                                              SourceLocation RBrac,
6386                                              AttributeList *AttrList) {
6387   if (!TagDecl)
6388     return;
6389 
6390   AdjustDeclIfTemplate(TagDecl);
6391 
6392   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6393     if (l->getKind() != AttributeList::AT_Visibility)
6394       continue;
6395     l->setInvalid();
6396     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6397       l->getName();
6398   }
6399 
6400   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6401               // strict aliasing violation!
6402               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6403               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6404 
6405   CheckCompletedCXXClass(
6406                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6407 }
6408 
6409 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6410 /// special functions, such as the default constructor, copy
6411 /// constructor, or destructor, to the given C++ class (C++
6412 /// [special]p1).  This routine can only be executed just before the
6413 /// definition of the class is complete.
6414 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6415   if (!ClassDecl->hasUserDeclaredConstructor())
6416     ++ASTContext::NumImplicitDefaultConstructors;
6417 
6418   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6419     ++ASTContext::NumImplicitCopyConstructors;
6420 
6421     // If the properties or semantics of the copy constructor couldn't be
6422     // determined while the class was being declared, force a declaration
6423     // of it now.
6424     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6425       DeclareImplicitCopyConstructor(ClassDecl);
6426   }
6427 
6428   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6429     ++ASTContext::NumImplicitMoveConstructors;
6430 
6431     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6432       DeclareImplicitMoveConstructor(ClassDecl);
6433   }
6434 
6435   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6436     ++ASTContext::NumImplicitCopyAssignmentOperators;
6437 
6438     // If we have a dynamic class, then the copy assignment operator may be
6439     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6440     // it shows up in the right place in the vtable and that we diagnose
6441     // problems with the implicit exception specification.
6442     if (ClassDecl->isDynamicClass() ||
6443         ClassDecl->needsOverloadResolutionForCopyAssignment())
6444       DeclareImplicitCopyAssignment(ClassDecl);
6445   }
6446 
6447   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6448     ++ASTContext::NumImplicitMoveAssignmentOperators;
6449 
6450     // Likewise for the move assignment operator.
6451     if (ClassDecl->isDynamicClass() ||
6452         ClassDecl->needsOverloadResolutionForMoveAssignment())
6453       DeclareImplicitMoveAssignment(ClassDecl);
6454   }
6455 
6456   if (!ClassDecl->hasUserDeclaredDestructor()) {
6457     ++ASTContext::NumImplicitDestructors;
6458 
6459     // If we have a dynamic class, then the destructor may be virtual, so we
6460     // have to declare the destructor immediately. This ensures that, e.g., it
6461     // shows up in the right place in the vtable and that we diagnose problems
6462     // with the implicit exception specification.
6463     if (ClassDecl->isDynamicClass() ||
6464         ClassDecl->needsOverloadResolutionForDestructor())
6465       DeclareImplicitDestructor(ClassDecl);
6466   }
6467 }
6468 
6469 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6470   if (!D)
6471     return 0;
6472 
6473   // The order of template parameters is not important here. All names
6474   // get added to the same scope.
6475   SmallVector<TemplateParameterList *, 4> ParameterLists;
6476 
6477   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6478     D = TD->getTemplatedDecl();
6479 
6480   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6481     ParameterLists.push_back(PSD->getTemplateParameters());
6482 
6483   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6484     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6485       ParameterLists.push_back(DD->getTemplateParameterList(i));
6486 
6487     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6488       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6489         ParameterLists.push_back(FTD->getTemplateParameters());
6490     }
6491   }
6492 
6493   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6494     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6495       ParameterLists.push_back(TD->getTemplateParameterList(i));
6496 
6497     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6498       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6499         ParameterLists.push_back(CTD->getTemplateParameters());
6500     }
6501   }
6502 
6503   unsigned Count = 0;
6504   for (TemplateParameterList *Params : ParameterLists) {
6505     if (Params->size() > 0)
6506       // Ignore explicit specializations; they don't contribute to the template
6507       // depth.
6508       ++Count;
6509     for (NamedDecl *Param : *Params) {
6510       if (Param->getDeclName()) {
6511         S->AddDecl(Param);
6512         IdResolver.AddDecl(Param);
6513       }
6514     }
6515   }
6516 
6517   return Count;
6518 }
6519 
6520 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6521   if (!RecordD) return;
6522   AdjustDeclIfTemplate(RecordD);
6523   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6524   PushDeclContext(S, Record);
6525 }
6526 
6527 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6528   if (!RecordD) return;
6529   PopDeclContext();
6530 }
6531 
6532 /// This is used to implement the constant expression evaluation part of the
6533 /// attribute enable_if extension. There is nothing in standard C++ which would
6534 /// require reentering parameters.
6535 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6536   if (!Param)
6537     return;
6538 
6539   S->AddDecl(Param);
6540   if (Param->getDeclName())
6541     IdResolver.AddDecl(Param);
6542 }
6543 
6544 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6545 /// parsing a top-level (non-nested) C++ class, and we are now
6546 /// parsing those parts of the given Method declaration that could
6547 /// not be parsed earlier (C++ [class.mem]p2), such as default
6548 /// arguments. This action should enter the scope of the given
6549 /// Method declaration as if we had just parsed the qualified method
6550 /// name. However, it should not bring the parameters into scope;
6551 /// that will be performed by ActOnDelayedCXXMethodParameter.
6552 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6553 }
6554 
6555 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6556 /// C++ method declaration. We're (re-)introducing the given
6557 /// function parameter into scope for use in parsing later parts of
6558 /// the method declaration. For example, we could see an
6559 /// ActOnParamDefaultArgument event for this parameter.
6560 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6561   if (!ParamD)
6562     return;
6563 
6564   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6565 
6566   // If this parameter has an unparsed default argument, clear it out
6567   // to make way for the parsed default argument.
6568   if (Param->hasUnparsedDefaultArg())
6569     Param->setDefaultArg(nullptr);
6570 
6571   S->AddDecl(Param);
6572   if (Param->getDeclName())
6573     IdResolver.AddDecl(Param);
6574 }
6575 
6576 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6577 /// processing the delayed method declaration for Method. The method
6578 /// declaration is now considered finished. There may be a separate
6579 /// ActOnStartOfFunctionDef action later (not necessarily
6580 /// immediately!) for this method, if it was also defined inside the
6581 /// class body.
6582 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6583   if (!MethodD)
6584     return;
6585 
6586   AdjustDeclIfTemplate(MethodD);
6587 
6588   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6589 
6590   // Now that we have our default arguments, check the constructor
6591   // again. It could produce additional diagnostics or affect whether
6592   // the class has implicitly-declared destructors, among other
6593   // things.
6594   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6595     CheckConstructor(Constructor);
6596 
6597   // Check the default arguments, which we may have added.
6598   if (!Method->isInvalidDecl())
6599     CheckCXXDefaultArguments(Method);
6600 }
6601 
6602 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6603 /// the well-formedness of the constructor declarator @p D with type @p
6604 /// R. If there are any errors in the declarator, this routine will
6605 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6606 /// will be updated to reflect a well-formed type for the constructor and
6607 /// returned.
6608 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6609                                           StorageClass &SC) {
6610   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6611 
6612   // C++ [class.ctor]p3:
6613   //   A constructor shall not be virtual (10.3) or static (9.4). A
6614   //   constructor can be invoked for a const, volatile or const
6615   //   volatile object. A constructor shall not be declared const,
6616   //   volatile, or const volatile (9.3.2).
6617   if (isVirtual) {
6618     if (!D.isInvalidType())
6619       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6620         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6621         << SourceRange(D.getIdentifierLoc());
6622     D.setInvalidType();
6623   }
6624   if (SC == SC_Static) {
6625     if (!D.isInvalidType())
6626       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6627         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6628         << SourceRange(D.getIdentifierLoc());
6629     D.setInvalidType();
6630     SC = SC_None;
6631   }
6632 
6633   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6634     diagnoseIgnoredQualifiers(
6635         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6636         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6637         D.getDeclSpec().getRestrictSpecLoc(),
6638         D.getDeclSpec().getAtomicSpecLoc());
6639     D.setInvalidType();
6640   }
6641 
6642   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6643   if (FTI.TypeQuals != 0) {
6644     if (FTI.TypeQuals & Qualifiers::Const)
6645       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6646         << "const" << SourceRange(D.getIdentifierLoc());
6647     if (FTI.TypeQuals & Qualifiers::Volatile)
6648       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6649         << "volatile" << SourceRange(D.getIdentifierLoc());
6650     if (FTI.TypeQuals & Qualifiers::Restrict)
6651       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6652         << "restrict" << SourceRange(D.getIdentifierLoc());
6653     D.setInvalidType();
6654   }
6655 
6656   // C++0x [class.ctor]p4:
6657   //   A constructor shall not be declared with a ref-qualifier.
6658   if (FTI.hasRefQualifier()) {
6659     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6660       << FTI.RefQualifierIsLValueRef
6661       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6662     D.setInvalidType();
6663   }
6664 
6665   // Rebuild the function type "R" without any type qualifiers (in
6666   // case any of the errors above fired) and with "void" as the
6667   // return type, since constructors don't have return types.
6668   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6669   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6670     return R;
6671 
6672   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6673   EPI.TypeQuals = 0;
6674   EPI.RefQualifier = RQ_None;
6675 
6676   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6677 }
6678 
6679 /// CheckConstructor - Checks a fully-formed constructor for
6680 /// well-formedness, issuing any diagnostics required. Returns true if
6681 /// the constructor declarator is invalid.
6682 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6683   CXXRecordDecl *ClassDecl
6684     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6685   if (!ClassDecl)
6686     return Constructor->setInvalidDecl();
6687 
6688   // C++ [class.copy]p3:
6689   //   A declaration of a constructor for a class X is ill-formed if
6690   //   its first parameter is of type (optionally cv-qualified) X and
6691   //   either there are no other parameters or else all other
6692   //   parameters have default arguments.
6693   if (!Constructor->isInvalidDecl() &&
6694       ((Constructor->getNumParams() == 1) ||
6695        (Constructor->getNumParams() > 1 &&
6696         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6697       Constructor->getTemplateSpecializationKind()
6698                                               != TSK_ImplicitInstantiation) {
6699     QualType ParamType = Constructor->getParamDecl(0)->getType();
6700     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6701     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6702       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6703       const char *ConstRef
6704         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6705                                                         : " const &";
6706       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6707         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6708 
6709       // FIXME: Rather that making the constructor invalid, we should endeavor
6710       // to fix the type.
6711       Constructor->setInvalidDecl();
6712     }
6713   }
6714 }
6715 
6716 /// CheckDestructor - Checks a fully-formed destructor definition for
6717 /// well-formedness, issuing any diagnostics required.  Returns true
6718 /// on error.
6719 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6720   CXXRecordDecl *RD = Destructor->getParent();
6721 
6722   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6723     SourceLocation Loc;
6724 
6725     if (!Destructor->isImplicit())
6726       Loc = Destructor->getLocation();
6727     else
6728       Loc = RD->getLocation();
6729 
6730     // If we have a virtual destructor, look up the deallocation function
6731     FunctionDecl *OperatorDelete = nullptr;
6732     DeclarationName Name =
6733     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6734     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6735       return true;
6736     // If there's no class-specific operator delete, look up the global
6737     // non-array delete.
6738     if (!OperatorDelete)
6739       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6740 
6741     MarkFunctionReferenced(Loc, OperatorDelete);
6742 
6743     Destructor->setOperatorDelete(OperatorDelete);
6744   }
6745 
6746   return false;
6747 }
6748 
6749 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6750 /// the well-formednes of the destructor declarator @p D with type @p
6751 /// R. If there are any errors in the declarator, this routine will
6752 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6753 /// will be updated to reflect a well-formed type for the destructor and
6754 /// returned.
6755 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6756                                          StorageClass& SC) {
6757   // C++ [class.dtor]p1:
6758   //   [...] A typedef-name that names a class is a class-name
6759   //   (7.1.3); however, a typedef-name that names a class shall not
6760   //   be used as the identifier in the declarator for a destructor
6761   //   declaration.
6762   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6763   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6764     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6765       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6766   else if (const TemplateSpecializationType *TST =
6767              DeclaratorType->getAs<TemplateSpecializationType>())
6768     if (TST->isTypeAlias())
6769       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6770         << DeclaratorType << 1;
6771 
6772   // C++ [class.dtor]p2:
6773   //   A destructor is used to destroy objects of its class type. A
6774   //   destructor takes no parameters, and no return type can be
6775   //   specified for it (not even void). The address of a destructor
6776   //   shall not be taken. A destructor shall not be static. A
6777   //   destructor can be invoked for a const, volatile or const
6778   //   volatile object. A destructor shall not be declared const,
6779   //   volatile or const volatile (9.3.2).
6780   if (SC == SC_Static) {
6781     if (!D.isInvalidType())
6782       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6783         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6784         << SourceRange(D.getIdentifierLoc())
6785         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6786 
6787     SC = SC_None;
6788   }
6789   if (!D.isInvalidType()) {
6790     // Destructors don't have return types, but the parser will
6791     // happily parse something like:
6792     //
6793     //   class X {
6794     //     float ~X();
6795     //   };
6796     //
6797     // The return type will be eliminated later.
6798     if (D.getDeclSpec().hasTypeSpecifier())
6799       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6800         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6801         << SourceRange(D.getIdentifierLoc());
6802     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6803       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6804                                 SourceLocation(),
6805                                 D.getDeclSpec().getConstSpecLoc(),
6806                                 D.getDeclSpec().getVolatileSpecLoc(),
6807                                 D.getDeclSpec().getRestrictSpecLoc(),
6808                                 D.getDeclSpec().getAtomicSpecLoc());
6809       D.setInvalidType();
6810     }
6811   }
6812 
6813   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6814   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6815     if (FTI.TypeQuals & Qualifiers::Const)
6816       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6817         << "const" << SourceRange(D.getIdentifierLoc());
6818     if (FTI.TypeQuals & Qualifiers::Volatile)
6819       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6820         << "volatile" << SourceRange(D.getIdentifierLoc());
6821     if (FTI.TypeQuals & Qualifiers::Restrict)
6822       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6823         << "restrict" << SourceRange(D.getIdentifierLoc());
6824     D.setInvalidType();
6825   }
6826 
6827   // C++0x [class.dtor]p2:
6828   //   A destructor shall not be declared with a ref-qualifier.
6829   if (FTI.hasRefQualifier()) {
6830     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6831       << FTI.RefQualifierIsLValueRef
6832       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6833     D.setInvalidType();
6834   }
6835 
6836   // Make sure we don't have any parameters.
6837   if (FTIHasNonVoidParameters(FTI)) {
6838     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6839 
6840     // Delete the parameters.
6841     FTI.freeParams();
6842     D.setInvalidType();
6843   }
6844 
6845   // Make sure the destructor isn't variadic.
6846   if (FTI.isVariadic) {
6847     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6848     D.setInvalidType();
6849   }
6850 
6851   // Rebuild the function type "R" without any type qualifiers or
6852   // parameters (in case any of the errors above fired) and with
6853   // "void" as the return type, since destructors don't have return
6854   // types.
6855   if (!D.isInvalidType())
6856     return R;
6857 
6858   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6859   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6860   EPI.Variadic = false;
6861   EPI.TypeQuals = 0;
6862   EPI.RefQualifier = RQ_None;
6863   return Context.getFunctionType(Context.VoidTy, None, EPI);
6864 }
6865 
6866 static void extendLeft(SourceRange &R, const SourceRange &Before) {
6867   if (Before.isInvalid())
6868     return;
6869   R.setBegin(Before.getBegin());
6870   if (R.getEnd().isInvalid())
6871     R.setEnd(Before.getEnd());
6872 }
6873 
6874 static void extendRight(SourceRange &R, const SourceRange &After) {
6875   if (After.isInvalid())
6876     return;
6877   if (R.getBegin().isInvalid())
6878     R.setBegin(After.getBegin());
6879   R.setEnd(After.getEnd());
6880 }
6881 
6882 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6883 /// well-formednes of the conversion function declarator @p D with
6884 /// type @p R. If there are any errors in the declarator, this routine
6885 /// will emit diagnostics and return true. Otherwise, it will return
6886 /// false. Either way, the type @p R will be updated to reflect a
6887 /// well-formed type for the conversion operator.
6888 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6889                                      StorageClass& SC) {
6890   // C++ [class.conv.fct]p1:
6891   //   Neither parameter types nor return type can be specified. The
6892   //   type of a conversion function (8.3.5) is "function taking no
6893   //   parameter returning conversion-type-id."
6894   if (SC == SC_Static) {
6895     if (!D.isInvalidType())
6896       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6897         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6898         << D.getName().getSourceRange();
6899     D.setInvalidType();
6900     SC = SC_None;
6901   }
6902 
6903   TypeSourceInfo *ConvTSI = nullptr;
6904   QualType ConvType =
6905       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
6906 
6907   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6908     // Conversion functions don't have return types, but the parser will
6909     // happily parse something like:
6910     //
6911     //   class X {
6912     //     float operator bool();
6913     //   };
6914     //
6915     // The return type will be changed later anyway.
6916     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6917       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6918       << SourceRange(D.getIdentifierLoc());
6919     D.setInvalidType();
6920   }
6921 
6922   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6923 
6924   // Make sure we don't have any parameters.
6925   if (Proto->getNumParams() > 0) {
6926     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6927 
6928     // Delete the parameters.
6929     D.getFunctionTypeInfo().freeParams();
6930     D.setInvalidType();
6931   } else if (Proto->isVariadic()) {
6932     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6933     D.setInvalidType();
6934   }
6935 
6936   // Diagnose "&operator bool()" and other such nonsense.  This
6937   // is actually a gcc extension which we don't support.
6938   if (Proto->getReturnType() != ConvType) {
6939     bool NeedsTypedef = false;
6940     SourceRange Before, After;
6941 
6942     // Walk the chunks and extract information on them for our diagnostic.
6943     bool PastFunctionChunk = false;
6944     for (auto &Chunk : D.type_objects()) {
6945       switch (Chunk.Kind) {
6946       case DeclaratorChunk::Function:
6947         if (!PastFunctionChunk) {
6948           if (Chunk.Fun.HasTrailingReturnType) {
6949             TypeSourceInfo *TRT = nullptr;
6950             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6951             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6952           }
6953           PastFunctionChunk = true;
6954           break;
6955         }
6956         // Fall through.
6957       case DeclaratorChunk::Array:
6958         NeedsTypedef = true;
6959         extendRight(After, Chunk.getSourceRange());
6960         break;
6961 
6962       case DeclaratorChunk::Pointer:
6963       case DeclaratorChunk::BlockPointer:
6964       case DeclaratorChunk::Reference:
6965       case DeclaratorChunk::MemberPointer:
6966         extendLeft(Before, Chunk.getSourceRange());
6967         break;
6968 
6969       case DeclaratorChunk::Paren:
6970         extendLeft(Before, Chunk.Loc);
6971         extendRight(After, Chunk.EndLoc);
6972         break;
6973       }
6974     }
6975 
6976     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
6977                          After.isValid()  ? After.getBegin() :
6978                                             D.getIdentifierLoc();
6979     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
6980     DB << Before << After;
6981 
6982     if (!NeedsTypedef) {
6983       DB << /*don't need a typedef*/0;
6984 
6985       // If we can provide a correct fix-it hint, do so.
6986       if (After.isInvalid() && ConvTSI) {
6987         SourceLocation InsertLoc =
6988             PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
6989         DB << FixItHint::CreateInsertion(InsertLoc, " ")
6990            << FixItHint::CreateInsertionFromRange(
6991                   InsertLoc, CharSourceRange::getTokenRange(Before))
6992            << FixItHint::CreateRemoval(Before);
6993       }
6994     } else if (!Proto->getReturnType()->isDependentType()) {
6995       DB << /*typedef*/1 << Proto->getReturnType();
6996     } else if (getLangOpts().CPlusPlus11) {
6997       DB << /*alias template*/2 << Proto->getReturnType();
6998     } else {
6999       DB << /*might not be fixable*/3;
7000     }
7001 
7002     // Recover by incorporating the other type chunks into the result type.
7003     // Note, this does *not* change the name of the function. This is compatible
7004     // with the GCC extension:
7005     //   struct S { &operator int(); } s;
7006     //   int &r = s.operator int(); // ok in GCC
7007     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
7008     ConvType = Proto->getReturnType();
7009   }
7010 
7011   // C++ [class.conv.fct]p4:
7012   //   The conversion-type-id shall not represent a function type nor
7013   //   an array type.
7014   if (ConvType->isArrayType()) {
7015     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7016     ConvType = Context.getPointerType(ConvType);
7017     D.setInvalidType();
7018   } else if (ConvType->isFunctionType()) {
7019     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7020     ConvType = Context.getPointerType(ConvType);
7021     D.setInvalidType();
7022   }
7023 
7024   // Rebuild the function type "R" without any parameters (in case any
7025   // of the errors above fired) and with the conversion type as the
7026   // return type.
7027   if (D.isInvalidType())
7028     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7029 
7030   // C++0x explicit conversion operators.
7031   if (D.getDeclSpec().isExplicitSpecified())
7032     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7033          getLangOpts().CPlusPlus11 ?
7034            diag::warn_cxx98_compat_explicit_conversion_functions :
7035            diag::ext_explicit_conversion_functions)
7036       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7037 }
7038 
7039 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7040 /// the declaration of the given C++ conversion function. This routine
7041 /// is responsible for recording the conversion function in the C++
7042 /// class, if possible.
7043 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7044   assert(Conversion && "Expected to receive a conversion function declaration");
7045 
7046   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7047 
7048   // Make sure we aren't redeclaring the conversion function.
7049   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7050 
7051   // C++ [class.conv.fct]p1:
7052   //   [...] A conversion function is never used to convert a
7053   //   (possibly cv-qualified) object to the (possibly cv-qualified)
7054   //   same object type (or a reference to it), to a (possibly
7055   //   cv-qualified) base class of that type (or a reference to it),
7056   //   or to (possibly cv-qualified) void.
7057   // FIXME: Suppress this warning if the conversion function ends up being a
7058   // virtual function that overrides a virtual function in a base class.
7059   QualType ClassType
7060     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7061   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7062     ConvType = ConvTypeRef->getPointeeType();
7063   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7064       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7065     /* Suppress diagnostics for instantiations. */;
7066   else if (ConvType->isRecordType()) {
7067     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7068     if (ConvType == ClassType)
7069       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7070         << ClassType;
7071     else if (IsDerivedFrom(ClassType, ConvType))
7072       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7073         <<  ClassType << ConvType;
7074   } else if (ConvType->isVoidType()) {
7075     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7076       << ClassType << ConvType;
7077   }
7078 
7079   if (FunctionTemplateDecl *ConversionTemplate
7080                                 = Conversion->getDescribedFunctionTemplate())
7081     return ConversionTemplate;
7082 
7083   return Conversion;
7084 }
7085 
7086 //===----------------------------------------------------------------------===//
7087 // Namespace Handling
7088 //===----------------------------------------------------------------------===//
7089 
7090 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7091 /// reopened.
7092 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7093                                             SourceLocation Loc,
7094                                             IdentifierInfo *II, bool *IsInline,
7095                                             NamespaceDecl *PrevNS) {
7096   assert(*IsInline != PrevNS->isInline());
7097 
7098   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7099   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7100   // inline namespaces, with the intention of bringing names into namespace std.
7101   //
7102   // We support this just well enough to get that case working; this is not
7103   // sufficient to support reopening namespaces as inline in general.
7104   if (*IsInline && II && II->getName().startswith("__atomic") &&
7105       S.getSourceManager().isInSystemHeader(Loc)) {
7106     // Mark all prior declarations of the namespace as inline.
7107     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7108          NS = NS->getPreviousDecl())
7109       NS->setInline(*IsInline);
7110     // Patch up the lookup table for the containing namespace. This isn't really
7111     // correct, but it's good enough for this particular case.
7112     for (auto *I : PrevNS->decls())
7113       if (auto *ND = dyn_cast<NamedDecl>(I))
7114         PrevNS->getParent()->makeDeclVisibleInContext(ND);
7115     return;
7116   }
7117 
7118   if (PrevNS->isInline())
7119     // The user probably just forgot the 'inline', so suggest that it
7120     // be added back.
7121     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7122       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7123   else
7124     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7125 
7126   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7127   *IsInline = PrevNS->isInline();
7128 }
7129 
7130 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7131 /// definition.
7132 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7133                                    SourceLocation InlineLoc,
7134                                    SourceLocation NamespaceLoc,
7135                                    SourceLocation IdentLoc,
7136                                    IdentifierInfo *II,
7137                                    SourceLocation LBrace,
7138                                    AttributeList *AttrList) {
7139   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7140   // For anonymous namespace, take the location of the left brace.
7141   SourceLocation Loc = II ? IdentLoc : LBrace;
7142   bool IsInline = InlineLoc.isValid();
7143   bool IsInvalid = false;
7144   bool IsStd = false;
7145   bool AddToKnown = false;
7146   Scope *DeclRegionScope = NamespcScope->getParent();
7147 
7148   NamespaceDecl *PrevNS = nullptr;
7149   if (II) {
7150     // C++ [namespace.def]p2:
7151     //   The identifier in an original-namespace-definition shall not
7152     //   have been previously defined in the declarative region in
7153     //   which the original-namespace-definition appears. The
7154     //   identifier in an original-namespace-definition is the name of
7155     //   the namespace. Subsequently in that declarative region, it is
7156     //   treated as an original-namespace-name.
7157     //
7158     // Since namespace names are unique in their scope, and we don't
7159     // look through using directives, just look for any ordinary names.
7160 
7161     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
7162     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7163     Decl::IDNS_Namespace;
7164     NamedDecl *PrevDecl = nullptr;
7165     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7166     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7167          ++I) {
7168       if ((*I)->getIdentifierNamespace() & IDNS) {
7169         PrevDecl = *I;
7170         break;
7171       }
7172     }
7173 
7174     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7175 
7176     if (PrevNS) {
7177       // This is an extended namespace definition.
7178       if (IsInline != PrevNS->isInline())
7179         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7180                                         &IsInline, PrevNS);
7181     } else if (PrevDecl) {
7182       // This is an invalid name redefinition.
7183       Diag(Loc, diag::err_redefinition_different_kind)
7184         << II;
7185       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7186       IsInvalid = true;
7187       // Continue on to push Namespc as current DeclContext and return it.
7188     } else if (II->isStr("std") &&
7189                CurContext->getRedeclContext()->isTranslationUnit()) {
7190       // This is the first "real" definition of the namespace "std", so update
7191       // our cache of the "std" namespace to point at this definition.
7192       PrevNS = getStdNamespace();
7193       IsStd = true;
7194       AddToKnown = !IsInline;
7195     } else {
7196       // We've seen this namespace for the first time.
7197       AddToKnown = !IsInline;
7198     }
7199   } else {
7200     // Anonymous namespaces.
7201 
7202     // Determine whether the parent already has an anonymous namespace.
7203     DeclContext *Parent = CurContext->getRedeclContext();
7204     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7205       PrevNS = TU->getAnonymousNamespace();
7206     } else {
7207       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7208       PrevNS = ND->getAnonymousNamespace();
7209     }
7210 
7211     if (PrevNS && IsInline != PrevNS->isInline())
7212       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7213                                       &IsInline, PrevNS);
7214   }
7215 
7216   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7217                                                  StartLoc, Loc, II, PrevNS);
7218   if (IsInvalid)
7219     Namespc->setInvalidDecl();
7220 
7221   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7222 
7223   // FIXME: Should we be merging attributes?
7224   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7225     PushNamespaceVisibilityAttr(Attr, Loc);
7226 
7227   if (IsStd)
7228     StdNamespace = Namespc;
7229   if (AddToKnown)
7230     KnownNamespaces[Namespc] = false;
7231 
7232   if (II) {
7233     PushOnScopeChains(Namespc, DeclRegionScope);
7234   } else {
7235     // Link the anonymous namespace into its parent.
7236     DeclContext *Parent = CurContext->getRedeclContext();
7237     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7238       TU->setAnonymousNamespace(Namespc);
7239     } else {
7240       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7241     }
7242 
7243     CurContext->addDecl(Namespc);
7244 
7245     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
7246     //   behaves as if it were replaced by
7247     //     namespace unique { /* empty body */ }
7248     //     using namespace unique;
7249     //     namespace unique { namespace-body }
7250     //   where all occurrences of 'unique' in a translation unit are
7251     //   replaced by the same identifier and this identifier differs
7252     //   from all other identifiers in the entire program.
7253 
7254     // We just create the namespace with an empty name and then add an
7255     // implicit using declaration, just like the standard suggests.
7256     //
7257     // CodeGen enforces the "universally unique" aspect by giving all
7258     // declarations semantically contained within an anonymous
7259     // namespace internal linkage.
7260 
7261     if (!PrevNS) {
7262       UsingDirectiveDecl* UD
7263         = UsingDirectiveDecl::Create(Context, Parent,
7264                                      /* 'using' */ LBrace,
7265                                      /* 'namespace' */ SourceLocation(),
7266                                      /* qualifier */ NestedNameSpecifierLoc(),
7267                                      /* identifier */ SourceLocation(),
7268                                      Namespc,
7269                                      /* Ancestor */ Parent);
7270       UD->setImplicit();
7271       Parent->addDecl(UD);
7272     }
7273   }
7274 
7275   ActOnDocumentableDecl(Namespc);
7276 
7277   // Although we could have an invalid decl (i.e. the namespace name is a
7278   // redefinition), push it as current DeclContext and try to continue parsing.
7279   // FIXME: We should be able to push Namespc here, so that the each DeclContext
7280   // for the namespace has the declarations that showed up in that particular
7281   // namespace definition.
7282   PushDeclContext(NamespcScope, Namespc);
7283   return Namespc;
7284 }
7285 
7286 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7287 /// is a namespace alias, returns the namespace it points to.
7288 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7289   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7290     return AD->getNamespace();
7291   return dyn_cast_or_null<NamespaceDecl>(D);
7292 }
7293 
7294 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7295 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7296 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7297   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7298   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7299   Namespc->setRBraceLoc(RBrace);
7300   PopDeclContext();
7301   if (Namespc->hasAttr<VisibilityAttr>())
7302     PopPragmaVisibility(true, RBrace);
7303 }
7304 
7305 CXXRecordDecl *Sema::getStdBadAlloc() const {
7306   return cast_or_null<CXXRecordDecl>(
7307                                   StdBadAlloc.get(Context.getExternalSource()));
7308 }
7309 
7310 NamespaceDecl *Sema::getStdNamespace() const {
7311   return cast_or_null<NamespaceDecl>(
7312                                  StdNamespace.get(Context.getExternalSource()));
7313 }
7314 
7315 /// \brief Retrieve the special "std" namespace, which may require us to
7316 /// implicitly define the namespace.
7317 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7318   if (!StdNamespace) {
7319     // The "std" namespace has not yet been defined, so build one implicitly.
7320     StdNamespace = NamespaceDecl::Create(Context,
7321                                          Context.getTranslationUnitDecl(),
7322                                          /*Inline=*/false,
7323                                          SourceLocation(), SourceLocation(),
7324                                          &PP.getIdentifierTable().get("std"),
7325                                          /*PrevDecl=*/nullptr);
7326     getStdNamespace()->setImplicit(true);
7327   }
7328 
7329   return getStdNamespace();
7330 }
7331 
7332 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7333   assert(getLangOpts().CPlusPlus &&
7334          "Looking for std::initializer_list outside of C++.");
7335 
7336   // We're looking for implicit instantiations of
7337   // template <typename E> class std::initializer_list.
7338 
7339   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7340     return false;
7341 
7342   ClassTemplateDecl *Template = nullptr;
7343   const TemplateArgument *Arguments = nullptr;
7344 
7345   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7346 
7347     ClassTemplateSpecializationDecl *Specialization =
7348         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7349     if (!Specialization)
7350       return false;
7351 
7352     Template = Specialization->getSpecializedTemplate();
7353     Arguments = Specialization->getTemplateArgs().data();
7354   } else if (const TemplateSpecializationType *TST =
7355                  Ty->getAs<TemplateSpecializationType>()) {
7356     Template = dyn_cast_or_null<ClassTemplateDecl>(
7357         TST->getTemplateName().getAsTemplateDecl());
7358     Arguments = TST->getArgs();
7359   }
7360   if (!Template)
7361     return false;
7362 
7363   if (!StdInitializerList) {
7364     // Haven't recognized std::initializer_list yet, maybe this is it.
7365     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7366     if (TemplateClass->getIdentifier() !=
7367             &PP.getIdentifierTable().get("initializer_list") ||
7368         !getStdNamespace()->InEnclosingNamespaceSetOf(
7369             TemplateClass->getDeclContext()))
7370       return false;
7371     // This is a template called std::initializer_list, but is it the right
7372     // template?
7373     TemplateParameterList *Params = Template->getTemplateParameters();
7374     if (Params->getMinRequiredArguments() != 1)
7375       return false;
7376     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7377       return false;
7378 
7379     // It's the right template.
7380     StdInitializerList = Template;
7381   }
7382 
7383   if (Template != StdInitializerList)
7384     return false;
7385 
7386   // This is an instance of std::initializer_list. Find the argument type.
7387   if (Element)
7388     *Element = Arguments[0].getAsType();
7389   return true;
7390 }
7391 
7392 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7393   NamespaceDecl *Std = S.getStdNamespace();
7394   if (!Std) {
7395     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7396     return nullptr;
7397   }
7398 
7399   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7400                       Loc, Sema::LookupOrdinaryName);
7401   if (!S.LookupQualifiedName(Result, Std)) {
7402     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7403     return nullptr;
7404   }
7405   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7406   if (!Template) {
7407     Result.suppressDiagnostics();
7408     // We found something weird. Complain about the first thing we found.
7409     NamedDecl *Found = *Result.begin();
7410     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7411     return nullptr;
7412   }
7413 
7414   // We found some template called std::initializer_list. Now verify that it's
7415   // correct.
7416   TemplateParameterList *Params = Template->getTemplateParameters();
7417   if (Params->getMinRequiredArguments() != 1 ||
7418       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7419     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7420     return nullptr;
7421   }
7422 
7423   return Template;
7424 }
7425 
7426 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7427   if (!StdInitializerList) {
7428     StdInitializerList = LookupStdInitializerList(*this, Loc);
7429     if (!StdInitializerList)
7430       return QualType();
7431   }
7432 
7433   TemplateArgumentListInfo Args(Loc, Loc);
7434   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7435                                        Context.getTrivialTypeSourceInfo(Element,
7436                                                                         Loc)));
7437   return Context.getCanonicalType(
7438       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7439 }
7440 
7441 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7442   // C++ [dcl.init.list]p2:
7443   //   A constructor is an initializer-list constructor if its first parameter
7444   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7445   //   std::initializer_list<E> for some type E, and either there are no other
7446   //   parameters or else all other parameters have default arguments.
7447   if (Ctor->getNumParams() < 1 ||
7448       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7449     return false;
7450 
7451   QualType ArgType = Ctor->getParamDecl(0)->getType();
7452   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7453     ArgType = RT->getPointeeType().getUnqualifiedType();
7454 
7455   return isStdInitializerList(ArgType, nullptr);
7456 }
7457 
7458 /// \brief Determine whether a using statement is in a context where it will be
7459 /// apply in all contexts.
7460 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7461   switch (CurContext->getDeclKind()) {
7462     case Decl::TranslationUnit:
7463       return true;
7464     case Decl::LinkageSpec:
7465       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7466     default:
7467       return false;
7468   }
7469 }
7470 
7471 namespace {
7472 
7473 // Callback to only accept typo corrections that are namespaces.
7474 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7475 public:
7476   bool ValidateCandidate(const TypoCorrection &candidate) override {
7477     if (NamedDecl *ND = candidate.getCorrectionDecl())
7478       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7479     return false;
7480   }
7481 };
7482 
7483 }
7484 
7485 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7486                                        CXXScopeSpec &SS,
7487                                        SourceLocation IdentLoc,
7488                                        IdentifierInfo *Ident) {
7489   R.clear();
7490   if (TypoCorrection Corrected =
7491           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7492                         llvm::make_unique<NamespaceValidatorCCC>(),
7493                         Sema::CTK_ErrorRecovery)) {
7494     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7495       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7496       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7497                               Ident->getName().equals(CorrectedStr);
7498       S.diagnoseTypo(Corrected,
7499                      S.PDiag(diag::err_using_directive_member_suggest)
7500                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7501                      S.PDiag(diag::note_namespace_defined_here));
7502     } else {
7503       S.diagnoseTypo(Corrected,
7504                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7505                      S.PDiag(diag::note_namespace_defined_here));
7506     }
7507     R.addDecl(Corrected.getCorrectionDecl());
7508     return true;
7509   }
7510   return false;
7511 }
7512 
7513 Decl *Sema::ActOnUsingDirective(Scope *S,
7514                                           SourceLocation UsingLoc,
7515                                           SourceLocation NamespcLoc,
7516                                           CXXScopeSpec &SS,
7517                                           SourceLocation IdentLoc,
7518                                           IdentifierInfo *NamespcName,
7519                                           AttributeList *AttrList) {
7520   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7521   assert(NamespcName && "Invalid NamespcName.");
7522   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7523 
7524   // This can only happen along a recovery path.
7525   while (S->getFlags() & Scope::TemplateParamScope)
7526     S = S->getParent();
7527   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7528 
7529   UsingDirectiveDecl *UDir = nullptr;
7530   NestedNameSpecifier *Qualifier = nullptr;
7531   if (SS.isSet())
7532     Qualifier = SS.getScopeRep();
7533 
7534   // Lookup namespace name.
7535   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7536   LookupParsedName(R, S, &SS);
7537   if (R.isAmbiguous())
7538     return nullptr;
7539 
7540   if (R.empty()) {
7541     R.clear();
7542     // Allow "using namespace std;" or "using namespace ::std;" even if
7543     // "std" hasn't been defined yet, for GCC compatibility.
7544     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7545         NamespcName->isStr("std")) {
7546       Diag(IdentLoc, diag::ext_using_undefined_std);
7547       R.addDecl(getOrCreateStdNamespace());
7548       R.resolveKind();
7549     }
7550     // Otherwise, attempt typo correction.
7551     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7552   }
7553 
7554   if (!R.empty()) {
7555     NamedDecl *Named = R.getFoundDecl();
7556     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7557         && "expected namespace decl");
7558 
7559     // The use of a nested name specifier may trigger deprecation warnings.
7560     DiagnoseUseOfDecl(Named, IdentLoc);
7561 
7562     // C++ [namespace.udir]p1:
7563     //   A using-directive specifies that the names in the nominated
7564     //   namespace can be used in the scope in which the
7565     //   using-directive appears after the using-directive. During
7566     //   unqualified name lookup (3.4.1), the names appear as if they
7567     //   were declared in the nearest enclosing namespace which
7568     //   contains both the using-directive and the nominated
7569     //   namespace. [Note: in this context, "contains" means "contains
7570     //   directly or indirectly". ]
7571 
7572     // Find enclosing context containing both using-directive and
7573     // nominated namespace.
7574     NamespaceDecl *NS = getNamespaceDecl(Named);
7575     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7576     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7577       CommonAncestor = CommonAncestor->getParent();
7578 
7579     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7580                                       SS.getWithLocInContext(Context),
7581                                       IdentLoc, Named, CommonAncestor);
7582 
7583     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7584         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7585       Diag(IdentLoc, diag::warn_using_directive_in_header);
7586     }
7587 
7588     PushUsingDirective(S, UDir);
7589   } else {
7590     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7591   }
7592 
7593   if (UDir)
7594     ProcessDeclAttributeList(S, UDir, AttrList);
7595 
7596   return UDir;
7597 }
7598 
7599 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7600   // If the scope has an associated entity and the using directive is at
7601   // namespace or translation unit scope, add the UsingDirectiveDecl into
7602   // its lookup structure so qualified name lookup can find it.
7603   DeclContext *Ctx = S->getEntity();
7604   if (Ctx && !Ctx->isFunctionOrMethod())
7605     Ctx->addDecl(UDir);
7606   else
7607     // Otherwise, it is at block scope. The using-directives will affect lookup
7608     // only to the end of the scope.
7609     S->PushUsingDirective(UDir);
7610 }
7611 
7612 
7613 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7614                                   AccessSpecifier AS,
7615                                   bool HasUsingKeyword,
7616                                   SourceLocation UsingLoc,
7617                                   CXXScopeSpec &SS,
7618                                   UnqualifiedId &Name,
7619                                   AttributeList *AttrList,
7620                                   bool HasTypenameKeyword,
7621                                   SourceLocation TypenameLoc) {
7622   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7623 
7624   switch (Name.getKind()) {
7625   case UnqualifiedId::IK_ImplicitSelfParam:
7626   case UnqualifiedId::IK_Identifier:
7627   case UnqualifiedId::IK_OperatorFunctionId:
7628   case UnqualifiedId::IK_LiteralOperatorId:
7629   case UnqualifiedId::IK_ConversionFunctionId:
7630     break;
7631 
7632   case UnqualifiedId::IK_ConstructorName:
7633   case UnqualifiedId::IK_ConstructorTemplateId:
7634     // C++11 inheriting constructors.
7635     Diag(Name.getLocStart(),
7636          getLangOpts().CPlusPlus11 ?
7637            diag::warn_cxx98_compat_using_decl_constructor :
7638            diag::err_using_decl_constructor)
7639       << SS.getRange();
7640 
7641     if (getLangOpts().CPlusPlus11) break;
7642 
7643     return nullptr;
7644 
7645   case UnqualifiedId::IK_DestructorName:
7646     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7647       << SS.getRange();
7648     return nullptr;
7649 
7650   case UnqualifiedId::IK_TemplateId:
7651     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7652       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7653     return nullptr;
7654   }
7655 
7656   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7657   DeclarationName TargetName = TargetNameInfo.getName();
7658   if (!TargetName)
7659     return nullptr;
7660 
7661   // Warn about access declarations.
7662   if (!HasUsingKeyword) {
7663     Diag(Name.getLocStart(),
7664          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7665                                    : diag::warn_access_decl_deprecated)
7666       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7667   }
7668 
7669   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7670       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7671     return nullptr;
7672 
7673   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7674                                         TargetNameInfo, AttrList,
7675                                         /* IsInstantiation */ false,
7676                                         HasTypenameKeyword, TypenameLoc);
7677   if (UD)
7678     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7679 
7680   return UD;
7681 }
7682 
7683 /// \brief Determine whether a using declaration considers the given
7684 /// declarations as "equivalent", e.g., if they are redeclarations of
7685 /// the same entity or are both typedefs of the same type.
7686 static bool
7687 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7688   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7689     return true;
7690 
7691   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7692     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7693       return Context.hasSameType(TD1->getUnderlyingType(),
7694                                  TD2->getUnderlyingType());
7695 
7696   return false;
7697 }
7698 
7699 
7700 /// Determines whether to create a using shadow decl for a particular
7701 /// decl, given the set of decls existing prior to this using lookup.
7702 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7703                                 const LookupResult &Previous,
7704                                 UsingShadowDecl *&PrevShadow) {
7705   // Diagnose finding a decl which is not from a base class of the
7706   // current class.  We do this now because there are cases where this
7707   // function will silently decide not to build a shadow decl, which
7708   // will pre-empt further diagnostics.
7709   //
7710   // We don't need to do this in C++0x because we do the check once on
7711   // the qualifier.
7712   //
7713   // FIXME: diagnose the following if we care enough:
7714   //   struct A { int foo; };
7715   //   struct B : A { using A::foo; };
7716   //   template <class T> struct C : A {};
7717   //   template <class T> struct D : C<T> { using B::foo; } // <---
7718   // This is invalid (during instantiation) in C++03 because B::foo
7719   // resolves to the using decl in B, which is not a base class of D<T>.
7720   // We can't diagnose it immediately because C<T> is an unknown
7721   // specialization.  The UsingShadowDecl in D<T> then points directly
7722   // to A::foo, which will look well-formed when we instantiate.
7723   // The right solution is to not collapse the shadow-decl chain.
7724   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7725     DeclContext *OrigDC = Orig->getDeclContext();
7726 
7727     // Handle enums and anonymous structs.
7728     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7729     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7730     while (OrigRec->isAnonymousStructOrUnion())
7731       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7732 
7733     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7734       if (OrigDC == CurContext) {
7735         Diag(Using->getLocation(),
7736              diag::err_using_decl_nested_name_specifier_is_current_class)
7737           << Using->getQualifierLoc().getSourceRange();
7738         Diag(Orig->getLocation(), diag::note_using_decl_target);
7739         return true;
7740       }
7741 
7742       Diag(Using->getQualifierLoc().getBeginLoc(),
7743            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7744         << Using->getQualifier()
7745         << cast<CXXRecordDecl>(CurContext)
7746         << Using->getQualifierLoc().getSourceRange();
7747       Diag(Orig->getLocation(), diag::note_using_decl_target);
7748       return true;
7749     }
7750   }
7751 
7752   if (Previous.empty()) return false;
7753 
7754   NamedDecl *Target = Orig;
7755   if (isa<UsingShadowDecl>(Target))
7756     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7757 
7758   // If the target happens to be one of the previous declarations, we
7759   // don't have a conflict.
7760   //
7761   // FIXME: but we might be increasing its access, in which case we
7762   // should redeclare it.
7763   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7764   bool FoundEquivalentDecl = false;
7765   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7766          I != E; ++I) {
7767     NamedDecl *D = (*I)->getUnderlyingDecl();
7768     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7769       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7770         PrevShadow = Shadow;
7771       FoundEquivalentDecl = true;
7772     }
7773 
7774     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7775   }
7776 
7777   if (FoundEquivalentDecl)
7778     return false;
7779 
7780   if (FunctionDecl *FD = Target->getAsFunction()) {
7781     NamedDecl *OldDecl = nullptr;
7782     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7783                           /*IsForUsingDecl*/ true)) {
7784     case Ovl_Overload:
7785       return false;
7786 
7787     case Ovl_NonFunction:
7788       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7789       break;
7790 
7791     // We found a decl with the exact signature.
7792     case Ovl_Match:
7793       // If we're in a record, we want to hide the target, so we
7794       // return true (without a diagnostic) to tell the caller not to
7795       // build a shadow decl.
7796       if (CurContext->isRecord())
7797         return true;
7798 
7799       // If we're not in a record, this is an error.
7800       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7801       break;
7802     }
7803 
7804     Diag(Target->getLocation(), diag::note_using_decl_target);
7805     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7806     return true;
7807   }
7808 
7809   // Target is not a function.
7810 
7811   if (isa<TagDecl>(Target)) {
7812     // No conflict between a tag and a non-tag.
7813     if (!Tag) return false;
7814 
7815     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7816     Diag(Target->getLocation(), diag::note_using_decl_target);
7817     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7818     return true;
7819   }
7820 
7821   // No conflict between a tag and a non-tag.
7822   if (!NonTag) return false;
7823 
7824   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7825   Diag(Target->getLocation(), diag::note_using_decl_target);
7826   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7827   return true;
7828 }
7829 
7830 /// Builds a shadow declaration corresponding to a 'using' declaration.
7831 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7832                                             UsingDecl *UD,
7833                                             NamedDecl *Orig,
7834                                             UsingShadowDecl *PrevDecl) {
7835 
7836   // If we resolved to another shadow declaration, just coalesce them.
7837   NamedDecl *Target = Orig;
7838   if (isa<UsingShadowDecl>(Target)) {
7839     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7840     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7841   }
7842 
7843   UsingShadowDecl *Shadow
7844     = UsingShadowDecl::Create(Context, CurContext,
7845                               UD->getLocation(), UD, Target);
7846   UD->addShadowDecl(Shadow);
7847 
7848   Shadow->setAccess(UD->getAccess());
7849   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7850     Shadow->setInvalidDecl();
7851 
7852   Shadow->setPreviousDecl(PrevDecl);
7853 
7854   if (S)
7855     PushOnScopeChains(Shadow, S);
7856   else
7857     CurContext->addDecl(Shadow);
7858 
7859 
7860   return Shadow;
7861 }
7862 
7863 /// Hides a using shadow declaration.  This is required by the current
7864 /// using-decl implementation when a resolvable using declaration in a
7865 /// class is followed by a declaration which would hide or override
7866 /// one or more of the using decl's targets; for example:
7867 ///
7868 ///   struct Base { void foo(int); };
7869 ///   struct Derived : Base {
7870 ///     using Base::foo;
7871 ///     void foo(int);
7872 ///   };
7873 ///
7874 /// The governing language is C++03 [namespace.udecl]p12:
7875 ///
7876 ///   When a using-declaration brings names from a base class into a
7877 ///   derived class scope, member functions in the derived class
7878 ///   override and/or hide member functions with the same name and
7879 ///   parameter types in a base class (rather than conflicting).
7880 ///
7881 /// There are two ways to implement this:
7882 ///   (1) optimistically create shadow decls when they're not hidden
7883 ///       by existing declarations, or
7884 ///   (2) don't create any shadow decls (or at least don't make them
7885 ///       visible) until we've fully parsed/instantiated the class.
7886 /// The problem with (1) is that we might have to retroactively remove
7887 /// a shadow decl, which requires several O(n) operations because the
7888 /// decl structures are (very reasonably) not designed for removal.
7889 /// (2) avoids this but is very fiddly and phase-dependent.
7890 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7891   if (Shadow->getDeclName().getNameKind() ==
7892         DeclarationName::CXXConversionFunctionName)
7893     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7894 
7895   // Remove it from the DeclContext...
7896   Shadow->getDeclContext()->removeDecl(Shadow);
7897 
7898   // ...and the scope, if applicable...
7899   if (S) {
7900     S->RemoveDecl(Shadow);
7901     IdResolver.RemoveDecl(Shadow);
7902   }
7903 
7904   // ...and the using decl.
7905   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7906 
7907   // TODO: complain somehow if Shadow was used.  It shouldn't
7908   // be possible for this to happen, because...?
7909 }
7910 
7911 /// Find the base specifier for a base class with the given type.
7912 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7913                                                 QualType DesiredBase,
7914                                                 bool &AnyDependentBases) {
7915   // Check whether the named type is a direct base class.
7916   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7917   for (auto &Base : Derived->bases()) {
7918     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7919     if (CanonicalDesiredBase == BaseType)
7920       return &Base;
7921     if (BaseType->isDependentType())
7922       AnyDependentBases = true;
7923   }
7924   return nullptr;
7925 }
7926 
7927 namespace {
7928 class UsingValidatorCCC : public CorrectionCandidateCallback {
7929 public:
7930   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7931                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7932       : HasTypenameKeyword(HasTypenameKeyword),
7933         IsInstantiation(IsInstantiation), OldNNS(NNS),
7934         RequireMemberOf(RequireMemberOf) {}
7935 
7936   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7937     NamedDecl *ND = Candidate.getCorrectionDecl();
7938 
7939     // Keywords are not valid here.
7940     if (!ND || isa<NamespaceDecl>(ND))
7941       return false;
7942 
7943     // Completely unqualified names are invalid for a 'using' declaration.
7944     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7945       return false;
7946 
7947     if (RequireMemberOf) {
7948       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7949       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7950         // No-one ever wants a using-declaration to name an injected-class-name
7951         // of a base class, unless they're declaring an inheriting constructor.
7952         ASTContext &Ctx = ND->getASTContext();
7953         if (!Ctx.getLangOpts().CPlusPlus11)
7954           return false;
7955         QualType FoundType = Ctx.getRecordType(FoundRecord);
7956 
7957         // Check that the injected-class-name is named as a member of its own
7958         // type; we don't want to suggest 'using Derived::Base;', since that
7959         // means something else.
7960         NestedNameSpecifier *Specifier =
7961             Candidate.WillReplaceSpecifier()
7962                 ? Candidate.getCorrectionSpecifier()
7963                 : OldNNS;
7964         if (!Specifier->getAsType() ||
7965             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7966           return false;
7967 
7968         // Check that this inheriting constructor declaration actually names a
7969         // direct base class of the current class.
7970         bool AnyDependentBases = false;
7971         if (!findDirectBaseWithType(RequireMemberOf,
7972                                     Ctx.getRecordType(FoundRecord),
7973                                     AnyDependentBases) &&
7974             !AnyDependentBases)
7975           return false;
7976       } else {
7977         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7978         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7979           return false;
7980 
7981         // FIXME: Check that the base class member is accessible?
7982       }
7983     }
7984 
7985     if (isa<TypeDecl>(ND))
7986       return HasTypenameKeyword || !IsInstantiation;
7987 
7988     return !HasTypenameKeyword;
7989   }
7990 
7991 private:
7992   bool HasTypenameKeyword;
7993   bool IsInstantiation;
7994   NestedNameSpecifier *OldNNS;
7995   CXXRecordDecl *RequireMemberOf;
7996 };
7997 } // end anonymous namespace
7998 
7999 /// Builds a using declaration.
8000 ///
8001 /// \param IsInstantiation - Whether this call arises from an
8002 ///   instantiation of an unresolved using declaration.  We treat
8003 ///   the lookup differently for these declarations.
8004 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8005                                        SourceLocation UsingLoc,
8006                                        CXXScopeSpec &SS,
8007                                        DeclarationNameInfo NameInfo,
8008                                        AttributeList *AttrList,
8009                                        bool IsInstantiation,
8010                                        bool HasTypenameKeyword,
8011                                        SourceLocation TypenameLoc) {
8012   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8013   SourceLocation IdentLoc = NameInfo.getLoc();
8014   assert(IdentLoc.isValid() && "Invalid TargetName location.");
8015 
8016   // FIXME: We ignore attributes for now.
8017 
8018   if (SS.isEmpty()) {
8019     Diag(IdentLoc, diag::err_using_requires_qualname);
8020     return nullptr;
8021   }
8022 
8023   // Do the redeclaration lookup in the current scope.
8024   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
8025                         ForRedeclaration);
8026   Previous.setHideTags(false);
8027   if (S) {
8028     LookupName(Previous, S);
8029 
8030     // It is really dumb that we have to do this.
8031     LookupResult::Filter F = Previous.makeFilter();
8032     while (F.hasNext()) {
8033       NamedDecl *D = F.next();
8034       if (!isDeclInScope(D, CurContext, S))
8035         F.erase();
8036       // If we found a local extern declaration that's not ordinarily visible,
8037       // and this declaration is being added to a non-block scope, ignore it.
8038       // We're only checking for scope conflicts here, not also for violations
8039       // of the linkage rules.
8040       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8041                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8042         F.erase();
8043     }
8044     F.done();
8045   } else {
8046     assert(IsInstantiation && "no scope in non-instantiation");
8047     assert(CurContext->isRecord() && "scope not record in instantiation");
8048     LookupQualifiedName(Previous, CurContext);
8049   }
8050 
8051   // Check for invalid redeclarations.
8052   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8053                                   SS, IdentLoc, Previous))
8054     return nullptr;
8055 
8056   // Check for bad qualifiers.
8057   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8058     return nullptr;
8059 
8060   DeclContext *LookupContext = computeDeclContext(SS);
8061   NamedDecl *D;
8062   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8063   if (!LookupContext) {
8064     if (HasTypenameKeyword) {
8065       // FIXME: not all declaration name kinds are legal here
8066       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8067                                               UsingLoc, TypenameLoc,
8068                                               QualifierLoc,
8069                                               IdentLoc, NameInfo.getName());
8070     } else {
8071       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8072                                            QualifierLoc, NameInfo);
8073     }
8074     D->setAccess(AS);
8075     CurContext->addDecl(D);
8076     return D;
8077   }
8078 
8079   auto Build = [&](bool Invalid) {
8080     UsingDecl *UD =
8081         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8082                           HasTypenameKeyword);
8083     UD->setAccess(AS);
8084     CurContext->addDecl(UD);
8085     UD->setInvalidDecl(Invalid);
8086     return UD;
8087   };
8088   auto BuildInvalid = [&]{ return Build(true); };
8089   auto BuildValid = [&]{ return Build(false); };
8090 
8091   if (RequireCompleteDeclContext(SS, LookupContext))
8092     return BuildInvalid();
8093 
8094   // The normal rules do not apply to inheriting constructor declarations.
8095   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8096     UsingDecl *UD = BuildValid();
8097     CheckInheritingConstructorUsingDecl(UD);
8098     return UD;
8099   }
8100 
8101   // Otherwise, look up the target name.
8102 
8103   LookupResult R(*this, NameInfo, LookupOrdinaryName);
8104 
8105   // Unlike most lookups, we don't always want to hide tag
8106   // declarations: tag names are visible through the using declaration
8107   // even if hidden by ordinary names, *except* in a dependent context
8108   // where it's important for the sanity of two-phase lookup.
8109   if (!IsInstantiation)
8110     R.setHideTags(false);
8111 
8112   // For the purposes of this lookup, we have a base object type
8113   // equal to that of the current context.
8114   if (CurContext->isRecord()) {
8115     R.setBaseObjectType(
8116                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8117   }
8118 
8119   LookupQualifiedName(R, LookupContext);
8120 
8121   // Try to correct typos if possible.
8122   if (R.empty()) {
8123     if (TypoCorrection Corrected = CorrectTypo(
8124             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8125             llvm::make_unique<UsingValidatorCCC>(
8126                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8127                 dyn_cast<CXXRecordDecl>(CurContext)),
8128             CTK_ErrorRecovery)) {
8129       // We reject any correction for which ND would be NULL.
8130       NamedDecl *ND = Corrected.getCorrectionDecl();
8131 
8132       // We reject candidates where DroppedSpecifier == true, hence the
8133       // literal '0' below.
8134       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8135                                 << NameInfo.getName() << LookupContext << 0
8136                                 << SS.getRange());
8137 
8138       // If we corrected to an inheriting constructor, handle it as one.
8139       auto *RD = dyn_cast<CXXRecordDecl>(ND);
8140       if (RD && RD->isInjectedClassName()) {
8141         // Fix up the information we'll use to build the using declaration.
8142         if (Corrected.WillReplaceSpecifier()) {
8143           NestedNameSpecifierLocBuilder Builder;
8144           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8145                               QualifierLoc.getSourceRange());
8146           QualifierLoc = Builder.getWithLocInContext(Context);
8147         }
8148 
8149         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8150             Context.getCanonicalType(Context.getRecordType(RD))));
8151         NameInfo.setNamedTypeInfo(nullptr);
8152 
8153         // Build it and process it as an inheriting constructor.
8154         UsingDecl *UD = BuildValid();
8155         CheckInheritingConstructorUsingDecl(UD);
8156         return UD;
8157       }
8158 
8159       // FIXME: Pick up all the declarations if we found an overloaded function.
8160       R.setLookupName(Corrected.getCorrection());
8161       R.addDecl(ND);
8162     } else {
8163       Diag(IdentLoc, diag::err_no_member)
8164         << NameInfo.getName() << LookupContext << SS.getRange();
8165       return BuildInvalid();
8166     }
8167   }
8168 
8169   if (R.isAmbiguous())
8170     return BuildInvalid();
8171 
8172   if (HasTypenameKeyword) {
8173     // If we asked for a typename and got a non-type decl, error out.
8174     if (!R.getAsSingle<TypeDecl>()) {
8175       Diag(IdentLoc, diag::err_using_typename_non_type);
8176       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8177         Diag((*I)->getUnderlyingDecl()->getLocation(),
8178              diag::note_using_decl_target);
8179       return BuildInvalid();
8180     }
8181   } else {
8182     // If we asked for a non-typename and we got a type, error out,
8183     // but only if this is an instantiation of an unresolved using
8184     // decl.  Otherwise just silently find the type name.
8185     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8186       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8187       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8188       return BuildInvalid();
8189     }
8190   }
8191 
8192   // C++0x N2914 [namespace.udecl]p6:
8193   // A using-declaration shall not name a namespace.
8194   if (R.getAsSingle<NamespaceDecl>()) {
8195     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8196       << SS.getRange();
8197     return BuildInvalid();
8198   }
8199 
8200   UsingDecl *UD = BuildValid();
8201   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8202     UsingShadowDecl *PrevDecl = nullptr;
8203     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8204       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8205   }
8206 
8207   return UD;
8208 }
8209 
8210 /// Additional checks for a using declaration referring to a constructor name.
8211 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8212   assert(!UD->hasTypename() && "expecting a constructor name");
8213 
8214   const Type *SourceType = UD->getQualifier()->getAsType();
8215   assert(SourceType &&
8216          "Using decl naming constructor doesn't have type in scope spec.");
8217   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8218 
8219   // Check whether the named type is a direct base class.
8220   bool AnyDependentBases = false;
8221   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8222                                       AnyDependentBases);
8223   if (!Base && !AnyDependentBases) {
8224     Diag(UD->getUsingLoc(),
8225          diag::err_using_decl_constructor_not_in_direct_base)
8226       << UD->getNameInfo().getSourceRange()
8227       << QualType(SourceType, 0) << TargetClass;
8228     UD->setInvalidDecl();
8229     return true;
8230   }
8231 
8232   if (Base)
8233     Base->setInheritConstructors();
8234 
8235   return false;
8236 }
8237 
8238 /// Checks that the given using declaration is not an invalid
8239 /// redeclaration.  Note that this is checking only for the using decl
8240 /// itself, not for any ill-formedness among the UsingShadowDecls.
8241 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8242                                        bool HasTypenameKeyword,
8243                                        const CXXScopeSpec &SS,
8244                                        SourceLocation NameLoc,
8245                                        const LookupResult &Prev) {
8246   // C++03 [namespace.udecl]p8:
8247   // C++0x [namespace.udecl]p10:
8248   //   A using-declaration is a declaration and can therefore be used
8249   //   repeatedly where (and only where) multiple declarations are
8250   //   allowed.
8251   //
8252   // That's in non-member contexts.
8253   if (!CurContext->getRedeclContext()->isRecord())
8254     return false;
8255 
8256   NestedNameSpecifier *Qual = SS.getScopeRep();
8257 
8258   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8259     NamedDecl *D = *I;
8260 
8261     bool DTypename;
8262     NestedNameSpecifier *DQual;
8263     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8264       DTypename = UD->hasTypename();
8265       DQual = UD->getQualifier();
8266     } else if (UnresolvedUsingValueDecl *UD
8267                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8268       DTypename = false;
8269       DQual = UD->getQualifier();
8270     } else if (UnresolvedUsingTypenameDecl *UD
8271                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8272       DTypename = true;
8273       DQual = UD->getQualifier();
8274     } else continue;
8275 
8276     // using decls differ if one says 'typename' and the other doesn't.
8277     // FIXME: non-dependent using decls?
8278     if (HasTypenameKeyword != DTypename) continue;
8279 
8280     // using decls differ if they name different scopes (but note that
8281     // template instantiation can cause this check to trigger when it
8282     // didn't before instantiation).
8283     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8284         Context.getCanonicalNestedNameSpecifier(DQual))
8285       continue;
8286 
8287     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8288     Diag(D->getLocation(), diag::note_using_decl) << 1;
8289     return true;
8290   }
8291 
8292   return false;
8293 }
8294 
8295 
8296 /// Checks that the given nested-name qualifier used in a using decl
8297 /// in the current context is appropriately related to the current
8298 /// scope.  If an error is found, diagnoses it and returns true.
8299 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8300                                    const CXXScopeSpec &SS,
8301                                    const DeclarationNameInfo &NameInfo,
8302                                    SourceLocation NameLoc) {
8303   DeclContext *NamedContext = computeDeclContext(SS);
8304 
8305   if (!CurContext->isRecord()) {
8306     // C++03 [namespace.udecl]p3:
8307     // C++0x [namespace.udecl]p8:
8308     //   A using-declaration for a class member shall be a member-declaration.
8309 
8310     // If we weren't able to compute a valid scope, it must be a
8311     // dependent class scope.
8312     if (!NamedContext || NamedContext->isRecord()) {
8313       auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
8314       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8315         RD = nullptr;
8316 
8317       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8318         << SS.getRange();
8319 
8320       // If we have a complete, non-dependent source type, try to suggest a
8321       // way to get the same effect.
8322       if (!RD)
8323         return true;
8324 
8325       // Find what this using-declaration was referring to.
8326       LookupResult R(*this, NameInfo, LookupOrdinaryName);
8327       R.setHideTags(false);
8328       R.suppressDiagnostics();
8329       LookupQualifiedName(R, RD);
8330 
8331       if (R.getAsSingle<TypeDecl>()) {
8332         if (getLangOpts().CPlusPlus11) {
8333           // Convert 'using X::Y;' to 'using Y = X::Y;'.
8334           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8335             << 0 // alias declaration
8336             << FixItHint::CreateInsertion(SS.getBeginLoc(),
8337                                           NameInfo.getName().getAsString() +
8338                                               " = ");
8339         } else {
8340           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8341           SourceLocation InsertLoc =
8342               PP.getLocForEndOfToken(NameInfo.getLocEnd());
8343           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8344             << 1 // typedef declaration
8345             << FixItHint::CreateReplacement(UsingLoc, "typedef")
8346             << FixItHint::CreateInsertion(
8347                    InsertLoc, " " + NameInfo.getName().getAsString());
8348         }
8349       } else if (R.getAsSingle<VarDecl>()) {
8350         // Don't provide a fixit outside C++11 mode; we don't want to suggest
8351         // repeating the type of the static data member here.
8352         FixItHint FixIt;
8353         if (getLangOpts().CPlusPlus11) {
8354           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8355           FixIt = FixItHint::CreateReplacement(
8356               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8357         }
8358 
8359         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8360           << 2 // reference declaration
8361           << FixIt;
8362       }
8363       return true;
8364     }
8365 
8366     // Otherwise, everything is known to be fine.
8367     return false;
8368   }
8369 
8370   // The current scope is a record.
8371 
8372   // If the named context is dependent, we can't decide much.
8373   if (!NamedContext) {
8374     // FIXME: in C++0x, we can diagnose if we can prove that the
8375     // nested-name-specifier does not refer to a base class, which is
8376     // still possible in some cases.
8377 
8378     // Otherwise we have to conservatively report that things might be
8379     // okay.
8380     return false;
8381   }
8382 
8383   if (!NamedContext->isRecord()) {
8384     // Ideally this would point at the last name in the specifier,
8385     // but we don't have that level of source info.
8386     Diag(SS.getRange().getBegin(),
8387          diag::err_using_decl_nested_name_specifier_is_not_class)
8388       << SS.getScopeRep() << SS.getRange();
8389     return true;
8390   }
8391 
8392   if (!NamedContext->isDependentContext() &&
8393       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8394     return true;
8395 
8396   if (getLangOpts().CPlusPlus11) {
8397     // C++0x [namespace.udecl]p3:
8398     //   In a using-declaration used as a member-declaration, the
8399     //   nested-name-specifier shall name a base class of the class
8400     //   being defined.
8401 
8402     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8403                                  cast<CXXRecordDecl>(NamedContext))) {
8404       if (CurContext == NamedContext) {
8405         Diag(NameLoc,
8406              diag::err_using_decl_nested_name_specifier_is_current_class)
8407           << SS.getRange();
8408         return true;
8409       }
8410 
8411       Diag(SS.getRange().getBegin(),
8412            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8413         << SS.getScopeRep()
8414         << cast<CXXRecordDecl>(CurContext)
8415         << SS.getRange();
8416       return true;
8417     }
8418 
8419     return false;
8420   }
8421 
8422   // C++03 [namespace.udecl]p4:
8423   //   A using-declaration used as a member-declaration shall refer
8424   //   to a member of a base class of the class being defined [etc.].
8425 
8426   // Salient point: SS doesn't have to name a base class as long as
8427   // lookup only finds members from base classes.  Therefore we can
8428   // diagnose here only if we can prove that that can't happen,
8429   // i.e. if the class hierarchies provably don't intersect.
8430 
8431   // TODO: it would be nice if "definitely valid" results were cached
8432   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8433   // need to be repeated.
8434 
8435   struct UserData {
8436     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8437 
8438     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8439       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8440       Data->Bases.insert(Base);
8441       return true;
8442     }
8443 
8444     bool hasDependentBases(const CXXRecordDecl *Class) {
8445       return !Class->forallBases(collect, this);
8446     }
8447 
8448     /// Returns true if the base is dependent or is one of the
8449     /// accumulated base classes.
8450     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8451       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8452       return !Data->Bases.count(Base);
8453     }
8454 
8455     bool mightShareBases(const CXXRecordDecl *Class) {
8456       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8457     }
8458   };
8459 
8460   UserData Data;
8461 
8462   // Returns false if we find a dependent base.
8463   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8464     return false;
8465 
8466   // Returns false if the class has a dependent base or if it or one
8467   // of its bases is present in the base set of the current context.
8468   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8469     return false;
8470 
8471   Diag(SS.getRange().getBegin(),
8472        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8473     << SS.getScopeRep()
8474     << cast<CXXRecordDecl>(CurContext)
8475     << SS.getRange();
8476 
8477   return true;
8478 }
8479 
8480 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8481                                   AccessSpecifier AS,
8482                                   MultiTemplateParamsArg TemplateParamLists,
8483                                   SourceLocation UsingLoc,
8484                                   UnqualifiedId &Name,
8485                                   AttributeList *AttrList,
8486                                   TypeResult Type) {
8487   // Skip up to the relevant declaration scope.
8488   while (S->getFlags() & Scope::TemplateParamScope)
8489     S = S->getParent();
8490   assert((S->getFlags() & Scope::DeclScope) &&
8491          "got alias-declaration outside of declaration scope");
8492 
8493   if (Type.isInvalid())
8494     return nullptr;
8495 
8496   bool Invalid = false;
8497   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8498   TypeSourceInfo *TInfo = nullptr;
8499   GetTypeFromParser(Type.get(), &TInfo);
8500 
8501   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8502     return nullptr;
8503 
8504   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8505                                       UPPC_DeclarationType)) {
8506     Invalid = true;
8507     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8508                                              TInfo->getTypeLoc().getBeginLoc());
8509   }
8510 
8511   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8512   LookupName(Previous, S);
8513 
8514   // Warn about shadowing the name of a template parameter.
8515   if (Previous.isSingleResult() &&
8516       Previous.getFoundDecl()->isTemplateParameter()) {
8517     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8518     Previous.clear();
8519   }
8520 
8521   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8522          "name in alias declaration must be an identifier");
8523   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8524                                                Name.StartLocation,
8525                                                Name.Identifier, TInfo);
8526 
8527   NewTD->setAccess(AS);
8528 
8529   if (Invalid)
8530     NewTD->setInvalidDecl();
8531 
8532   ProcessDeclAttributeList(S, NewTD, AttrList);
8533 
8534   CheckTypedefForVariablyModifiedType(S, NewTD);
8535   Invalid |= NewTD->isInvalidDecl();
8536 
8537   bool Redeclaration = false;
8538 
8539   NamedDecl *NewND;
8540   if (TemplateParamLists.size()) {
8541     TypeAliasTemplateDecl *OldDecl = nullptr;
8542     TemplateParameterList *OldTemplateParams = nullptr;
8543 
8544     if (TemplateParamLists.size() != 1) {
8545       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8546         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8547          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8548     }
8549     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8550 
8551     // Only consider previous declarations in the same scope.
8552     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8553                          /*ExplicitInstantiationOrSpecialization*/false);
8554     if (!Previous.empty()) {
8555       Redeclaration = true;
8556 
8557       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8558       if (!OldDecl && !Invalid) {
8559         Diag(UsingLoc, diag::err_redefinition_different_kind)
8560           << Name.Identifier;
8561 
8562         NamedDecl *OldD = Previous.getRepresentativeDecl();
8563         if (OldD->getLocation().isValid())
8564           Diag(OldD->getLocation(), diag::note_previous_definition);
8565 
8566         Invalid = true;
8567       }
8568 
8569       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8570         if (TemplateParameterListsAreEqual(TemplateParams,
8571                                            OldDecl->getTemplateParameters(),
8572                                            /*Complain=*/true,
8573                                            TPL_TemplateMatch))
8574           OldTemplateParams = OldDecl->getTemplateParameters();
8575         else
8576           Invalid = true;
8577 
8578         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8579         if (!Invalid &&
8580             !Context.hasSameType(OldTD->getUnderlyingType(),
8581                                  NewTD->getUnderlyingType())) {
8582           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8583           // but we can't reasonably accept it.
8584           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8585             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8586           if (OldTD->getLocation().isValid())
8587             Diag(OldTD->getLocation(), diag::note_previous_definition);
8588           Invalid = true;
8589         }
8590       }
8591     }
8592 
8593     // Merge any previous default template arguments into our parameters,
8594     // and check the parameter list.
8595     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8596                                    TPC_TypeAliasTemplate))
8597       return nullptr;
8598 
8599     TypeAliasTemplateDecl *NewDecl =
8600       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8601                                     Name.Identifier, TemplateParams,
8602                                     NewTD);
8603     NewTD->setDescribedAliasTemplate(NewDecl);
8604 
8605     NewDecl->setAccess(AS);
8606 
8607     if (Invalid)
8608       NewDecl->setInvalidDecl();
8609     else if (OldDecl)
8610       NewDecl->setPreviousDecl(OldDecl);
8611 
8612     NewND = NewDecl;
8613   } else {
8614     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8615     NewND = NewTD;
8616   }
8617 
8618   if (!Redeclaration)
8619     PushOnScopeChains(NewND, S);
8620 
8621   ActOnDocumentableDecl(NewND);
8622   return NewND;
8623 }
8624 
8625 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8626                                    SourceLocation AliasLoc,
8627                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
8628                                    SourceLocation IdentLoc,
8629                                    IdentifierInfo *Ident) {
8630 
8631   // Lookup the namespace name.
8632   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8633   LookupParsedName(R, S, &SS);
8634 
8635   if (R.isAmbiguous())
8636     return nullptr;
8637 
8638   if (R.empty()) {
8639     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8640       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8641       return nullptr;
8642     }
8643   }
8644   assert(!R.isAmbiguous() && !R.empty());
8645 
8646   // Check if we have a previous declaration with the same name.
8647   NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8648                                          ForRedeclaration);
8649   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8650     PrevDecl = nullptr;
8651 
8652   NamedDecl *ND = R.getFoundDecl();
8653 
8654   if (PrevDecl) {
8655     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8656       // We already have an alias with the same name that points to the same
8657       // namespace; check that it matches.
8658       if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8659         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8660           << Alias;
8661         Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8662           << AD->getNamespace();
8663         return nullptr;
8664       }
8665     } else {
8666       unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8667                             ? diag::err_redefinition
8668                             : diag::err_redefinition_different_kind;
8669       Diag(AliasLoc, DiagID) << Alias;
8670       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8671       return nullptr;
8672     }
8673   }
8674 
8675   // The use of a nested name specifier may trigger deprecation warnings.
8676   DiagnoseUseOfDecl(ND, IdentLoc);
8677 
8678   NamespaceAliasDecl *AliasDecl =
8679     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8680                                Alias, SS.getWithLocInContext(Context),
8681                                IdentLoc, ND);
8682   if (PrevDecl)
8683     AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
8684 
8685   PushOnScopeChains(AliasDecl, S);
8686   return AliasDecl;
8687 }
8688 
8689 Sema::ImplicitExceptionSpecification
8690 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8691                                                CXXMethodDecl *MD) {
8692   CXXRecordDecl *ClassDecl = MD->getParent();
8693 
8694   // C++ [except.spec]p14:
8695   //   An implicitly declared special member function (Clause 12) shall have an
8696   //   exception-specification. [...]
8697   ImplicitExceptionSpecification ExceptSpec(*this);
8698   if (ClassDecl->isInvalidDecl())
8699     return ExceptSpec;
8700 
8701   // Direct base-class constructors.
8702   for (const auto &B : ClassDecl->bases()) {
8703     if (B.isVirtual()) // Handled below.
8704       continue;
8705 
8706     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8707       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8708       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8709       // If this is a deleted function, add it anyway. This might be conformant
8710       // with the standard. This might not. I'm not sure. It might not matter.
8711       if (Constructor)
8712         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8713     }
8714   }
8715 
8716   // Virtual base-class constructors.
8717   for (const auto &B : ClassDecl->vbases()) {
8718     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8719       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8720       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8721       // If this is a deleted function, add it anyway. This might be conformant
8722       // with the standard. This might not. I'm not sure. It might not matter.
8723       if (Constructor)
8724         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8725     }
8726   }
8727 
8728   // Field constructors.
8729   for (const auto *F : ClassDecl->fields()) {
8730     if (F->hasInClassInitializer()) {
8731       if (Expr *E = F->getInClassInitializer())
8732         ExceptSpec.CalledExpr(E);
8733     } else if (const RecordType *RecordTy
8734               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8735       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8736       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8737       // If this is a deleted function, add it anyway. This might be conformant
8738       // with the standard. This might not. I'm not sure. It might not matter.
8739       // In particular, the problem is that this function never gets called. It
8740       // might just be ill-formed because this function attempts to refer to
8741       // a deleted function here.
8742       if (Constructor)
8743         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8744     }
8745   }
8746 
8747   return ExceptSpec;
8748 }
8749 
8750 Sema::ImplicitExceptionSpecification
8751 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8752   CXXRecordDecl *ClassDecl = CD->getParent();
8753 
8754   // C++ [except.spec]p14:
8755   //   An inheriting constructor [...] shall have an exception-specification. [...]
8756   ImplicitExceptionSpecification ExceptSpec(*this);
8757   if (ClassDecl->isInvalidDecl())
8758     return ExceptSpec;
8759 
8760   // Inherited constructor.
8761   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8762   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8763   // FIXME: Copying or moving the parameters could add extra exceptions to the
8764   // set, as could the default arguments for the inherited constructor. This
8765   // will be addressed when we implement the resolution of core issue 1351.
8766   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8767 
8768   // Direct base-class constructors.
8769   for (const auto &B : ClassDecl->bases()) {
8770     if (B.isVirtual()) // Handled below.
8771       continue;
8772 
8773     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8774       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8775       if (BaseClassDecl == InheritedDecl)
8776         continue;
8777       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8778       if (Constructor)
8779         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8780     }
8781   }
8782 
8783   // Virtual base-class constructors.
8784   for (const auto &B : ClassDecl->vbases()) {
8785     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8786       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8787       if (BaseClassDecl == InheritedDecl)
8788         continue;
8789       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8790       if (Constructor)
8791         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8792     }
8793   }
8794 
8795   // Field constructors.
8796   for (const auto *F : ClassDecl->fields()) {
8797     if (F->hasInClassInitializer()) {
8798       if (Expr *E = F->getInClassInitializer())
8799         ExceptSpec.CalledExpr(E);
8800     } else if (const RecordType *RecordTy
8801               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8802       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8803       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8804       if (Constructor)
8805         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8806     }
8807   }
8808 
8809   return ExceptSpec;
8810 }
8811 
8812 namespace {
8813 /// RAII object to register a special member as being currently declared.
8814 struct DeclaringSpecialMember {
8815   Sema &S;
8816   Sema::SpecialMemberDecl D;
8817   bool WasAlreadyBeingDeclared;
8818 
8819   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8820     : S(S), D(RD, CSM) {
8821     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
8822     if (WasAlreadyBeingDeclared)
8823       // This almost never happens, but if it does, ensure that our cache
8824       // doesn't contain a stale result.
8825       S.SpecialMemberCache.clear();
8826 
8827     // FIXME: Register a note to be produced if we encounter an error while
8828     // declaring the special member.
8829   }
8830   ~DeclaringSpecialMember() {
8831     if (!WasAlreadyBeingDeclared)
8832       S.SpecialMembersBeingDeclared.erase(D);
8833   }
8834 
8835   /// \brief Are we already trying to declare this special member?
8836   bool isAlreadyBeingDeclared() const {
8837     return WasAlreadyBeingDeclared;
8838   }
8839 };
8840 }
8841 
8842 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8843                                                      CXXRecordDecl *ClassDecl) {
8844   // C++ [class.ctor]p5:
8845   //   A default constructor for a class X is a constructor of class X
8846   //   that can be called without an argument. If there is no
8847   //   user-declared constructor for class X, a default constructor is
8848   //   implicitly declared. An implicitly-declared default constructor
8849   //   is an inline public member of its class.
8850   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8851          "Should not build implicit default constructor!");
8852 
8853   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8854   if (DSM.isAlreadyBeingDeclared())
8855     return nullptr;
8856 
8857   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8858                                                      CXXDefaultConstructor,
8859                                                      false);
8860 
8861   // Create the actual constructor declaration.
8862   CanQualType ClassType
8863     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8864   SourceLocation ClassLoc = ClassDecl->getLocation();
8865   DeclarationName Name
8866     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8867   DeclarationNameInfo NameInfo(Name, ClassLoc);
8868   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8869       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8870       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8871       /*isImplicitlyDeclared=*/true, Constexpr);
8872   DefaultCon->setAccess(AS_public);
8873   DefaultCon->setDefaulted();
8874 
8875   if (getLangOpts().CUDA) {
8876     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8877                                             DefaultCon,
8878                                             /* ConstRHS */ false,
8879                                             /* Diagnose */ false);
8880   }
8881 
8882   // Build an exception specification pointing back at this constructor.
8883   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8884   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8885 
8886   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8887   // constructors is easy to compute.
8888   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8889 
8890   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8891     SetDeclDeleted(DefaultCon, ClassLoc);
8892 
8893   // Note that we have declared this constructor.
8894   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8895 
8896   if (Scope *S = getScopeForContext(ClassDecl))
8897     PushOnScopeChains(DefaultCon, S, false);
8898   ClassDecl->addDecl(DefaultCon);
8899 
8900   return DefaultCon;
8901 }
8902 
8903 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8904                                             CXXConstructorDecl *Constructor) {
8905   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8906           !Constructor->doesThisDeclarationHaveABody() &&
8907           !Constructor->isDeleted()) &&
8908     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8909 
8910   CXXRecordDecl *ClassDecl = Constructor->getParent();
8911   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8912 
8913   SynthesizedFunctionScope Scope(*this, Constructor);
8914   DiagnosticErrorTrap Trap(Diags);
8915   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8916       Trap.hasErrorOccurred()) {
8917     Diag(CurrentLocation, diag::note_member_synthesized_at)
8918       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8919     Constructor->setInvalidDecl();
8920     return;
8921   }
8922 
8923   // The exception specification is needed because we are defining the
8924   // function.
8925   ResolveExceptionSpec(CurrentLocation,
8926                        Constructor->getType()->castAs<FunctionProtoType>());
8927 
8928   SourceLocation Loc = Constructor->getLocEnd().isValid()
8929                            ? Constructor->getLocEnd()
8930                            : Constructor->getLocation();
8931   Constructor->setBody(new (Context) CompoundStmt(Loc));
8932 
8933   Constructor->markUsed(Context);
8934   MarkVTableUsed(CurrentLocation, ClassDecl);
8935 
8936   if (ASTMutationListener *L = getASTMutationListener()) {
8937     L->CompletedImplicitDefinition(Constructor);
8938   }
8939 
8940   DiagnoseUninitializedFields(*this, Constructor);
8941 }
8942 
8943 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8944   // Perform any delayed checks on exception specifications.
8945   CheckDelayedMemberExceptionSpecs();
8946 }
8947 
8948 namespace {
8949 /// Information on inheriting constructors to declare.
8950 class InheritingConstructorInfo {
8951 public:
8952   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8953       : SemaRef(SemaRef), Derived(Derived) {
8954     // Mark the constructors that we already have in the derived class.
8955     //
8956     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8957     //   unless there is a user-declared constructor with the same signature in
8958     //   the class where the using-declaration appears.
8959     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8960   }
8961 
8962   void inheritAll(CXXRecordDecl *RD) {
8963     visitAll(RD, &InheritingConstructorInfo::inherit);
8964   }
8965 
8966 private:
8967   /// Information about an inheriting constructor.
8968   struct InheritingConstructor {
8969     InheritingConstructor()
8970       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
8971 
8972     /// If \c true, a constructor with this signature is already declared
8973     /// in the derived class.
8974     bool DeclaredInDerived;
8975 
8976     /// The constructor which is inherited.
8977     const CXXConstructorDecl *BaseCtor;
8978 
8979     /// The derived constructor we declared.
8980     CXXConstructorDecl *DerivedCtor;
8981   };
8982 
8983   /// Inheriting constructors with a given canonical type. There can be at
8984   /// most one such non-template constructor, and any number of templated
8985   /// constructors.
8986   struct InheritingConstructorsForType {
8987     InheritingConstructor NonTemplate;
8988     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8989         Templates;
8990 
8991     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8992       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8993         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8994         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8995           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8996                                                false, S.TPL_TemplateMatch))
8997             return Templates[I].second;
8998         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8999         return Templates.back().second;
9000       }
9001 
9002       return NonTemplate;
9003     }
9004   };
9005 
9006   /// Get or create the inheriting constructor record for a constructor.
9007   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9008                                   QualType CtorType) {
9009     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9010         .getEntry(SemaRef, Ctor);
9011   }
9012 
9013   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9014 
9015   /// Process all constructors for a class.
9016   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
9017     for (const auto *Ctor : RD->ctors())
9018       (this->*Callback)(Ctor);
9019     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9020              I(RD->decls_begin()), E(RD->decls_end());
9021          I != E; ++I) {
9022       const FunctionDecl *FD = (*I)->getTemplatedDecl();
9023       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9024         (this->*Callback)(CD);
9025     }
9026   }
9027 
9028   /// Note that a constructor (or constructor template) was declared in Derived.
9029   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9030     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9031   }
9032 
9033   /// Inherit a single constructor.
9034   void inherit(const CXXConstructorDecl *Ctor) {
9035     const FunctionProtoType *CtorType =
9036         Ctor->getType()->castAs<FunctionProtoType>();
9037     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
9038     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9039 
9040     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9041 
9042     // Core issue (no number yet): the ellipsis is always discarded.
9043     if (EPI.Variadic) {
9044       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9045       SemaRef.Diag(Ctor->getLocation(),
9046                    diag::note_using_decl_constructor_ellipsis);
9047       EPI.Variadic = false;
9048     }
9049 
9050     // Declare a constructor for each number of parameters.
9051     //
9052     // C++11 [class.inhctor]p1:
9053     //   The candidate set of inherited constructors from the class X named in
9054     //   the using-declaration consists of [... modulo defects ...] for each
9055     //   constructor or constructor template of X, the set of constructors or
9056     //   constructor templates that results from omitting any ellipsis parameter
9057     //   specification and successively omitting parameters with a default
9058     //   argument from the end of the parameter-type-list
9059     unsigned MinParams = minParamsToInherit(Ctor);
9060     unsigned Params = Ctor->getNumParams();
9061     if (Params >= MinParams) {
9062       do
9063         declareCtor(UsingLoc, Ctor,
9064                     SemaRef.Context.getFunctionType(
9065                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
9066       while (Params > MinParams &&
9067              Ctor->getParamDecl(--Params)->hasDefaultArg());
9068     }
9069   }
9070 
9071   /// Find the using-declaration which specified that we should inherit the
9072   /// constructors of \p Base.
9073   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9074     // No fancy lookup required; just look for the base constructor name
9075     // directly within the derived class.
9076     ASTContext &Context = SemaRef.Context;
9077     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9078         Context.getCanonicalType(Context.getRecordType(Base)));
9079     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
9080     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9081   }
9082 
9083   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9084     // C++11 [class.inhctor]p3:
9085     //   [F]or each constructor template in the candidate set of inherited
9086     //   constructors, a constructor template is implicitly declared
9087     if (Ctor->getDescribedFunctionTemplate())
9088       return 0;
9089 
9090     //   For each non-template constructor in the candidate set of inherited
9091     //   constructors other than a constructor having no parameters or a
9092     //   copy/move constructor having a single parameter, a constructor is
9093     //   implicitly declared [...]
9094     if (Ctor->getNumParams() == 0)
9095       return 1;
9096     if (Ctor->isCopyOrMoveConstructor())
9097       return 2;
9098 
9099     // Per discussion on core reflector, never inherit a constructor which
9100     // would become a default, copy, or move constructor of Derived either.
9101     const ParmVarDecl *PD = Ctor->getParamDecl(0);
9102     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9103     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9104   }
9105 
9106   /// Declare a single inheriting constructor, inheriting the specified
9107   /// constructor, with the given type.
9108   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9109                    QualType DerivedType) {
9110     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9111 
9112     // C++11 [class.inhctor]p3:
9113     //   ... a constructor is implicitly declared with the same constructor
9114     //   characteristics unless there is a user-declared constructor with
9115     //   the same signature in the class where the using-declaration appears
9116     if (Entry.DeclaredInDerived)
9117       return;
9118 
9119     // C++11 [class.inhctor]p7:
9120     //   If two using-declarations declare inheriting constructors with the
9121     //   same signature, the program is ill-formed
9122     if (Entry.DerivedCtor) {
9123       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9124         // Only diagnose this once per constructor.
9125         if (Entry.DerivedCtor->isInvalidDecl())
9126           return;
9127         Entry.DerivedCtor->setInvalidDecl();
9128 
9129         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9130         SemaRef.Diag(BaseCtor->getLocation(),
9131                      diag::note_using_decl_constructor_conflict_current_ctor);
9132         SemaRef.Diag(Entry.BaseCtor->getLocation(),
9133                      diag::note_using_decl_constructor_conflict_previous_ctor);
9134         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9135                      diag::note_using_decl_constructor_conflict_previous_using);
9136       } else {
9137         // Core issue (no number): if the same inheriting constructor is
9138         // produced by multiple base class constructors from the same base
9139         // class, the inheriting constructor is defined as deleted.
9140         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9141       }
9142 
9143       return;
9144     }
9145 
9146     ASTContext &Context = SemaRef.Context;
9147     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9148         Context.getCanonicalType(Context.getRecordType(Derived)));
9149     DeclarationNameInfo NameInfo(Name, UsingLoc);
9150 
9151     TemplateParameterList *TemplateParams = nullptr;
9152     if (const FunctionTemplateDecl *FTD =
9153             BaseCtor->getDescribedFunctionTemplate()) {
9154       TemplateParams = FTD->getTemplateParameters();
9155       // We're reusing template parameters from a different DeclContext. This
9156       // is questionable at best, but works out because the template depth in
9157       // both places is guaranteed to be 0.
9158       // FIXME: Rebuild the template parameters in the new context, and
9159       // transform the function type to refer to them.
9160     }
9161 
9162     // Build type source info pointing at the using-declaration. This is
9163     // required by template instantiation.
9164     TypeSourceInfo *TInfo =
9165         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9166     FunctionProtoTypeLoc ProtoLoc =
9167         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9168 
9169     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9170         Context, Derived, UsingLoc, NameInfo, DerivedType,
9171         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9172         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9173 
9174     // Build an unevaluated exception specification for this constructor.
9175     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9176     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9177     EPI.ExceptionSpec.Type = EST_Unevaluated;
9178     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9179     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9180                                                  FPT->getParamTypes(), EPI));
9181 
9182     // Build the parameter declarations.
9183     SmallVector<ParmVarDecl *, 16> ParamDecls;
9184     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9185       TypeSourceInfo *TInfo =
9186           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9187       ParmVarDecl *PD = ParmVarDecl::Create(
9188           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9189           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9190       PD->setScopeInfo(0, I);
9191       PD->setImplicit();
9192       ParamDecls.push_back(PD);
9193       ProtoLoc.setParam(I, PD);
9194     }
9195 
9196     // Set up the new constructor.
9197     DerivedCtor->setAccess(BaseCtor->getAccess());
9198     DerivedCtor->setParams(ParamDecls);
9199     DerivedCtor->setInheritedConstructor(BaseCtor);
9200     if (BaseCtor->isDeleted())
9201       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9202 
9203     // If this is a constructor template, build the template declaration.
9204     if (TemplateParams) {
9205       FunctionTemplateDecl *DerivedTemplate =
9206           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9207                                        TemplateParams, DerivedCtor);
9208       DerivedTemplate->setAccess(BaseCtor->getAccess());
9209       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9210       Derived->addDecl(DerivedTemplate);
9211     } else {
9212       Derived->addDecl(DerivedCtor);
9213     }
9214 
9215     Entry.BaseCtor = BaseCtor;
9216     Entry.DerivedCtor = DerivedCtor;
9217   }
9218 
9219   Sema &SemaRef;
9220   CXXRecordDecl *Derived;
9221   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9222   MapType Map;
9223 };
9224 }
9225 
9226 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9227   // Defer declaring the inheriting constructors until the class is
9228   // instantiated.
9229   if (ClassDecl->isDependentContext())
9230     return;
9231 
9232   // Find base classes from which we might inherit constructors.
9233   SmallVector<CXXRecordDecl*, 4> InheritedBases;
9234   for (const auto &BaseIt : ClassDecl->bases())
9235     if (BaseIt.getInheritConstructors())
9236       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9237 
9238   // Go no further if we're not inheriting any constructors.
9239   if (InheritedBases.empty())
9240     return;
9241 
9242   // Declare the inherited constructors.
9243   InheritingConstructorInfo ICI(*this, ClassDecl);
9244   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9245     ICI.inheritAll(InheritedBases[I]);
9246 }
9247 
9248 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9249                                        CXXConstructorDecl *Constructor) {
9250   CXXRecordDecl *ClassDecl = Constructor->getParent();
9251   assert(Constructor->getInheritedConstructor() &&
9252          !Constructor->doesThisDeclarationHaveABody() &&
9253          !Constructor->isDeleted());
9254 
9255   SynthesizedFunctionScope Scope(*this, Constructor);
9256   DiagnosticErrorTrap Trap(Diags);
9257   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9258       Trap.hasErrorOccurred()) {
9259     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9260       << Context.getTagDeclType(ClassDecl);
9261     Constructor->setInvalidDecl();
9262     return;
9263   }
9264 
9265   SourceLocation Loc = Constructor->getLocation();
9266   Constructor->setBody(new (Context) CompoundStmt(Loc));
9267 
9268   Constructor->markUsed(Context);
9269   MarkVTableUsed(CurrentLocation, ClassDecl);
9270 
9271   if (ASTMutationListener *L = getASTMutationListener()) {
9272     L->CompletedImplicitDefinition(Constructor);
9273   }
9274 }
9275 
9276 
9277 Sema::ImplicitExceptionSpecification
9278 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9279   CXXRecordDecl *ClassDecl = MD->getParent();
9280 
9281   // C++ [except.spec]p14:
9282   //   An implicitly declared special member function (Clause 12) shall have
9283   //   an exception-specification.
9284   ImplicitExceptionSpecification ExceptSpec(*this);
9285   if (ClassDecl->isInvalidDecl())
9286     return ExceptSpec;
9287 
9288   // Direct base-class destructors.
9289   for (const auto &B : ClassDecl->bases()) {
9290     if (B.isVirtual()) // Handled below.
9291       continue;
9292 
9293     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9294       ExceptSpec.CalledDecl(B.getLocStart(),
9295                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9296   }
9297 
9298   // Virtual base-class destructors.
9299   for (const auto &B : ClassDecl->vbases()) {
9300     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9301       ExceptSpec.CalledDecl(B.getLocStart(),
9302                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9303   }
9304 
9305   // Field destructors.
9306   for (const auto *F : ClassDecl->fields()) {
9307     if (const RecordType *RecordTy
9308         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9309       ExceptSpec.CalledDecl(F->getLocation(),
9310                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9311   }
9312 
9313   return ExceptSpec;
9314 }
9315 
9316 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9317   // C++ [class.dtor]p2:
9318   //   If a class has no user-declared destructor, a destructor is
9319   //   declared implicitly. An implicitly-declared destructor is an
9320   //   inline public member of its class.
9321   assert(ClassDecl->needsImplicitDestructor());
9322 
9323   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9324   if (DSM.isAlreadyBeingDeclared())
9325     return nullptr;
9326 
9327   // Create the actual destructor declaration.
9328   CanQualType ClassType
9329     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9330   SourceLocation ClassLoc = ClassDecl->getLocation();
9331   DeclarationName Name
9332     = Context.DeclarationNames.getCXXDestructorName(ClassType);
9333   DeclarationNameInfo NameInfo(Name, ClassLoc);
9334   CXXDestructorDecl *Destructor
9335       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9336                                   QualType(), nullptr, /*isInline=*/true,
9337                                   /*isImplicitlyDeclared=*/true);
9338   Destructor->setAccess(AS_public);
9339   Destructor->setDefaulted();
9340 
9341   if (getLangOpts().CUDA) {
9342     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9343                                             Destructor,
9344                                             /* ConstRHS */ false,
9345                                             /* Diagnose */ false);
9346   }
9347 
9348   // Build an exception specification pointing back at this destructor.
9349   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9350   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9351 
9352   AddOverriddenMethods(ClassDecl, Destructor);
9353 
9354   // We don't need to use SpecialMemberIsTrivial here; triviality for
9355   // destructors is easy to compute.
9356   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9357 
9358   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9359     SetDeclDeleted(Destructor, ClassLoc);
9360 
9361   // Note that we have declared this destructor.
9362   ++ASTContext::NumImplicitDestructorsDeclared;
9363 
9364   // Introduce this destructor into its scope.
9365   if (Scope *S = getScopeForContext(ClassDecl))
9366     PushOnScopeChains(Destructor, S, false);
9367   ClassDecl->addDecl(Destructor);
9368 
9369   return Destructor;
9370 }
9371 
9372 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9373                                     CXXDestructorDecl *Destructor) {
9374   assert((Destructor->isDefaulted() &&
9375           !Destructor->doesThisDeclarationHaveABody() &&
9376           !Destructor->isDeleted()) &&
9377          "DefineImplicitDestructor - call it for implicit default dtor");
9378   CXXRecordDecl *ClassDecl = Destructor->getParent();
9379   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9380 
9381   if (Destructor->isInvalidDecl())
9382     return;
9383 
9384   SynthesizedFunctionScope Scope(*this, Destructor);
9385 
9386   DiagnosticErrorTrap Trap(Diags);
9387   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9388                                          Destructor->getParent());
9389 
9390   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9391     Diag(CurrentLocation, diag::note_member_synthesized_at)
9392       << CXXDestructor << Context.getTagDeclType(ClassDecl);
9393 
9394     Destructor->setInvalidDecl();
9395     return;
9396   }
9397 
9398   // The exception specification is needed because we are defining the
9399   // function.
9400   ResolveExceptionSpec(CurrentLocation,
9401                        Destructor->getType()->castAs<FunctionProtoType>());
9402 
9403   SourceLocation Loc = Destructor->getLocEnd().isValid()
9404                            ? Destructor->getLocEnd()
9405                            : Destructor->getLocation();
9406   Destructor->setBody(new (Context) CompoundStmt(Loc));
9407   Destructor->markUsed(Context);
9408   MarkVTableUsed(CurrentLocation, ClassDecl);
9409 
9410   if (ASTMutationListener *L = getASTMutationListener()) {
9411     L->CompletedImplicitDefinition(Destructor);
9412   }
9413 }
9414 
9415 /// \brief Perform any semantic analysis which needs to be delayed until all
9416 /// pending class member declarations have been parsed.
9417 void Sema::ActOnFinishCXXMemberDecls() {
9418   // If the context is an invalid C++ class, just suppress these checks.
9419   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9420     if (Record->isInvalidDecl()) {
9421       DelayedDefaultedMemberExceptionSpecs.clear();
9422       DelayedExceptionSpecChecks.clear();
9423       return;
9424     }
9425   }
9426 }
9427 
9428 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9429                                          CXXDestructorDecl *Destructor) {
9430   assert(getLangOpts().CPlusPlus11 &&
9431          "adjusting dtor exception specs was introduced in c++11");
9432 
9433   // C++11 [class.dtor]p3:
9434   //   A declaration of a destructor that does not have an exception-
9435   //   specification is implicitly considered to have the same exception-
9436   //   specification as an implicit declaration.
9437   const FunctionProtoType *DtorType = Destructor->getType()->
9438                                         getAs<FunctionProtoType>();
9439   if (DtorType->hasExceptionSpec())
9440     return;
9441 
9442   // Replace the destructor's type, building off the existing one. Fortunately,
9443   // the only thing of interest in the destructor type is its extended info.
9444   // The return and arguments are fixed.
9445   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9446   EPI.ExceptionSpec.Type = EST_Unevaluated;
9447   EPI.ExceptionSpec.SourceDecl = Destructor;
9448   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9449 
9450   // FIXME: If the destructor has a body that could throw, and the newly created
9451   // spec doesn't allow exceptions, we should emit a warning, because this
9452   // change in behavior can break conforming C++03 programs at runtime.
9453   // However, we don't have a body or an exception specification yet, so it
9454   // needs to be done somewhere else.
9455 }
9456 
9457 namespace {
9458 /// \brief An abstract base class for all helper classes used in building the
9459 //  copy/move operators. These classes serve as factory functions and help us
9460 //  avoid using the same Expr* in the AST twice.
9461 class ExprBuilder {
9462   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9463   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9464 
9465 protected:
9466   static Expr *assertNotNull(Expr *E) {
9467     assert(E && "Expression construction must not fail.");
9468     return E;
9469   }
9470 
9471 public:
9472   ExprBuilder() {}
9473   virtual ~ExprBuilder() {}
9474 
9475   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9476 };
9477 
9478 class RefBuilder: public ExprBuilder {
9479   VarDecl *Var;
9480   QualType VarType;
9481 
9482 public:
9483   Expr *build(Sema &S, SourceLocation Loc) const override {
9484     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9485   }
9486 
9487   RefBuilder(VarDecl *Var, QualType VarType)
9488       : Var(Var), VarType(VarType) {}
9489 };
9490 
9491 class ThisBuilder: public ExprBuilder {
9492 public:
9493   Expr *build(Sema &S, SourceLocation Loc) const override {
9494     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9495   }
9496 };
9497 
9498 class CastBuilder: public ExprBuilder {
9499   const ExprBuilder &Builder;
9500   QualType Type;
9501   ExprValueKind Kind;
9502   const CXXCastPath &Path;
9503 
9504 public:
9505   Expr *build(Sema &S, SourceLocation Loc) const override {
9506     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9507                                              CK_UncheckedDerivedToBase, Kind,
9508                                              &Path).get());
9509   }
9510 
9511   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9512               const CXXCastPath &Path)
9513       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9514 };
9515 
9516 class DerefBuilder: public ExprBuilder {
9517   const ExprBuilder &Builder;
9518 
9519 public:
9520   Expr *build(Sema &S, SourceLocation Loc) const override {
9521     return assertNotNull(
9522         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9523   }
9524 
9525   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9526 };
9527 
9528 class MemberBuilder: public ExprBuilder {
9529   const ExprBuilder &Builder;
9530   QualType Type;
9531   CXXScopeSpec SS;
9532   bool IsArrow;
9533   LookupResult &MemberLookup;
9534 
9535 public:
9536   Expr *build(Sema &S, SourceLocation Loc) const override {
9537     return assertNotNull(S.BuildMemberReferenceExpr(
9538         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9539         nullptr, MemberLookup, nullptr).get());
9540   }
9541 
9542   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9543                 LookupResult &MemberLookup)
9544       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9545         MemberLookup(MemberLookup) {}
9546 };
9547 
9548 class MoveCastBuilder: public ExprBuilder {
9549   const ExprBuilder &Builder;
9550 
9551 public:
9552   Expr *build(Sema &S, SourceLocation Loc) const override {
9553     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9554   }
9555 
9556   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9557 };
9558 
9559 class LvalueConvBuilder: public ExprBuilder {
9560   const ExprBuilder &Builder;
9561 
9562 public:
9563   Expr *build(Sema &S, SourceLocation Loc) const override {
9564     return assertNotNull(
9565         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9566   }
9567 
9568   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9569 };
9570 
9571 class SubscriptBuilder: public ExprBuilder {
9572   const ExprBuilder &Base;
9573   const ExprBuilder &Index;
9574 
9575 public:
9576   Expr *build(Sema &S, SourceLocation Loc) const override {
9577     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9578         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9579   }
9580 
9581   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9582       : Base(Base), Index(Index) {}
9583 };
9584 
9585 } // end anonymous namespace
9586 
9587 /// When generating a defaulted copy or move assignment operator, if a field
9588 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9589 /// do so. This optimization only applies for arrays of scalars, and for arrays
9590 /// of class type where the selected copy/move-assignment operator is trivial.
9591 static StmtResult
9592 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9593                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9594   // Compute the size of the memory buffer to be copied.
9595   QualType SizeType = S.Context.getSizeType();
9596   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9597                    S.Context.getTypeSizeInChars(T).getQuantity());
9598 
9599   // Take the address of the field references for "from" and "to". We
9600   // directly construct UnaryOperators here because semantic analysis
9601   // does not permit us to take the address of an xvalue.
9602   Expr *From = FromB.build(S, Loc);
9603   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9604                          S.Context.getPointerType(From->getType()),
9605                          VK_RValue, OK_Ordinary, Loc);
9606   Expr *To = ToB.build(S, Loc);
9607   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9608                        S.Context.getPointerType(To->getType()),
9609                        VK_RValue, OK_Ordinary, Loc);
9610 
9611   const Type *E = T->getBaseElementTypeUnsafe();
9612   bool NeedsCollectableMemCpy =
9613     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9614 
9615   // Create a reference to the __builtin_objc_memmove_collectable function
9616   StringRef MemCpyName = NeedsCollectableMemCpy ?
9617     "__builtin_objc_memmove_collectable" :
9618     "__builtin_memcpy";
9619   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9620                  Sema::LookupOrdinaryName);
9621   S.LookupName(R, S.TUScope, true);
9622 
9623   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9624   if (!MemCpy)
9625     // Something went horribly wrong earlier, and we will have complained
9626     // about it.
9627     return StmtError();
9628 
9629   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9630                                             VK_RValue, Loc, nullptr);
9631   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9632 
9633   Expr *CallArgs[] = {
9634     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9635   };
9636   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9637                                     Loc, CallArgs, Loc);
9638 
9639   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9640   return Call.getAs<Stmt>();
9641 }
9642 
9643 /// \brief Builds a statement that copies/moves the given entity from \p From to
9644 /// \c To.
9645 ///
9646 /// This routine is used to copy/move the members of a class with an
9647 /// implicitly-declared copy/move assignment operator. When the entities being
9648 /// copied are arrays, this routine builds for loops to copy them.
9649 ///
9650 /// \param S The Sema object used for type-checking.
9651 ///
9652 /// \param Loc The location where the implicit copy/move is being generated.
9653 ///
9654 /// \param T The type of the expressions being copied/moved. Both expressions
9655 /// must have this type.
9656 ///
9657 /// \param To The expression we are copying/moving to.
9658 ///
9659 /// \param From The expression we are copying/moving from.
9660 ///
9661 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9662 /// Otherwise, it's a non-static member subobject.
9663 ///
9664 /// \param Copying Whether we're copying or moving.
9665 ///
9666 /// \param Depth Internal parameter recording the depth of the recursion.
9667 ///
9668 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9669 /// if a memcpy should be used instead.
9670 static StmtResult
9671 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9672                                  const ExprBuilder &To, const ExprBuilder &From,
9673                                  bool CopyingBaseSubobject, bool Copying,
9674                                  unsigned Depth = 0) {
9675   // C++11 [class.copy]p28:
9676   //   Each subobject is assigned in the manner appropriate to its type:
9677   //
9678   //     - if the subobject is of class type, as if by a call to operator= with
9679   //       the subobject as the object expression and the corresponding
9680   //       subobject of x as a single function argument (as if by explicit
9681   //       qualification; that is, ignoring any possible virtual overriding
9682   //       functions in more derived classes);
9683   //
9684   // C++03 [class.copy]p13:
9685   //     - if the subobject is of class type, the copy assignment operator for
9686   //       the class is used (as if by explicit qualification; that is,
9687   //       ignoring any possible virtual overriding functions in more derived
9688   //       classes);
9689   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9690     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9691 
9692     // Look for operator=.
9693     DeclarationName Name
9694       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9695     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9696     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9697 
9698     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9699     // operator.
9700     if (!S.getLangOpts().CPlusPlus11) {
9701       LookupResult::Filter F = OpLookup.makeFilter();
9702       while (F.hasNext()) {
9703         NamedDecl *D = F.next();
9704         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9705           if (Method->isCopyAssignmentOperator() ||
9706               (!Copying && Method->isMoveAssignmentOperator()))
9707             continue;
9708 
9709         F.erase();
9710       }
9711       F.done();
9712     }
9713 
9714     // Suppress the protected check (C++ [class.protected]) for each of the
9715     // assignment operators we found. This strange dance is required when
9716     // we're assigning via a base classes's copy-assignment operator. To
9717     // ensure that we're getting the right base class subobject (without
9718     // ambiguities), we need to cast "this" to that subobject type; to
9719     // ensure that we don't go through the virtual call mechanism, we need
9720     // to qualify the operator= name with the base class (see below). However,
9721     // this means that if the base class has a protected copy assignment
9722     // operator, the protected member access check will fail. So, we
9723     // rewrite "protected" access to "public" access in this case, since we
9724     // know by construction that we're calling from a derived class.
9725     if (CopyingBaseSubobject) {
9726       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9727            L != LEnd; ++L) {
9728         if (L.getAccess() == AS_protected)
9729           L.setAccess(AS_public);
9730       }
9731     }
9732 
9733     // Create the nested-name-specifier that will be used to qualify the
9734     // reference to operator=; this is required to suppress the virtual
9735     // call mechanism.
9736     CXXScopeSpec SS;
9737     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9738     SS.MakeTrivial(S.Context,
9739                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9740                                                CanonicalT),
9741                    Loc);
9742 
9743     // Create the reference to operator=.
9744     ExprResult OpEqualRef
9745       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9746                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9747                                    /*FirstQualifierInScope=*/nullptr,
9748                                    OpLookup,
9749                                    /*TemplateArgs=*/nullptr,
9750                                    /*SuppressQualifierCheck=*/true);
9751     if (OpEqualRef.isInvalid())
9752       return StmtError();
9753 
9754     // Build the call to the assignment operator.
9755 
9756     Expr *FromInst = From.build(S, Loc);
9757     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9758                                                   OpEqualRef.getAs<Expr>(),
9759                                                   Loc, FromInst, Loc);
9760     if (Call.isInvalid())
9761       return StmtError();
9762 
9763     // If we built a call to a trivial 'operator=' while copying an array,
9764     // bail out. We'll replace the whole shebang with a memcpy.
9765     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9766     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9767       return StmtResult((Stmt*)nullptr);
9768 
9769     // Convert to an expression-statement, and clean up any produced
9770     // temporaries.
9771     return S.ActOnExprStmt(Call);
9772   }
9773 
9774   //     - if the subobject is of scalar type, the built-in assignment
9775   //       operator is used.
9776   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9777   if (!ArrayTy) {
9778     ExprResult Assignment = S.CreateBuiltinBinOp(
9779         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9780     if (Assignment.isInvalid())
9781       return StmtError();
9782     return S.ActOnExprStmt(Assignment);
9783   }
9784 
9785   //     - if the subobject is an array, each element is assigned, in the
9786   //       manner appropriate to the element type;
9787 
9788   // Construct a loop over the array bounds, e.g.,
9789   //
9790   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9791   //
9792   // that will copy each of the array elements.
9793   QualType SizeType = S.Context.getSizeType();
9794 
9795   // Create the iteration variable.
9796   IdentifierInfo *IterationVarName = nullptr;
9797   {
9798     SmallString<8> Str;
9799     llvm::raw_svector_ostream OS(Str);
9800     OS << "__i" << Depth;
9801     IterationVarName = &S.Context.Idents.get(OS.str());
9802   }
9803   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9804                                           IterationVarName, SizeType,
9805                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9806                                           SC_None);
9807 
9808   // Initialize the iteration variable to zero.
9809   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9810   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9811 
9812   // Creates a reference to the iteration variable.
9813   RefBuilder IterationVarRef(IterationVar, SizeType);
9814   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9815 
9816   // Create the DeclStmt that holds the iteration variable.
9817   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9818 
9819   // Subscript the "from" and "to" expressions with the iteration variable.
9820   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9821   MoveCastBuilder FromIndexMove(FromIndexCopy);
9822   const ExprBuilder *FromIndex;
9823   if (Copying)
9824     FromIndex = &FromIndexCopy;
9825   else
9826     FromIndex = &FromIndexMove;
9827 
9828   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9829 
9830   // Build the copy/move for an individual element of the array.
9831   StmtResult Copy =
9832     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9833                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9834                                      Copying, Depth + 1);
9835   // Bail out if copying fails or if we determined that we should use memcpy.
9836   if (Copy.isInvalid() || !Copy.get())
9837     return Copy;
9838 
9839   // Create the comparison against the array bound.
9840   llvm::APInt Upper
9841     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9842   Expr *Comparison
9843     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9844                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9845                                      BO_NE, S.Context.BoolTy,
9846                                      VK_RValue, OK_Ordinary, Loc, false);
9847 
9848   // Create the pre-increment of the iteration variable.
9849   Expr *Increment
9850     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9851                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9852 
9853   // Construct the loop that copies all elements of this array.
9854   return S.ActOnForStmt(Loc, Loc, InitStmt,
9855                         S.MakeFullExpr(Comparison),
9856                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9857                         Loc, Copy.get());
9858 }
9859 
9860 static StmtResult
9861 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9862                       const ExprBuilder &To, const ExprBuilder &From,
9863                       bool CopyingBaseSubobject, bool Copying) {
9864   // Maybe we should use a memcpy?
9865   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9866       T.isTriviallyCopyableType(S.Context))
9867     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9868 
9869   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9870                                                      CopyingBaseSubobject,
9871                                                      Copying, 0));
9872 
9873   // If we ended up picking a trivial assignment operator for an array of a
9874   // non-trivially-copyable class type, just emit a memcpy.
9875   if (!Result.isInvalid() && !Result.get())
9876     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9877 
9878   return Result;
9879 }
9880 
9881 Sema::ImplicitExceptionSpecification
9882 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9883   CXXRecordDecl *ClassDecl = MD->getParent();
9884 
9885   ImplicitExceptionSpecification ExceptSpec(*this);
9886   if (ClassDecl->isInvalidDecl())
9887     return ExceptSpec;
9888 
9889   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9890   assert(T->getNumParams() == 1 && "not a copy assignment op");
9891   unsigned ArgQuals =
9892       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9893 
9894   // C++ [except.spec]p14:
9895   //   An implicitly declared special member function (Clause 12) shall have an
9896   //   exception-specification. [...]
9897 
9898   // It is unspecified whether or not an implicit copy assignment operator
9899   // attempts to deduplicate calls to assignment operators of virtual bases are
9900   // made. As such, this exception specification is effectively unspecified.
9901   // Based on a similar decision made for constness in C++0x, we're erring on
9902   // the side of assuming such calls to be made regardless of whether they
9903   // actually happen.
9904   for (const auto &Base : ClassDecl->bases()) {
9905     if (Base.isVirtual())
9906       continue;
9907 
9908     CXXRecordDecl *BaseClassDecl
9909       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9910     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9911                                                             ArgQuals, false, 0))
9912       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9913   }
9914 
9915   for (const auto &Base : ClassDecl->vbases()) {
9916     CXXRecordDecl *BaseClassDecl
9917       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9918     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9919                                                             ArgQuals, false, 0))
9920       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9921   }
9922 
9923   for (const auto *Field : ClassDecl->fields()) {
9924     QualType FieldType = Context.getBaseElementType(Field->getType());
9925     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9926       if (CXXMethodDecl *CopyAssign =
9927           LookupCopyingAssignment(FieldClassDecl,
9928                                   ArgQuals | FieldType.getCVRQualifiers(),
9929                                   false, 0))
9930         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9931     }
9932   }
9933 
9934   return ExceptSpec;
9935 }
9936 
9937 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9938   // Note: The following rules are largely analoguous to the copy
9939   // constructor rules. Note that virtual bases are not taken into account
9940   // for determining the argument type of the operator. Note also that
9941   // operators taking an object instead of a reference are allowed.
9942   assert(ClassDecl->needsImplicitCopyAssignment());
9943 
9944   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9945   if (DSM.isAlreadyBeingDeclared())
9946     return nullptr;
9947 
9948   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9949   QualType RetType = Context.getLValueReferenceType(ArgType);
9950   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9951   if (Const)
9952     ArgType = ArgType.withConst();
9953   ArgType = Context.getLValueReferenceType(ArgType);
9954 
9955   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9956                                                      CXXCopyAssignment,
9957                                                      Const);
9958 
9959   //   An implicitly-declared copy assignment operator is an inline public
9960   //   member of its class.
9961   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9962   SourceLocation ClassLoc = ClassDecl->getLocation();
9963   DeclarationNameInfo NameInfo(Name, ClassLoc);
9964   CXXMethodDecl *CopyAssignment =
9965       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9966                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9967                             /*isInline=*/true, Constexpr, SourceLocation());
9968   CopyAssignment->setAccess(AS_public);
9969   CopyAssignment->setDefaulted();
9970   CopyAssignment->setImplicit();
9971 
9972   if (getLangOpts().CUDA) {
9973     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
9974                                             CopyAssignment,
9975                                             /* ConstRHS */ Const,
9976                                             /* Diagnose */ false);
9977   }
9978 
9979   // Build an exception specification pointing back at this member.
9980   FunctionProtoType::ExtProtoInfo EPI =
9981       getImplicitMethodEPI(*this, CopyAssignment);
9982   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9983 
9984   // Add the parameter to the operator.
9985   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9986                                                ClassLoc, ClassLoc,
9987                                                /*Id=*/nullptr, ArgType,
9988                                                /*TInfo=*/nullptr, SC_None,
9989                                                nullptr);
9990   CopyAssignment->setParams(FromParam);
9991 
9992   AddOverriddenMethods(ClassDecl, CopyAssignment);
9993 
9994   CopyAssignment->setTrivial(
9995     ClassDecl->needsOverloadResolutionForCopyAssignment()
9996       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9997       : ClassDecl->hasTrivialCopyAssignment());
9998 
9999   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10000     SetDeclDeleted(CopyAssignment, ClassLoc);
10001 
10002   // Note that we have added this copy-assignment operator.
10003   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10004 
10005   if (Scope *S = getScopeForContext(ClassDecl))
10006     PushOnScopeChains(CopyAssignment, S, false);
10007   ClassDecl->addDecl(CopyAssignment);
10008 
10009   return CopyAssignment;
10010 }
10011 
10012 /// Diagnose an implicit copy operation for a class which is odr-used, but
10013 /// which is deprecated because the class has a user-declared copy constructor,
10014 /// copy assignment operator, or destructor.
10015 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10016                                             SourceLocation UseLoc) {
10017   assert(CopyOp->isImplicit());
10018 
10019   CXXRecordDecl *RD = CopyOp->getParent();
10020   CXXMethodDecl *UserDeclaredOperation = nullptr;
10021 
10022   // In Microsoft mode, assignment operations don't affect constructors and
10023   // vice versa.
10024   if (RD->hasUserDeclaredDestructor()) {
10025     UserDeclaredOperation = RD->getDestructor();
10026   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10027              RD->hasUserDeclaredCopyConstructor() &&
10028              !S.getLangOpts().MSVCCompat) {
10029     // Find any user-declared copy constructor.
10030     for (auto *I : RD->ctors()) {
10031       if (I->isCopyConstructor()) {
10032         UserDeclaredOperation = I;
10033         break;
10034       }
10035     }
10036     assert(UserDeclaredOperation);
10037   } else if (isa<CXXConstructorDecl>(CopyOp) &&
10038              RD->hasUserDeclaredCopyAssignment() &&
10039              !S.getLangOpts().MSVCCompat) {
10040     // Find any user-declared move assignment operator.
10041     for (auto *I : RD->methods()) {
10042       if (I->isCopyAssignmentOperator()) {
10043         UserDeclaredOperation = I;
10044         break;
10045       }
10046     }
10047     assert(UserDeclaredOperation);
10048   }
10049 
10050   if (UserDeclaredOperation) {
10051     S.Diag(UserDeclaredOperation->getLocation(),
10052          diag::warn_deprecated_copy_operation)
10053       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10054       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10055     S.Diag(UseLoc, diag::note_member_synthesized_at)
10056       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10057                                           : Sema::CXXCopyAssignment)
10058       << RD;
10059   }
10060 }
10061 
10062 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10063                                         CXXMethodDecl *CopyAssignOperator) {
10064   assert((CopyAssignOperator->isDefaulted() &&
10065           CopyAssignOperator->isOverloadedOperator() &&
10066           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10067           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10068           !CopyAssignOperator->isDeleted()) &&
10069          "DefineImplicitCopyAssignment called for wrong function");
10070 
10071   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10072 
10073   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10074     CopyAssignOperator->setInvalidDecl();
10075     return;
10076   }
10077 
10078   // C++11 [class.copy]p18:
10079   //   The [definition of an implicitly declared copy assignment operator] is
10080   //   deprecated if the class has a user-declared copy constructor or a
10081   //   user-declared destructor.
10082   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10083     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10084 
10085   CopyAssignOperator->markUsed(Context);
10086 
10087   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10088   DiagnosticErrorTrap Trap(Diags);
10089 
10090   // C++0x [class.copy]p30:
10091   //   The implicitly-defined or explicitly-defaulted copy assignment operator
10092   //   for a non-union class X performs memberwise copy assignment of its
10093   //   subobjects. The direct base classes of X are assigned first, in the
10094   //   order of their declaration in the base-specifier-list, and then the
10095   //   immediate non-static data members of X are assigned, in the order in
10096   //   which they were declared in the class definition.
10097 
10098   // The statements that form the synthesized function body.
10099   SmallVector<Stmt*, 8> Statements;
10100 
10101   // The parameter for the "other" object, which we are copying from.
10102   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10103   Qualifiers OtherQuals = Other->getType().getQualifiers();
10104   QualType OtherRefType = Other->getType();
10105   if (const LValueReferenceType *OtherRef
10106                                 = OtherRefType->getAs<LValueReferenceType>()) {
10107     OtherRefType = OtherRef->getPointeeType();
10108     OtherQuals = OtherRefType.getQualifiers();
10109   }
10110 
10111   // Our location for everything implicitly-generated.
10112   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10113                            ? CopyAssignOperator->getLocEnd()
10114                            : CopyAssignOperator->getLocation();
10115 
10116   // Builds a DeclRefExpr for the "other" object.
10117   RefBuilder OtherRef(Other, OtherRefType);
10118 
10119   // Builds the "this" pointer.
10120   ThisBuilder This;
10121 
10122   // Assign base classes.
10123   bool Invalid = false;
10124   for (auto &Base : ClassDecl->bases()) {
10125     // Form the assignment:
10126     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10127     QualType BaseType = Base.getType().getUnqualifiedType();
10128     if (!BaseType->isRecordType()) {
10129       Invalid = true;
10130       continue;
10131     }
10132 
10133     CXXCastPath BasePath;
10134     BasePath.push_back(&Base);
10135 
10136     // Construct the "from" expression, which is an implicit cast to the
10137     // appropriately-qualified base type.
10138     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10139                      VK_LValue, BasePath);
10140 
10141     // Dereference "this".
10142     DerefBuilder DerefThis(This);
10143     CastBuilder To(DerefThis,
10144                    Context.getCVRQualifiedType(
10145                        BaseType, CopyAssignOperator->getTypeQualifiers()),
10146                    VK_LValue, BasePath);
10147 
10148     // Build the copy.
10149     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10150                                             To, From,
10151                                             /*CopyingBaseSubobject=*/true,
10152                                             /*Copying=*/true);
10153     if (Copy.isInvalid()) {
10154       Diag(CurrentLocation, diag::note_member_synthesized_at)
10155         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10156       CopyAssignOperator->setInvalidDecl();
10157       return;
10158     }
10159 
10160     // Success! Record the copy.
10161     Statements.push_back(Copy.getAs<Expr>());
10162   }
10163 
10164   // Assign non-static members.
10165   for (auto *Field : ClassDecl->fields()) {
10166     if (Field->isUnnamedBitfield())
10167       continue;
10168 
10169     if (Field->isInvalidDecl()) {
10170       Invalid = true;
10171       continue;
10172     }
10173 
10174     // Check for members of reference type; we can't copy those.
10175     if (Field->getType()->isReferenceType()) {
10176       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10177         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10178       Diag(Field->getLocation(), diag::note_declared_at);
10179       Diag(CurrentLocation, diag::note_member_synthesized_at)
10180         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10181       Invalid = true;
10182       continue;
10183     }
10184 
10185     // Check for members of const-qualified, non-class type.
10186     QualType BaseType = Context.getBaseElementType(Field->getType());
10187     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10188       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10189         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10190       Diag(Field->getLocation(), diag::note_declared_at);
10191       Diag(CurrentLocation, diag::note_member_synthesized_at)
10192         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10193       Invalid = true;
10194       continue;
10195     }
10196 
10197     // Suppress assigning zero-width bitfields.
10198     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10199       continue;
10200 
10201     QualType FieldType = Field->getType().getNonReferenceType();
10202     if (FieldType->isIncompleteArrayType()) {
10203       assert(ClassDecl->hasFlexibleArrayMember() &&
10204              "Incomplete array type is not valid");
10205       continue;
10206     }
10207 
10208     // Build references to the field in the object we're copying from and to.
10209     CXXScopeSpec SS; // Intentionally empty
10210     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10211                               LookupMemberName);
10212     MemberLookup.addDecl(Field);
10213     MemberLookup.resolveKind();
10214 
10215     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10216 
10217     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10218 
10219     // Build the copy of this field.
10220     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10221                                             To, From,
10222                                             /*CopyingBaseSubobject=*/false,
10223                                             /*Copying=*/true);
10224     if (Copy.isInvalid()) {
10225       Diag(CurrentLocation, diag::note_member_synthesized_at)
10226         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10227       CopyAssignOperator->setInvalidDecl();
10228       return;
10229     }
10230 
10231     // Success! Record the copy.
10232     Statements.push_back(Copy.getAs<Stmt>());
10233   }
10234 
10235   if (!Invalid) {
10236     // Add a "return *this;"
10237     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10238 
10239     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10240     if (Return.isInvalid())
10241       Invalid = true;
10242     else {
10243       Statements.push_back(Return.getAs<Stmt>());
10244 
10245       if (Trap.hasErrorOccurred()) {
10246         Diag(CurrentLocation, diag::note_member_synthesized_at)
10247           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10248         Invalid = true;
10249       }
10250     }
10251   }
10252 
10253   // The exception specification is needed because we are defining the
10254   // function.
10255   ResolveExceptionSpec(CurrentLocation,
10256                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10257 
10258   if (Invalid) {
10259     CopyAssignOperator->setInvalidDecl();
10260     return;
10261   }
10262 
10263   StmtResult Body;
10264   {
10265     CompoundScopeRAII CompoundScope(*this);
10266     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10267                              /*isStmtExpr=*/false);
10268     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10269   }
10270   CopyAssignOperator->setBody(Body.getAs<Stmt>());
10271 
10272   if (ASTMutationListener *L = getASTMutationListener()) {
10273     L->CompletedImplicitDefinition(CopyAssignOperator);
10274   }
10275 }
10276 
10277 Sema::ImplicitExceptionSpecification
10278 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10279   CXXRecordDecl *ClassDecl = MD->getParent();
10280 
10281   ImplicitExceptionSpecification ExceptSpec(*this);
10282   if (ClassDecl->isInvalidDecl())
10283     return ExceptSpec;
10284 
10285   // C++0x [except.spec]p14:
10286   //   An implicitly declared special member function (Clause 12) shall have an
10287   //   exception-specification. [...]
10288 
10289   // It is unspecified whether or not an implicit move assignment operator
10290   // attempts to deduplicate calls to assignment operators of virtual bases are
10291   // made. As such, this exception specification is effectively unspecified.
10292   // Based on a similar decision made for constness in C++0x, we're erring on
10293   // the side of assuming such calls to be made regardless of whether they
10294   // actually happen.
10295   // Note that a move constructor is not implicitly declared when there are
10296   // virtual bases, but it can still be user-declared and explicitly defaulted.
10297   for (const auto &Base : ClassDecl->bases()) {
10298     if (Base.isVirtual())
10299       continue;
10300 
10301     CXXRecordDecl *BaseClassDecl
10302       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10303     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10304                                                            0, false, 0))
10305       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10306   }
10307 
10308   for (const auto &Base : ClassDecl->vbases()) {
10309     CXXRecordDecl *BaseClassDecl
10310       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10311     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10312                                                            0, false, 0))
10313       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10314   }
10315 
10316   for (const auto *Field : ClassDecl->fields()) {
10317     QualType FieldType = Context.getBaseElementType(Field->getType());
10318     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10319       if (CXXMethodDecl *MoveAssign =
10320               LookupMovingAssignment(FieldClassDecl,
10321                                      FieldType.getCVRQualifiers(),
10322                                      false, 0))
10323         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10324     }
10325   }
10326 
10327   return ExceptSpec;
10328 }
10329 
10330 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10331   assert(ClassDecl->needsImplicitMoveAssignment());
10332 
10333   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10334   if (DSM.isAlreadyBeingDeclared())
10335     return nullptr;
10336 
10337   // Note: The following rules are largely analoguous to the move
10338   // constructor rules.
10339 
10340   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10341   QualType RetType = Context.getLValueReferenceType(ArgType);
10342   ArgType = Context.getRValueReferenceType(ArgType);
10343 
10344   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10345                                                      CXXMoveAssignment,
10346                                                      false);
10347 
10348   //   An implicitly-declared move assignment operator is an inline public
10349   //   member of its class.
10350   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10351   SourceLocation ClassLoc = ClassDecl->getLocation();
10352   DeclarationNameInfo NameInfo(Name, ClassLoc);
10353   CXXMethodDecl *MoveAssignment =
10354       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10355                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10356                             /*isInline=*/true, Constexpr, SourceLocation());
10357   MoveAssignment->setAccess(AS_public);
10358   MoveAssignment->setDefaulted();
10359   MoveAssignment->setImplicit();
10360 
10361   if (getLangOpts().CUDA) {
10362     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10363                                             MoveAssignment,
10364                                             /* ConstRHS */ false,
10365                                             /* Diagnose */ false);
10366   }
10367 
10368   // Build an exception specification pointing back at this member.
10369   FunctionProtoType::ExtProtoInfo EPI =
10370       getImplicitMethodEPI(*this, MoveAssignment);
10371   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10372 
10373   // Add the parameter to the operator.
10374   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10375                                                ClassLoc, ClassLoc,
10376                                                /*Id=*/nullptr, ArgType,
10377                                                /*TInfo=*/nullptr, SC_None,
10378                                                nullptr);
10379   MoveAssignment->setParams(FromParam);
10380 
10381   AddOverriddenMethods(ClassDecl, MoveAssignment);
10382 
10383   MoveAssignment->setTrivial(
10384     ClassDecl->needsOverloadResolutionForMoveAssignment()
10385       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10386       : ClassDecl->hasTrivialMoveAssignment());
10387 
10388   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10389     ClassDecl->setImplicitMoveAssignmentIsDeleted();
10390     SetDeclDeleted(MoveAssignment, ClassLoc);
10391   }
10392 
10393   // Note that we have added this copy-assignment operator.
10394   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10395 
10396   if (Scope *S = getScopeForContext(ClassDecl))
10397     PushOnScopeChains(MoveAssignment, S, false);
10398   ClassDecl->addDecl(MoveAssignment);
10399 
10400   return MoveAssignment;
10401 }
10402 
10403 /// Check if we're implicitly defining a move assignment operator for a class
10404 /// with virtual bases. Such a move assignment might move-assign the virtual
10405 /// base multiple times.
10406 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10407                                                SourceLocation CurrentLocation) {
10408   assert(!Class->isDependentContext() && "should not define dependent move");
10409 
10410   // Only a virtual base could get implicitly move-assigned multiple times.
10411   // Only a non-trivial move assignment can observe this. We only want to
10412   // diagnose if we implicitly define an assignment operator that assigns
10413   // two base classes, both of which move-assign the same virtual base.
10414   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10415       Class->getNumBases() < 2)
10416     return;
10417 
10418   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10419   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10420   VBaseMap VBases;
10421 
10422   for (auto &BI : Class->bases()) {
10423     Worklist.push_back(&BI);
10424     while (!Worklist.empty()) {
10425       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10426       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10427 
10428       // If the base has no non-trivial move assignment operators,
10429       // we don't care about moves from it.
10430       if (!Base->hasNonTrivialMoveAssignment())
10431         continue;
10432 
10433       // If there's nothing virtual here, skip it.
10434       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10435         continue;
10436 
10437       // If we're not actually going to call a move assignment for this base,
10438       // or the selected move assignment is trivial, skip it.
10439       Sema::SpecialMemberOverloadResult *SMOR =
10440         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10441                               /*ConstArg*/false, /*VolatileArg*/false,
10442                               /*RValueThis*/true, /*ConstThis*/false,
10443                               /*VolatileThis*/false);
10444       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10445           !SMOR->getMethod()->isMoveAssignmentOperator())
10446         continue;
10447 
10448       if (BaseSpec->isVirtual()) {
10449         // We're going to move-assign this virtual base, and its move
10450         // assignment operator is not trivial. If this can happen for
10451         // multiple distinct direct bases of Class, diagnose it. (If it
10452         // only happens in one base, we'll diagnose it when synthesizing
10453         // that base class's move assignment operator.)
10454         CXXBaseSpecifier *&Existing =
10455             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10456                 .first->second;
10457         if (Existing && Existing != &BI) {
10458           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10459             << Class << Base;
10460           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10461             << (Base->getCanonicalDecl() ==
10462                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10463             << Base << Existing->getType() << Existing->getSourceRange();
10464           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10465             << (Base->getCanonicalDecl() ==
10466                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10467             << Base << BI.getType() << BaseSpec->getSourceRange();
10468 
10469           // Only diagnose each vbase once.
10470           Existing = nullptr;
10471         }
10472       } else {
10473         // Only walk over bases that have defaulted move assignment operators.
10474         // We assume that any user-provided move assignment operator handles
10475         // the multiple-moves-of-vbase case itself somehow.
10476         if (!SMOR->getMethod()->isDefaulted())
10477           continue;
10478 
10479         // We're going to move the base classes of Base. Add them to the list.
10480         for (auto &BI : Base->bases())
10481           Worklist.push_back(&BI);
10482       }
10483     }
10484   }
10485 }
10486 
10487 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10488                                         CXXMethodDecl *MoveAssignOperator) {
10489   assert((MoveAssignOperator->isDefaulted() &&
10490           MoveAssignOperator->isOverloadedOperator() &&
10491           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10492           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10493           !MoveAssignOperator->isDeleted()) &&
10494          "DefineImplicitMoveAssignment called for wrong function");
10495 
10496   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10497 
10498   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10499     MoveAssignOperator->setInvalidDecl();
10500     return;
10501   }
10502 
10503   MoveAssignOperator->markUsed(Context);
10504 
10505   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10506   DiagnosticErrorTrap Trap(Diags);
10507 
10508   // C++0x [class.copy]p28:
10509   //   The implicitly-defined or move assignment operator for a non-union class
10510   //   X performs memberwise move assignment of its subobjects. The direct base
10511   //   classes of X are assigned first, in the order of their declaration in the
10512   //   base-specifier-list, and then the immediate non-static data members of X
10513   //   are assigned, in the order in which they were declared in the class
10514   //   definition.
10515 
10516   // Issue a warning if our implicit move assignment operator will move
10517   // from a virtual base more than once.
10518   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10519 
10520   // The statements that form the synthesized function body.
10521   SmallVector<Stmt*, 8> Statements;
10522 
10523   // The parameter for the "other" object, which we are move from.
10524   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10525   QualType OtherRefType = Other->getType()->
10526       getAs<RValueReferenceType>()->getPointeeType();
10527   assert(!OtherRefType.getQualifiers() &&
10528          "Bad argument type of defaulted move assignment");
10529 
10530   // Our location for everything implicitly-generated.
10531   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10532                            ? MoveAssignOperator->getLocEnd()
10533                            : MoveAssignOperator->getLocation();
10534 
10535   // Builds a reference to the "other" object.
10536   RefBuilder OtherRef(Other, OtherRefType);
10537   // Cast to rvalue.
10538   MoveCastBuilder MoveOther(OtherRef);
10539 
10540   // Builds the "this" pointer.
10541   ThisBuilder This;
10542 
10543   // Assign base classes.
10544   bool Invalid = false;
10545   for (auto &Base : ClassDecl->bases()) {
10546     // C++11 [class.copy]p28:
10547     //   It is unspecified whether subobjects representing virtual base classes
10548     //   are assigned more than once by the implicitly-defined copy assignment
10549     //   operator.
10550     // FIXME: Do not assign to a vbase that will be assigned by some other base
10551     // class. For a move-assignment, this can result in the vbase being moved
10552     // multiple times.
10553 
10554     // Form the assignment:
10555     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10556     QualType BaseType = Base.getType().getUnqualifiedType();
10557     if (!BaseType->isRecordType()) {
10558       Invalid = true;
10559       continue;
10560     }
10561 
10562     CXXCastPath BasePath;
10563     BasePath.push_back(&Base);
10564 
10565     // Construct the "from" expression, which is an implicit cast to the
10566     // appropriately-qualified base type.
10567     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10568 
10569     // Dereference "this".
10570     DerefBuilder DerefThis(This);
10571 
10572     // Implicitly cast "this" to the appropriately-qualified base type.
10573     CastBuilder To(DerefThis,
10574                    Context.getCVRQualifiedType(
10575                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10576                    VK_LValue, BasePath);
10577 
10578     // Build the move.
10579     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10580                                             To, From,
10581                                             /*CopyingBaseSubobject=*/true,
10582                                             /*Copying=*/false);
10583     if (Move.isInvalid()) {
10584       Diag(CurrentLocation, diag::note_member_synthesized_at)
10585         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10586       MoveAssignOperator->setInvalidDecl();
10587       return;
10588     }
10589 
10590     // Success! Record the move.
10591     Statements.push_back(Move.getAs<Expr>());
10592   }
10593 
10594   // Assign non-static members.
10595   for (auto *Field : ClassDecl->fields()) {
10596     if (Field->isUnnamedBitfield())
10597       continue;
10598 
10599     if (Field->isInvalidDecl()) {
10600       Invalid = true;
10601       continue;
10602     }
10603 
10604     // Check for members of reference type; we can't move those.
10605     if (Field->getType()->isReferenceType()) {
10606       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10607         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10608       Diag(Field->getLocation(), diag::note_declared_at);
10609       Diag(CurrentLocation, diag::note_member_synthesized_at)
10610         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10611       Invalid = true;
10612       continue;
10613     }
10614 
10615     // Check for members of const-qualified, non-class type.
10616     QualType BaseType = Context.getBaseElementType(Field->getType());
10617     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10618       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10619         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10620       Diag(Field->getLocation(), diag::note_declared_at);
10621       Diag(CurrentLocation, diag::note_member_synthesized_at)
10622         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10623       Invalid = true;
10624       continue;
10625     }
10626 
10627     // Suppress assigning zero-width bitfields.
10628     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10629       continue;
10630 
10631     QualType FieldType = Field->getType().getNonReferenceType();
10632     if (FieldType->isIncompleteArrayType()) {
10633       assert(ClassDecl->hasFlexibleArrayMember() &&
10634              "Incomplete array type is not valid");
10635       continue;
10636     }
10637 
10638     // Build references to the field in the object we're copying from and to.
10639     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10640                               LookupMemberName);
10641     MemberLookup.addDecl(Field);
10642     MemberLookup.resolveKind();
10643     MemberBuilder From(MoveOther, OtherRefType,
10644                        /*IsArrow=*/false, MemberLookup);
10645     MemberBuilder To(This, getCurrentThisType(),
10646                      /*IsArrow=*/true, MemberLookup);
10647 
10648     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10649         "Member reference with rvalue base must be rvalue except for reference "
10650         "members, which aren't allowed for move assignment.");
10651 
10652     // Build the move of this field.
10653     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10654                                             To, From,
10655                                             /*CopyingBaseSubobject=*/false,
10656                                             /*Copying=*/false);
10657     if (Move.isInvalid()) {
10658       Diag(CurrentLocation, diag::note_member_synthesized_at)
10659         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10660       MoveAssignOperator->setInvalidDecl();
10661       return;
10662     }
10663 
10664     // Success! Record the copy.
10665     Statements.push_back(Move.getAs<Stmt>());
10666   }
10667 
10668   if (!Invalid) {
10669     // Add a "return *this;"
10670     ExprResult ThisObj =
10671         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10672 
10673     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10674     if (Return.isInvalid())
10675       Invalid = true;
10676     else {
10677       Statements.push_back(Return.getAs<Stmt>());
10678 
10679       if (Trap.hasErrorOccurred()) {
10680         Diag(CurrentLocation, diag::note_member_synthesized_at)
10681           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10682         Invalid = true;
10683       }
10684     }
10685   }
10686 
10687   // The exception specification is needed because we are defining the
10688   // function.
10689   ResolveExceptionSpec(CurrentLocation,
10690                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10691 
10692   if (Invalid) {
10693     MoveAssignOperator->setInvalidDecl();
10694     return;
10695   }
10696 
10697   StmtResult Body;
10698   {
10699     CompoundScopeRAII CompoundScope(*this);
10700     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10701                              /*isStmtExpr=*/false);
10702     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10703   }
10704   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10705 
10706   if (ASTMutationListener *L = getASTMutationListener()) {
10707     L->CompletedImplicitDefinition(MoveAssignOperator);
10708   }
10709 }
10710 
10711 Sema::ImplicitExceptionSpecification
10712 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10713   CXXRecordDecl *ClassDecl = MD->getParent();
10714 
10715   ImplicitExceptionSpecification ExceptSpec(*this);
10716   if (ClassDecl->isInvalidDecl())
10717     return ExceptSpec;
10718 
10719   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10720   assert(T->getNumParams() >= 1 && "not a copy ctor");
10721   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10722 
10723   // C++ [except.spec]p14:
10724   //   An implicitly declared special member function (Clause 12) shall have an
10725   //   exception-specification. [...]
10726   for (const auto &Base : ClassDecl->bases()) {
10727     // Virtual bases are handled below.
10728     if (Base.isVirtual())
10729       continue;
10730 
10731     CXXRecordDecl *BaseClassDecl
10732       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10733     if (CXXConstructorDecl *CopyConstructor =
10734           LookupCopyingConstructor(BaseClassDecl, Quals))
10735       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10736   }
10737   for (const auto &Base : ClassDecl->vbases()) {
10738     CXXRecordDecl *BaseClassDecl
10739       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10740     if (CXXConstructorDecl *CopyConstructor =
10741           LookupCopyingConstructor(BaseClassDecl, Quals))
10742       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10743   }
10744   for (const auto *Field : ClassDecl->fields()) {
10745     QualType FieldType = Context.getBaseElementType(Field->getType());
10746     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10747       if (CXXConstructorDecl *CopyConstructor =
10748               LookupCopyingConstructor(FieldClassDecl,
10749                                        Quals | FieldType.getCVRQualifiers()))
10750       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10751     }
10752   }
10753 
10754   return ExceptSpec;
10755 }
10756 
10757 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10758                                                     CXXRecordDecl *ClassDecl) {
10759   // C++ [class.copy]p4:
10760   //   If the class definition does not explicitly declare a copy
10761   //   constructor, one is declared implicitly.
10762   assert(ClassDecl->needsImplicitCopyConstructor());
10763 
10764   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10765   if (DSM.isAlreadyBeingDeclared())
10766     return nullptr;
10767 
10768   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10769   QualType ArgType = ClassType;
10770   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10771   if (Const)
10772     ArgType = ArgType.withConst();
10773   ArgType = Context.getLValueReferenceType(ArgType);
10774 
10775   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10776                                                      CXXCopyConstructor,
10777                                                      Const);
10778 
10779   DeclarationName Name
10780     = Context.DeclarationNames.getCXXConstructorName(
10781                                            Context.getCanonicalType(ClassType));
10782   SourceLocation ClassLoc = ClassDecl->getLocation();
10783   DeclarationNameInfo NameInfo(Name, ClassLoc);
10784 
10785   //   An implicitly-declared copy constructor is an inline public
10786   //   member of its class.
10787   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10788       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10789       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10790       Constexpr);
10791   CopyConstructor->setAccess(AS_public);
10792   CopyConstructor->setDefaulted();
10793 
10794   if (getLangOpts().CUDA) {
10795     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10796                                             CopyConstructor,
10797                                             /* ConstRHS */ Const,
10798                                             /* Diagnose */ false);
10799   }
10800 
10801   // Build an exception specification pointing back at this member.
10802   FunctionProtoType::ExtProtoInfo EPI =
10803       getImplicitMethodEPI(*this, CopyConstructor);
10804   CopyConstructor->setType(
10805       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10806 
10807   // Add the parameter to the constructor.
10808   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10809                                                ClassLoc, ClassLoc,
10810                                                /*IdentifierInfo=*/nullptr,
10811                                                ArgType, /*TInfo=*/nullptr,
10812                                                SC_None, nullptr);
10813   CopyConstructor->setParams(FromParam);
10814 
10815   CopyConstructor->setTrivial(
10816     ClassDecl->needsOverloadResolutionForCopyConstructor()
10817       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10818       : ClassDecl->hasTrivialCopyConstructor());
10819 
10820   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10821     SetDeclDeleted(CopyConstructor, ClassLoc);
10822 
10823   // Note that we have declared this constructor.
10824   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10825 
10826   if (Scope *S = getScopeForContext(ClassDecl))
10827     PushOnScopeChains(CopyConstructor, S, false);
10828   ClassDecl->addDecl(CopyConstructor);
10829 
10830   return CopyConstructor;
10831 }
10832 
10833 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10834                                    CXXConstructorDecl *CopyConstructor) {
10835   assert((CopyConstructor->isDefaulted() &&
10836           CopyConstructor->isCopyConstructor() &&
10837           !CopyConstructor->doesThisDeclarationHaveABody() &&
10838           !CopyConstructor->isDeleted()) &&
10839          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10840 
10841   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10842   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10843 
10844   // C++11 [class.copy]p7:
10845   //   The [definition of an implicitly declared copy constructor] is
10846   //   deprecated if the class has a user-declared copy assignment operator
10847   //   or a user-declared destructor.
10848   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10849     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10850 
10851   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10852   DiagnosticErrorTrap Trap(Diags);
10853 
10854   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10855       Trap.hasErrorOccurred()) {
10856     Diag(CurrentLocation, diag::note_member_synthesized_at)
10857       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10858     CopyConstructor->setInvalidDecl();
10859   }  else {
10860     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10861                              ? CopyConstructor->getLocEnd()
10862                              : CopyConstructor->getLocation();
10863     Sema::CompoundScopeRAII CompoundScope(*this);
10864     CopyConstructor->setBody(
10865         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10866   }
10867 
10868   // The exception specification is needed because we are defining the
10869   // function.
10870   ResolveExceptionSpec(CurrentLocation,
10871                        CopyConstructor->getType()->castAs<FunctionProtoType>());
10872 
10873   CopyConstructor->markUsed(Context);
10874   MarkVTableUsed(CurrentLocation, ClassDecl);
10875 
10876   if (ASTMutationListener *L = getASTMutationListener()) {
10877     L->CompletedImplicitDefinition(CopyConstructor);
10878   }
10879 }
10880 
10881 Sema::ImplicitExceptionSpecification
10882 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10883   CXXRecordDecl *ClassDecl = MD->getParent();
10884 
10885   // C++ [except.spec]p14:
10886   //   An implicitly declared special member function (Clause 12) shall have an
10887   //   exception-specification. [...]
10888   ImplicitExceptionSpecification ExceptSpec(*this);
10889   if (ClassDecl->isInvalidDecl())
10890     return ExceptSpec;
10891 
10892   // Direct base-class constructors.
10893   for (const auto &B : ClassDecl->bases()) {
10894     if (B.isVirtual()) // Handled below.
10895       continue;
10896 
10897     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10898       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10899       CXXConstructorDecl *Constructor =
10900           LookupMovingConstructor(BaseClassDecl, 0);
10901       // If this is a deleted function, add it anyway. This might be conformant
10902       // with the standard. This might not. I'm not sure. It might not matter.
10903       if (Constructor)
10904         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10905     }
10906   }
10907 
10908   // Virtual base-class constructors.
10909   for (const auto &B : ClassDecl->vbases()) {
10910     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10911       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10912       CXXConstructorDecl *Constructor =
10913           LookupMovingConstructor(BaseClassDecl, 0);
10914       // If this is a deleted function, add it anyway. This might be conformant
10915       // with the standard. This might not. I'm not sure. It might not matter.
10916       if (Constructor)
10917         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10918     }
10919   }
10920 
10921   // Field constructors.
10922   for (const auto *F : ClassDecl->fields()) {
10923     QualType FieldType = Context.getBaseElementType(F->getType());
10924     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10925       CXXConstructorDecl *Constructor =
10926           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10927       // If this is a deleted function, add it anyway. This might be conformant
10928       // with the standard. This might not. I'm not sure. It might not matter.
10929       // In particular, the problem is that this function never gets called. It
10930       // might just be ill-formed because this function attempts to refer to
10931       // a deleted function here.
10932       if (Constructor)
10933         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10934     }
10935   }
10936 
10937   return ExceptSpec;
10938 }
10939 
10940 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10941                                                     CXXRecordDecl *ClassDecl) {
10942   assert(ClassDecl->needsImplicitMoveConstructor());
10943 
10944   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10945   if (DSM.isAlreadyBeingDeclared())
10946     return nullptr;
10947 
10948   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10949   QualType ArgType = Context.getRValueReferenceType(ClassType);
10950 
10951   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10952                                                      CXXMoveConstructor,
10953                                                      false);
10954 
10955   DeclarationName Name
10956     = Context.DeclarationNames.getCXXConstructorName(
10957                                            Context.getCanonicalType(ClassType));
10958   SourceLocation ClassLoc = ClassDecl->getLocation();
10959   DeclarationNameInfo NameInfo(Name, ClassLoc);
10960 
10961   // C++11 [class.copy]p11:
10962   //   An implicitly-declared copy/move constructor is an inline public
10963   //   member of its class.
10964   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10965       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10966       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10967       Constexpr);
10968   MoveConstructor->setAccess(AS_public);
10969   MoveConstructor->setDefaulted();
10970 
10971   if (getLangOpts().CUDA) {
10972     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10973                                             MoveConstructor,
10974                                             /* ConstRHS */ false,
10975                                             /* Diagnose */ false);
10976   }
10977 
10978   // Build an exception specification pointing back at this member.
10979   FunctionProtoType::ExtProtoInfo EPI =
10980       getImplicitMethodEPI(*this, MoveConstructor);
10981   MoveConstructor->setType(
10982       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10983 
10984   // Add the parameter to the constructor.
10985   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10986                                                ClassLoc, ClassLoc,
10987                                                /*IdentifierInfo=*/nullptr,
10988                                                ArgType, /*TInfo=*/nullptr,
10989                                                SC_None, nullptr);
10990   MoveConstructor->setParams(FromParam);
10991 
10992   MoveConstructor->setTrivial(
10993     ClassDecl->needsOverloadResolutionForMoveConstructor()
10994       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10995       : ClassDecl->hasTrivialMoveConstructor());
10996 
10997   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10998     ClassDecl->setImplicitMoveConstructorIsDeleted();
10999     SetDeclDeleted(MoveConstructor, ClassLoc);
11000   }
11001 
11002   // Note that we have declared this constructor.
11003   ++ASTContext::NumImplicitMoveConstructorsDeclared;
11004 
11005   if (Scope *S = getScopeForContext(ClassDecl))
11006     PushOnScopeChains(MoveConstructor, S, false);
11007   ClassDecl->addDecl(MoveConstructor);
11008 
11009   return MoveConstructor;
11010 }
11011 
11012 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11013                                    CXXConstructorDecl *MoveConstructor) {
11014   assert((MoveConstructor->isDefaulted() &&
11015           MoveConstructor->isMoveConstructor() &&
11016           !MoveConstructor->doesThisDeclarationHaveABody() &&
11017           !MoveConstructor->isDeleted()) &&
11018          "DefineImplicitMoveConstructor - call it for implicit move ctor");
11019 
11020   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11021   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11022 
11023   SynthesizedFunctionScope Scope(*this, MoveConstructor);
11024   DiagnosticErrorTrap Trap(Diags);
11025 
11026   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11027       Trap.hasErrorOccurred()) {
11028     Diag(CurrentLocation, diag::note_member_synthesized_at)
11029       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11030     MoveConstructor->setInvalidDecl();
11031   }  else {
11032     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11033                              ? MoveConstructor->getLocEnd()
11034                              : MoveConstructor->getLocation();
11035     Sema::CompoundScopeRAII CompoundScope(*this);
11036     MoveConstructor->setBody(ActOnCompoundStmt(
11037         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11038   }
11039 
11040   // The exception specification is needed because we are defining the
11041   // function.
11042   ResolveExceptionSpec(CurrentLocation,
11043                        MoveConstructor->getType()->castAs<FunctionProtoType>());
11044 
11045   MoveConstructor->markUsed(Context);
11046   MarkVTableUsed(CurrentLocation, ClassDecl);
11047 
11048   if (ASTMutationListener *L = getASTMutationListener()) {
11049     L->CompletedImplicitDefinition(MoveConstructor);
11050   }
11051 }
11052 
11053 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
11054   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11055 }
11056 
11057 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
11058                             SourceLocation CurrentLocation,
11059                             CXXConversionDecl *Conv) {
11060   CXXRecordDecl *Lambda = Conv->getParent();
11061   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11062   // If we are defining a specialization of a conversion to function-ptr
11063   // cache the deduced template arguments for this specialization
11064   // so that we can use them to retrieve the corresponding call-operator
11065   // and static-invoker.
11066   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11067 
11068   // Retrieve the corresponding call-operator specialization.
11069   if (Lambda->isGenericLambda()) {
11070     assert(Conv->isFunctionTemplateSpecialization());
11071     FunctionTemplateDecl *CallOpTemplate =
11072         CallOp->getDescribedFunctionTemplate();
11073     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11074     void *InsertPos = nullptr;
11075     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11076                                                 DeducedTemplateArgs->asArray(),
11077                                                 InsertPos);
11078     assert(CallOpSpec &&
11079           "Conversion operator must have a corresponding call operator");
11080     CallOp = cast<CXXMethodDecl>(CallOpSpec);
11081   }
11082   // Mark the call operator referenced (and add to pending instantiations
11083   // if necessary).
11084   // For both the conversion and static-invoker template specializations
11085   // we construct their body's in this function, so no need to add them
11086   // to the PendingInstantiations.
11087   MarkFunctionReferenced(CurrentLocation, CallOp);
11088 
11089   SynthesizedFunctionScope Scope(*this, Conv);
11090   DiagnosticErrorTrap Trap(Diags);
11091 
11092   // Retrieve the static invoker...
11093   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11094   // ... and get the corresponding specialization for a generic lambda.
11095   if (Lambda->isGenericLambda()) {
11096     assert(DeducedTemplateArgs &&
11097       "Must have deduced template arguments from Conversion Operator");
11098     FunctionTemplateDecl *InvokeTemplate =
11099                           Invoker->getDescribedFunctionTemplate();
11100     void *InsertPos = nullptr;
11101     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11102                                                 DeducedTemplateArgs->asArray(),
11103                                                 InsertPos);
11104     assert(InvokeSpec &&
11105       "Must have a corresponding static invoker specialization");
11106     Invoker = cast<CXXMethodDecl>(InvokeSpec);
11107   }
11108   // Construct the body of the conversion function { return __invoke; }.
11109   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11110                                         VK_LValue, Conv->getLocation()).get();
11111    assert(FunctionRef && "Can't refer to __invoke function?");
11112    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11113    Conv->setBody(new (Context) CompoundStmt(Context, Return,
11114                                             Conv->getLocation(),
11115                                             Conv->getLocation()));
11116 
11117   Conv->markUsed(Context);
11118   Conv->setReferenced();
11119 
11120   // Fill in the __invoke function with a dummy implementation. IR generation
11121   // will fill in the actual details.
11122   Invoker->markUsed(Context);
11123   Invoker->setReferenced();
11124   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11125 
11126   if (ASTMutationListener *L = getASTMutationListener()) {
11127     L->CompletedImplicitDefinition(Conv);
11128     L->CompletedImplicitDefinition(Invoker);
11129    }
11130 }
11131 
11132 
11133 
11134 void Sema::DefineImplicitLambdaToBlockPointerConversion(
11135        SourceLocation CurrentLocation,
11136        CXXConversionDecl *Conv)
11137 {
11138   assert(!Conv->getParent()->isGenericLambda());
11139 
11140   Conv->markUsed(Context);
11141 
11142   SynthesizedFunctionScope Scope(*this, Conv);
11143   DiagnosticErrorTrap Trap(Diags);
11144 
11145   // Copy-initialize the lambda object as needed to capture it.
11146   Expr *This = ActOnCXXThis(CurrentLocation).get();
11147   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11148 
11149   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11150                                                         Conv->getLocation(),
11151                                                         Conv, DerefThis);
11152 
11153   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11154   // behavior.  Note that only the general conversion function does this
11155   // (since it's unusable otherwise); in the case where we inline the
11156   // block literal, it has block literal lifetime semantics.
11157   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11158     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11159                                           CK_CopyAndAutoreleaseBlockObject,
11160                                           BuildBlock.get(), nullptr, VK_RValue);
11161 
11162   if (BuildBlock.isInvalid()) {
11163     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11164     Conv->setInvalidDecl();
11165     return;
11166   }
11167 
11168   // Create the return statement that returns the block from the conversion
11169   // function.
11170   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11171   if (Return.isInvalid()) {
11172     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11173     Conv->setInvalidDecl();
11174     return;
11175   }
11176 
11177   // Set the body of the conversion function.
11178   Stmt *ReturnS = Return.get();
11179   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11180                                            Conv->getLocation(),
11181                                            Conv->getLocation()));
11182 
11183   // We're done; notify the mutation listener, if any.
11184   if (ASTMutationListener *L = getASTMutationListener()) {
11185     L->CompletedImplicitDefinition(Conv);
11186   }
11187 }
11188 
11189 /// \brief Determine whether the given list arguments contains exactly one
11190 /// "real" (non-default) argument.
11191 static bool hasOneRealArgument(MultiExprArg Args) {
11192   switch (Args.size()) {
11193   case 0:
11194     return false;
11195 
11196   default:
11197     if (!Args[1]->isDefaultArgument())
11198       return false;
11199 
11200     // fall through
11201   case 1:
11202     return !Args[0]->isDefaultArgument();
11203   }
11204 
11205   return false;
11206 }
11207 
11208 ExprResult
11209 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11210                             CXXConstructorDecl *Constructor,
11211                             MultiExprArg ExprArgs,
11212                             bool HadMultipleCandidates,
11213                             bool IsListInitialization,
11214                             bool IsStdInitListInitialization,
11215                             bool RequiresZeroInit,
11216                             unsigned ConstructKind,
11217                             SourceRange ParenRange) {
11218   bool Elidable = false;
11219 
11220   // C++0x [class.copy]p34:
11221   //   When certain criteria are met, an implementation is allowed to
11222   //   omit the copy/move construction of a class object, even if the
11223   //   copy/move constructor and/or destructor for the object have
11224   //   side effects. [...]
11225   //     - when a temporary class object that has not been bound to a
11226   //       reference (12.2) would be copied/moved to a class object
11227   //       with the same cv-unqualified type, the copy/move operation
11228   //       can be omitted by constructing the temporary object
11229   //       directly into the target of the omitted copy/move
11230   if (ConstructKind == CXXConstructExpr::CK_Complete &&
11231       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11232     Expr *SubExpr = ExprArgs[0];
11233     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11234   }
11235 
11236   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11237                                Elidable, ExprArgs, HadMultipleCandidates,
11238                                IsListInitialization,
11239                                IsStdInitListInitialization, RequiresZeroInit,
11240                                ConstructKind, ParenRange);
11241 }
11242 
11243 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11244 /// including handling of its default argument expressions.
11245 ExprResult
11246 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11247                             CXXConstructorDecl *Constructor, bool Elidable,
11248                             MultiExprArg ExprArgs,
11249                             bool HadMultipleCandidates,
11250                             bool IsListInitialization,
11251                             bool IsStdInitListInitialization,
11252                             bool RequiresZeroInit,
11253                             unsigned ConstructKind,
11254                             SourceRange ParenRange) {
11255   MarkFunctionReferenced(ConstructLoc, Constructor);
11256   return CXXConstructExpr::Create(
11257       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11258       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11259       RequiresZeroInit,
11260       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11261       ParenRange);
11262 }
11263 
11264 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11265   assert(Field->hasInClassInitializer());
11266 
11267   // If we already have the in-class initializer nothing needs to be done.
11268   if (Field->getInClassInitializer())
11269     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11270 
11271   // Maybe we haven't instantiated the in-class initializer. Go check the
11272   // pattern FieldDecl to see if it has one.
11273   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11274 
11275   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11276     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11277     DeclContext::lookup_result Lookup =
11278         ClassPattern->lookup(Field->getDeclName());
11279     assert(Lookup.size() == 1);
11280     FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11281     if (InstantiateInClassInitializer(Loc, Field, Pattern,
11282                                       getTemplateInstantiationArgs(Field)))
11283       return ExprError();
11284     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11285   }
11286 
11287   // DR1351:
11288   //   If the brace-or-equal-initializer of a non-static data member
11289   //   invokes a defaulted default constructor of its class or of an
11290   //   enclosing class in a potentially evaluated subexpression, the
11291   //   program is ill-formed.
11292   //
11293   // This resolution is unworkable: the exception specification of the
11294   // default constructor can be needed in an unevaluated context, in
11295   // particular, in the operand of a noexcept-expression, and we can be
11296   // unable to compute an exception specification for an enclosed class.
11297   //
11298   // Any attempt to resolve the exception specification of a defaulted default
11299   // constructor before the initializer is lexically complete will ultimately
11300   // come here at which point we can diagnose it.
11301   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11302   if (OutermostClass == ParentRD) {
11303     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11304         << ParentRD << Field;
11305   } else {
11306     Diag(Field->getLocEnd(),
11307          diag::err_in_class_initializer_not_yet_parsed_outer_class)
11308         << ParentRD << OutermostClass << Field;
11309   }
11310 
11311   return ExprError();
11312 }
11313 
11314 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11315   if (VD->isInvalidDecl()) return;
11316 
11317   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11318   if (ClassDecl->isInvalidDecl()) return;
11319   if (ClassDecl->hasIrrelevantDestructor()) return;
11320   if (ClassDecl->isDependentContext()) return;
11321 
11322   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11323   MarkFunctionReferenced(VD->getLocation(), Destructor);
11324   CheckDestructorAccess(VD->getLocation(), Destructor,
11325                         PDiag(diag::err_access_dtor_var)
11326                         << VD->getDeclName()
11327                         << VD->getType());
11328   DiagnoseUseOfDecl(Destructor, VD->getLocation());
11329 
11330   if (Destructor->isTrivial()) return;
11331   if (!VD->hasGlobalStorage()) return;
11332 
11333   // Emit warning for non-trivial dtor in global scope (a real global,
11334   // class-static, function-static).
11335   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11336 
11337   // TODO: this should be re-enabled for static locals by !CXAAtExit
11338   if (!VD->isStaticLocal())
11339     Diag(VD->getLocation(), diag::warn_global_destructor);
11340 }
11341 
11342 /// \brief Given a constructor and the set of arguments provided for the
11343 /// constructor, convert the arguments and add any required default arguments
11344 /// to form a proper call to this constructor.
11345 ///
11346 /// \returns true if an error occurred, false otherwise.
11347 bool
11348 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11349                               MultiExprArg ArgsPtr,
11350                               SourceLocation Loc,
11351                               SmallVectorImpl<Expr*> &ConvertedArgs,
11352                               bool AllowExplicit,
11353                               bool IsListInitialization) {
11354   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11355   unsigned NumArgs = ArgsPtr.size();
11356   Expr **Args = ArgsPtr.data();
11357 
11358   const FunctionProtoType *Proto
11359     = Constructor->getType()->getAs<FunctionProtoType>();
11360   assert(Proto && "Constructor without a prototype?");
11361   unsigned NumParams = Proto->getNumParams();
11362 
11363   // If too few arguments are available, we'll fill in the rest with defaults.
11364   if (NumArgs < NumParams)
11365     ConvertedArgs.reserve(NumParams);
11366   else
11367     ConvertedArgs.reserve(NumArgs);
11368 
11369   VariadicCallType CallType =
11370     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11371   SmallVector<Expr *, 8> AllArgs;
11372   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11373                                         Proto, 0,
11374                                         llvm::makeArrayRef(Args, NumArgs),
11375                                         AllArgs,
11376                                         CallType, AllowExplicit,
11377                                         IsListInitialization);
11378   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11379 
11380   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11381 
11382   CheckConstructorCall(Constructor,
11383                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11384                        Proto, Loc);
11385 
11386   return Invalid;
11387 }
11388 
11389 static inline bool
11390 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11391                                        const FunctionDecl *FnDecl) {
11392   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11393   if (isa<NamespaceDecl>(DC)) {
11394     return SemaRef.Diag(FnDecl->getLocation(),
11395                         diag::err_operator_new_delete_declared_in_namespace)
11396       << FnDecl->getDeclName();
11397   }
11398 
11399   if (isa<TranslationUnitDecl>(DC) &&
11400       FnDecl->getStorageClass() == SC_Static) {
11401     return SemaRef.Diag(FnDecl->getLocation(),
11402                         diag::err_operator_new_delete_declared_static)
11403       << FnDecl->getDeclName();
11404   }
11405 
11406   return false;
11407 }
11408 
11409 static inline bool
11410 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11411                             CanQualType ExpectedResultType,
11412                             CanQualType ExpectedFirstParamType,
11413                             unsigned DependentParamTypeDiag,
11414                             unsigned InvalidParamTypeDiag) {
11415   QualType ResultType =
11416       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11417 
11418   // Check that the result type is not dependent.
11419   if (ResultType->isDependentType())
11420     return SemaRef.Diag(FnDecl->getLocation(),
11421                         diag::err_operator_new_delete_dependent_result_type)
11422     << FnDecl->getDeclName() << ExpectedResultType;
11423 
11424   // Check that the result type is what we expect.
11425   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11426     return SemaRef.Diag(FnDecl->getLocation(),
11427                         diag::err_operator_new_delete_invalid_result_type)
11428     << FnDecl->getDeclName() << ExpectedResultType;
11429 
11430   // A function template must have at least 2 parameters.
11431   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11432     return SemaRef.Diag(FnDecl->getLocation(),
11433                       diag::err_operator_new_delete_template_too_few_parameters)
11434         << FnDecl->getDeclName();
11435 
11436   // The function decl must have at least 1 parameter.
11437   if (FnDecl->getNumParams() == 0)
11438     return SemaRef.Diag(FnDecl->getLocation(),
11439                         diag::err_operator_new_delete_too_few_parameters)
11440       << FnDecl->getDeclName();
11441 
11442   // Check the first parameter type is not dependent.
11443   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11444   if (FirstParamType->isDependentType())
11445     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11446       << FnDecl->getDeclName() << ExpectedFirstParamType;
11447 
11448   // Check that the first parameter type is what we expect.
11449   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11450       ExpectedFirstParamType)
11451     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11452     << FnDecl->getDeclName() << ExpectedFirstParamType;
11453 
11454   return false;
11455 }
11456 
11457 static bool
11458 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11459   // C++ [basic.stc.dynamic.allocation]p1:
11460   //   A program is ill-formed if an allocation function is declared in a
11461   //   namespace scope other than global scope or declared static in global
11462   //   scope.
11463   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11464     return true;
11465 
11466   CanQualType SizeTy =
11467     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11468 
11469   // C++ [basic.stc.dynamic.allocation]p1:
11470   //  The return type shall be void*. The first parameter shall have type
11471   //  std::size_t.
11472   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11473                                   SizeTy,
11474                                   diag::err_operator_new_dependent_param_type,
11475                                   diag::err_operator_new_param_type))
11476     return true;
11477 
11478   // C++ [basic.stc.dynamic.allocation]p1:
11479   //  The first parameter shall not have an associated default argument.
11480   if (FnDecl->getParamDecl(0)->hasDefaultArg())
11481     return SemaRef.Diag(FnDecl->getLocation(),
11482                         diag::err_operator_new_default_arg)
11483       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11484 
11485   return false;
11486 }
11487 
11488 static bool
11489 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11490   // C++ [basic.stc.dynamic.deallocation]p1:
11491   //   A program is ill-formed if deallocation functions are declared in a
11492   //   namespace scope other than global scope or declared static in global
11493   //   scope.
11494   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11495     return true;
11496 
11497   // C++ [basic.stc.dynamic.deallocation]p2:
11498   //   Each deallocation function shall return void and its first parameter
11499   //   shall be void*.
11500   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11501                                   SemaRef.Context.VoidPtrTy,
11502                                  diag::err_operator_delete_dependent_param_type,
11503                                  diag::err_operator_delete_param_type))
11504     return true;
11505 
11506   return false;
11507 }
11508 
11509 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11510 /// of this overloaded operator is well-formed. If so, returns false;
11511 /// otherwise, emits appropriate diagnostics and returns true.
11512 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11513   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11514          "Expected an overloaded operator declaration");
11515 
11516   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11517 
11518   // C++ [over.oper]p5:
11519   //   The allocation and deallocation functions, operator new,
11520   //   operator new[], operator delete and operator delete[], are
11521   //   described completely in 3.7.3. The attributes and restrictions
11522   //   found in the rest of this subclause do not apply to them unless
11523   //   explicitly stated in 3.7.3.
11524   if (Op == OO_Delete || Op == OO_Array_Delete)
11525     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11526 
11527   if (Op == OO_New || Op == OO_Array_New)
11528     return CheckOperatorNewDeclaration(*this, FnDecl);
11529 
11530   // C++ [over.oper]p6:
11531   //   An operator function shall either be a non-static member
11532   //   function or be a non-member function and have at least one
11533   //   parameter whose type is a class, a reference to a class, an
11534   //   enumeration, or a reference to an enumeration.
11535   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11536     if (MethodDecl->isStatic())
11537       return Diag(FnDecl->getLocation(),
11538                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11539   } else {
11540     bool ClassOrEnumParam = false;
11541     for (auto Param : FnDecl->params()) {
11542       QualType ParamType = Param->getType().getNonReferenceType();
11543       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11544           ParamType->isEnumeralType()) {
11545         ClassOrEnumParam = true;
11546         break;
11547       }
11548     }
11549 
11550     if (!ClassOrEnumParam)
11551       return Diag(FnDecl->getLocation(),
11552                   diag::err_operator_overload_needs_class_or_enum)
11553         << FnDecl->getDeclName();
11554   }
11555 
11556   // C++ [over.oper]p8:
11557   //   An operator function cannot have default arguments (8.3.6),
11558   //   except where explicitly stated below.
11559   //
11560   // Only the function-call operator allows default arguments
11561   // (C++ [over.call]p1).
11562   if (Op != OO_Call) {
11563     for (auto Param : FnDecl->params()) {
11564       if (Param->hasDefaultArg())
11565         return Diag(Param->getLocation(),
11566                     diag::err_operator_overload_default_arg)
11567           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11568     }
11569   }
11570 
11571   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11572     { false, false, false }
11573 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11574     , { Unary, Binary, MemberOnly }
11575 #include "clang/Basic/OperatorKinds.def"
11576   };
11577 
11578   bool CanBeUnaryOperator = OperatorUses[Op][0];
11579   bool CanBeBinaryOperator = OperatorUses[Op][1];
11580   bool MustBeMemberOperator = OperatorUses[Op][2];
11581 
11582   // C++ [over.oper]p8:
11583   //   [...] Operator functions cannot have more or fewer parameters
11584   //   than the number required for the corresponding operator, as
11585   //   described in the rest of this subclause.
11586   unsigned NumParams = FnDecl->getNumParams()
11587                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11588   if (Op != OO_Call &&
11589       ((NumParams == 1 && !CanBeUnaryOperator) ||
11590        (NumParams == 2 && !CanBeBinaryOperator) ||
11591        (NumParams < 1) || (NumParams > 2))) {
11592     // We have the wrong number of parameters.
11593     unsigned ErrorKind;
11594     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11595       ErrorKind = 2;  // 2 -> unary or binary.
11596     } else if (CanBeUnaryOperator) {
11597       ErrorKind = 0;  // 0 -> unary
11598     } else {
11599       assert(CanBeBinaryOperator &&
11600              "All non-call overloaded operators are unary or binary!");
11601       ErrorKind = 1;  // 1 -> binary
11602     }
11603 
11604     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11605       << FnDecl->getDeclName() << NumParams << ErrorKind;
11606   }
11607 
11608   // Overloaded operators other than operator() cannot be variadic.
11609   if (Op != OO_Call &&
11610       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11611     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11612       << FnDecl->getDeclName();
11613   }
11614 
11615   // Some operators must be non-static member functions.
11616   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11617     return Diag(FnDecl->getLocation(),
11618                 diag::err_operator_overload_must_be_member)
11619       << FnDecl->getDeclName();
11620   }
11621 
11622   // C++ [over.inc]p1:
11623   //   The user-defined function called operator++ implements the
11624   //   prefix and postfix ++ operator. If this function is a member
11625   //   function with no parameters, or a non-member function with one
11626   //   parameter of class or enumeration type, it defines the prefix
11627   //   increment operator ++ for objects of that type. If the function
11628   //   is a member function with one parameter (which shall be of type
11629   //   int) or a non-member function with two parameters (the second
11630   //   of which shall be of type int), it defines the postfix
11631   //   increment operator ++ for objects of that type.
11632   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11633     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11634     QualType ParamType = LastParam->getType();
11635 
11636     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11637         !ParamType->isDependentType())
11638       return Diag(LastParam->getLocation(),
11639                   diag::err_operator_overload_post_incdec_must_be_int)
11640         << LastParam->getType() << (Op == OO_MinusMinus);
11641   }
11642 
11643   return false;
11644 }
11645 
11646 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11647 /// of this literal operator function is well-formed. If so, returns
11648 /// false; otherwise, emits appropriate diagnostics and returns true.
11649 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11650   if (isa<CXXMethodDecl>(FnDecl)) {
11651     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11652       << FnDecl->getDeclName();
11653     return true;
11654   }
11655 
11656   if (FnDecl->isExternC()) {
11657     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11658     return true;
11659   }
11660 
11661   bool Valid = false;
11662 
11663   // This might be the definition of a literal operator template.
11664   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11665   // This might be a specialization of a literal operator template.
11666   if (!TpDecl)
11667     TpDecl = FnDecl->getPrimaryTemplate();
11668 
11669   // template <char...> type operator "" name() and
11670   // template <class T, T...> type operator "" name() are the only valid
11671   // template signatures, and the only valid signatures with no parameters.
11672   if (TpDecl) {
11673     if (FnDecl->param_size() == 0) {
11674       // Must have one or two template parameters
11675       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11676       if (Params->size() == 1) {
11677         NonTypeTemplateParmDecl *PmDecl =
11678           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11679 
11680         // The template parameter must be a char parameter pack.
11681         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11682             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11683           Valid = true;
11684       } else if (Params->size() == 2) {
11685         TemplateTypeParmDecl *PmType =
11686           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11687         NonTypeTemplateParmDecl *PmArgs =
11688           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11689 
11690         // The second template parameter must be a parameter pack with the
11691         // first template parameter as its type.
11692         if (PmType && PmArgs &&
11693             !PmType->isTemplateParameterPack() &&
11694             PmArgs->isTemplateParameterPack()) {
11695           const TemplateTypeParmType *TArgs =
11696             PmArgs->getType()->getAs<TemplateTypeParmType>();
11697           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11698               TArgs->getIndex() == PmType->getIndex()) {
11699             Valid = true;
11700             if (ActiveTemplateInstantiations.empty())
11701               Diag(FnDecl->getLocation(),
11702                    diag::ext_string_literal_operator_template);
11703           }
11704         }
11705       }
11706     }
11707   } else if (FnDecl->param_size()) {
11708     // Check the first parameter
11709     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11710 
11711     QualType T = (*Param)->getType().getUnqualifiedType();
11712 
11713     // unsigned long long int, long double, and any character type are allowed
11714     // as the only parameters.
11715     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11716         Context.hasSameType(T, Context.LongDoubleTy) ||
11717         Context.hasSameType(T, Context.CharTy) ||
11718         Context.hasSameType(T, Context.WideCharTy) ||
11719         Context.hasSameType(T, Context.Char16Ty) ||
11720         Context.hasSameType(T, Context.Char32Ty)) {
11721       if (++Param == FnDecl->param_end())
11722         Valid = true;
11723       goto FinishedParams;
11724     }
11725 
11726     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11727     const PointerType *PT = T->getAs<PointerType>();
11728     if (!PT)
11729       goto FinishedParams;
11730     T = PT->getPointeeType();
11731     if (!T.isConstQualified() || T.isVolatileQualified())
11732       goto FinishedParams;
11733     T = T.getUnqualifiedType();
11734 
11735     // Move on to the second parameter;
11736     ++Param;
11737 
11738     // If there is no second parameter, the first must be a const char *
11739     if (Param == FnDecl->param_end()) {
11740       if (Context.hasSameType(T, Context.CharTy))
11741         Valid = true;
11742       goto FinishedParams;
11743     }
11744 
11745     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11746     // are allowed as the first parameter to a two-parameter function
11747     if (!(Context.hasSameType(T, Context.CharTy) ||
11748           Context.hasSameType(T, Context.WideCharTy) ||
11749           Context.hasSameType(T, Context.Char16Ty) ||
11750           Context.hasSameType(T, Context.Char32Ty)))
11751       goto FinishedParams;
11752 
11753     // The second and final parameter must be an std::size_t
11754     T = (*Param)->getType().getUnqualifiedType();
11755     if (Context.hasSameType(T, Context.getSizeType()) &&
11756         ++Param == FnDecl->param_end())
11757       Valid = true;
11758   }
11759 
11760   // FIXME: This diagnostic is absolutely terrible.
11761 FinishedParams:
11762   if (!Valid) {
11763     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11764       << FnDecl->getDeclName();
11765     return true;
11766   }
11767 
11768   // A parameter-declaration-clause containing a default argument is not
11769   // equivalent to any of the permitted forms.
11770   for (auto Param : FnDecl->params()) {
11771     if (Param->hasDefaultArg()) {
11772       Diag(Param->getDefaultArgRange().getBegin(),
11773            diag::err_literal_operator_default_argument)
11774         << Param->getDefaultArgRange();
11775       break;
11776     }
11777   }
11778 
11779   StringRef LiteralName
11780     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11781   if (LiteralName[0] != '_') {
11782     // C++11 [usrlit.suffix]p1:
11783     //   Literal suffix identifiers that do not start with an underscore
11784     //   are reserved for future standardization.
11785     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11786       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11787   }
11788 
11789   return false;
11790 }
11791 
11792 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11793 /// linkage specification, including the language and (if present)
11794 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11795 /// language string literal. LBraceLoc, if valid, provides the location of
11796 /// the '{' brace. Otherwise, this linkage specification does not
11797 /// have any braces.
11798 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11799                                            Expr *LangStr,
11800                                            SourceLocation LBraceLoc) {
11801   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11802   if (!Lit->isAscii()) {
11803     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11804       << LangStr->getSourceRange();
11805     return nullptr;
11806   }
11807 
11808   StringRef Lang = Lit->getString();
11809   LinkageSpecDecl::LanguageIDs Language;
11810   if (Lang == "C")
11811     Language = LinkageSpecDecl::lang_c;
11812   else if (Lang == "C++")
11813     Language = LinkageSpecDecl::lang_cxx;
11814   else {
11815     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11816       << LangStr->getSourceRange();
11817     return nullptr;
11818   }
11819 
11820   // FIXME: Add all the various semantics of linkage specifications
11821 
11822   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11823                                                LangStr->getExprLoc(), Language,
11824                                                LBraceLoc.isValid());
11825   CurContext->addDecl(D);
11826   PushDeclContext(S, D);
11827   return D;
11828 }
11829 
11830 /// ActOnFinishLinkageSpecification - Complete the definition of
11831 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11832 /// valid, it's the position of the closing '}' brace in a linkage
11833 /// specification that uses braces.
11834 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11835                                             Decl *LinkageSpec,
11836                                             SourceLocation RBraceLoc) {
11837   if (RBraceLoc.isValid()) {
11838     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11839     LSDecl->setRBraceLoc(RBraceLoc);
11840   }
11841   PopDeclContext();
11842   return LinkageSpec;
11843 }
11844 
11845 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11846                                   AttributeList *AttrList,
11847                                   SourceLocation SemiLoc) {
11848   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11849   // Attribute declarations appertain to empty declaration so we handle
11850   // them here.
11851   if (AttrList)
11852     ProcessDeclAttributeList(S, ED, AttrList);
11853 
11854   CurContext->addDecl(ED);
11855   return ED;
11856 }
11857 
11858 /// \brief Perform semantic analysis for the variable declaration that
11859 /// occurs within a C++ catch clause, returning the newly-created
11860 /// variable.
11861 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11862                                          TypeSourceInfo *TInfo,
11863                                          SourceLocation StartLoc,
11864                                          SourceLocation Loc,
11865                                          IdentifierInfo *Name) {
11866   bool Invalid = false;
11867   QualType ExDeclType = TInfo->getType();
11868 
11869   // Arrays and functions decay.
11870   if (ExDeclType->isArrayType())
11871     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11872   else if (ExDeclType->isFunctionType())
11873     ExDeclType = Context.getPointerType(ExDeclType);
11874 
11875   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11876   // The exception-declaration shall not denote a pointer or reference to an
11877   // incomplete type, other than [cv] void*.
11878   // N2844 forbids rvalue references.
11879   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11880     Diag(Loc, diag::err_catch_rvalue_ref);
11881     Invalid = true;
11882   }
11883 
11884   QualType BaseType = ExDeclType;
11885   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11886   unsigned DK = diag::err_catch_incomplete;
11887   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11888     BaseType = Ptr->getPointeeType();
11889     Mode = 1;
11890     DK = diag::err_catch_incomplete_ptr;
11891   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11892     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11893     BaseType = Ref->getPointeeType();
11894     Mode = 2;
11895     DK = diag::err_catch_incomplete_ref;
11896   }
11897   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11898       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11899     Invalid = true;
11900 
11901   if (!Invalid && !ExDeclType->isDependentType() &&
11902       RequireNonAbstractType(Loc, ExDeclType,
11903                              diag::err_abstract_type_in_decl,
11904                              AbstractVariableType))
11905     Invalid = true;
11906 
11907   // Only the non-fragile NeXT runtime currently supports C++ catches
11908   // of ObjC types, and no runtime supports catching ObjC types by value.
11909   if (!Invalid && getLangOpts().ObjC1) {
11910     QualType T = ExDeclType;
11911     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11912       T = RT->getPointeeType();
11913 
11914     if (T->isObjCObjectType()) {
11915       Diag(Loc, diag::err_objc_object_catch);
11916       Invalid = true;
11917     } else if (T->isObjCObjectPointerType()) {
11918       // FIXME: should this be a test for macosx-fragile specifically?
11919       if (getLangOpts().ObjCRuntime.isFragile())
11920         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11921     }
11922   }
11923 
11924   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11925                                     ExDeclType, TInfo, SC_None);
11926   ExDecl->setExceptionVariable(true);
11927 
11928   // In ARC, infer 'retaining' for variables of retainable type.
11929   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11930     Invalid = true;
11931 
11932   if (!Invalid && !ExDeclType->isDependentType()) {
11933     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11934       // Insulate this from anything else we might currently be parsing.
11935       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11936 
11937       // C++ [except.handle]p16:
11938       //   The object declared in an exception-declaration or, if the
11939       //   exception-declaration does not specify a name, a temporary (12.2) is
11940       //   copy-initialized (8.5) from the exception object. [...]
11941       //   The object is destroyed when the handler exits, after the destruction
11942       //   of any automatic objects initialized within the handler.
11943       //
11944       // We just pretend to initialize the object with itself, then make sure
11945       // it can be destroyed later.
11946       QualType initType = ExDeclType;
11947 
11948       InitializedEntity entity =
11949         InitializedEntity::InitializeVariable(ExDecl);
11950       InitializationKind initKind =
11951         InitializationKind::CreateCopy(Loc, SourceLocation());
11952 
11953       Expr *opaqueValue =
11954         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11955       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11956       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11957       if (result.isInvalid())
11958         Invalid = true;
11959       else {
11960         // If the constructor used was non-trivial, set this as the
11961         // "initializer".
11962         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
11963         if (!construct->getConstructor()->isTrivial()) {
11964           Expr *init = MaybeCreateExprWithCleanups(construct);
11965           ExDecl->setInit(init);
11966         }
11967 
11968         // And make sure it's destructable.
11969         FinalizeVarWithDestructor(ExDecl, recordType);
11970       }
11971     }
11972   }
11973 
11974   if (Invalid)
11975     ExDecl->setInvalidDecl();
11976 
11977   return ExDecl;
11978 }
11979 
11980 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11981 /// handler.
11982 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11983   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11984   bool Invalid = D.isInvalidType();
11985 
11986   // Check for unexpanded parameter packs.
11987   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11988                                       UPPC_ExceptionType)) {
11989     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11990                                              D.getIdentifierLoc());
11991     Invalid = true;
11992   }
11993 
11994   IdentifierInfo *II = D.getIdentifier();
11995   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11996                                              LookupOrdinaryName,
11997                                              ForRedeclaration)) {
11998     // The scope should be freshly made just for us. There is just no way
11999     // it contains any previous declaration, except for function parameters in
12000     // a function-try-block's catch statement.
12001     assert(!S->isDeclScope(PrevDecl));
12002     if (isDeclInScope(PrevDecl, CurContext, S)) {
12003       Diag(D.getIdentifierLoc(), diag::err_redefinition)
12004         << D.getIdentifier();
12005       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12006       Invalid = true;
12007     } else if (PrevDecl->isTemplateParameter())
12008       // Maybe we will complain about the shadowed template parameter.
12009       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12010   }
12011 
12012   if (D.getCXXScopeSpec().isSet() && !Invalid) {
12013     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12014       << D.getCXXScopeSpec().getRange();
12015     Invalid = true;
12016   }
12017 
12018   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12019                                               D.getLocStart(),
12020                                               D.getIdentifierLoc(),
12021                                               D.getIdentifier());
12022   if (Invalid)
12023     ExDecl->setInvalidDecl();
12024 
12025   // Add the exception declaration into this scope.
12026   if (II)
12027     PushOnScopeChains(ExDecl, S);
12028   else
12029     CurContext->addDecl(ExDecl);
12030 
12031   ProcessDeclAttributes(S, ExDecl, D);
12032   return ExDecl;
12033 }
12034 
12035 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12036                                          Expr *AssertExpr,
12037                                          Expr *AssertMessageExpr,
12038                                          SourceLocation RParenLoc) {
12039   StringLiteral *AssertMessage =
12040       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12041 
12042   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
12043     return nullptr;
12044 
12045   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12046                                       AssertMessage, RParenLoc, false);
12047 }
12048 
12049 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12050                                          Expr *AssertExpr,
12051                                          StringLiteral *AssertMessage,
12052                                          SourceLocation RParenLoc,
12053                                          bool Failed) {
12054   assert(AssertExpr != nullptr && "Expected non-null condition");
12055   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12056       !Failed) {
12057     // In a static_assert-declaration, the constant-expression shall be a
12058     // constant expression that can be contextually converted to bool.
12059     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12060     if (Converted.isInvalid())
12061       Failed = true;
12062 
12063     llvm::APSInt Cond;
12064     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12065           diag::err_static_assert_expression_is_not_constant,
12066           /*AllowFold=*/false).isInvalid())
12067       Failed = true;
12068 
12069     if (!Failed && !Cond) {
12070       SmallString<256> MsgBuffer;
12071       llvm::raw_svector_ostream Msg(MsgBuffer);
12072       if (AssertMessage)
12073         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12074       Diag(StaticAssertLoc, diag::err_static_assert_failed)
12075         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12076       Failed = true;
12077     }
12078   }
12079 
12080   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12081                                         AssertExpr, AssertMessage, RParenLoc,
12082                                         Failed);
12083 
12084   CurContext->addDecl(Decl);
12085   return Decl;
12086 }
12087 
12088 /// \brief Perform semantic analysis of the given friend type declaration.
12089 ///
12090 /// \returns A friend declaration that.
12091 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12092                                       SourceLocation FriendLoc,
12093                                       TypeSourceInfo *TSInfo) {
12094   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12095 
12096   QualType T = TSInfo->getType();
12097   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12098 
12099   // C++03 [class.friend]p2:
12100   //   An elaborated-type-specifier shall be used in a friend declaration
12101   //   for a class.*
12102   //
12103   //   * The class-key of the elaborated-type-specifier is required.
12104   if (!ActiveTemplateInstantiations.empty()) {
12105     // Do not complain about the form of friend template types during
12106     // template instantiation; we will already have complained when the
12107     // template was declared.
12108   } else {
12109     if (!T->isElaboratedTypeSpecifier()) {
12110       // If we evaluated the type to a record type, suggest putting
12111       // a tag in front.
12112       if (const RecordType *RT = T->getAs<RecordType>()) {
12113         RecordDecl *RD = RT->getDecl();
12114 
12115         SmallString<16> InsertionText(" ");
12116         InsertionText += RD->getKindName();
12117 
12118         Diag(TypeRange.getBegin(),
12119              getLangOpts().CPlusPlus11 ?
12120                diag::warn_cxx98_compat_unelaborated_friend_type :
12121                diag::ext_unelaborated_friend_type)
12122           << (unsigned) RD->getTagKind()
12123           << T
12124           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12125                                         InsertionText);
12126       } else {
12127         Diag(FriendLoc,
12128              getLangOpts().CPlusPlus11 ?
12129                diag::warn_cxx98_compat_nonclass_type_friend :
12130                diag::ext_nonclass_type_friend)
12131           << T
12132           << TypeRange;
12133       }
12134     } else if (T->getAs<EnumType>()) {
12135       Diag(FriendLoc,
12136            getLangOpts().CPlusPlus11 ?
12137              diag::warn_cxx98_compat_enum_friend :
12138              diag::ext_enum_friend)
12139         << T
12140         << TypeRange;
12141     }
12142 
12143     // C++11 [class.friend]p3:
12144     //   A friend declaration that does not declare a function shall have one
12145     //   of the following forms:
12146     //     friend elaborated-type-specifier ;
12147     //     friend simple-type-specifier ;
12148     //     friend typename-specifier ;
12149     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12150       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12151   }
12152 
12153   //   If the type specifier in a friend declaration designates a (possibly
12154   //   cv-qualified) class type, that class is declared as a friend; otherwise,
12155   //   the friend declaration is ignored.
12156   return FriendDecl::Create(Context, CurContext,
12157                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
12158                             FriendLoc);
12159 }
12160 
12161 /// Handle a friend tag declaration where the scope specifier was
12162 /// templated.
12163 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12164                                     unsigned TagSpec, SourceLocation TagLoc,
12165                                     CXXScopeSpec &SS,
12166                                     IdentifierInfo *Name,
12167                                     SourceLocation NameLoc,
12168                                     AttributeList *Attr,
12169                                     MultiTemplateParamsArg TempParamLists) {
12170   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12171 
12172   bool isExplicitSpecialization = false;
12173   bool Invalid = false;
12174 
12175   if (TemplateParameterList *TemplateParams =
12176           MatchTemplateParametersToScopeSpecifier(
12177               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12178               isExplicitSpecialization, Invalid)) {
12179     if (TemplateParams->size() > 0) {
12180       // This is a declaration of a class template.
12181       if (Invalid)
12182         return nullptr;
12183 
12184       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12185                                 NameLoc, Attr, TemplateParams, AS_public,
12186                                 /*ModulePrivateLoc=*/SourceLocation(),
12187                                 FriendLoc, TempParamLists.size() - 1,
12188                                 TempParamLists.data()).get();
12189     } else {
12190       // The "template<>" header is extraneous.
12191       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12192         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12193       isExplicitSpecialization = true;
12194     }
12195   }
12196 
12197   if (Invalid) return nullptr;
12198 
12199   bool isAllExplicitSpecializations = true;
12200   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12201     if (TempParamLists[I]->size()) {
12202       isAllExplicitSpecializations = false;
12203       break;
12204     }
12205   }
12206 
12207   // FIXME: don't ignore attributes.
12208 
12209   // If it's explicit specializations all the way down, just forget
12210   // about the template header and build an appropriate non-templated
12211   // friend.  TODO: for source fidelity, remember the headers.
12212   if (isAllExplicitSpecializations) {
12213     if (SS.isEmpty()) {
12214       bool Owned = false;
12215       bool IsDependent = false;
12216       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12217                       Attr, AS_public,
12218                       /*ModulePrivateLoc=*/SourceLocation(),
12219                       MultiTemplateParamsArg(), Owned, IsDependent,
12220                       /*ScopedEnumKWLoc=*/SourceLocation(),
12221                       /*ScopedEnumUsesClassTag=*/false,
12222                       /*UnderlyingType=*/TypeResult(),
12223                       /*IsTypeSpecifier=*/false);
12224     }
12225 
12226     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12227     ElaboratedTypeKeyword Keyword
12228       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12229     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12230                                    *Name, NameLoc);
12231     if (T.isNull())
12232       return nullptr;
12233 
12234     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12235     if (isa<DependentNameType>(T)) {
12236       DependentNameTypeLoc TL =
12237           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12238       TL.setElaboratedKeywordLoc(TagLoc);
12239       TL.setQualifierLoc(QualifierLoc);
12240       TL.setNameLoc(NameLoc);
12241     } else {
12242       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12243       TL.setElaboratedKeywordLoc(TagLoc);
12244       TL.setQualifierLoc(QualifierLoc);
12245       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12246     }
12247 
12248     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12249                                             TSI, FriendLoc, TempParamLists);
12250     Friend->setAccess(AS_public);
12251     CurContext->addDecl(Friend);
12252     return Friend;
12253   }
12254 
12255   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12256 
12257 
12258 
12259   // Handle the case of a templated-scope friend class.  e.g.
12260   //   template <class T> class A<T>::B;
12261   // FIXME: we don't support these right now.
12262   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12263     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12264   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12265   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12266   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12267   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12268   TL.setElaboratedKeywordLoc(TagLoc);
12269   TL.setQualifierLoc(SS.getWithLocInContext(Context));
12270   TL.setNameLoc(NameLoc);
12271 
12272   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12273                                           TSI, FriendLoc, TempParamLists);
12274   Friend->setAccess(AS_public);
12275   Friend->setUnsupportedFriend(true);
12276   CurContext->addDecl(Friend);
12277   return Friend;
12278 }
12279 
12280 
12281 /// Handle a friend type declaration.  This works in tandem with
12282 /// ActOnTag.
12283 ///
12284 /// Notes on friend class templates:
12285 ///
12286 /// We generally treat friend class declarations as if they were
12287 /// declaring a class.  So, for example, the elaborated type specifier
12288 /// in a friend declaration is required to obey the restrictions of a
12289 /// class-head (i.e. no typedefs in the scope chain), template
12290 /// parameters are required to match up with simple template-ids, &c.
12291 /// However, unlike when declaring a template specialization, it's
12292 /// okay to refer to a template specialization without an empty
12293 /// template parameter declaration, e.g.
12294 ///   friend class A<T>::B<unsigned>;
12295 /// We permit this as a special case; if there are any template
12296 /// parameters present at all, require proper matching, i.e.
12297 ///   template <> template \<class T> friend class A<int>::B;
12298 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12299                                 MultiTemplateParamsArg TempParams) {
12300   SourceLocation Loc = DS.getLocStart();
12301 
12302   assert(DS.isFriendSpecified());
12303   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12304 
12305   // Try to convert the decl specifier to a type.  This works for
12306   // friend templates because ActOnTag never produces a ClassTemplateDecl
12307   // for a TUK_Friend.
12308   Declarator TheDeclarator(DS, Declarator::MemberContext);
12309   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12310   QualType T = TSI->getType();
12311   if (TheDeclarator.isInvalidType())
12312     return nullptr;
12313 
12314   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12315     return nullptr;
12316 
12317   // This is definitely an error in C++98.  It's probably meant to
12318   // be forbidden in C++0x, too, but the specification is just
12319   // poorly written.
12320   //
12321   // The problem is with declarations like the following:
12322   //   template <T> friend A<T>::foo;
12323   // where deciding whether a class C is a friend or not now hinges
12324   // on whether there exists an instantiation of A that causes
12325   // 'foo' to equal C.  There are restrictions on class-heads
12326   // (which we declare (by fiat) elaborated friend declarations to
12327   // be) that makes this tractable.
12328   //
12329   // FIXME: handle "template <> friend class A<T>;", which
12330   // is possibly well-formed?  Who even knows?
12331   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12332     Diag(Loc, diag::err_tagless_friend_type_template)
12333       << DS.getSourceRange();
12334     return nullptr;
12335   }
12336 
12337   // C++98 [class.friend]p1: A friend of a class is a function
12338   //   or class that is not a member of the class . . .
12339   // This is fixed in DR77, which just barely didn't make the C++03
12340   // deadline.  It's also a very silly restriction that seriously
12341   // affects inner classes and which nobody else seems to implement;
12342   // thus we never diagnose it, not even in -pedantic.
12343   //
12344   // But note that we could warn about it: it's always useless to
12345   // friend one of your own members (it's not, however, worthless to
12346   // friend a member of an arbitrary specialization of your template).
12347 
12348   Decl *D;
12349   if (unsigned NumTempParamLists = TempParams.size())
12350     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12351                                    NumTempParamLists,
12352                                    TempParams.data(),
12353                                    TSI,
12354                                    DS.getFriendSpecLoc());
12355   else
12356     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12357 
12358   if (!D)
12359     return nullptr;
12360 
12361   D->setAccess(AS_public);
12362   CurContext->addDecl(D);
12363 
12364   return D;
12365 }
12366 
12367 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12368                                         MultiTemplateParamsArg TemplateParams) {
12369   const DeclSpec &DS = D.getDeclSpec();
12370 
12371   assert(DS.isFriendSpecified());
12372   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12373 
12374   SourceLocation Loc = D.getIdentifierLoc();
12375   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12376 
12377   // C++ [class.friend]p1
12378   //   A friend of a class is a function or class....
12379   // Note that this sees through typedefs, which is intended.
12380   // It *doesn't* see through dependent types, which is correct
12381   // according to [temp.arg.type]p3:
12382   //   If a declaration acquires a function type through a
12383   //   type dependent on a template-parameter and this causes
12384   //   a declaration that does not use the syntactic form of a
12385   //   function declarator to have a function type, the program
12386   //   is ill-formed.
12387   if (!TInfo->getType()->isFunctionType()) {
12388     Diag(Loc, diag::err_unexpected_friend);
12389 
12390     // It might be worthwhile to try to recover by creating an
12391     // appropriate declaration.
12392     return nullptr;
12393   }
12394 
12395   // C++ [namespace.memdef]p3
12396   //  - If a friend declaration in a non-local class first declares a
12397   //    class or function, the friend class or function is a member
12398   //    of the innermost enclosing namespace.
12399   //  - The name of the friend is not found by simple name lookup
12400   //    until a matching declaration is provided in that namespace
12401   //    scope (either before or after the class declaration granting
12402   //    friendship).
12403   //  - If a friend function is called, its name may be found by the
12404   //    name lookup that considers functions from namespaces and
12405   //    classes associated with the types of the function arguments.
12406   //  - When looking for a prior declaration of a class or a function
12407   //    declared as a friend, scopes outside the innermost enclosing
12408   //    namespace scope are not considered.
12409 
12410   CXXScopeSpec &SS = D.getCXXScopeSpec();
12411   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12412   DeclarationName Name = NameInfo.getName();
12413   assert(Name);
12414 
12415   // Check for unexpanded parameter packs.
12416   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12417       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12418       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12419     return nullptr;
12420 
12421   // The context we found the declaration in, or in which we should
12422   // create the declaration.
12423   DeclContext *DC;
12424   Scope *DCScope = S;
12425   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12426                         ForRedeclaration);
12427 
12428   // There are five cases here.
12429   //   - There's no scope specifier and we're in a local class. Only look
12430   //     for functions declared in the immediately-enclosing block scope.
12431   // We recover from invalid scope qualifiers as if they just weren't there.
12432   FunctionDecl *FunctionContainingLocalClass = nullptr;
12433   if ((SS.isInvalid() || !SS.isSet()) &&
12434       (FunctionContainingLocalClass =
12435            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12436     // C++11 [class.friend]p11:
12437     //   If a friend declaration appears in a local class and the name
12438     //   specified is an unqualified name, a prior declaration is
12439     //   looked up without considering scopes that are outside the
12440     //   innermost enclosing non-class scope. For a friend function
12441     //   declaration, if there is no prior declaration, the program is
12442     //   ill-formed.
12443 
12444     // Find the innermost enclosing non-class scope. This is the block
12445     // scope containing the local class definition (or for a nested class,
12446     // the outer local class).
12447     DCScope = S->getFnParent();
12448 
12449     // Look up the function name in the scope.
12450     Previous.clear(LookupLocalFriendName);
12451     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12452 
12453     if (!Previous.empty()) {
12454       // All possible previous declarations must have the same context:
12455       // either they were declared at block scope or they are members of
12456       // one of the enclosing local classes.
12457       DC = Previous.getRepresentativeDecl()->getDeclContext();
12458     } else {
12459       // This is ill-formed, but provide the context that we would have
12460       // declared the function in, if we were permitted to, for error recovery.
12461       DC = FunctionContainingLocalClass;
12462     }
12463     adjustContextForLocalExternDecl(DC);
12464 
12465     // C++ [class.friend]p6:
12466     //   A function can be defined in a friend declaration of a class if and
12467     //   only if the class is a non-local class (9.8), the function name is
12468     //   unqualified, and the function has namespace scope.
12469     if (D.isFunctionDefinition()) {
12470       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12471     }
12472 
12473   //   - There's no scope specifier, in which case we just go to the
12474   //     appropriate scope and look for a function or function template
12475   //     there as appropriate.
12476   } else if (SS.isInvalid() || !SS.isSet()) {
12477     // C++11 [namespace.memdef]p3:
12478     //   If the name in a friend declaration is neither qualified nor
12479     //   a template-id and the declaration is a function or an
12480     //   elaborated-type-specifier, the lookup to determine whether
12481     //   the entity has been previously declared shall not consider
12482     //   any scopes outside the innermost enclosing namespace.
12483     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12484 
12485     // Find the appropriate context according to the above.
12486     DC = CurContext;
12487 
12488     // Skip class contexts.  If someone can cite chapter and verse
12489     // for this behavior, that would be nice --- it's what GCC and
12490     // EDG do, and it seems like a reasonable intent, but the spec
12491     // really only says that checks for unqualified existing
12492     // declarations should stop at the nearest enclosing namespace,
12493     // not that they should only consider the nearest enclosing
12494     // namespace.
12495     while (DC->isRecord())
12496       DC = DC->getParent();
12497 
12498     DeclContext *LookupDC = DC;
12499     while (LookupDC->isTransparentContext())
12500       LookupDC = LookupDC->getParent();
12501 
12502     while (true) {
12503       LookupQualifiedName(Previous, LookupDC);
12504 
12505       if (!Previous.empty()) {
12506         DC = LookupDC;
12507         break;
12508       }
12509 
12510       if (isTemplateId) {
12511         if (isa<TranslationUnitDecl>(LookupDC)) break;
12512       } else {
12513         if (LookupDC->isFileContext()) break;
12514       }
12515       LookupDC = LookupDC->getParent();
12516     }
12517 
12518     DCScope = getScopeForDeclContext(S, DC);
12519 
12520   //   - There's a non-dependent scope specifier, in which case we
12521   //     compute it and do a previous lookup there for a function
12522   //     or function template.
12523   } else if (!SS.getScopeRep()->isDependent()) {
12524     DC = computeDeclContext(SS);
12525     if (!DC) return nullptr;
12526 
12527     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12528 
12529     LookupQualifiedName(Previous, DC);
12530 
12531     // Ignore things found implicitly in the wrong scope.
12532     // TODO: better diagnostics for this case.  Suggesting the right
12533     // qualified scope would be nice...
12534     LookupResult::Filter F = Previous.makeFilter();
12535     while (F.hasNext()) {
12536       NamedDecl *D = F.next();
12537       if (!DC->InEnclosingNamespaceSetOf(
12538               D->getDeclContext()->getRedeclContext()))
12539         F.erase();
12540     }
12541     F.done();
12542 
12543     if (Previous.empty()) {
12544       D.setInvalidType();
12545       Diag(Loc, diag::err_qualified_friend_not_found)
12546           << Name << TInfo->getType();
12547       return nullptr;
12548     }
12549 
12550     // C++ [class.friend]p1: A friend of a class is a function or
12551     //   class that is not a member of the class . . .
12552     if (DC->Equals(CurContext))
12553       Diag(DS.getFriendSpecLoc(),
12554            getLangOpts().CPlusPlus11 ?
12555              diag::warn_cxx98_compat_friend_is_member :
12556              diag::err_friend_is_member);
12557 
12558     if (D.isFunctionDefinition()) {
12559       // C++ [class.friend]p6:
12560       //   A function can be defined in a friend declaration of a class if and
12561       //   only if the class is a non-local class (9.8), the function name is
12562       //   unqualified, and the function has namespace scope.
12563       SemaDiagnosticBuilder DB
12564         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12565 
12566       DB << SS.getScopeRep();
12567       if (DC->isFileContext())
12568         DB << FixItHint::CreateRemoval(SS.getRange());
12569       SS.clear();
12570     }
12571 
12572   //   - There's a scope specifier that does not match any template
12573   //     parameter lists, in which case we use some arbitrary context,
12574   //     create a method or method template, and wait for instantiation.
12575   //   - There's a scope specifier that does match some template
12576   //     parameter lists, which we don't handle right now.
12577   } else {
12578     if (D.isFunctionDefinition()) {
12579       // C++ [class.friend]p6:
12580       //   A function can be defined in a friend declaration of a class if and
12581       //   only if the class is a non-local class (9.8), the function name is
12582       //   unqualified, and the function has namespace scope.
12583       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12584         << SS.getScopeRep();
12585     }
12586 
12587     DC = CurContext;
12588     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12589   }
12590 
12591   if (!DC->isRecord()) {
12592     // This implies that it has to be an operator or function.
12593     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12594         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12595         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12596       Diag(Loc, diag::err_introducing_special_friend) <<
12597         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12598          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12599       return nullptr;
12600     }
12601   }
12602 
12603   // FIXME: This is an egregious hack to cope with cases where the scope stack
12604   // does not contain the declaration context, i.e., in an out-of-line
12605   // definition of a class.
12606   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12607   if (!DCScope) {
12608     FakeDCScope.setEntity(DC);
12609     DCScope = &FakeDCScope;
12610   }
12611 
12612   bool AddToScope = true;
12613   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12614                                           TemplateParams, AddToScope);
12615   if (!ND) return nullptr;
12616 
12617   assert(ND->getLexicalDeclContext() == CurContext);
12618 
12619   // If we performed typo correction, we might have added a scope specifier
12620   // and changed the decl context.
12621   DC = ND->getDeclContext();
12622 
12623   // Add the function declaration to the appropriate lookup tables,
12624   // adjusting the redeclarations list as necessary.  We don't
12625   // want to do this yet if the friending class is dependent.
12626   //
12627   // Also update the scope-based lookup if the target context's
12628   // lookup context is in lexical scope.
12629   if (!CurContext->isDependentContext()) {
12630     DC = DC->getRedeclContext();
12631     DC->makeDeclVisibleInContext(ND);
12632     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12633       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12634   }
12635 
12636   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12637                                        D.getIdentifierLoc(), ND,
12638                                        DS.getFriendSpecLoc());
12639   FrD->setAccess(AS_public);
12640   CurContext->addDecl(FrD);
12641 
12642   if (ND->isInvalidDecl()) {
12643     FrD->setInvalidDecl();
12644   } else {
12645     if (DC->isRecord()) CheckFriendAccess(ND);
12646 
12647     FunctionDecl *FD;
12648     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12649       FD = FTD->getTemplatedDecl();
12650     else
12651       FD = cast<FunctionDecl>(ND);
12652 
12653     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12654     // default argument expression, that declaration shall be a definition
12655     // and shall be the only declaration of the function or function
12656     // template in the translation unit.
12657     if (functionDeclHasDefaultArgument(FD)) {
12658       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12659         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12660         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12661       } else if (!D.isFunctionDefinition())
12662         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12663     }
12664 
12665     // Mark templated-scope function declarations as unsupported.
12666     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12667       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12668         << SS.getScopeRep() << SS.getRange()
12669         << cast<CXXRecordDecl>(CurContext);
12670       FrD->setUnsupportedFriend(true);
12671     }
12672   }
12673 
12674   return ND;
12675 }
12676 
12677 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12678   AdjustDeclIfTemplate(Dcl);
12679 
12680   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12681   if (!Fn) {
12682     Diag(DelLoc, diag::err_deleted_non_function);
12683     return;
12684   }
12685 
12686   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12687     // Don't consider the implicit declaration we generate for explicit
12688     // specializations. FIXME: Do not generate these implicit declarations.
12689     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12690          Prev->getPreviousDecl()) &&
12691         !Prev->isDefined()) {
12692       Diag(DelLoc, diag::err_deleted_decl_not_first);
12693       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12694            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12695                               : diag::note_previous_declaration);
12696     }
12697     // If the declaration wasn't the first, we delete the function anyway for
12698     // recovery.
12699     Fn = Fn->getCanonicalDecl();
12700   }
12701 
12702   // dllimport/dllexport cannot be deleted.
12703   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12704     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12705     Fn->setInvalidDecl();
12706   }
12707 
12708   if (Fn->isDeleted())
12709     return;
12710 
12711   // See if we're deleting a function which is already known to override a
12712   // non-deleted virtual function.
12713   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12714     bool IssuedDiagnostic = false;
12715     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12716                                         E = MD->end_overridden_methods();
12717          I != E; ++I) {
12718       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12719         if (!IssuedDiagnostic) {
12720           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12721           IssuedDiagnostic = true;
12722         }
12723         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12724       }
12725     }
12726   }
12727 
12728   // C++11 [basic.start.main]p3:
12729   //   A program that defines main as deleted [...] is ill-formed.
12730   if (Fn->isMain())
12731     Diag(DelLoc, diag::err_deleted_main);
12732 
12733   Fn->setDeletedAsWritten();
12734 }
12735 
12736 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12737   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12738 
12739   if (MD) {
12740     if (MD->getParent()->isDependentType()) {
12741       MD->setDefaulted();
12742       MD->setExplicitlyDefaulted();
12743       return;
12744     }
12745 
12746     CXXSpecialMember Member = getSpecialMember(MD);
12747     if (Member == CXXInvalid) {
12748       if (!MD->isInvalidDecl())
12749         Diag(DefaultLoc, diag::err_default_special_members);
12750       return;
12751     }
12752 
12753     MD->setDefaulted();
12754     MD->setExplicitlyDefaulted();
12755 
12756     // If this definition appears within the record, do the checking when
12757     // the record is complete.
12758     const FunctionDecl *Primary = MD;
12759     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12760       // Find the uninstantiated declaration that actually had the '= default'
12761       // on it.
12762       Pattern->isDefined(Primary);
12763 
12764     // If the method was defaulted on its first declaration, we will have
12765     // already performed the checking in CheckCompletedCXXClass. Such a
12766     // declaration doesn't trigger an implicit definition.
12767     if (Primary == Primary->getCanonicalDecl())
12768       return;
12769 
12770     CheckExplicitlyDefaultedSpecialMember(MD);
12771 
12772     if (MD->isInvalidDecl())
12773       return;
12774 
12775     switch (Member) {
12776     case CXXDefaultConstructor:
12777       DefineImplicitDefaultConstructor(DefaultLoc,
12778                                        cast<CXXConstructorDecl>(MD));
12779       break;
12780     case CXXCopyConstructor:
12781       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12782       break;
12783     case CXXCopyAssignment:
12784       DefineImplicitCopyAssignment(DefaultLoc, MD);
12785       break;
12786     case CXXDestructor:
12787       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12788       break;
12789     case CXXMoveConstructor:
12790       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12791       break;
12792     case CXXMoveAssignment:
12793       DefineImplicitMoveAssignment(DefaultLoc, MD);
12794       break;
12795     case CXXInvalid:
12796       llvm_unreachable("Invalid special member.");
12797     }
12798   } else {
12799     Diag(DefaultLoc, diag::err_default_special_members);
12800   }
12801 }
12802 
12803 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12804   for (Stmt::child_range CI = S->children(); CI; ++CI) {
12805     Stmt *SubStmt = *CI;
12806     if (!SubStmt)
12807       continue;
12808     if (isa<ReturnStmt>(SubStmt))
12809       Self.Diag(SubStmt->getLocStart(),
12810            diag::err_return_in_constructor_handler);
12811     if (!isa<Expr>(SubStmt))
12812       SearchForReturnInStmt(Self, SubStmt);
12813   }
12814 }
12815 
12816 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12817   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12818     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12819     SearchForReturnInStmt(*this, Handler);
12820   }
12821 }
12822 
12823 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12824                                              const CXXMethodDecl *Old) {
12825   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12826   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12827 
12828   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12829 
12830   // If the calling conventions match, everything is fine
12831   if (NewCC == OldCC)
12832     return false;
12833 
12834   // If the calling conventions mismatch because the new function is static,
12835   // suppress the calling convention mismatch error; the error about static
12836   // function override (err_static_overrides_virtual from
12837   // Sema::CheckFunctionDeclaration) is more clear.
12838   if (New->getStorageClass() == SC_Static)
12839     return false;
12840 
12841   Diag(New->getLocation(),
12842        diag::err_conflicting_overriding_cc_attributes)
12843     << New->getDeclName() << New->getType() << Old->getType();
12844   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12845   return true;
12846 }
12847 
12848 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12849                                              const CXXMethodDecl *Old) {
12850   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12851   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12852 
12853   if (Context.hasSameType(NewTy, OldTy) ||
12854       NewTy->isDependentType() || OldTy->isDependentType())
12855     return false;
12856 
12857   // Check if the return types are covariant
12858   QualType NewClassTy, OldClassTy;
12859 
12860   /// Both types must be pointers or references to classes.
12861   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12862     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12863       NewClassTy = NewPT->getPointeeType();
12864       OldClassTy = OldPT->getPointeeType();
12865     }
12866   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12867     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12868       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12869         NewClassTy = NewRT->getPointeeType();
12870         OldClassTy = OldRT->getPointeeType();
12871       }
12872     }
12873   }
12874 
12875   // The return types aren't either both pointers or references to a class type.
12876   if (NewClassTy.isNull()) {
12877     Diag(New->getLocation(),
12878          diag::err_different_return_type_for_overriding_virtual_function)
12879         << New->getDeclName() << NewTy << OldTy
12880         << New->getReturnTypeSourceRange();
12881     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12882         << Old->getReturnTypeSourceRange();
12883 
12884     return true;
12885   }
12886 
12887   // C++ [class.virtual]p6:
12888   //   If the return type of D::f differs from the return type of B::f, the
12889   //   class type in the return type of D::f shall be complete at the point of
12890   //   declaration of D::f or shall be the class type D.
12891   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12892     if (!RT->isBeingDefined() &&
12893         RequireCompleteType(New->getLocation(), NewClassTy,
12894                             diag::err_covariant_return_incomplete,
12895                             New->getDeclName()))
12896     return true;
12897   }
12898 
12899   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12900     // Check if the new class derives from the old class.
12901     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12902       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12903           << New->getDeclName() << NewTy << OldTy
12904           << New->getReturnTypeSourceRange();
12905       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12906           << Old->getReturnTypeSourceRange();
12907       return true;
12908     }
12909 
12910     // Check if we the conversion from derived to base is valid.
12911     if (CheckDerivedToBaseConversion(
12912             NewClassTy, OldClassTy,
12913             diag::err_covariant_return_inaccessible_base,
12914             diag::err_covariant_return_ambiguous_derived_to_base_conv,
12915             New->getLocation(), New->getReturnTypeSourceRange(),
12916             New->getDeclName(), nullptr)) {
12917       // FIXME: this note won't trigger for delayed access control
12918       // diagnostics, and it's impossible to get an undelayed error
12919       // here from access control during the original parse because
12920       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12921       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12922           << Old->getReturnTypeSourceRange();
12923       return true;
12924     }
12925   }
12926 
12927   // The qualifiers of the return types must be the same.
12928   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12929     Diag(New->getLocation(),
12930          diag::err_covariant_return_type_different_qualifications)
12931         << New->getDeclName() << NewTy << OldTy
12932         << New->getReturnTypeSourceRange();
12933     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12934         << Old->getReturnTypeSourceRange();
12935     return true;
12936   };
12937 
12938 
12939   // The new class type must have the same or less qualifiers as the old type.
12940   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12941     Diag(New->getLocation(),
12942          diag::err_covariant_return_type_class_type_more_qualified)
12943         << New->getDeclName() << NewTy << OldTy
12944         << New->getReturnTypeSourceRange();
12945     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12946         << Old->getReturnTypeSourceRange();
12947     return true;
12948   };
12949 
12950   return false;
12951 }
12952 
12953 /// \brief Mark the given method pure.
12954 ///
12955 /// \param Method the method to be marked pure.
12956 ///
12957 /// \param InitRange the source range that covers the "0" initializer.
12958 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12959   SourceLocation EndLoc = InitRange.getEnd();
12960   if (EndLoc.isValid())
12961     Method->setRangeEnd(EndLoc);
12962 
12963   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12964     Method->setPure();
12965     return false;
12966   }
12967 
12968   if (!Method->isInvalidDecl())
12969     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12970       << Method->getDeclName() << InitRange;
12971   return true;
12972 }
12973 
12974 /// \brief Determine whether the given declaration is a static data member.
12975 static bool isStaticDataMember(const Decl *D) {
12976   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12977     return Var->isStaticDataMember();
12978 
12979   return false;
12980 }
12981 
12982 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12983 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12984 /// is a fresh scope pushed for just this purpose.
12985 ///
12986 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12987 /// static data member of class X, names should be looked up in the scope of
12988 /// class X.
12989 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12990   // If there is no declaration, there was an error parsing it.
12991   if (!D || D->isInvalidDecl())
12992     return;
12993 
12994   // We will always have a nested name specifier here, but this declaration
12995   // might not be out of line if the specifier names the current namespace:
12996   //   extern int n;
12997   //   int ::n = 0;
12998   if (D->isOutOfLine())
12999     EnterDeclaratorContext(S, D->getDeclContext());
13000 
13001   // If we are parsing the initializer for a static data member, push a
13002   // new expression evaluation context that is associated with this static
13003   // data member.
13004   if (isStaticDataMember(D))
13005     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
13006 }
13007 
13008 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
13009 /// initializer for the out-of-line declaration 'D'.
13010 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
13011   // If there is no declaration, there was an error parsing it.
13012   if (!D || D->isInvalidDecl())
13013     return;
13014 
13015   if (isStaticDataMember(D))
13016     PopExpressionEvaluationContext();
13017 
13018   if (D->isOutOfLine())
13019     ExitDeclaratorContext(S);
13020 }
13021 
13022 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13023 /// C++ if/switch/while/for statement.
13024 /// e.g: "if (int x = f()) {...}"
13025 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
13026   // C++ 6.4p2:
13027   // The declarator shall not specify a function or an array.
13028   // The type-specifier-seq shall not contain typedef and shall not declare a
13029   // new class or enumeration.
13030   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13031          "Parser allowed 'typedef' as storage class of condition decl.");
13032 
13033   Decl *Dcl = ActOnDeclarator(S, D);
13034   if (!Dcl)
13035     return true;
13036 
13037   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13038     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13039       << D.getSourceRange();
13040     return true;
13041   }
13042 
13043   return Dcl;
13044 }
13045 
13046 void Sema::LoadExternalVTableUses() {
13047   if (!ExternalSource)
13048     return;
13049 
13050   SmallVector<ExternalVTableUse, 4> VTables;
13051   ExternalSource->ReadUsedVTables(VTables);
13052   SmallVector<VTableUse, 4> NewUses;
13053   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13054     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13055       = VTablesUsed.find(VTables[I].Record);
13056     // Even if a definition wasn't required before, it may be required now.
13057     if (Pos != VTablesUsed.end()) {
13058       if (!Pos->second && VTables[I].DefinitionRequired)
13059         Pos->second = true;
13060       continue;
13061     }
13062 
13063     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13064     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13065   }
13066 
13067   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13068 }
13069 
13070 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13071                           bool DefinitionRequired) {
13072   // Ignore any vtable uses in unevaluated operands or for classes that do
13073   // not have a vtable.
13074   if (!Class->isDynamicClass() || Class->isDependentContext() ||
13075       CurContext->isDependentContext() || isUnevaluatedContext())
13076     return;
13077 
13078   // Try to insert this class into the map.
13079   LoadExternalVTableUses();
13080   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13081   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13082     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13083   if (!Pos.second) {
13084     // If we already had an entry, check to see if we are promoting this vtable
13085     // to require a definition. If so, we need to reappend to the VTableUses
13086     // list, since we may have already processed the first entry.
13087     if (DefinitionRequired && !Pos.first->second) {
13088       Pos.first->second = true;
13089     } else {
13090       // Otherwise, we can early exit.
13091       return;
13092     }
13093   } else {
13094     // The Microsoft ABI requires that we perform the destructor body
13095     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13096     // the deleting destructor is emitted with the vtable, not with the
13097     // destructor definition as in the Itanium ABI.
13098     // If it has a definition, we do the check at that point instead.
13099     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13100         Class->hasUserDeclaredDestructor() &&
13101         !Class->getDestructor()->isDefined() &&
13102         !Class->getDestructor()->isDeleted()) {
13103       CXXDestructorDecl *DD = Class->getDestructor();
13104       ContextRAII SavedContext(*this, DD);
13105       CheckDestructor(DD);
13106     }
13107   }
13108 
13109   // Local classes need to have their virtual members marked
13110   // immediately. For all other classes, we mark their virtual members
13111   // at the end of the translation unit.
13112   if (Class->isLocalClass())
13113     MarkVirtualMembersReferenced(Loc, Class);
13114   else
13115     VTableUses.push_back(std::make_pair(Class, Loc));
13116 }
13117 
13118 bool Sema::DefineUsedVTables() {
13119   LoadExternalVTableUses();
13120   if (VTableUses.empty())
13121     return false;
13122 
13123   // Note: The VTableUses vector could grow as a result of marking
13124   // the members of a class as "used", so we check the size each
13125   // time through the loop and prefer indices (which are stable) to
13126   // iterators (which are not).
13127   bool DefinedAnything = false;
13128   for (unsigned I = 0; I != VTableUses.size(); ++I) {
13129     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13130     if (!Class)
13131       continue;
13132 
13133     SourceLocation Loc = VTableUses[I].second;
13134 
13135     bool DefineVTable = true;
13136 
13137     // If this class has a key function, but that key function is
13138     // defined in another translation unit, we don't need to emit the
13139     // vtable even though we're using it.
13140     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13141     if (KeyFunction && !KeyFunction->hasBody()) {
13142       // The key function is in another translation unit.
13143       DefineVTable = false;
13144       TemplateSpecializationKind TSK =
13145           KeyFunction->getTemplateSpecializationKind();
13146       assert(TSK != TSK_ExplicitInstantiationDefinition &&
13147              TSK != TSK_ImplicitInstantiation &&
13148              "Instantiations don't have key functions");
13149       (void)TSK;
13150     } else if (!KeyFunction) {
13151       // If we have a class with no key function that is the subject
13152       // of an explicit instantiation declaration, suppress the
13153       // vtable; it will live with the explicit instantiation
13154       // definition.
13155       bool IsExplicitInstantiationDeclaration
13156         = Class->getTemplateSpecializationKind()
13157                                       == TSK_ExplicitInstantiationDeclaration;
13158       for (auto R : Class->redecls()) {
13159         TemplateSpecializationKind TSK
13160           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13161         if (TSK == TSK_ExplicitInstantiationDeclaration)
13162           IsExplicitInstantiationDeclaration = true;
13163         else if (TSK == TSK_ExplicitInstantiationDefinition) {
13164           IsExplicitInstantiationDeclaration = false;
13165           break;
13166         }
13167       }
13168 
13169       if (IsExplicitInstantiationDeclaration)
13170         DefineVTable = false;
13171     }
13172 
13173     // The exception specifications for all virtual members may be needed even
13174     // if we are not providing an authoritative form of the vtable in this TU.
13175     // We may choose to emit it available_externally anyway.
13176     if (!DefineVTable) {
13177       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13178       continue;
13179     }
13180 
13181     // Mark all of the virtual members of this class as referenced, so
13182     // that we can build a vtable. Then, tell the AST consumer that a
13183     // vtable for this class is required.
13184     DefinedAnything = true;
13185     MarkVirtualMembersReferenced(Loc, Class);
13186     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13187     if (VTablesUsed[Canonical])
13188       Consumer.HandleVTable(Class);
13189 
13190     // Optionally warn if we're emitting a weak vtable.
13191     if (Class->isExternallyVisible() &&
13192         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13193       const FunctionDecl *KeyFunctionDef = nullptr;
13194       if (!KeyFunction ||
13195           (KeyFunction->hasBody(KeyFunctionDef) &&
13196            KeyFunctionDef->isInlined()))
13197         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13198              TSK_ExplicitInstantiationDefinition
13199              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13200           << Class;
13201     }
13202   }
13203   VTableUses.clear();
13204 
13205   return DefinedAnything;
13206 }
13207 
13208 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13209                                                  const CXXRecordDecl *RD) {
13210   for (const auto *I : RD->methods())
13211     if (I->isVirtual() && !I->isPure())
13212       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13213 }
13214 
13215 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13216                                         const CXXRecordDecl *RD) {
13217   // Mark all functions which will appear in RD's vtable as used.
13218   CXXFinalOverriderMap FinalOverriders;
13219   RD->getFinalOverriders(FinalOverriders);
13220   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13221                                             E = FinalOverriders.end();
13222        I != E; ++I) {
13223     for (OverridingMethods::const_iterator OI = I->second.begin(),
13224                                            OE = I->second.end();
13225          OI != OE; ++OI) {
13226       assert(OI->second.size() > 0 && "no final overrider");
13227       CXXMethodDecl *Overrider = OI->second.front().Method;
13228 
13229       // C++ [basic.def.odr]p2:
13230       //   [...] A virtual member function is used if it is not pure. [...]
13231       if (!Overrider->isPure())
13232         MarkFunctionReferenced(Loc, Overrider);
13233     }
13234   }
13235 
13236   // Only classes that have virtual bases need a VTT.
13237   if (RD->getNumVBases() == 0)
13238     return;
13239 
13240   for (const auto &I : RD->bases()) {
13241     const CXXRecordDecl *Base =
13242         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13243     if (Base->getNumVBases() == 0)
13244       continue;
13245     MarkVirtualMembersReferenced(Loc, Base);
13246   }
13247 }
13248 
13249 /// SetIvarInitializers - This routine builds initialization ASTs for the
13250 /// Objective-C implementation whose ivars need be initialized.
13251 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13252   if (!getLangOpts().CPlusPlus)
13253     return;
13254   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13255     SmallVector<ObjCIvarDecl*, 8> ivars;
13256     CollectIvarsToConstructOrDestruct(OID, ivars);
13257     if (ivars.empty())
13258       return;
13259     SmallVector<CXXCtorInitializer*, 32> AllToInit;
13260     for (unsigned i = 0; i < ivars.size(); i++) {
13261       FieldDecl *Field = ivars[i];
13262       if (Field->isInvalidDecl())
13263         continue;
13264 
13265       CXXCtorInitializer *Member;
13266       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13267       InitializationKind InitKind =
13268         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13269 
13270       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13271       ExprResult MemberInit =
13272         InitSeq.Perform(*this, InitEntity, InitKind, None);
13273       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13274       // Note, MemberInit could actually come back empty if no initialization
13275       // is required (e.g., because it would call a trivial default constructor)
13276       if (!MemberInit.get() || MemberInit.isInvalid())
13277         continue;
13278 
13279       Member =
13280         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13281                                          SourceLocation(),
13282                                          MemberInit.getAs<Expr>(),
13283                                          SourceLocation());
13284       AllToInit.push_back(Member);
13285 
13286       // Be sure that the destructor is accessible and is marked as referenced.
13287       if (const RecordType *RecordTy =
13288               Context.getBaseElementType(Field->getType())
13289                   ->getAs<RecordType>()) {
13290         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13291         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13292           MarkFunctionReferenced(Field->getLocation(), Destructor);
13293           CheckDestructorAccess(Field->getLocation(), Destructor,
13294                             PDiag(diag::err_access_dtor_ivar)
13295                               << Context.getBaseElementType(Field->getType()));
13296         }
13297       }
13298     }
13299     ObjCImplementation->setIvarInitializers(Context,
13300                                             AllToInit.data(), AllToInit.size());
13301   }
13302 }
13303 
13304 static
13305 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13306                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13307                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13308                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13309                            Sema &S) {
13310   if (Ctor->isInvalidDecl())
13311     return;
13312 
13313   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13314 
13315   // Target may not be determinable yet, for instance if this is a dependent
13316   // call in an uninstantiated template.
13317   if (Target) {
13318     const FunctionDecl *FNTarget = nullptr;
13319     (void)Target->hasBody(FNTarget);
13320     Target = const_cast<CXXConstructorDecl*>(
13321       cast_or_null<CXXConstructorDecl>(FNTarget));
13322   }
13323 
13324   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13325                      // Avoid dereferencing a null pointer here.
13326                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13327 
13328   if (!Current.insert(Canonical).second)
13329     return;
13330 
13331   // We know that beyond here, we aren't chaining into a cycle.
13332   if (!Target || !Target->isDelegatingConstructor() ||
13333       Target->isInvalidDecl() || Valid.count(TCanonical)) {
13334     Valid.insert(Current.begin(), Current.end());
13335     Current.clear();
13336   // We've hit a cycle.
13337   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13338              Current.count(TCanonical)) {
13339     // If we haven't diagnosed this cycle yet, do so now.
13340     if (!Invalid.count(TCanonical)) {
13341       S.Diag((*Ctor->init_begin())->getSourceLocation(),
13342              diag::warn_delegating_ctor_cycle)
13343         << Ctor;
13344 
13345       // Don't add a note for a function delegating directly to itself.
13346       if (TCanonical != Canonical)
13347         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13348 
13349       CXXConstructorDecl *C = Target;
13350       while (C->getCanonicalDecl() != Canonical) {
13351         const FunctionDecl *FNTarget = nullptr;
13352         (void)C->getTargetConstructor()->hasBody(FNTarget);
13353         assert(FNTarget && "Ctor cycle through bodiless function");
13354 
13355         C = const_cast<CXXConstructorDecl*>(
13356           cast<CXXConstructorDecl>(FNTarget));
13357         S.Diag(C->getLocation(), diag::note_which_delegates_to);
13358       }
13359     }
13360 
13361     Invalid.insert(Current.begin(), Current.end());
13362     Current.clear();
13363   } else {
13364     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13365   }
13366 }
13367 
13368 
13369 void Sema::CheckDelegatingCtorCycles() {
13370   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13371 
13372   for (DelegatingCtorDeclsType::iterator
13373          I = DelegatingCtorDecls.begin(ExternalSource),
13374          E = DelegatingCtorDecls.end();
13375        I != E; ++I)
13376     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13377 
13378   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13379                                                          CE = Invalid.end();
13380        CI != CE; ++CI)
13381     (*CI)->setInvalidDecl();
13382 }
13383 
13384 namespace {
13385   /// \brief AST visitor that finds references to the 'this' expression.
13386   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13387     Sema &S;
13388 
13389   public:
13390     explicit FindCXXThisExpr(Sema &S) : S(S) { }
13391 
13392     bool VisitCXXThisExpr(CXXThisExpr *E) {
13393       S.Diag(E->getLocation(), diag::err_this_static_member_func)
13394         << E->isImplicit();
13395       return false;
13396     }
13397   };
13398 }
13399 
13400 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13401   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13402   if (!TSInfo)
13403     return false;
13404 
13405   TypeLoc TL = TSInfo->getTypeLoc();
13406   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13407   if (!ProtoTL)
13408     return false;
13409 
13410   // C++11 [expr.prim.general]p3:
13411   //   [The expression this] shall not appear before the optional
13412   //   cv-qualifier-seq and it shall not appear within the declaration of a
13413   //   static member function (although its type and value category are defined
13414   //   within a static member function as they are within a non-static member
13415   //   function). [ Note: this is because declaration matching does not occur
13416   //  until the complete declarator is known. - end note ]
13417   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13418   FindCXXThisExpr Finder(*this);
13419 
13420   // If the return type came after the cv-qualifier-seq, check it now.
13421   if (Proto->hasTrailingReturn() &&
13422       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13423     return true;
13424 
13425   // Check the exception specification.
13426   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13427     return true;
13428 
13429   return checkThisInStaticMemberFunctionAttributes(Method);
13430 }
13431 
13432 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13433   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13434   if (!TSInfo)
13435     return false;
13436 
13437   TypeLoc TL = TSInfo->getTypeLoc();
13438   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13439   if (!ProtoTL)
13440     return false;
13441 
13442   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13443   FindCXXThisExpr Finder(*this);
13444 
13445   switch (Proto->getExceptionSpecType()) {
13446   case EST_Unparsed:
13447   case EST_Uninstantiated:
13448   case EST_Unevaluated:
13449   case EST_BasicNoexcept:
13450   case EST_DynamicNone:
13451   case EST_MSAny:
13452   case EST_None:
13453     break;
13454 
13455   case EST_ComputedNoexcept:
13456     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13457       return true;
13458 
13459   case EST_Dynamic:
13460     for (const auto &E : Proto->exceptions()) {
13461       if (!Finder.TraverseType(E))
13462         return true;
13463     }
13464     break;
13465   }
13466 
13467   return false;
13468 }
13469 
13470 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13471   FindCXXThisExpr Finder(*this);
13472 
13473   // Check attributes.
13474   for (const auto *A : Method->attrs()) {
13475     // FIXME: This should be emitted by tblgen.
13476     Expr *Arg = nullptr;
13477     ArrayRef<Expr *> Args;
13478     if (const auto *G = dyn_cast<GuardedByAttr>(A))
13479       Arg = G->getArg();
13480     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13481       Arg = G->getArg();
13482     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13483       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13484     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13485       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13486     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13487       Arg = ETLF->getSuccessValue();
13488       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13489     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13490       Arg = STLF->getSuccessValue();
13491       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13492     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13493       Arg = LR->getArg();
13494     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13495       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13496     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13497       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13498     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13499       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13500     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13501       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13502     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13503       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13504 
13505     if (Arg && !Finder.TraverseStmt(Arg))
13506       return true;
13507 
13508     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13509       if (!Finder.TraverseStmt(Args[I]))
13510         return true;
13511     }
13512   }
13513 
13514   return false;
13515 }
13516 
13517 void Sema::checkExceptionSpecification(
13518     bool IsTopLevel, ExceptionSpecificationType EST,
13519     ArrayRef<ParsedType> DynamicExceptions,
13520     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13521     SmallVectorImpl<QualType> &Exceptions,
13522     FunctionProtoType::ExceptionSpecInfo &ESI) {
13523   Exceptions.clear();
13524   ESI.Type = EST;
13525   if (EST == EST_Dynamic) {
13526     Exceptions.reserve(DynamicExceptions.size());
13527     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13528       // FIXME: Preserve type source info.
13529       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13530 
13531       if (IsTopLevel) {
13532         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13533         collectUnexpandedParameterPacks(ET, Unexpanded);
13534         if (!Unexpanded.empty()) {
13535           DiagnoseUnexpandedParameterPacks(
13536               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13537               Unexpanded);
13538           continue;
13539         }
13540       }
13541 
13542       // Check that the type is valid for an exception spec, and
13543       // drop it if not.
13544       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13545         Exceptions.push_back(ET);
13546     }
13547     ESI.Exceptions = Exceptions;
13548     return;
13549   }
13550 
13551   if (EST == EST_ComputedNoexcept) {
13552     // If an error occurred, there's no expression here.
13553     if (NoexceptExpr) {
13554       assert((NoexceptExpr->isTypeDependent() ||
13555               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13556               Context.BoolTy) &&
13557              "Parser should have made sure that the expression is boolean");
13558       if (IsTopLevel && NoexceptExpr &&
13559           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13560         ESI.Type = EST_BasicNoexcept;
13561         return;
13562       }
13563 
13564       if (!NoexceptExpr->isValueDependent())
13565         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13566                          diag::err_noexcept_needs_constant_expression,
13567                          /*AllowFold*/ false).get();
13568       ESI.NoexceptExpr = NoexceptExpr;
13569     }
13570     return;
13571   }
13572 }
13573 
13574 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13575              ExceptionSpecificationType EST,
13576              SourceRange SpecificationRange,
13577              ArrayRef<ParsedType> DynamicExceptions,
13578              ArrayRef<SourceRange> DynamicExceptionRanges,
13579              Expr *NoexceptExpr) {
13580   if (!MethodD)
13581     return;
13582 
13583   // Dig out the method we're referring to.
13584   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13585     MethodD = FunTmpl->getTemplatedDecl();
13586 
13587   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13588   if (!Method)
13589     return;
13590 
13591   // Check the exception specification.
13592   llvm::SmallVector<QualType, 4> Exceptions;
13593   FunctionProtoType::ExceptionSpecInfo ESI;
13594   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13595                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
13596                               ESI);
13597 
13598   // Update the exception specification on the function type.
13599   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13600 
13601   if (Method->isStatic())
13602     checkThisInStaticMemberFunctionExceptionSpec(Method);
13603 
13604   if (Method->isVirtual()) {
13605     // Check overrides, which we previously had to delay.
13606     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13607                                      OEnd = Method->end_overridden_methods();
13608          O != OEnd; ++O)
13609       CheckOverridingFunctionExceptionSpec(Method, *O);
13610   }
13611 }
13612 
13613 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13614 ///
13615 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13616                                        SourceLocation DeclStart,
13617                                        Declarator &D, Expr *BitWidth,
13618                                        InClassInitStyle InitStyle,
13619                                        AccessSpecifier AS,
13620                                        AttributeList *MSPropertyAttr) {
13621   IdentifierInfo *II = D.getIdentifier();
13622   if (!II) {
13623     Diag(DeclStart, diag::err_anonymous_property);
13624     return nullptr;
13625   }
13626   SourceLocation Loc = D.getIdentifierLoc();
13627 
13628   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13629   QualType T = TInfo->getType();
13630   if (getLangOpts().CPlusPlus) {
13631     CheckExtraCXXDefaultArguments(D);
13632 
13633     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13634                                         UPPC_DataMemberType)) {
13635       D.setInvalidType();
13636       T = Context.IntTy;
13637       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13638     }
13639   }
13640 
13641   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13642 
13643   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13644     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13645          diag::err_invalid_thread)
13646       << DeclSpec::getSpecifierName(TSCS);
13647 
13648   // Check to see if this name was declared as a member previously
13649   NamedDecl *PrevDecl = nullptr;
13650   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13651   LookupName(Previous, S);
13652   switch (Previous.getResultKind()) {
13653   case LookupResult::Found:
13654   case LookupResult::FoundUnresolvedValue:
13655     PrevDecl = Previous.getAsSingle<NamedDecl>();
13656     break;
13657 
13658   case LookupResult::FoundOverloaded:
13659     PrevDecl = Previous.getRepresentativeDecl();
13660     break;
13661 
13662   case LookupResult::NotFound:
13663   case LookupResult::NotFoundInCurrentInstantiation:
13664   case LookupResult::Ambiguous:
13665     break;
13666   }
13667 
13668   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13669     // Maybe we will complain about the shadowed template parameter.
13670     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13671     // Just pretend that we didn't see the previous declaration.
13672     PrevDecl = nullptr;
13673   }
13674 
13675   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13676     PrevDecl = nullptr;
13677 
13678   SourceLocation TSSL = D.getLocStart();
13679   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13680   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13681       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13682   ProcessDeclAttributes(TUScope, NewPD, D);
13683   NewPD->setAccess(AS);
13684 
13685   if (NewPD->isInvalidDecl())
13686     Record->setInvalidDecl();
13687 
13688   if (D.getDeclSpec().isModulePrivateSpecified())
13689     NewPD->setModulePrivate();
13690 
13691   if (NewPD->isInvalidDecl() && PrevDecl) {
13692     // Don't introduce NewFD into scope; there's already something
13693     // with the same name in the same scope.
13694   } else if (II) {
13695     PushOnScopeChains(NewPD, S);
13696   } else
13697     Record->addDecl(NewPD);
13698 
13699   return NewPD;
13700 }
13701