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 "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/SmallString.h"
41 #include <map>
42 #include <set>
43 
44 using namespace clang;
45 
46 //===----------------------------------------------------------------------===//
47 // CheckDefaultArgumentVisitor
48 //===----------------------------------------------------------------------===//
49 
50 namespace {
51   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
52   /// the default argument of a parameter to determine whether it
53   /// contains any ill-formed subexpressions. For example, this will
54   /// diagnose the use of local variables or parameters within the
55   /// default argument expression.
56   class CheckDefaultArgumentVisitor
57     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
58     Expr *DefaultArg;
59     Sema *S;
60 
61   public:
62     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
63       : DefaultArg(defarg), S(s) {}
64 
65     bool VisitExpr(Expr *Node);
66     bool VisitDeclRefExpr(DeclRefExpr *DRE);
67     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
68     bool VisitLambdaExpr(LambdaExpr *Lambda);
69     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
70   };
71 
72   /// VisitExpr - Visit all of the children of this expression.
73   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
74     bool IsInvalid = false;
75     for (Stmt::child_range I = Node->children(); I; ++I)
76       IsInvalid |= Visit(*I);
77     return IsInvalid;
78   }
79 
80   /// VisitDeclRefExpr - Visit a reference to a declaration, to
81   /// determine whether this declaration can be used in the default
82   /// argument expression.
83   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
84     NamedDecl *Decl = DRE->getDecl();
85     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
86       // C++ [dcl.fct.default]p9
87       //   Default arguments are evaluated each time the function is
88       //   called. The order of evaluation of function arguments is
89       //   unspecified. Consequently, parameters of a function shall not
90       //   be used in default argument expressions, even if they are not
91       //   evaluated. Parameters of a function declared before a default
92       //   argument expression are in scope and can hide namespace and
93       //   class member names.
94       return S->Diag(DRE->getLocStart(),
95                      diag::err_param_default_argument_references_param)
96          << Param->getDeclName() << DefaultArg->getSourceRange();
97     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
98       // C++ [dcl.fct.default]p7
99       //   Local variables shall not be used in default argument
100       //   expressions.
101       if (VDecl->isLocalVarDecl())
102         return S->Diag(DRE->getLocStart(),
103                        diag::err_param_default_argument_references_local)
104           << VDecl->getDeclName() << DefaultArg->getSourceRange();
105     }
106 
107     return false;
108   }
109 
110   /// VisitCXXThisExpr - Visit a C++ "this" expression.
111   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
112     // C++ [dcl.fct.default]p8:
113     //   The keyword this shall not be used in a default argument of a
114     //   member function.
115     return S->Diag(ThisE->getLocStart(),
116                    diag::err_param_default_argument_references_this)
117                << ThisE->getSourceRange();
118   }
119 
120   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
121     bool Invalid = false;
122     for (PseudoObjectExpr::semantics_iterator
123            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
124       Expr *E = *i;
125 
126       // Look through bindings.
127       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
128         E = OVE->getSourceExpr();
129         assert(E && "pseudo-object binding without source expression?");
130       }
131 
132       Invalid |= Visit(E);
133     }
134     return Invalid;
135   }
136 
137   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
138     // C++11 [expr.lambda.prim]p13:
139     //   A lambda-expression appearing in a default argument shall not
140     //   implicitly or explicitly capture any entity.
141     if (Lambda->capture_begin() == Lambda->capture_end())
142       return false;
143 
144     return S->Diag(Lambda->getLocStart(),
145                    diag::err_lambda_capture_default_arg);
146   }
147 }
148 
149 void
150 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151                                                  const CXXMethodDecl *Method) {
152   // If we have an MSAny spec already, don't bother.
153   if (!Method || ComputedEST == EST_MSAny)
154     return;
155 
156   const FunctionProtoType *Proto
157     = Method->getType()->getAs<FunctionProtoType>();
158   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159   if (!Proto)
160     return;
161 
162   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
163 
164   // If this function can throw any exceptions, make a note of that.
165   if (EST == EST_MSAny || EST == EST_None) {
166     ClearExceptions();
167     ComputedEST = EST;
168     return;
169   }
170 
171   // FIXME: If the call to this decl is using any of its default arguments, we
172   // need to search them for potentially-throwing calls.
173 
174   // If this function has a basic noexcept, it doesn't affect the outcome.
175   if (EST == EST_BasicNoexcept)
176     return;
177 
178   // If we have a throw-all spec at this point, ignore the function.
179   if (ComputedEST == EST_None)
180     return;
181 
182   // If we're still at noexcept(true) and there's a nothrow() callee,
183   // change to that specification.
184   if (EST == EST_DynamicNone) {
185     if (ComputedEST == EST_BasicNoexcept)
186       ComputedEST = EST_DynamicNone;
187     return;
188   }
189 
190   // Check out noexcept specs.
191   if (EST == EST_ComputedNoexcept) {
192     FunctionProtoType::NoexceptResult NR =
193         Proto->getNoexceptSpec(Self->Context);
194     assert(NR != FunctionProtoType::NR_NoNoexcept &&
195            "Must have noexcept result for EST_ComputedNoexcept.");
196     assert(NR != FunctionProtoType::NR_Dependent &&
197            "Should not generate implicit declarations for dependent cases, "
198            "and don't know how to handle them anyway.");
199 
200     // noexcept(false) -> no spec on the new function
201     if (NR == FunctionProtoType::NR_Throw) {
202       ClearExceptions();
203       ComputedEST = EST_None;
204     }
205     // noexcept(true) won't change anything either.
206     return;
207   }
208 
209   assert(EST == EST_Dynamic && "EST case not considered earlier.");
210   assert(ComputedEST != EST_None &&
211          "Shouldn't collect exceptions when throw-all is guaranteed.");
212   ComputedEST = EST_Dynamic;
213   // Record the exceptions in this function's exception specification.
214   for (const auto &E : Proto->exceptions())
215     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
216       Exceptions.push_back(E);
217 }
218 
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220   if (!E || ComputedEST == EST_MSAny)
221     return;
222 
223   // FIXME:
224   //
225   // C++0x [except.spec]p14:
226   //   [An] implicit exception-specification specifies the type-id T if and
227   // only if T is allowed by the exception-specification of a function directly
228   // invoked by f's implicit definition; f shall allow all exceptions if any
229   // function it directly invokes allows all exceptions, and f shall allow no
230   // exceptions if every function it directly invokes allows no exceptions.
231   //
232   // Note in particular that if an implicit exception-specification is generated
233   // for a function containing a throw-expression, that specification can still
234   // be noexcept(true).
235   //
236   // Note also that 'directly invoked' is not defined in the standard, and there
237   // is no indication that we should only consider potentially-evaluated calls.
238   //
239   // Ultimately we should implement the intent of the standard: the exception
240   // specification should be the set of exceptions which can be thrown by the
241   // implicit definition. For now, we assume that any non-nothrow expression can
242   // throw any exception.
243 
244   if (Self->canThrow(E))
245     ComputedEST = EST_None;
246 }
247 
248 bool
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250                               SourceLocation EqualLoc) {
251   if (RequireCompleteType(Param->getLocation(), Param->getType(),
252                           diag::err_typecheck_decl_incomplete_type)) {
253     Param->setInvalidDecl();
254     return true;
255   }
256 
257   // C++ [dcl.fct.default]p5
258   //   A default argument expression is implicitly converted (clause
259   //   4) to the parameter type. The default argument expression has
260   //   the same semantic constraints as the initializer expression in
261   //   a declaration of a variable of the parameter type, using the
262   //   copy-initialization semantics (8.5).
263   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264                                                                     Param);
265   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266                                                            EqualLoc);
267   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269   if (Result.isInvalid())
270     return true;
271   Arg = Result.getAs<Expr>();
272 
273   CheckCompletedExpr(Arg, EqualLoc);
274   Arg = MaybeCreateExprWithCleanups(Arg);
275 
276   // Okay: add the default argument to the parameter
277   Param->setDefaultArg(Arg);
278 
279   // We have already instantiated this parameter; provide each of the
280   // instantiations with the uninstantiated default argument.
281   UnparsedDefaultArgInstantiationsMap::iterator InstPos
282     = UnparsedDefaultArgInstantiations.find(Param);
283   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287     // We're done tracking this parameter's instantiations.
288     UnparsedDefaultArgInstantiations.erase(InstPos);
289   }
290 
291   return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299                                 Expr *DefaultArg) {
300   if (!param || !DefaultArg)
301     return;
302 
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   UnparsedDefaultArgLocs.erase(Param);
305 
306   // Default arguments are only permitted in C++
307   if (!getLangOpts().CPlusPlus) {
308     Diag(EqualLoc, diag::err_param_default_argument)
309       << DefaultArg->getSourceRange();
310     Param->setInvalidDecl();
311     return;
312   }
313 
314   // Check for unexpanded parameter packs.
315   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316     Param->setInvalidDecl();
317     return;
318   }
319 
320   // Check that the default argument is well-formed
321   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
322   if (DefaultArgChecker.Visit(DefaultArg)) {
323     Param->setInvalidDecl();
324     return;
325   }
326 
327   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
328 }
329 
330 /// ActOnParamUnparsedDefaultArgument - We've seen a default
331 /// argument for a function parameter, but we can't parse it yet
332 /// because we're inside a class definition. Note that this default
333 /// argument will be parsed later.
334 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
335                                              SourceLocation EqualLoc,
336                                              SourceLocation ArgLoc) {
337   if (!param)
338     return;
339 
340   ParmVarDecl *Param = cast<ParmVarDecl>(param);
341   Param->setUnparsedDefaultArg();
342   UnparsedDefaultArgLocs[Param] = ArgLoc;
343 }
344 
345 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
346 /// the default argument for the parameter param failed.
347 void Sema::ActOnParamDefaultArgumentError(Decl *param,
348                                           SourceLocation EqualLoc) {
349   if (!param)
350     return;
351 
352   ParmVarDecl *Param = cast<ParmVarDecl>(param);
353   Param->setInvalidDecl();
354   UnparsedDefaultArgLocs.erase(Param);
355   Param->setDefaultArg(new(Context)
356                        OpaqueValueExpr(EqualLoc,
357                                        Param->getType().getNonReferenceType(),
358                                        VK_RValue));
359 }
360 
361 /// CheckExtraCXXDefaultArguments - Check for any extra default
362 /// arguments in the declarator, which is not a function declaration
363 /// or definition and therefore is not permitted to have default
364 /// arguments. This routine should be invoked for every declarator
365 /// that is not a function declaration or definition.
366 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367   // C++ [dcl.fct.default]p3
368   //   A default argument expression shall be specified only in the
369   //   parameter-declaration-clause of a function declaration or in a
370   //   template-parameter (14.1). It shall not be specified for a
371   //   parameter pack. If it is specified in a
372   //   parameter-declaration-clause, it shall not occur within a
373   //   declarator or abstract-declarator of a parameter-declaration.
374   bool MightBeFunction = D.isFunctionDeclarationContext();
375   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
376     DeclaratorChunk &chunk = D.getTypeObject(i);
377     if (chunk.Kind == DeclaratorChunk::Function) {
378       if (MightBeFunction) {
379         // This is a function declaration. It can have default arguments, but
380         // keep looking in case its return type is a function type with default
381         // arguments.
382         MightBeFunction = false;
383         continue;
384       }
385       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
386            ++argIdx) {
387         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
388         if (Param->hasUnparsedDefaultArg()) {
389           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
390           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
391             << SourceRange((*Toks)[1].getLocation(),
392                            Toks->back().getLocation());
393           delete Toks;
394           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
395         } else if (Param->getDefaultArg()) {
396           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397             << Param->getDefaultArg()->getSourceRange();
398           Param->setDefaultArg(nullptr);
399         }
400       }
401     } else if (chunk.Kind != DeclaratorChunk::Paren) {
402       MightBeFunction = false;
403     }
404   }
405 }
406 
407 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
408   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
409     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
410     if (!PVD->hasDefaultArg())
411       return false;
412     if (!PVD->hasInheritedDefaultArg())
413       return true;
414   }
415   return false;
416 }
417 
418 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
419 /// function, once we already know that they have the same
420 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
421 /// error, false otherwise.
422 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
423                                 Scope *S) {
424   bool Invalid = false;
425 
426   // C++ [dcl.fct.default]p4:
427   //   For non-template functions, default arguments can be added in
428   //   later declarations of a function in the same
429   //   scope. Declarations in different scopes have completely
430   //   distinct sets of default arguments. That is, declarations in
431   //   inner scopes do not acquire default arguments from
432   //   declarations in outer scopes, and vice versa. In a given
433   //   function declaration, all parameters subsequent to a
434   //   parameter with a default argument shall have default
435   //   arguments supplied in this or previous declarations. A
436   //   default argument shall not be redefined by a later
437   //   declaration (not even to the same value).
438   //
439   // C++ [dcl.fct.default]p6:
440   //   Except for member functions of class templates, the default arguments
441   //   in a member function definition that appears outside of the class
442   //   definition are added to the set of default arguments provided by the
443   //   member function declaration in the class definition.
444   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
445     ParmVarDecl *OldParam = Old->getParamDecl(p);
446     ParmVarDecl *NewParam = New->getParamDecl(p);
447 
448     bool OldParamHasDfl = OldParam->hasDefaultArg();
449     bool NewParamHasDfl = NewParam->hasDefaultArg();
450 
451     // The declaration context corresponding to the scope is the semantic
452     // parent, unless this is a local function declaration, in which case
453     // it is that surrounding function.
454     DeclContext *ScopeDC = New->isLocalExternDecl()
455                                ? New->getLexicalDeclContext()
456                                : New->getDeclContext();
457     if (S && !isDeclInScope(Old, ScopeDC, S) &&
458         !New->getDeclContext()->isRecord())
459       // Ignore default parameters of old decl if they are not in
460       // the same scope and this is not an out-of-line definition of
461       // a member function.
462       OldParamHasDfl = false;
463     if (New->isLocalExternDecl() != Old->isLocalExternDecl())
464       // If only one of these is a local function declaration, then they are
465       // declared in different scopes, even though isDeclInScope may think
466       // they're in the same scope. (If both are local, the scope check is
467       // sufficent, and if neither is local, then they are in the same scope.)
468       OldParamHasDfl = false;
469 
470     if (OldParamHasDfl && NewParamHasDfl) {
471 
472       unsigned DiagDefaultParamID =
473         diag::err_param_default_argument_redefinition;
474 
475       // MSVC accepts that default parameters be redefined for member functions
476       // of template class. The new default parameter's value is ignored.
477       Invalid = true;
478       if (getLangOpts().MicrosoftExt) {
479         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
480         if (MD && MD->getParent()->getDescribedClassTemplate()) {
481           // Merge the old default argument into the new parameter.
482           NewParam->setHasInheritedDefaultArg();
483           if (OldParam->hasUninstantiatedDefaultArg())
484             NewParam->setUninstantiatedDefaultArg(
485                                       OldParam->getUninstantiatedDefaultArg());
486           else
487             NewParam->setDefaultArg(OldParam->getInit());
488           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
489           Invalid = false;
490         }
491       }
492 
493       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
494       // hint here. Alternatively, we could walk the type-source information
495       // for NewParam to find the last source location in the type... but it
496       // isn't worth the effort right now. This is the kind of test case that
497       // is hard to get right:
498       //   int f(int);
499       //   void g(int (*fp)(int) = f);
500       //   void g(int (*fp)(int) = &f);
501       Diag(NewParam->getLocation(), DiagDefaultParamID)
502         << NewParam->getDefaultArgRange();
503 
504       // Look for the function declaration where the default argument was
505       // actually written, which may be a declaration prior to Old.
506       for (FunctionDecl *Older = Old->getPreviousDecl();
507            Older; Older = Older->getPreviousDecl()) {
508         if (!Older->getParamDecl(p)->hasDefaultArg())
509           break;
510 
511         OldParam = Older->getParamDecl(p);
512       }
513 
514       Diag(OldParam->getLocation(), diag::note_previous_definition)
515         << OldParam->getDefaultArgRange();
516     } else if (OldParamHasDfl) {
517       // Merge the old default argument into the new parameter.
518       // It's important to use getInit() here;  getDefaultArg()
519       // strips off any top-level ExprWithCleanups.
520       NewParam->setHasInheritedDefaultArg();
521       if (OldParam->hasUninstantiatedDefaultArg())
522         NewParam->setUninstantiatedDefaultArg(
523                                       OldParam->getUninstantiatedDefaultArg());
524       else
525         NewParam->setDefaultArg(OldParam->getInit());
526     } else if (NewParamHasDfl) {
527       if (New->getDescribedFunctionTemplate()) {
528         // Paragraph 4, quoted above, only applies to non-template functions.
529         Diag(NewParam->getLocation(),
530              diag::err_param_default_argument_template_redecl)
531           << NewParam->getDefaultArgRange();
532         Diag(Old->getLocation(), diag::note_template_prev_declaration)
533           << false;
534       } else if (New->getTemplateSpecializationKind()
535                    != TSK_ImplicitInstantiation &&
536                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
537         // C++ [temp.expr.spec]p21:
538         //   Default function arguments shall not be specified in a declaration
539         //   or a definition for one of the following explicit specializations:
540         //     - the explicit specialization of a function template;
541         //     - the explicit specialization of a member function template;
542         //     - the explicit specialization of a member function of a class
543         //       template where the class template specialization to which the
544         //       member function specialization belongs is implicitly
545         //       instantiated.
546         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
547           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
548           << New->getDeclName()
549           << NewParam->getDefaultArgRange();
550       } else if (New->getDeclContext()->isDependentContext()) {
551         // C++ [dcl.fct.default]p6 (DR217):
552         //   Default arguments for a member function of a class template shall
553         //   be specified on the initial declaration of the member function
554         //   within the class template.
555         //
556         // Reading the tea leaves a bit in DR217 and its reference to DR205
557         // leads me to the conclusion that one cannot add default function
558         // arguments for an out-of-line definition of a member function of a
559         // dependent type.
560         int WhichKind = 2;
561         if (CXXRecordDecl *Record
562               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
563           if (Record->getDescribedClassTemplate())
564             WhichKind = 0;
565           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
566             WhichKind = 1;
567           else
568             WhichKind = 2;
569         }
570 
571         Diag(NewParam->getLocation(),
572              diag::err_param_default_argument_member_template_redecl)
573           << WhichKind
574           << NewParam->getDefaultArgRange();
575       }
576     }
577   }
578 
579   // DR1344: If a default argument is added outside a class definition and that
580   // default argument makes the function a special member function, the program
581   // is ill-formed. This can only happen for constructors.
582   if (isa<CXXConstructorDecl>(New) &&
583       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
584     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
585                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
586     if (NewSM != OldSM) {
587       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
588       assert(NewParam->hasDefaultArg());
589       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
590         << NewParam->getDefaultArgRange() << NewSM;
591       Diag(Old->getLocation(), diag::note_previous_declaration);
592     }
593   }
594 
595   const FunctionDecl *Def;
596   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
597   // template has a constexpr specifier then all its declarations shall
598   // contain the constexpr specifier.
599   if (New->isConstexpr() != Old->isConstexpr()) {
600     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
601       << New << New->isConstexpr();
602     Diag(Old->getLocation(), diag::note_previous_declaration);
603     Invalid = true;
604   } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
605     // C++11 [dcl.fcn.spec]p4:
606     //   If the definition of a function appears in a translation unit before its
607     //   first declaration as inline, the program is ill-formed.
608     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
609     Diag(Def->getLocation(), diag::note_previous_definition);
610     Invalid = true;
611   }
612 
613   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
614   // argument expression, that declaration shall be a definition and shall be
615   // the only declaration of the function or function template in the
616   // translation unit.
617   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
618       functionDeclHasDefaultArgument(Old)) {
619     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
620     Diag(Old->getLocation(), diag::note_previous_declaration);
621     Invalid = true;
622   }
623 
624   if (CheckEquivalentExceptionSpec(Old, New))
625     Invalid = true;
626 
627   return Invalid;
628 }
629 
630 /// \brief Merge the exception specifications of two variable declarations.
631 ///
632 /// This is called when there's a redeclaration of a VarDecl. The function
633 /// checks if the redeclaration might have an exception specification and
634 /// validates compatibility and merges the specs if necessary.
635 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
636   // Shortcut if exceptions are disabled.
637   if (!getLangOpts().CXXExceptions)
638     return;
639 
640   assert(Context.hasSameType(New->getType(), Old->getType()) &&
641          "Should only be called if types are otherwise the same.");
642 
643   QualType NewType = New->getType();
644   QualType OldType = Old->getType();
645 
646   // We're only interested in pointers and references to functions, as well
647   // as pointers to member functions.
648   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
649     NewType = R->getPointeeType();
650     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
651   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
652     NewType = P->getPointeeType();
653     OldType = OldType->getAs<PointerType>()->getPointeeType();
654   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
655     NewType = M->getPointeeType();
656     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
657   }
658 
659   if (!NewType->isFunctionProtoType())
660     return;
661 
662   // There's lots of special cases for functions. For function pointers, system
663   // libraries are hopefully not as broken so that we don't need these
664   // workarounds.
665   if (CheckEquivalentExceptionSpec(
666         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
667         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
668     New->setInvalidDecl();
669   }
670 }
671 
672 /// CheckCXXDefaultArguments - Verify that the default arguments for a
673 /// function declaration are well-formed according to C++
674 /// [dcl.fct.default].
675 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
676   unsigned NumParams = FD->getNumParams();
677   unsigned p;
678 
679   // Find first parameter with a default argument
680   for (p = 0; p < NumParams; ++p) {
681     ParmVarDecl *Param = FD->getParamDecl(p);
682     if (Param->hasDefaultArg())
683       break;
684   }
685 
686   // C++ [dcl.fct.default]p4:
687   //   In a given function declaration, all parameters
688   //   subsequent to a parameter with a default argument shall
689   //   have default arguments supplied in this or previous
690   //   declarations. A default argument shall not be redefined
691   //   by a later declaration (not even to the same value).
692   unsigned LastMissingDefaultArg = 0;
693   for (; p < NumParams; ++p) {
694     ParmVarDecl *Param = FD->getParamDecl(p);
695     if (!Param->hasDefaultArg()) {
696       if (Param->isInvalidDecl())
697         /* We already complained about this parameter. */;
698       else if (Param->getIdentifier())
699         Diag(Param->getLocation(),
700              diag::err_param_default_argument_missing_name)
701           << Param->getIdentifier();
702       else
703         Diag(Param->getLocation(),
704              diag::err_param_default_argument_missing);
705 
706       LastMissingDefaultArg = p;
707     }
708   }
709 
710   if (LastMissingDefaultArg > 0) {
711     // Some default arguments were missing. Clear out all of the
712     // default arguments up to (and including) the last missing
713     // default argument, so that we leave the function parameters
714     // in a semantically valid state.
715     for (p = 0; p <= LastMissingDefaultArg; ++p) {
716       ParmVarDecl *Param = FD->getParamDecl(p);
717       if (Param->hasDefaultArg()) {
718         Param->setDefaultArg(nullptr);
719       }
720     }
721   }
722 }
723 
724 // CheckConstexprParameterTypes - Check whether a function's parameter types
725 // are all literal types. If so, return true. If not, produce a suitable
726 // diagnostic and return false.
727 static bool CheckConstexprParameterTypes(Sema &SemaRef,
728                                          const FunctionDecl *FD) {
729   unsigned ArgIndex = 0;
730   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
731   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
732                                               e = FT->param_type_end();
733        i != e; ++i, ++ArgIndex) {
734     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
735     SourceLocation ParamLoc = PD->getLocation();
736     if (!(*i)->isDependentType() &&
737         SemaRef.RequireLiteralType(ParamLoc, *i,
738                                    diag::err_constexpr_non_literal_param,
739                                    ArgIndex+1, PD->getSourceRange(),
740                                    isa<CXXConstructorDecl>(FD)))
741       return false;
742   }
743   return true;
744 }
745 
746 /// \brief Get diagnostic %select index for tag kind for
747 /// record diagnostic message.
748 /// WARNING: Indexes apply to particular diagnostics only!
749 ///
750 /// \returns diagnostic %select index.
751 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
752   switch (Tag) {
753   case TTK_Struct: return 0;
754   case TTK_Interface: return 1;
755   case TTK_Class:  return 2;
756   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
757   }
758 }
759 
760 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
761 // the requirements of a constexpr function definition or a constexpr
762 // constructor definition. If so, return true. If not, produce appropriate
763 // diagnostics and return false.
764 //
765 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
766 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
767   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
768   if (MD && MD->isInstance()) {
769     // C++11 [dcl.constexpr]p4:
770     //  The definition of a constexpr constructor shall satisfy the following
771     //  constraints:
772     //  - the class shall not have any virtual base classes;
773     const CXXRecordDecl *RD = MD->getParent();
774     if (RD->getNumVBases()) {
775       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
776         << isa<CXXConstructorDecl>(NewFD)
777         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
778       for (const auto &I : RD->vbases())
779         Diag(I.getLocStart(),
780              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
781       return false;
782     }
783   }
784 
785   if (!isa<CXXConstructorDecl>(NewFD)) {
786     // C++11 [dcl.constexpr]p3:
787     //  The definition of a constexpr function shall satisfy the following
788     //  constraints:
789     // - it shall not be virtual;
790     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
791     if (Method && Method->isVirtual()) {
792       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
793 
794       // If it's not obvious why this function is virtual, find an overridden
795       // function which uses the 'virtual' keyword.
796       const CXXMethodDecl *WrittenVirtual = Method;
797       while (!WrittenVirtual->isVirtualAsWritten())
798         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
799       if (WrittenVirtual != Method)
800         Diag(WrittenVirtual->getLocation(),
801              diag::note_overridden_virtual_function);
802       return false;
803     }
804 
805     // - its return type shall be a literal type;
806     QualType RT = NewFD->getReturnType();
807     if (!RT->isDependentType() &&
808         RequireLiteralType(NewFD->getLocation(), RT,
809                            diag::err_constexpr_non_literal_return))
810       return false;
811   }
812 
813   // - each of its parameter types shall be a literal type;
814   if (!CheckConstexprParameterTypes(*this, NewFD))
815     return false;
816 
817   return true;
818 }
819 
820 /// Check the given declaration statement is legal within a constexpr function
821 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
822 ///
823 /// \return true if the body is OK (maybe only as an extension), false if we
824 ///         have diagnosed a problem.
825 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
826                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
827   // C++11 [dcl.constexpr]p3 and p4:
828   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
829   //  contain only
830   for (const auto *DclIt : DS->decls()) {
831     switch (DclIt->getKind()) {
832     case Decl::StaticAssert:
833     case Decl::Using:
834     case Decl::UsingShadow:
835     case Decl::UsingDirective:
836     case Decl::UnresolvedUsingTypename:
837     case Decl::UnresolvedUsingValue:
838       //   - static_assert-declarations
839       //   - using-declarations,
840       //   - using-directives,
841       continue;
842 
843     case Decl::Typedef:
844     case Decl::TypeAlias: {
845       //   - typedef declarations and alias-declarations that do not define
846       //     classes or enumerations,
847       const auto *TN = cast<TypedefNameDecl>(DclIt);
848       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
849         // Don't allow variably-modified types in constexpr functions.
850         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
851         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
852           << TL.getSourceRange() << TL.getType()
853           << isa<CXXConstructorDecl>(Dcl);
854         return false;
855       }
856       continue;
857     }
858 
859     case Decl::Enum:
860     case Decl::CXXRecord:
861       // C++1y allows types to be defined, not just declared.
862       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
863         SemaRef.Diag(DS->getLocStart(),
864                      SemaRef.getLangOpts().CPlusPlus14
865                        ? diag::warn_cxx11_compat_constexpr_type_definition
866                        : diag::ext_constexpr_type_definition)
867           << isa<CXXConstructorDecl>(Dcl);
868       continue;
869 
870     case Decl::EnumConstant:
871     case Decl::IndirectField:
872     case Decl::ParmVar:
873       // These can only appear with other declarations which are banned in
874       // C++11 and permitted in C++1y, so ignore them.
875       continue;
876 
877     case Decl::Var: {
878       // C++1y [dcl.constexpr]p3 allows anything except:
879       //   a definition of a variable of non-literal type or of static or
880       //   thread storage duration or for which no initialization is performed.
881       const auto *VD = cast<VarDecl>(DclIt);
882       if (VD->isThisDeclarationADefinition()) {
883         if (VD->isStaticLocal()) {
884           SemaRef.Diag(VD->getLocation(),
885                        diag::err_constexpr_local_var_static)
886             << isa<CXXConstructorDecl>(Dcl)
887             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
888           return false;
889         }
890         if (!VD->getType()->isDependentType() &&
891             SemaRef.RequireLiteralType(
892               VD->getLocation(), VD->getType(),
893               diag::err_constexpr_local_var_non_literal_type,
894               isa<CXXConstructorDecl>(Dcl)))
895           return false;
896         if (!VD->getType()->isDependentType() &&
897             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
898           SemaRef.Diag(VD->getLocation(),
899                        diag::err_constexpr_local_var_no_init)
900             << isa<CXXConstructorDecl>(Dcl);
901           return false;
902         }
903       }
904       SemaRef.Diag(VD->getLocation(),
905                    SemaRef.getLangOpts().CPlusPlus14
906                     ? diag::warn_cxx11_compat_constexpr_local_var
907                     : diag::ext_constexpr_local_var)
908         << isa<CXXConstructorDecl>(Dcl);
909       continue;
910     }
911 
912     case Decl::NamespaceAlias:
913     case Decl::Function:
914       // These are disallowed in C++11 and permitted in C++1y. Allow them
915       // everywhere as an extension.
916       if (!Cxx1yLoc.isValid())
917         Cxx1yLoc = DS->getLocStart();
918       continue;
919 
920     default:
921       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
922         << isa<CXXConstructorDecl>(Dcl);
923       return false;
924     }
925   }
926 
927   return true;
928 }
929 
930 /// Check that the given field is initialized within a constexpr constructor.
931 ///
932 /// \param Dcl The constexpr constructor being checked.
933 /// \param Field The field being checked. This may be a member of an anonymous
934 ///        struct or union nested within the class being checked.
935 /// \param Inits All declarations, including anonymous struct/union members and
936 ///        indirect members, for which any initialization was provided.
937 /// \param Diagnosed Set to true if an error is produced.
938 static void CheckConstexprCtorInitializer(Sema &SemaRef,
939                                           const FunctionDecl *Dcl,
940                                           FieldDecl *Field,
941                                           llvm::SmallSet<Decl*, 16> &Inits,
942                                           bool &Diagnosed) {
943   if (Field->isInvalidDecl())
944     return;
945 
946   if (Field->isUnnamedBitfield())
947     return;
948 
949   // Anonymous unions with no variant members and empty anonymous structs do not
950   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
951   // indirect fields don't need initializing.
952   if (Field->isAnonymousStructOrUnion() &&
953       (Field->getType()->isUnionType()
954            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
955            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
956     return;
957 
958   if (!Inits.count(Field)) {
959     if (!Diagnosed) {
960       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
961       Diagnosed = true;
962     }
963     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
964   } else if (Field->isAnonymousStructOrUnion()) {
965     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
966     for (auto *I : RD->fields())
967       // If an anonymous union contains an anonymous struct of which any member
968       // is initialized, all members must be initialized.
969       if (!RD->isUnion() || Inits.count(I))
970         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
971   }
972 }
973 
974 /// Check the provided statement is allowed in a constexpr function
975 /// definition.
976 static bool
977 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
978                            SmallVectorImpl<SourceLocation> &ReturnStmts,
979                            SourceLocation &Cxx1yLoc) {
980   // - its function-body shall be [...] a compound-statement that contains only
981   switch (S->getStmtClass()) {
982   case Stmt::NullStmtClass:
983     //   - null statements,
984     return true;
985 
986   case Stmt::DeclStmtClass:
987     //   - static_assert-declarations
988     //   - using-declarations,
989     //   - using-directives,
990     //   - typedef declarations and alias-declarations that do not define
991     //     classes or enumerations,
992     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
993       return false;
994     return true;
995 
996   case Stmt::ReturnStmtClass:
997     //   - and exactly one return statement;
998     if (isa<CXXConstructorDecl>(Dcl)) {
999       // C++1y allows return statements in constexpr constructors.
1000       if (!Cxx1yLoc.isValid())
1001         Cxx1yLoc = S->getLocStart();
1002       return true;
1003     }
1004 
1005     ReturnStmts.push_back(S->getLocStart());
1006     return true;
1007 
1008   case Stmt::CompoundStmtClass: {
1009     // C++1y allows compound-statements.
1010     if (!Cxx1yLoc.isValid())
1011       Cxx1yLoc = S->getLocStart();
1012 
1013     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1014     for (auto *BodyIt : CompStmt->body()) {
1015       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1016                                       Cxx1yLoc))
1017         return false;
1018     }
1019     return true;
1020   }
1021 
1022   case Stmt::AttributedStmtClass:
1023     if (!Cxx1yLoc.isValid())
1024       Cxx1yLoc = S->getLocStart();
1025     return true;
1026 
1027   case Stmt::IfStmtClass: {
1028     // C++1y allows if-statements.
1029     if (!Cxx1yLoc.isValid())
1030       Cxx1yLoc = S->getLocStart();
1031 
1032     IfStmt *If = cast<IfStmt>(S);
1033     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1034                                     Cxx1yLoc))
1035       return false;
1036     if (If->getElse() &&
1037         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1038                                     Cxx1yLoc))
1039       return false;
1040     return true;
1041   }
1042 
1043   case Stmt::WhileStmtClass:
1044   case Stmt::DoStmtClass:
1045   case Stmt::ForStmtClass:
1046   case Stmt::CXXForRangeStmtClass:
1047   case Stmt::ContinueStmtClass:
1048     // C++1y allows all of these. We don't allow them as extensions in C++11,
1049     // because they don't make sense without variable mutation.
1050     if (!SemaRef.getLangOpts().CPlusPlus14)
1051       break;
1052     if (!Cxx1yLoc.isValid())
1053       Cxx1yLoc = S->getLocStart();
1054     for (Stmt::child_range Children = S->children(); Children; ++Children)
1055       if (*Children &&
1056           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1057                                       Cxx1yLoc))
1058         return false;
1059     return true;
1060 
1061   case Stmt::SwitchStmtClass:
1062   case Stmt::CaseStmtClass:
1063   case Stmt::DefaultStmtClass:
1064   case Stmt::BreakStmtClass:
1065     // C++1y allows switch-statements, and since they don't need variable
1066     // mutation, we can reasonably allow them in C++11 as an extension.
1067     if (!Cxx1yLoc.isValid())
1068       Cxx1yLoc = S->getLocStart();
1069     for (Stmt::child_range Children = S->children(); Children; ++Children)
1070       if (*Children &&
1071           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1072                                       Cxx1yLoc))
1073         return false;
1074     return true;
1075 
1076   default:
1077     if (!isa<Expr>(S))
1078       break;
1079 
1080     // C++1y allows expression-statements.
1081     if (!Cxx1yLoc.isValid())
1082       Cxx1yLoc = S->getLocStart();
1083     return true;
1084   }
1085 
1086   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1087     << isa<CXXConstructorDecl>(Dcl);
1088   return false;
1089 }
1090 
1091 /// Check the body for the given constexpr function declaration only contains
1092 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1093 ///
1094 /// \return true if the body is OK, false if we have diagnosed a problem.
1095 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1096   if (isa<CXXTryStmt>(Body)) {
1097     // C++11 [dcl.constexpr]p3:
1098     //  The definition of a constexpr function shall satisfy the following
1099     //  constraints: [...]
1100     // - its function-body shall be = delete, = default, or a
1101     //   compound-statement
1102     //
1103     // C++11 [dcl.constexpr]p4:
1104     //  In the definition of a constexpr constructor, [...]
1105     // - its function-body shall not be a function-try-block;
1106     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1107       << isa<CXXConstructorDecl>(Dcl);
1108     return false;
1109   }
1110 
1111   SmallVector<SourceLocation, 4> ReturnStmts;
1112 
1113   // - its function-body shall be [...] a compound-statement that contains only
1114   //   [... list of cases ...]
1115   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1116   SourceLocation Cxx1yLoc;
1117   for (auto *BodyIt : CompBody->body()) {
1118     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1119       return false;
1120   }
1121 
1122   if (Cxx1yLoc.isValid())
1123     Diag(Cxx1yLoc,
1124          getLangOpts().CPlusPlus14
1125            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1126            : diag::ext_constexpr_body_invalid_stmt)
1127       << isa<CXXConstructorDecl>(Dcl);
1128 
1129   if (const CXXConstructorDecl *Constructor
1130         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1131     const CXXRecordDecl *RD = Constructor->getParent();
1132     // DR1359:
1133     // - every non-variant non-static data member and base class sub-object
1134     //   shall be initialized;
1135     // DR1460:
1136     // - if the class is a union having variant members, exactly one of them
1137     //   shall be initialized;
1138     if (RD->isUnion()) {
1139       if (Constructor->getNumCtorInitializers() == 0 &&
1140           RD->hasVariantMembers()) {
1141         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1142         return false;
1143       }
1144     } else if (!Constructor->isDependentContext() &&
1145                !Constructor->isDelegatingConstructor()) {
1146       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1147 
1148       // Skip detailed checking if we have enough initializers, and we would
1149       // allow at most one initializer per member.
1150       bool AnyAnonStructUnionMembers = false;
1151       unsigned Fields = 0;
1152       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1153            E = RD->field_end(); I != E; ++I, ++Fields) {
1154         if (I->isAnonymousStructOrUnion()) {
1155           AnyAnonStructUnionMembers = true;
1156           break;
1157         }
1158       }
1159       // DR1460:
1160       // - if the class is a union-like class, but is not a union, for each of
1161       //   its anonymous union members having variant members, exactly one of
1162       //   them shall be initialized;
1163       if (AnyAnonStructUnionMembers ||
1164           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1165         // Check initialization of non-static data members. Base classes are
1166         // always initialized so do not need to be checked. Dependent bases
1167         // might not have initializers in the member initializer list.
1168         llvm::SmallSet<Decl*, 16> Inits;
1169         for (const auto *I: Constructor->inits()) {
1170           if (FieldDecl *FD = I->getMember())
1171             Inits.insert(FD);
1172           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1173             Inits.insert(ID->chain_begin(), ID->chain_end());
1174         }
1175 
1176         bool Diagnosed = false;
1177         for (auto *I : RD->fields())
1178           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1179         if (Diagnosed)
1180           return false;
1181       }
1182     }
1183   } else {
1184     if (ReturnStmts.empty()) {
1185       // C++1y doesn't require constexpr functions to contain a 'return'
1186       // statement. We still do, unless the return type might be void, because
1187       // otherwise if there's no return statement, the function cannot
1188       // be used in a core constant expression.
1189       bool OK = getLangOpts().CPlusPlus14 &&
1190                 (Dcl->getReturnType()->isVoidType() ||
1191                  Dcl->getReturnType()->isDependentType());
1192       Diag(Dcl->getLocation(),
1193            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1194               : diag::err_constexpr_body_no_return);
1195       return OK;
1196     }
1197     if (ReturnStmts.size() > 1) {
1198       Diag(ReturnStmts.back(),
1199            getLangOpts().CPlusPlus14
1200              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1201              : diag::ext_constexpr_body_multiple_return);
1202       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1203         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1204     }
1205   }
1206 
1207   // C++11 [dcl.constexpr]p5:
1208   //   if no function argument values exist such that the function invocation
1209   //   substitution would produce a constant expression, the program is
1210   //   ill-formed; no diagnostic required.
1211   // C++11 [dcl.constexpr]p3:
1212   //   - every constructor call and implicit conversion used in initializing the
1213   //     return value shall be one of those allowed in a constant expression.
1214   // C++11 [dcl.constexpr]p4:
1215   //   - every constructor involved in initializing non-static data members and
1216   //     base class sub-objects shall be a constexpr constructor.
1217   SmallVector<PartialDiagnosticAt, 8> Diags;
1218   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1219     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1220       << isa<CXXConstructorDecl>(Dcl);
1221     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1222       Diag(Diags[I].first, Diags[I].second);
1223     // Don't return false here: we allow this for compatibility in
1224     // system headers.
1225   }
1226 
1227   return true;
1228 }
1229 
1230 /// isCurrentClassName - Determine whether the identifier II is the
1231 /// name of the class type currently being defined. In the case of
1232 /// nested classes, this will only return true if II is the name of
1233 /// the innermost class.
1234 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1235                               const CXXScopeSpec *SS) {
1236   assert(getLangOpts().CPlusPlus && "No class names in C!");
1237 
1238   CXXRecordDecl *CurDecl;
1239   if (SS && SS->isSet() && !SS->isInvalid()) {
1240     DeclContext *DC = computeDeclContext(*SS, true);
1241     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1242   } else
1243     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1244 
1245   if (CurDecl && CurDecl->getIdentifier())
1246     return &II == CurDecl->getIdentifier();
1247   return false;
1248 }
1249 
1250 /// \brief Determine whether the identifier II is a typo for the name of
1251 /// the class type currently being defined. If so, update it to the identifier
1252 /// that should have been used.
1253 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1254   assert(getLangOpts().CPlusPlus && "No class names in C!");
1255 
1256   if (!getLangOpts().SpellChecking)
1257     return false;
1258 
1259   CXXRecordDecl *CurDecl;
1260   if (SS && SS->isSet() && !SS->isInvalid()) {
1261     DeclContext *DC = computeDeclContext(*SS, true);
1262     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1263   } else
1264     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1265 
1266   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1267       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1268           < II->getLength()) {
1269     II = CurDecl->getIdentifier();
1270     return true;
1271   }
1272 
1273   return false;
1274 }
1275 
1276 /// \brief Determine whether the given class is a base class of the given
1277 /// class, including looking at dependent bases.
1278 static bool findCircularInheritance(const CXXRecordDecl *Class,
1279                                     const CXXRecordDecl *Current) {
1280   SmallVector<const CXXRecordDecl*, 8> Queue;
1281 
1282   Class = Class->getCanonicalDecl();
1283   while (true) {
1284     for (const auto &I : Current->bases()) {
1285       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1286       if (!Base)
1287         continue;
1288 
1289       Base = Base->getDefinition();
1290       if (!Base)
1291         continue;
1292 
1293       if (Base->getCanonicalDecl() == Class)
1294         return true;
1295 
1296       Queue.push_back(Base);
1297     }
1298 
1299     if (Queue.empty())
1300       return false;
1301 
1302     Current = Queue.pop_back_val();
1303   }
1304 
1305   return false;
1306 }
1307 
1308 /// \brief Perform propagation of DLL attributes from a derived class to a
1309 /// templated base class for MS compatibility.
1310 static void propagateDLLAttrToBaseClassTemplate(
1311     Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1312     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1313   if (getDLLAttr(
1314           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1315     // If the base class template has a DLL attribute, don't try to change it.
1316     return;
1317   }
1318 
1319   if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1320     // If the base class is not already specialized, we can do the propagation.
1321     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1322     NewAttr->setInherited(true);
1323     BaseTemplateSpec->addAttr(NewAttr);
1324     return;
1325   }
1326 
1327   bool DifferentAttribute = false;
1328   if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1329     if (!SpecializationAttr->isInherited()) {
1330       // The template has previously been specialized or instantiated with an
1331       // explicit attribute. We should not try to change it.
1332       return;
1333     }
1334     if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1335       // The specialization already has the right attribute.
1336       return;
1337     }
1338     DifferentAttribute = true;
1339   }
1340 
1341   // The template was previously instantiated or explicitly specialized without
1342   // a dll attribute, or the template was previously instantiated with a
1343   // different inherited attribute. It's too late for us to change the
1344   // attribute, so warn that this is unsupported.
1345   S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1346       << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1347   S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1348   if (BaseTemplateSpec->isExplicitSpecialization()) {
1349     S.Diag(BaseTemplateSpec->getLocation(),
1350            diag::note_template_class_explicit_specialization_was_here)
1351         << BaseTemplateSpec;
1352   } else {
1353     S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1354            diag::note_template_class_instantiation_was_here)
1355         << BaseTemplateSpec;
1356   }
1357 }
1358 
1359 /// \brief Check the validity of a C++ base class specifier.
1360 ///
1361 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1362 /// and returns NULL otherwise.
1363 CXXBaseSpecifier *
1364 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1365                          SourceRange SpecifierRange,
1366                          bool Virtual, AccessSpecifier Access,
1367                          TypeSourceInfo *TInfo,
1368                          SourceLocation EllipsisLoc) {
1369   QualType BaseType = TInfo->getType();
1370 
1371   // C++ [class.union]p1:
1372   //   A union shall not have base classes.
1373   if (Class->isUnion()) {
1374     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1375       << SpecifierRange;
1376     return nullptr;
1377   }
1378 
1379   if (EllipsisLoc.isValid() &&
1380       !TInfo->getType()->containsUnexpandedParameterPack()) {
1381     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1382       << TInfo->getTypeLoc().getSourceRange();
1383     EllipsisLoc = SourceLocation();
1384   }
1385 
1386   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1387 
1388   if (BaseType->isDependentType()) {
1389     // Make sure that we don't have circular inheritance among our dependent
1390     // bases. For non-dependent bases, the check for completeness below handles
1391     // this.
1392     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1393       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1394           ((BaseDecl = BaseDecl->getDefinition()) &&
1395            findCircularInheritance(Class, BaseDecl))) {
1396         Diag(BaseLoc, diag::err_circular_inheritance)
1397           << BaseType << Context.getTypeDeclType(Class);
1398 
1399         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1400           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1401             << BaseType;
1402 
1403         return nullptr;
1404       }
1405     }
1406 
1407     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1408                                           Class->getTagKind() == TTK_Class,
1409                                           Access, TInfo, EllipsisLoc);
1410   }
1411 
1412   // Base specifiers must be record types.
1413   if (!BaseType->isRecordType()) {
1414     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1415     return nullptr;
1416   }
1417 
1418   // C++ [class.union]p1:
1419   //   A union shall not be used as a base class.
1420   if (BaseType->isUnionType()) {
1421     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1422     return nullptr;
1423   }
1424 
1425   // For the MS ABI, propagate DLL attributes to base class templates.
1426   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1427     if (Attr *ClassAttr = getDLLAttr(Class)) {
1428       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1429               BaseType->getAsCXXRecordDecl())) {
1430         propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1431                                             BaseTemplate, BaseLoc);
1432       }
1433     }
1434   }
1435 
1436   // C++ [class.derived]p2:
1437   //   The class-name in a base-specifier shall not be an incompletely
1438   //   defined class.
1439   if (RequireCompleteType(BaseLoc, BaseType,
1440                           diag::err_incomplete_base_class, SpecifierRange)) {
1441     Class->setInvalidDecl();
1442     return nullptr;
1443   }
1444 
1445   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1446   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1447   assert(BaseDecl && "Record type has no declaration");
1448   BaseDecl = BaseDecl->getDefinition();
1449   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1450   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1451   assert(CXXBaseDecl && "Base type is not a C++ type");
1452 
1453   // A class which contains a flexible array member is not suitable for use as a
1454   // base class:
1455   //   - If the layout determines that a base comes before another base,
1456   //     the flexible array member would index into the subsequent base.
1457   //   - If the layout determines that base comes before the derived class,
1458   //     the flexible array member would index into the derived class.
1459   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1460     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1461       << CXXBaseDecl->getDeclName();
1462     return nullptr;
1463   }
1464 
1465   // C++ [class]p3:
1466   //   If a class is marked final and it appears as a base-type-specifier in
1467   //   base-clause, the program is ill-formed.
1468   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1469     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1470       << CXXBaseDecl->getDeclName()
1471       << FA->isSpelledAsSealed();
1472     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1473         << CXXBaseDecl->getDeclName() << FA->getRange();
1474     return nullptr;
1475   }
1476 
1477   if (BaseDecl->isInvalidDecl())
1478     Class->setInvalidDecl();
1479 
1480   // Create the base specifier.
1481   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1482                                         Class->getTagKind() == TTK_Class,
1483                                         Access, TInfo, EllipsisLoc);
1484 }
1485 
1486 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1487 /// one entry in the base class list of a class specifier, for
1488 /// example:
1489 ///    class foo : public bar, virtual private baz {
1490 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1491 BaseResult
1492 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1493                          ParsedAttributes &Attributes,
1494                          bool Virtual, AccessSpecifier Access,
1495                          ParsedType basetype, SourceLocation BaseLoc,
1496                          SourceLocation EllipsisLoc) {
1497   if (!classdecl)
1498     return true;
1499 
1500   AdjustDeclIfTemplate(classdecl);
1501   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1502   if (!Class)
1503     return true;
1504 
1505   // We haven't yet attached the base specifiers.
1506   Class->setIsParsingBaseSpecifiers();
1507 
1508   // We do not support any C++11 attributes on base-specifiers yet.
1509   // Diagnose any attributes we see.
1510   if (!Attributes.empty()) {
1511     for (AttributeList *Attr = Attributes.getList(); Attr;
1512          Attr = Attr->getNext()) {
1513       if (Attr->isInvalid() ||
1514           Attr->getKind() == AttributeList::IgnoredAttribute)
1515         continue;
1516       Diag(Attr->getLoc(),
1517            Attr->getKind() == AttributeList::UnknownAttribute
1518              ? diag::warn_unknown_attribute_ignored
1519              : diag::err_base_specifier_attribute)
1520         << Attr->getName();
1521     }
1522   }
1523 
1524   TypeSourceInfo *TInfo = nullptr;
1525   GetTypeFromParser(basetype, &TInfo);
1526 
1527   if (EllipsisLoc.isInvalid() &&
1528       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1529                                       UPPC_BaseType))
1530     return true;
1531 
1532   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1533                                                       Virtual, Access, TInfo,
1534                                                       EllipsisLoc))
1535     return BaseSpec;
1536   else
1537     Class->setInvalidDecl();
1538 
1539   return true;
1540 }
1541 
1542 /// \brief Performs the actual work of attaching the given base class
1543 /// specifiers to a C++ class.
1544 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1545                                 unsigned NumBases) {
1546  if (NumBases == 0)
1547     return false;
1548 
1549   // Used to keep track of which base types we have already seen, so
1550   // that we can properly diagnose redundant direct base types. Note
1551   // that the key is always the unqualified canonical type of the base
1552   // class.
1553   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1554 
1555   // Copy non-redundant base specifiers into permanent storage.
1556   unsigned NumGoodBases = 0;
1557   bool Invalid = false;
1558   for (unsigned idx = 0; idx < NumBases; ++idx) {
1559     QualType NewBaseType
1560       = Context.getCanonicalType(Bases[idx]->getType());
1561     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1562 
1563     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1564     if (KnownBase) {
1565       // C++ [class.mi]p3:
1566       //   A class shall not be specified as a direct base class of a
1567       //   derived class more than once.
1568       Diag(Bases[idx]->getLocStart(),
1569            diag::err_duplicate_base_class)
1570         << KnownBase->getType()
1571         << Bases[idx]->getSourceRange();
1572 
1573       // Delete the duplicate base class specifier; we're going to
1574       // overwrite its pointer later.
1575       Context.Deallocate(Bases[idx]);
1576 
1577       Invalid = true;
1578     } else {
1579       // Okay, add this new base class.
1580       KnownBase = Bases[idx];
1581       Bases[NumGoodBases++] = Bases[idx];
1582       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1583         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1584         if (Class->isInterface() &&
1585               (!RD->isInterface() ||
1586                KnownBase->getAccessSpecifier() != AS_public)) {
1587           // The Microsoft extension __interface does not permit bases that
1588           // are not themselves public interfaces.
1589           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1590             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1591             << RD->getSourceRange();
1592           Invalid = true;
1593         }
1594         if (RD->hasAttr<WeakAttr>())
1595           Class->addAttr(WeakAttr::CreateImplicit(Context));
1596       }
1597     }
1598   }
1599 
1600   // Attach the remaining base class specifiers to the derived class.
1601   Class->setBases(Bases, NumGoodBases);
1602 
1603   // Delete the remaining (good) base class specifiers, since their
1604   // data has been copied into the CXXRecordDecl.
1605   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1606     Context.Deallocate(Bases[idx]);
1607 
1608   return Invalid;
1609 }
1610 
1611 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1612 /// class, after checking whether there are any duplicate base
1613 /// classes.
1614 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1615                                unsigned NumBases) {
1616   if (!ClassDecl || !Bases || !NumBases)
1617     return;
1618 
1619   AdjustDeclIfTemplate(ClassDecl);
1620   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1621 }
1622 
1623 /// \brief Determine whether the type \p Derived is a C++ class that is
1624 /// derived from the type \p Base.
1625 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1626   if (!getLangOpts().CPlusPlus)
1627     return false;
1628 
1629   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1630   if (!DerivedRD)
1631     return false;
1632 
1633   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1634   if (!BaseRD)
1635     return false;
1636 
1637   // If either the base or the derived type is invalid, don't try to
1638   // check whether one is derived from the other.
1639   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1640     return false;
1641 
1642   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1643   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1644 }
1645 
1646 /// \brief Determine whether the type \p Derived is a C++ class that is
1647 /// derived from the type \p Base.
1648 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1649   if (!getLangOpts().CPlusPlus)
1650     return false;
1651 
1652   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1653   if (!DerivedRD)
1654     return false;
1655 
1656   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1657   if (!BaseRD)
1658     return false;
1659 
1660   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1661 }
1662 
1663 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1664                               CXXCastPath &BasePathArray) {
1665   assert(BasePathArray.empty() && "Base path array must be empty!");
1666   assert(Paths.isRecordingPaths() && "Must record paths!");
1667 
1668   const CXXBasePath &Path = Paths.front();
1669 
1670   // We first go backward and check if we have a virtual base.
1671   // FIXME: It would be better if CXXBasePath had the base specifier for
1672   // the nearest virtual base.
1673   unsigned Start = 0;
1674   for (unsigned I = Path.size(); I != 0; --I) {
1675     if (Path[I - 1].Base->isVirtual()) {
1676       Start = I - 1;
1677       break;
1678     }
1679   }
1680 
1681   // Now add all bases.
1682   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1683     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1684 }
1685 
1686 /// \brief Determine whether the given base path includes a virtual
1687 /// base class.
1688 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1689   for (CXXCastPath::const_iterator B = BasePath.begin(),
1690                                 BEnd = BasePath.end();
1691        B != BEnd; ++B)
1692     if ((*B)->isVirtual())
1693       return true;
1694 
1695   return false;
1696 }
1697 
1698 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1699 /// conversion (where Derived and Base are class types) is
1700 /// well-formed, meaning that the conversion is unambiguous (and
1701 /// that all of the base classes are accessible). Returns true
1702 /// and emits a diagnostic if the code is ill-formed, returns false
1703 /// otherwise. Loc is the location where this routine should point to
1704 /// if there is an error, and Range is the source range to highlight
1705 /// if there is an error.
1706 bool
1707 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1708                                    unsigned InaccessibleBaseID,
1709                                    unsigned AmbigiousBaseConvID,
1710                                    SourceLocation Loc, SourceRange Range,
1711                                    DeclarationName Name,
1712                                    CXXCastPath *BasePath) {
1713   // First, determine whether the path from Derived to Base is
1714   // ambiguous. This is slightly more expensive than checking whether
1715   // the Derived to Base conversion exists, because here we need to
1716   // explore multiple paths to determine if there is an ambiguity.
1717   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1718                      /*DetectVirtual=*/false);
1719   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1720   assert(DerivationOkay &&
1721          "Can only be used with a derived-to-base conversion");
1722   (void)DerivationOkay;
1723 
1724   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1725     if (InaccessibleBaseID) {
1726       // Check that the base class can be accessed.
1727       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1728                                    InaccessibleBaseID)) {
1729         case AR_inaccessible:
1730           return true;
1731         case AR_accessible:
1732         case AR_dependent:
1733         case AR_delayed:
1734           break;
1735       }
1736     }
1737 
1738     // Build a base path if necessary.
1739     if (BasePath)
1740       BuildBasePathArray(Paths, *BasePath);
1741     return false;
1742   }
1743 
1744   if (AmbigiousBaseConvID) {
1745     // We know that the derived-to-base conversion is ambiguous, and
1746     // we're going to produce a diagnostic. Perform the derived-to-base
1747     // search just one more time to compute all of the possible paths so
1748     // that we can print them out. This is more expensive than any of
1749     // the previous derived-to-base checks we've done, but at this point
1750     // performance isn't as much of an issue.
1751     Paths.clear();
1752     Paths.setRecordingPaths(true);
1753     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1754     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1755     (void)StillOkay;
1756 
1757     // Build up a textual representation of the ambiguous paths, e.g.,
1758     // D -> B -> A, that will be used to illustrate the ambiguous
1759     // conversions in the diagnostic. We only print one of the paths
1760     // to each base class subobject.
1761     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1762 
1763     Diag(Loc, AmbigiousBaseConvID)
1764     << Derived << Base << PathDisplayStr << Range << Name;
1765   }
1766   return true;
1767 }
1768 
1769 bool
1770 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1771                                    SourceLocation Loc, SourceRange Range,
1772                                    CXXCastPath *BasePath,
1773                                    bool IgnoreAccess) {
1774   return CheckDerivedToBaseConversion(Derived, Base,
1775                                       IgnoreAccess ? 0
1776                                        : diag::err_upcast_to_inaccessible_base,
1777                                       diag::err_ambiguous_derived_to_base_conv,
1778                                       Loc, Range, DeclarationName(),
1779                                       BasePath);
1780 }
1781 
1782 
1783 /// @brief Builds a string representing ambiguous paths from a
1784 /// specific derived class to different subobjects of the same base
1785 /// class.
1786 ///
1787 /// This function builds a string that can be used in error messages
1788 /// to show the different paths that one can take through the
1789 /// inheritance hierarchy to go from the derived class to different
1790 /// subobjects of a base class. The result looks something like this:
1791 /// @code
1792 /// struct D -> struct B -> struct A
1793 /// struct D -> struct C -> struct A
1794 /// @endcode
1795 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1796   std::string PathDisplayStr;
1797   std::set<unsigned> DisplayedPaths;
1798   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1799        Path != Paths.end(); ++Path) {
1800     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1801       // We haven't displayed a path to this particular base
1802       // class subobject yet.
1803       PathDisplayStr += "\n    ";
1804       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1805       for (CXXBasePath::const_iterator Element = Path->begin();
1806            Element != Path->end(); ++Element)
1807         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1808     }
1809   }
1810 
1811   return PathDisplayStr;
1812 }
1813 
1814 //===----------------------------------------------------------------------===//
1815 // C++ class member Handling
1816 //===----------------------------------------------------------------------===//
1817 
1818 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1819 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1820                                 SourceLocation ASLoc,
1821                                 SourceLocation ColonLoc,
1822                                 AttributeList *Attrs) {
1823   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1824   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1825                                                   ASLoc, ColonLoc);
1826   CurContext->addHiddenDecl(ASDecl);
1827   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1828 }
1829 
1830 /// CheckOverrideControl - Check C++11 override control semantics.
1831 void Sema::CheckOverrideControl(NamedDecl *D) {
1832   if (D->isInvalidDecl())
1833     return;
1834 
1835   // We only care about "override" and "final" declarations.
1836   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1837     return;
1838 
1839   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1840 
1841   // We can't check dependent instance methods.
1842   if (MD && MD->isInstance() &&
1843       (MD->getParent()->hasAnyDependentBases() ||
1844        MD->getType()->isDependentType()))
1845     return;
1846 
1847   if (MD && !MD->isVirtual()) {
1848     // If we have a non-virtual method, check if if hides a virtual method.
1849     // (In that case, it's most likely the method has the wrong type.)
1850     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1851     FindHiddenVirtualMethods(MD, OverloadedMethods);
1852 
1853     if (!OverloadedMethods.empty()) {
1854       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1855         Diag(OA->getLocation(),
1856              diag::override_keyword_hides_virtual_member_function)
1857           << "override" << (OverloadedMethods.size() > 1);
1858       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1859         Diag(FA->getLocation(),
1860              diag::override_keyword_hides_virtual_member_function)
1861           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1862           << (OverloadedMethods.size() > 1);
1863       }
1864       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1865       MD->setInvalidDecl();
1866       return;
1867     }
1868     // Fall through into the general case diagnostic.
1869     // FIXME: We might want to attempt typo correction here.
1870   }
1871 
1872   if (!MD || !MD->isVirtual()) {
1873     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1874       Diag(OA->getLocation(),
1875            diag::override_keyword_only_allowed_on_virtual_member_functions)
1876         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1877       D->dropAttr<OverrideAttr>();
1878     }
1879     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1880       Diag(FA->getLocation(),
1881            diag::override_keyword_only_allowed_on_virtual_member_functions)
1882         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1883         << FixItHint::CreateRemoval(FA->getLocation());
1884       D->dropAttr<FinalAttr>();
1885     }
1886     return;
1887   }
1888 
1889   // C++11 [class.virtual]p5:
1890   //   If a virtual function is marked with the virt-specifier override and
1891   //   does not override a member function of a base class, the program is
1892   //   ill-formed.
1893   bool HasOverriddenMethods =
1894     MD->begin_overridden_methods() != MD->end_overridden_methods();
1895   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1896     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1897       << MD->getDeclName();
1898 }
1899 
1900 void Sema::DiagnoseAbsenseOfOverrideControl(NamedDecl *D) {
1901   if (D->isInvalidDecl())
1902     return;
1903   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1904   if (!MD || MD->isImplicit() || isa<CXXDestructorDecl>(MD))
1905     return;
1906 
1907   bool HasOverriddenMethods =
1908     MD->begin_overridden_methods() != MD->end_overridden_methods();
1909   if (HasOverriddenMethods) {
1910     SourceLocation EndLocation =
1911       (MD->isPure() || MD->hasAttr<FinalAttr>())
1912         ? SourceLocation() : MD->getSourceRange().getEnd();
1913     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1914       << MD->getDeclName()
1915       << FixItHint::CreateReplacement(EndLocation, ") override");
1916     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1917          E = MD->end_overridden_methods(); I != E; ++I) {
1918       const CXXMethodDecl *OMD = *I;
1919       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1920       break;
1921     }
1922   }
1923 }
1924 
1925 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1926 /// function overrides a virtual member function marked 'final', according to
1927 /// C++11 [class.virtual]p4.
1928 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1929                                                   const CXXMethodDecl *Old) {
1930   FinalAttr *FA = Old->getAttr<FinalAttr>();
1931   if (!FA)
1932     return false;
1933 
1934   Diag(New->getLocation(), diag::err_final_function_overridden)
1935     << New->getDeclName()
1936     << FA->isSpelledAsSealed();
1937   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1938   return true;
1939 }
1940 
1941 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1942   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1943   // FIXME: Destruction of ObjC lifetime types has side-effects.
1944   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1945     return !RD->isCompleteDefinition() ||
1946            !RD->hasTrivialDefaultConstructor() ||
1947            !RD->hasTrivialDestructor();
1948   return false;
1949 }
1950 
1951 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1952   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1953     if (it->isDeclspecPropertyAttribute())
1954       return it;
1955   return nullptr;
1956 }
1957 
1958 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1959 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1960 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1961 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1962 /// present (but parsing it has been deferred).
1963 NamedDecl *
1964 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1965                                MultiTemplateParamsArg TemplateParameterLists,
1966                                Expr *BW, const VirtSpecifiers &VS,
1967                                InClassInitStyle InitStyle) {
1968   const DeclSpec &DS = D.getDeclSpec();
1969   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1970   DeclarationName Name = NameInfo.getName();
1971   SourceLocation Loc = NameInfo.getLoc();
1972 
1973   // For anonymous bitfields, the location should point to the type.
1974   if (Loc.isInvalid())
1975     Loc = D.getLocStart();
1976 
1977   Expr *BitWidth = static_cast<Expr*>(BW);
1978 
1979   assert(isa<CXXRecordDecl>(CurContext));
1980   assert(!DS.isFriendSpecified());
1981 
1982   bool isFunc = D.isDeclarationOfFunction();
1983 
1984   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1985     // The Microsoft extension __interface only permits public member functions
1986     // and prohibits constructors, destructors, operators, non-public member
1987     // functions, static methods and data members.
1988     unsigned InvalidDecl;
1989     bool ShowDeclName = true;
1990     if (!isFunc)
1991       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1992     else if (AS != AS_public)
1993       InvalidDecl = 2;
1994     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1995       InvalidDecl = 3;
1996     else switch (Name.getNameKind()) {
1997       case DeclarationName::CXXConstructorName:
1998         InvalidDecl = 4;
1999         ShowDeclName = false;
2000         break;
2001 
2002       case DeclarationName::CXXDestructorName:
2003         InvalidDecl = 5;
2004         ShowDeclName = false;
2005         break;
2006 
2007       case DeclarationName::CXXOperatorName:
2008       case DeclarationName::CXXConversionFunctionName:
2009         InvalidDecl = 6;
2010         break;
2011 
2012       default:
2013         InvalidDecl = 0;
2014         break;
2015     }
2016 
2017     if (InvalidDecl) {
2018       if (ShowDeclName)
2019         Diag(Loc, diag::err_invalid_member_in_interface)
2020           << (InvalidDecl-1) << Name;
2021       else
2022         Diag(Loc, diag::err_invalid_member_in_interface)
2023           << (InvalidDecl-1) << "";
2024       return nullptr;
2025     }
2026   }
2027 
2028   // C++ 9.2p6: A member shall not be declared to have automatic storage
2029   // duration (auto, register) or with the extern storage-class-specifier.
2030   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2031   // data members and cannot be applied to names declared const or static,
2032   // and cannot be applied to reference members.
2033   switch (DS.getStorageClassSpec()) {
2034   case DeclSpec::SCS_unspecified:
2035   case DeclSpec::SCS_typedef:
2036   case DeclSpec::SCS_static:
2037     break;
2038   case DeclSpec::SCS_mutable:
2039     if (isFunc) {
2040       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2041 
2042       // FIXME: It would be nicer if the keyword was ignored only for this
2043       // declarator. Otherwise we could get follow-up errors.
2044       D.getMutableDeclSpec().ClearStorageClassSpecs();
2045     }
2046     break;
2047   default:
2048     Diag(DS.getStorageClassSpecLoc(),
2049          diag::err_storageclass_invalid_for_member);
2050     D.getMutableDeclSpec().ClearStorageClassSpecs();
2051     break;
2052   }
2053 
2054   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2055                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2056                       !isFunc);
2057 
2058   if (DS.isConstexprSpecified() && isInstField) {
2059     SemaDiagnosticBuilder B =
2060         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2061     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2062     if (InitStyle == ICIS_NoInit) {
2063       B << 0 << 0;
2064       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2065         B << FixItHint::CreateRemoval(ConstexprLoc);
2066       else {
2067         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2068         D.getMutableDeclSpec().ClearConstexprSpec();
2069         const char *PrevSpec;
2070         unsigned DiagID;
2071         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2072             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2073         (void)Failed;
2074         assert(!Failed && "Making a constexpr member const shouldn't fail");
2075       }
2076     } else {
2077       B << 1;
2078       const char *PrevSpec;
2079       unsigned DiagID;
2080       if (D.getMutableDeclSpec().SetStorageClassSpec(
2081           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2082           Context.getPrintingPolicy())) {
2083         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2084                "This is the only DeclSpec that should fail to be applied");
2085         B << 1;
2086       } else {
2087         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2088         isInstField = false;
2089       }
2090     }
2091   }
2092 
2093   NamedDecl *Member;
2094   if (isInstField) {
2095     CXXScopeSpec &SS = D.getCXXScopeSpec();
2096 
2097     // Data members must have identifiers for names.
2098     if (!Name.isIdentifier()) {
2099       Diag(Loc, diag::err_bad_variable_name)
2100         << Name;
2101       return nullptr;
2102     }
2103 
2104     IdentifierInfo *II = Name.getAsIdentifierInfo();
2105 
2106     // Member field could not be with "template" keyword.
2107     // So TemplateParameterLists should be empty in this case.
2108     if (TemplateParameterLists.size()) {
2109       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2110       if (TemplateParams->size()) {
2111         // There is no such thing as a member field template.
2112         Diag(D.getIdentifierLoc(), diag::err_template_member)
2113             << II
2114             << SourceRange(TemplateParams->getTemplateLoc(),
2115                 TemplateParams->getRAngleLoc());
2116       } else {
2117         // There is an extraneous 'template<>' for this member.
2118         Diag(TemplateParams->getTemplateLoc(),
2119             diag::err_template_member_noparams)
2120             << II
2121             << SourceRange(TemplateParams->getTemplateLoc(),
2122                 TemplateParams->getRAngleLoc());
2123       }
2124       return nullptr;
2125     }
2126 
2127     if (SS.isSet() && !SS.isInvalid()) {
2128       // The user provided a superfluous scope specifier inside a class
2129       // definition:
2130       //
2131       // class X {
2132       //   int X::member;
2133       // };
2134       if (DeclContext *DC = computeDeclContext(SS, false))
2135         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2136       else
2137         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2138           << Name << SS.getRange();
2139 
2140       SS.clear();
2141     }
2142 
2143     AttributeList *MSPropertyAttr =
2144       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2145     if (MSPropertyAttr) {
2146       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2147                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2148       if (!Member)
2149         return nullptr;
2150       isInstField = false;
2151     } else {
2152       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2153                                 BitWidth, InitStyle, AS);
2154       assert(Member && "HandleField never returns null");
2155     }
2156   } else {
2157     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2158 
2159     Member = HandleDeclarator(S, D, TemplateParameterLists);
2160     if (!Member)
2161       return nullptr;
2162 
2163     // Non-instance-fields can't have a bitfield.
2164     if (BitWidth) {
2165       if (Member->isInvalidDecl()) {
2166         // don't emit another diagnostic.
2167       } else if (isa<VarDecl>(Member)) {
2168         // C++ 9.6p3: A bit-field shall not be a static member.
2169         // "static member 'A' cannot be a bit-field"
2170         Diag(Loc, diag::err_static_not_bitfield)
2171           << Name << BitWidth->getSourceRange();
2172       } else if (isa<TypedefDecl>(Member)) {
2173         // "typedef member 'x' cannot be a bit-field"
2174         Diag(Loc, diag::err_typedef_not_bitfield)
2175           << Name << BitWidth->getSourceRange();
2176       } else {
2177         // A function typedef ("typedef int f(); f a;").
2178         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2179         Diag(Loc, diag::err_not_integral_type_bitfield)
2180           << Name << cast<ValueDecl>(Member)->getType()
2181           << BitWidth->getSourceRange();
2182       }
2183 
2184       BitWidth = nullptr;
2185       Member->setInvalidDecl();
2186     }
2187 
2188     Member->setAccess(AS);
2189 
2190     // If we have declared a member function template or static data member
2191     // template, set the access of the templated declaration as well.
2192     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2193       FunTmpl->getTemplatedDecl()->setAccess(AS);
2194     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2195       VarTmpl->getTemplatedDecl()->setAccess(AS);
2196   }
2197 
2198   if (VS.isOverrideSpecified())
2199     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2200   if (VS.isFinalSpecified())
2201     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2202                                             VS.isFinalSpelledSealed()));
2203 
2204   if (VS.getLastLocation().isValid()) {
2205     // Update the end location of a method that has a virt-specifiers.
2206     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2207       MD->setRangeEnd(VS.getLastLocation());
2208   }
2209 
2210   CheckOverrideControl(Member);
2211 
2212   assert((Name || isInstField) && "No identifier for non-field ?");
2213 
2214   if (isInstField) {
2215     FieldDecl *FD = cast<FieldDecl>(Member);
2216     FieldCollector->Add(FD);
2217 
2218     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2219       // Remember all explicit private FieldDecls that have a name, no side
2220       // effects and are not part of a dependent type declaration.
2221       if (!FD->isImplicit() && FD->getDeclName() &&
2222           FD->getAccess() == AS_private &&
2223           !FD->hasAttr<UnusedAttr>() &&
2224           !FD->getParent()->isDependentContext() &&
2225           !InitializationHasSideEffects(*FD))
2226         UnusedPrivateFields.insert(FD);
2227     }
2228   }
2229 
2230   return Member;
2231 }
2232 
2233 namespace {
2234   class UninitializedFieldVisitor
2235       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2236     Sema &S;
2237     // List of Decls to generate a warning on.  Also remove Decls that become
2238     // initialized.
2239     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2240     // Vector of decls to be removed from the Decl set prior to visiting the
2241     // nodes.  These Decls may have been initialized in the prior initializer.
2242     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2243     // If non-null, add a note to the warning pointing back to the constructor.
2244     const CXXConstructorDecl *Constructor;
2245   public:
2246     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2247     UninitializedFieldVisitor(Sema &S,
2248                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls)
2249       : Inherited(S.Context), S(S), Decls(Decls) { }
2250 
2251     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2252                           bool AddressOf) {
2253       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2254         return;
2255 
2256       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2257       // or union.
2258       MemberExpr *FieldME = ME;
2259 
2260       bool AllPODFields = FieldME->getType().isPODType(S.Context);
2261 
2262       Expr *Base = ME;
2263       while (isa<MemberExpr>(Base)) {
2264         ME = cast<MemberExpr>(Base);
2265 
2266         if (isa<VarDecl>(ME->getMemberDecl()))
2267           return;
2268 
2269         if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2270           if (!FD->isAnonymousStructOrUnion())
2271             FieldME = ME;
2272 
2273         if (!FieldME->getType().isPODType(S.Context))
2274           AllPODFields = false;
2275 
2276         Base = ME->getBase()->IgnoreParenImpCasts();
2277       }
2278 
2279       if (!isa<CXXThisExpr>(Base))
2280         return;
2281 
2282       if (AddressOf && AllPODFields)
2283         return;
2284 
2285       ValueDecl* FoundVD = FieldME->getMemberDecl();
2286 
2287       if (!Decls.count(FoundVD))
2288         return;
2289 
2290       const bool IsReference = FoundVD->getType()->isReferenceType();
2291 
2292       // Prevent double warnings on use of unbounded references.
2293       if (CheckReferenceOnly && !IsReference)
2294         return;
2295 
2296       unsigned diag = IsReference
2297           ? diag::warn_reference_field_is_uninit
2298           : diag::warn_field_is_uninit;
2299       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2300       if (Constructor)
2301         S.Diag(Constructor->getLocation(),
2302                diag::note_uninit_in_this_constructor)
2303           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2304 
2305     }
2306 
2307     void HandleValue(Expr *E, bool AddressOf) {
2308       E = E->IgnoreParens();
2309 
2310       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2311         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2312                          AddressOf /*AddressOf*/);
2313         return;
2314       }
2315 
2316       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2317         Visit(CO->getCond());
2318         HandleValue(CO->getTrueExpr(), AddressOf);
2319         HandleValue(CO->getFalseExpr(), AddressOf);
2320         return;
2321       }
2322 
2323       if (BinaryConditionalOperator *BCO =
2324               dyn_cast<BinaryConditionalOperator>(E)) {
2325         Visit(BCO->getCond());
2326         HandleValue(BCO->getFalseExpr(), AddressOf);
2327         return;
2328       }
2329 
2330       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2331         HandleValue(OVE->getSourceExpr(), AddressOf);
2332         return;
2333       }
2334 
2335       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2336         switch (BO->getOpcode()) {
2337         default:
2338           break;
2339         case(BO_PtrMemD):
2340         case(BO_PtrMemI):
2341           HandleValue(BO->getLHS(), AddressOf);
2342           Visit(BO->getRHS());
2343           return;
2344         case(BO_Comma):
2345           Visit(BO->getLHS());
2346           HandleValue(BO->getRHS(), AddressOf);
2347           return;
2348         }
2349       }
2350 
2351       Visit(E);
2352     }
2353 
2354     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2355                           FieldDecl *Field) {
2356       // Remove Decls that may have been initialized in the previous
2357       // initializer.
2358       for (ValueDecl* VD : DeclsToRemove)
2359         Decls.erase(VD);
2360 
2361       DeclsToRemove.clear();
2362       Constructor = FieldConstructor;
2363       Visit(E);
2364       if (Field)
2365         Decls.erase(Field);
2366     }
2367 
2368     void VisitMemberExpr(MemberExpr *ME) {
2369       // All uses of unbounded reference fields will warn.
2370       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2371     }
2372 
2373     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2374       if (E->getCastKind() == CK_LValueToRValue) {
2375         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2376         return;
2377       }
2378 
2379       Inherited::VisitImplicitCastExpr(E);
2380     }
2381 
2382     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2383       if (E->getConstructor()->isCopyConstructor()) {
2384         Expr *ArgExpr = E->getArg(0);
2385         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2386           if (ILE->getNumInits() == 1)
2387             ArgExpr = ILE->getInit(0);
2388         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2389           if (ICE->getCastKind() == CK_NoOp)
2390             ArgExpr = ICE->getSubExpr();
2391         HandleValue(ArgExpr, false /*AddressOf*/);
2392         return;
2393       }
2394       Inherited::VisitCXXConstructExpr(E);
2395     }
2396 
2397     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2398       Expr *Callee = E->getCallee();
2399       if (isa<MemberExpr>(Callee)) {
2400         HandleValue(Callee, false /*AddressOf*/);
2401         return;
2402       }
2403 
2404       Inherited::VisitCXXMemberCallExpr(E);
2405     }
2406 
2407     void VisitCallExpr(CallExpr *E) {
2408       // Treat std::move as a use.
2409       if (E->getNumArgs() == 1) {
2410         if (FunctionDecl *FD = E->getDirectCallee()) {
2411           if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
2412             HandleValue(E->getArg(0), false /*AddressOf*/);
2413             return;
2414           }
2415         }
2416       }
2417 
2418       Inherited::VisitCallExpr(E);
2419     }
2420 
2421     void VisitBinaryOperator(BinaryOperator *E) {
2422       // If a field assignment is detected, remove the field from the
2423       // uninitiailized field set.
2424       if (E->getOpcode() == BO_Assign)
2425         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2426           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2427             if (!FD->getType()->isReferenceType())
2428               DeclsToRemove.push_back(FD);
2429 
2430       if (E->isCompoundAssignmentOp()) {
2431         HandleValue(E->getLHS(), false /*AddressOf*/);
2432         Visit(E->getRHS());
2433         return;
2434       }
2435 
2436       Inherited::VisitBinaryOperator(E);
2437     }
2438 
2439     void VisitUnaryOperator(UnaryOperator *E) {
2440       if (E->isIncrementDecrementOp()) {
2441         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2442         return;
2443       }
2444       if (E->getOpcode() == UO_AddrOf) {
2445         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2446           HandleValue(ME->getBase(), true /*AddressOf*/);
2447           return;
2448         }
2449       }
2450 
2451       Inherited::VisitUnaryOperator(E);
2452     }
2453   };
2454 
2455   // Diagnose value-uses of fields to initialize themselves, e.g.
2456   //   foo(foo)
2457   // where foo is not also a parameter to the constructor.
2458   // Also diagnose across field uninitialized use such as
2459   //   x(y), y(x)
2460   // TODO: implement -Wuninitialized and fold this into that framework.
2461   static void DiagnoseUninitializedFields(
2462       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2463 
2464     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2465                                            Constructor->getLocation())) {
2466       return;
2467     }
2468 
2469     if (Constructor->isInvalidDecl())
2470       return;
2471 
2472     const CXXRecordDecl *RD = Constructor->getParent();
2473 
2474     // Holds fields that are uninitialized.
2475     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2476 
2477     // At the beginning, all fields are uninitialized.
2478     for (auto *I : RD->decls()) {
2479       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2480         UninitializedFields.insert(FD);
2481       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2482         UninitializedFields.insert(IFD->getAnonField());
2483       }
2484     }
2485 
2486     if (UninitializedFields.empty())
2487       return;
2488 
2489     UninitializedFieldVisitor UninitializedChecker(SemaRef,
2490                                                    UninitializedFields);
2491 
2492     for (const auto *FieldInit : Constructor->inits()) {
2493       if (UninitializedFields.empty())
2494         break;
2495 
2496       Expr *InitExpr = FieldInit->getInit();
2497       if (!InitExpr)
2498         continue;
2499 
2500       if (CXXDefaultInitExpr *Default =
2501               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2502         InitExpr = Default->getExpr();
2503         if (!InitExpr)
2504           continue;
2505         // In class initializers will point to the constructor.
2506         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2507                                               FieldInit->getAnyMember());
2508       } else {
2509         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2510                                               FieldInit->getAnyMember());
2511       }
2512     }
2513   }
2514 } // namespace
2515 
2516 /// \brief Enter a new C++ default initializer scope. After calling this, the
2517 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2518 /// parsing or instantiating the initializer failed.
2519 void Sema::ActOnStartCXXInClassMemberInitializer() {
2520   // Create a synthetic function scope to represent the call to the constructor
2521   // that notionally surrounds a use of this initializer.
2522   PushFunctionScope();
2523 }
2524 
2525 /// \brief This is invoked after parsing an in-class initializer for a
2526 /// non-static C++ class member, and after instantiating an in-class initializer
2527 /// in a class template. Such actions are deferred until the class is complete.
2528 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2529                                                   SourceLocation InitLoc,
2530                                                   Expr *InitExpr) {
2531   // Pop the notional constructor scope we created earlier.
2532   PopFunctionScopeInfo(nullptr, D);
2533 
2534   FieldDecl *FD = cast<FieldDecl>(D);
2535   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2536          "must set init style when field is created");
2537 
2538   if (!InitExpr) {
2539     FD->setInvalidDecl();
2540     FD->removeInClassInitializer();
2541     return;
2542   }
2543 
2544   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2545     FD->setInvalidDecl();
2546     FD->removeInClassInitializer();
2547     return;
2548   }
2549 
2550   ExprResult Init = InitExpr;
2551   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2552     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2553     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2554         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2555         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2556     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2557     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2558     if (Init.isInvalid()) {
2559       FD->setInvalidDecl();
2560       return;
2561     }
2562   }
2563 
2564   // C++11 [class.base.init]p7:
2565   //   The initialization of each base and member constitutes a
2566   //   full-expression.
2567   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2568   if (Init.isInvalid()) {
2569     FD->setInvalidDecl();
2570     return;
2571   }
2572 
2573   InitExpr = Init.get();
2574 
2575   FD->setInClassInitializer(InitExpr);
2576 }
2577 
2578 /// \brief Find the direct and/or virtual base specifiers that
2579 /// correspond to the given base type, for use in base initialization
2580 /// within a constructor.
2581 static bool FindBaseInitializer(Sema &SemaRef,
2582                                 CXXRecordDecl *ClassDecl,
2583                                 QualType BaseType,
2584                                 const CXXBaseSpecifier *&DirectBaseSpec,
2585                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2586   // First, check for a direct base class.
2587   DirectBaseSpec = nullptr;
2588   for (const auto &Base : ClassDecl->bases()) {
2589     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2590       // We found a direct base of this type. That's what we're
2591       // initializing.
2592       DirectBaseSpec = &Base;
2593       break;
2594     }
2595   }
2596 
2597   // Check for a virtual base class.
2598   // FIXME: We might be able to short-circuit this if we know in advance that
2599   // there are no virtual bases.
2600   VirtualBaseSpec = nullptr;
2601   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2602     // We haven't found a base yet; search the class hierarchy for a
2603     // virtual base class.
2604     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2605                        /*DetectVirtual=*/false);
2606     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2607                               BaseType, Paths)) {
2608       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2609            Path != Paths.end(); ++Path) {
2610         if (Path->back().Base->isVirtual()) {
2611           VirtualBaseSpec = Path->back().Base;
2612           break;
2613         }
2614       }
2615     }
2616   }
2617 
2618   return DirectBaseSpec || VirtualBaseSpec;
2619 }
2620 
2621 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2622 MemInitResult
2623 Sema::ActOnMemInitializer(Decl *ConstructorD,
2624                           Scope *S,
2625                           CXXScopeSpec &SS,
2626                           IdentifierInfo *MemberOrBase,
2627                           ParsedType TemplateTypeTy,
2628                           const DeclSpec &DS,
2629                           SourceLocation IdLoc,
2630                           Expr *InitList,
2631                           SourceLocation EllipsisLoc) {
2632   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2633                              DS, IdLoc, InitList,
2634                              EllipsisLoc);
2635 }
2636 
2637 /// \brief Handle a C++ member initializer using parentheses syntax.
2638 MemInitResult
2639 Sema::ActOnMemInitializer(Decl *ConstructorD,
2640                           Scope *S,
2641                           CXXScopeSpec &SS,
2642                           IdentifierInfo *MemberOrBase,
2643                           ParsedType TemplateTypeTy,
2644                           const DeclSpec &DS,
2645                           SourceLocation IdLoc,
2646                           SourceLocation LParenLoc,
2647                           ArrayRef<Expr *> Args,
2648                           SourceLocation RParenLoc,
2649                           SourceLocation EllipsisLoc) {
2650   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2651                                            Args, RParenLoc);
2652   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2653                              DS, IdLoc, List, EllipsisLoc);
2654 }
2655 
2656 namespace {
2657 
2658 // Callback to only accept typo corrections that can be a valid C++ member
2659 // intializer: either a non-static field member or a base class.
2660 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2661 public:
2662   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2663       : ClassDecl(ClassDecl) {}
2664 
2665   bool ValidateCandidate(const TypoCorrection &candidate) override {
2666     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2667       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2668         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2669       return isa<TypeDecl>(ND);
2670     }
2671     return false;
2672   }
2673 
2674 private:
2675   CXXRecordDecl *ClassDecl;
2676 };
2677 
2678 }
2679 
2680 /// \brief Handle a C++ member initializer.
2681 MemInitResult
2682 Sema::BuildMemInitializer(Decl *ConstructorD,
2683                           Scope *S,
2684                           CXXScopeSpec &SS,
2685                           IdentifierInfo *MemberOrBase,
2686                           ParsedType TemplateTypeTy,
2687                           const DeclSpec &DS,
2688                           SourceLocation IdLoc,
2689                           Expr *Init,
2690                           SourceLocation EllipsisLoc) {
2691   if (!ConstructorD)
2692     return true;
2693 
2694   AdjustDeclIfTemplate(ConstructorD);
2695 
2696   CXXConstructorDecl *Constructor
2697     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2698   if (!Constructor) {
2699     // The user wrote a constructor initializer on a function that is
2700     // not a C++ constructor. Ignore the error for now, because we may
2701     // have more member initializers coming; we'll diagnose it just
2702     // once in ActOnMemInitializers.
2703     return true;
2704   }
2705 
2706   CXXRecordDecl *ClassDecl = Constructor->getParent();
2707 
2708   // C++ [class.base.init]p2:
2709   //   Names in a mem-initializer-id are looked up in the scope of the
2710   //   constructor's class and, if not found in that scope, are looked
2711   //   up in the scope containing the constructor's definition.
2712   //   [Note: if the constructor's class contains a member with the
2713   //   same name as a direct or virtual base class of the class, a
2714   //   mem-initializer-id naming the member or base class and composed
2715   //   of a single identifier refers to the class member. A
2716   //   mem-initializer-id for the hidden base class may be specified
2717   //   using a qualified name. ]
2718   if (!SS.getScopeRep() && !TemplateTypeTy) {
2719     // Look for a member, first.
2720     DeclContext::lookup_result Result
2721       = ClassDecl->lookup(MemberOrBase);
2722     if (!Result.empty()) {
2723       ValueDecl *Member;
2724       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2725           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2726         if (EllipsisLoc.isValid())
2727           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2728             << MemberOrBase
2729             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2730 
2731         return BuildMemberInitializer(Member, Init, IdLoc);
2732       }
2733     }
2734   }
2735   // It didn't name a member, so see if it names a class.
2736   QualType BaseType;
2737   TypeSourceInfo *TInfo = nullptr;
2738 
2739   if (TemplateTypeTy) {
2740     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2741   } else if (DS.getTypeSpecType() == TST_decltype) {
2742     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2743   } else {
2744     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2745     LookupParsedName(R, S, &SS);
2746 
2747     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2748     if (!TyD) {
2749       if (R.isAmbiguous()) return true;
2750 
2751       // We don't want access-control diagnostics here.
2752       R.suppressDiagnostics();
2753 
2754       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2755         bool NotUnknownSpecialization = false;
2756         DeclContext *DC = computeDeclContext(SS, false);
2757         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2758           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2759 
2760         if (!NotUnknownSpecialization) {
2761           // When the scope specifier can refer to a member of an unknown
2762           // specialization, we take it as a type name.
2763           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2764                                        SS.getWithLocInContext(Context),
2765                                        *MemberOrBase, IdLoc);
2766           if (BaseType.isNull())
2767             return true;
2768 
2769           R.clear();
2770           R.setLookupName(MemberOrBase);
2771         }
2772       }
2773 
2774       // If no results were found, try to correct typos.
2775       TypoCorrection Corr;
2776       MemInitializerValidatorCCC Validator(ClassDecl);
2777       if (R.empty() && BaseType.isNull() &&
2778           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2779                               Validator, CTK_ErrorRecovery, ClassDecl))) {
2780         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2781           // We have found a non-static data member with a similar
2782           // name to what was typed; complain and initialize that
2783           // member.
2784           diagnoseTypo(Corr,
2785                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2786                          << MemberOrBase << true);
2787           return BuildMemberInitializer(Member, Init, IdLoc);
2788         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2789           const CXXBaseSpecifier *DirectBaseSpec;
2790           const CXXBaseSpecifier *VirtualBaseSpec;
2791           if (FindBaseInitializer(*this, ClassDecl,
2792                                   Context.getTypeDeclType(Type),
2793                                   DirectBaseSpec, VirtualBaseSpec)) {
2794             // We have found a direct or virtual base class with a
2795             // similar name to what was typed; complain and initialize
2796             // that base class.
2797             diagnoseTypo(Corr,
2798                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2799                            << MemberOrBase << false,
2800                          PDiag() /*Suppress note, we provide our own.*/);
2801 
2802             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2803                                                               : VirtualBaseSpec;
2804             Diag(BaseSpec->getLocStart(),
2805                  diag::note_base_class_specified_here)
2806               << BaseSpec->getType()
2807               << BaseSpec->getSourceRange();
2808 
2809             TyD = Type;
2810           }
2811         }
2812       }
2813 
2814       if (!TyD && BaseType.isNull()) {
2815         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2816           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2817         return true;
2818       }
2819     }
2820 
2821     if (BaseType.isNull()) {
2822       BaseType = Context.getTypeDeclType(TyD);
2823       if (SS.isSet())
2824         // FIXME: preserve source range information
2825         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2826                                              BaseType);
2827     }
2828   }
2829 
2830   if (!TInfo)
2831     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2832 
2833   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2834 }
2835 
2836 /// Checks a member initializer expression for cases where reference (or
2837 /// pointer) members are bound to by-value parameters (or their addresses).
2838 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2839                                                Expr *Init,
2840                                                SourceLocation IdLoc) {
2841   QualType MemberTy = Member->getType();
2842 
2843   // We only handle pointers and references currently.
2844   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2845   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2846     return;
2847 
2848   const bool IsPointer = MemberTy->isPointerType();
2849   if (IsPointer) {
2850     if (const UnaryOperator *Op
2851           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2852       // The only case we're worried about with pointers requires taking the
2853       // address.
2854       if (Op->getOpcode() != UO_AddrOf)
2855         return;
2856 
2857       Init = Op->getSubExpr();
2858     } else {
2859       // We only handle address-of expression initializers for pointers.
2860       return;
2861     }
2862   }
2863 
2864   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2865     // We only warn when referring to a non-reference parameter declaration.
2866     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2867     if (!Parameter || Parameter->getType()->isReferenceType())
2868       return;
2869 
2870     S.Diag(Init->getExprLoc(),
2871            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2872                      : diag::warn_bind_ref_member_to_parameter)
2873       << Member << Parameter << Init->getSourceRange();
2874   } else {
2875     // Other initializers are fine.
2876     return;
2877   }
2878 
2879   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2880     << (unsigned)IsPointer;
2881 }
2882 
2883 MemInitResult
2884 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2885                              SourceLocation IdLoc) {
2886   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2887   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2888   assert((DirectMember || IndirectMember) &&
2889          "Member must be a FieldDecl or IndirectFieldDecl");
2890 
2891   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2892     return true;
2893 
2894   if (Member->isInvalidDecl())
2895     return true;
2896 
2897   MultiExprArg Args;
2898   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2899     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2900   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2901     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2902   } else {
2903     // Template instantiation doesn't reconstruct ParenListExprs for us.
2904     Args = Init;
2905   }
2906 
2907   SourceRange InitRange = Init->getSourceRange();
2908 
2909   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2910     // Can't check initialization for a member of dependent type or when
2911     // any of the arguments are type-dependent expressions.
2912     DiscardCleanupsInEvaluationContext();
2913   } else {
2914     bool InitList = false;
2915     if (isa<InitListExpr>(Init)) {
2916       InitList = true;
2917       Args = Init;
2918     }
2919 
2920     // Initialize the member.
2921     InitializedEntity MemberEntity =
2922       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2923                    : InitializedEntity::InitializeMember(IndirectMember,
2924                                                          nullptr);
2925     InitializationKind Kind =
2926       InitList ? InitializationKind::CreateDirectList(IdLoc)
2927                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2928                                                   InitRange.getEnd());
2929 
2930     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2931     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2932                                             nullptr);
2933     if (MemberInit.isInvalid())
2934       return true;
2935 
2936     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2937 
2938     // C++11 [class.base.init]p7:
2939     //   The initialization of each base and member constitutes a
2940     //   full-expression.
2941     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2942     if (MemberInit.isInvalid())
2943       return true;
2944 
2945     Init = MemberInit.get();
2946   }
2947 
2948   if (DirectMember) {
2949     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2950                                             InitRange.getBegin(), Init,
2951                                             InitRange.getEnd());
2952   } else {
2953     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2954                                             InitRange.getBegin(), Init,
2955                                             InitRange.getEnd());
2956   }
2957 }
2958 
2959 MemInitResult
2960 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2961                                  CXXRecordDecl *ClassDecl) {
2962   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2963   if (!LangOpts.CPlusPlus11)
2964     return Diag(NameLoc, diag::err_delegating_ctor)
2965       << TInfo->getTypeLoc().getLocalSourceRange();
2966   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2967 
2968   bool InitList = true;
2969   MultiExprArg Args = Init;
2970   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2971     InitList = false;
2972     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2973   }
2974 
2975   SourceRange InitRange = Init->getSourceRange();
2976   // Initialize the object.
2977   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2978                                      QualType(ClassDecl->getTypeForDecl(), 0));
2979   InitializationKind Kind =
2980     InitList ? InitializationKind::CreateDirectList(NameLoc)
2981              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2982                                                 InitRange.getEnd());
2983   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2984   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2985                                               Args, nullptr);
2986   if (DelegationInit.isInvalid())
2987     return true;
2988 
2989   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2990          "Delegating constructor with no target?");
2991 
2992   // C++11 [class.base.init]p7:
2993   //   The initialization of each base and member constitutes a
2994   //   full-expression.
2995   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2996                                        InitRange.getBegin());
2997   if (DelegationInit.isInvalid())
2998     return true;
2999 
3000   // If we are in a dependent context, template instantiation will
3001   // perform this type-checking again. Just save the arguments that we
3002   // received in a ParenListExpr.
3003   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3004   // of the information that we have about the base
3005   // initializer. However, deconstructing the ASTs is a dicey process,
3006   // and this approach is far more likely to get the corner cases right.
3007   if (CurContext->isDependentContext())
3008     DelegationInit = Init;
3009 
3010   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3011                                           DelegationInit.getAs<Expr>(),
3012                                           InitRange.getEnd());
3013 }
3014 
3015 MemInitResult
3016 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3017                            Expr *Init, CXXRecordDecl *ClassDecl,
3018                            SourceLocation EllipsisLoc) {
3019   SourceLocation BaseLoc
3020     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3021 
3022   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3023     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3024              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3025 
3026   // C++ [class.base.init]p2:
3027   //   [...] Unless the mem-initializer-id names a nonstatic data
3028   //   member of the constructor's class or a direct or virtual base
3029   //   of that class, the mem-initializer is ill-formed. A
3030   //   mem-initializer-list can initialize a base class using any
3031   //   name that denotes that base class type.
3032   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3033 
3034   SourceRange InitRange = Init->getSourceRange();
3035   if (EllipsisLoc.isValid()) {
3036     // This is a pack expansion.
3037     if (!BaseType->containsUnexpandedParameterPack())  {
3038       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3039         << SourceRange(BaseLoc, InitRange.getEnd());
3040 
3041       EllipsisLoc = SourceLocation();
3042     }
3043   } else {
3044     // Check for any unexpanded parameter packs.
3045     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3046       return true;
3047 
3048     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3049       return true;
3050   }
3051 
3052   // Check for direct and virtual base classes.
3053   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3054   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3055   if (!Dependent) {
3056     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3057                                        BaseType))
3058       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3059 
3060     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3061                         VirtualBaseSpec);
3062 
3063     // C++ [base.class.init]p2:
3064     // Unless the mem-initializer-id names a nonstatic data member of the
3065     // constructor's class or a direct or virtual base of that class, the
3066     // mem-initializer is ill-formed.
3067     if (!DirectBaseSpec && !VirtualBaseSpec) {
3068       // If the class has any dependent bases, then it's possible that
3069       // one of those types will resolve to the same type as
3070       // BaseType. Therefore, just treat this as a dependent base
3071       // class initialization.  FIXME: Should we try to check the
3072       // initialization anyway? It seems odd.
3073       if (ClassDecl->hasAnyDependentBases())
3074         Dependent = true;
3075       else
3076         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3077           << BaseType << Context.getTypeDeclType(ClassDecl)
3078           << BaseTInfo->getTypeLoc().getLocalSourceRange();
3079     }
3080   }
3081 
3082   if (Dependent) {
3083     DiscardCleanupsInEvaluationContext();
3084 
3085     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3086                                             /*IsVirtual=*/false,
3087                                             InitRange.getBegin(), Init,
3088                                             InitRange.getEnd(), EllipsisLoc);
3089   }
3090 
3091   // C++ [base.class.init]p2:
3092   //   If a mem-initializer-id is ambiguous because it designates both
3093   //   a direct non-virtual base class and an inherited virtual base
3094   //   class, the mem-initializer is ill-formed.
3095   if (DirectBaseSpec && VirtualBaseSpec)
3096     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3097       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3098 
3099   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3100   if (!BaseSpec)
3101     BaseSpec = VirtualBaseSpec;
3102 
3103   // Initialize the base.
3104   bool InitList = true;
3105   MultiExprArg Args = Init;
3106   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3107     InitList = false;
3108     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3109   }
3110 
3111   InitializedEntity BaseEntity =
3112     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3113   InitializationKind Kind =
3114     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3115              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3116                                                 InitRange.getEnd());
3117   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3118   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3119   if (BaseInit.isInvalid())
3120     return true;
3121 
3122   // C++11 [class.base.init]p7:
3123   //   The initialization of each base and member constitutes a
3124   //   full-expression.
3125   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3126   if (BaseInit.isInvalid())
3127     return true;
3128 
3129   // If we are in a dependent context, template instantiation will
3130   // perform this type-checking again. Just save the arguments that we
3131   // received in a ParenListExpr.
3132   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3133   // of the information that we have about the base
3134   // initializer. However, deconstructing the ASTs is a dicey process,
3135   // and this approach is far more likely to get the corner cases right.
3136   if (CurContext->isDependentContext())
3137     BaseInit = Init;
3138 
3139   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3140                                           BaseSpec->isVirtual(),
3141                                           InitRange.getBegin(),
3142                                           BaseInit.getAs<Expr>(),
3143                                           InitRange.getEnd(), EllipsisLoc);
3144 }
3145 
3146 // Create a static_cast\<T&&>(expr).
3147 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3148   if (T.isNull()) T = E->getType();
3149   QualType TargetType = SemaRef.BuildReferenceType(
3150       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3151   SourceLocation ExprLoc = E->getLocStart();
3152   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3153       TargetType, ExprLoc);
3154 
3155   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3156                                    SourceRange(ExprLoc, ExprLoc),
3157                                    E->getSourceRange()).get();
3158 }
3159 
3160 /// ImplicitInitializerKind - How an implicit base or member initializer should
3161 /// initialize its base or member.
3162 enum ImplicitInitializerKind {
3163   IIK_Default,
3164   IIK_Copy,
3165   IIK_Move,
3166   IIK_Inherit
3167 };
3168 
3169 static bool
3170 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3171                              ImplicitInitializerKind ImplicitInitKind,
3172                              CXXBaseSpecifier *BaseSpec,
3173                              bool IsInheritedVirtualBase,
3174                              CXXCtorInitializer *&CXXBaseInit) {
3175   InitializedEntity InitEntity
3176     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3177                                         IsInheritedVirtualBase);
3178 
3179   ExprResult BaseInit;
3180 
3181   switch (ImplicitInitKind) {
3182   case IIK_Inherit: {
3183     const CXXRecordDecl *Inherited =
3184         Constructor->getInheritedConstructor()->getParent();
3185     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3186     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3187       // C++11 [class.inhctor]p8:
3188       //   Each expression in the expression-list is of the form
3189       //   static_cast<T&&>(p), where p is the name of the corresponding
3190       //   constructor parameter and T is the declared type of p.
3191       SmallVector<Expr*, 16> Args;
3192       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3193         ParmVarDecl *PD = Constructor->getParamDecl(I);
3194         ExprResult ArgExpr =
3195             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3196                                      VK_LValue, SourceLocation());
3197         if (ArgExpr.isInvalid())
3198           return true;
3199         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3200       }
3201 
3202       InitializationKind InitKind = InitializationKind::CreateDirect(
3203           Constructor->getLocation(), SourceLocation(), SourceLocation());
3204       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3205       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3206       break;
3207     }
3208   }
3209   // Fall through.
3210   case IIK_Default: {
3211     InitializationKind InitKind
3212       = InitializationKind::CreateDefault(Constructor->getLocation());
3213     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3214     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3215     break;
3216   }
3217 
3218   case IIK_Move:
3219   case IIK_Copy: {
3220     bool Moving = ImplicitInitKind == IIK_Move;
3221     ParmVarDecl *Param = Constructor->getParamDecl(0);
3222     QualType ParamType = Param->getType().getNonReferenceType();
3223 
3224     Expr *CopyCtorArg =
3225       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3226                           SourceLocation(), Param, false,
3227                           Constructor->getLocation(), ParamType,
3228                           VK_LValue, nullptr);
3229 
3230     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3231 
3232     // Cast to the base class to avoid ambiguities.
3233     QualType ArgTy =
3234       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3235                                        ParamType.getQualifiers());
3236 
3237     if (Moving) {
3238       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3239     }
3240 
3241     CXXCastPath BasePath;
3242     BasePath.push_back(BaseSpec);
3243     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3244                                             CK_UncheckedDerivedToBase,
3245                                             Moving ? VK_XValue : VK_LValue,
3246                                             &BasePath).get();
3247 
3248     InitializationKind InitKind
3249       = InitializationKind::CreateDirect(Constructor->getLocation(),
3250                                          SourceLocation(), SourceLocation());
3251     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3252     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3253     break;
3254   }
3255   }
3256 
3257   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3258   if (BaseInit.isInvalid())
3259     return true;
3260 
3261   CXXBaseInit =
3262     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3263                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3264                                                         SourceLocation()),
3265                                              BaseSpec->isVirtual(),
3266                                              SourceLocation(),
3267                                              BaseInit.getAs<Expr>(),
3268                                              SourceLocation(),
3269                                              SourceLocation());
3270 
3271   return false;
3272 }
3273 
3274 static bool RefersToRValueRef(Expr *MemRef) {
3275   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3276   return Referenced->getType()->isRValueReferenceType();
3277 }
3278 
3279 static bool
3280 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3281                                ImplicitInitializerKind ImplicitInitKind,
3282                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3283                                CXXCtorInitializer *&CXXMemberInit) {
3284   if (Field->isInvalidDecl())
3285     return true;
3286 
3287   SourceLocation Loc = Constructor->getLocation();
3288 
3289   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3290     bool Moving = ImplicitInitKind == IIK_Move;
3291     ParmVarDecl *Param = Constructor->getParamDecl(0);
3292     QualType ParamType = Param->getType().getNonReferenceType();
3293 
3294     // Suppress copying zero-width bitfields.
3295     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3296       return false;
3297 
3298     Expr *MemberExprBase =
3299       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3300                           SourceLocation(), Param, false,
3301                           Loc, ParamType, VK_LValue, nullptr);
3302 
3303     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3304 
3305     if (Moving) {
3306       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3307     }
3308 
3309     // Build a reference to this field within the parameter.
3310     CXXScopeSpec SS;
3311     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3312                               Sema::LookupMemberName);
3313     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3314                                   : cast<ValueDecl>(Field), AS_public);
3315     MemberLookup.resolveKind();
3316     ExprResult CtorArg
3317       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3318                                          ParamType, Loc,
3319                                          /*IsArrow=*/false,
3320                                          SS,
3321                                          /*TemplateKWLoc=*/SourceLocation(),
3322                                          /*FirstQualifierInScope=*/nullptr,
3323                                          MemberLookup,
3324                                          /*TemplateArgs=*/nullptr);
3325     if (CtorArg.isInvalid())
3326       return true;
3327 
3328     // C++11 [class.copy]p15:
3329     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3330     //     with static_cast<T&&>(x.m);
3331     if (RefersToRValueRef(CtorArg.get())) {
3332       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3333     }
3334 
3335     // When the field we are copying is an array, create index variables for
3336     // each dimension of the array. We use these index variables to subscript
3337     // the source array, and other clients (e.g., CodeGen) will perform the
3338     // necessary iteration with these index variables.
3339     SmallVector<VarDecl *, 4> IndexVariables;
3340     QualType BaseType = Field->getType();
3341     QualType SizeType = SemaRef.Context.getSizeType();
3342     bool InitializingArray = false;
3343     while (const ConstantArrayType *Array
3344                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3345       InitializingArray = true;
3346       // Create the iteration variable for this array index.
3347       IdentifierInfo *IterationVarName = nullptr;
3348       {
3349         SmallString<8> Str;
3350         llvm::raw_svector_ostream OS(Str);
3351         OS << "__i" << IndexVariables.size();
3352         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3353       }
3354       VarDecl *IterationVar
3355         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3356                           IterationVarName, SizeType,
3357                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3358                           SC_None);
3359       IndexVariables.push_back(IterationVar);
3360 
3361       // Create a reference to the iteration variable.
3362       ExprResult IterationVarRef
3363         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3364       assert(!IterationVarRef.isInvalid() &&
3365              "Reference to invented variable cannot fail!");
3366       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3367       assert(!IterationVarRef.isInvalid() &&
3368              "Conversion of invented variable cannot fail!");
3369 
3370       // Subscript the array with this iteration variable.
3371       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3372                                                         IterationVarRef.get(),
3373                                                         Loc);
3374       if (CtorArg.isInvalid())
3375         return true;
3376 
3377       BaseType = Array->getElementType();
3378     }
3379 
3380     // The array subscript expression is an lvalue, which is wrong for moving.
3381     if (Moving && InitializingArray)
3382       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3383 
3384     // Construct the entity that we will be initializing. For an array, this
3385     // will be first element in the array, which may require several levels
3386     // of array-subscript entities.
3387     SmallVector<InitializedEntity, 4> Entities;
3388     Entities.reserve(1 + IndexVariables.size());
3389     if (Indirect)
3390       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3391     else
3392       Entities.push_back(InitializedEntity::InitializeMember(Field));
3393     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3394       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3395                                                               0,
3396                                                               Entities.back()));
3397 
3398     // Direct-initialize to use the copy constructor.
3399     InitializationKind InitKind =
3400       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3401 
3402     Expr *CtorArgE = CtorArg.getAs<Expr>();
3403     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3404 
3405     ExprResult MemberInit
3406       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3407                         MultiExprArg(&CtorArgE, 1));
3408     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3409     if (MemberInit.isInvalid())
3410       return true;
3411 
3412     if (Indirect) {
3413       assert(IndexVariables.size() == 0 &&
3414              "Indirect field improperly initialized");
3415       CXXMemberInit
3416         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3417                                                    Loc, Loc,
3418                                                    MemberInit.getAs<Expr>(),
3419                                                    Loc);
3420     } else
3421       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3422                                                  Loc, MemberInit.getAs<Expr>(),
3423                                                  Loc,
3424                                                  IndexVariables.data(),
3425                                                  IndexVariables.size());
3426     return false;
3427   }
3428 
3429   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3430          "Unhandled implicit init kind!");
3431 
3432   QualType FieldBaseElementType =
3433     SemaRef.Context.getBaseElementType(Field->getType());
3434 
3435   if (FieldBaseElementType->isRecordType()) {
3436     InitializedEntity InitEntity
3437       = Indirect? InitializedEntity::InitializeMember(Indirect)
3438                 : InitializedEntity::InitializeMember(Field);
3439     InitializationKind InitKind =
3440       InitializationKind::CreateDefault(Loc);
3441 
3442     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3443     ExprResult MemberInit =
3444       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3445 
3446     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3447     if (MemberInit.isInvalid())
3448       return true;
3449 
3450     if (Indirect)
3451       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3452                                                                Indirect, Loc,
3453                                                                Loc,
3454                                                                MemberInit.get(),
3455                                                                Loc);
3456     else
3457       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3458                                                                Field, Loc, Loc,
3459                                                                MemberInit.get(),
3460                                                                Loc);
3461     return false;
3462   }
3463 
3464   if (!Field->getParent()->isUnion()) {
3465     if (FieldBaseElementType->isReferenceType()) {
3466       SemaRef.Diag(Constructor->getLocation(),
3467                    diag::err_uninitialized_member_in_ctor)
3468       << (int)Constructor->isImplicit()
3469       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3470       << 0 << Field->getDeclName();
3471       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3472       return true;
3473     }
3474 
3475     if (FieldBaseElementType.isConstQualified()) {
3476       SemaRef.Diag(Constructor->getLocation(),
3477                    diag::err_uninitialized_member_in_ctor)
3478       << (int)Constructor->isImplicit()
3479       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3480       << 1 << Field->getDeclName();
3481       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3482       return true;
3483     }
3484   }
3485 
3486   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3487       FieldBaseElementType->isObjCRetainableType() &&
3488       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3489       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3490     // ARC:
3491     //   Default-initialize Objective-C pointers to NULL.
3492     CXXMemberInit
3493       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3494                                                  Loc, Loc,
3495                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3496                                                  Loc);
3497     return false;
3498   }
3499 
3500   // Nothing to initialize.
3501   CXXMemberInit = nullptr;
3502   return false;
3503 }
3504 
3505 namespace {
3506 struct BaseAndFieldInfo {
3507   Sema &S;
3508   CXXConstructorDecl *Ctor;
3509   bool AnyErrorsInInits;
3510   ImplicitInitializerKind IIK;
3511   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3512   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3513   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3514 
3515   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3516     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3517     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3518     if (Generated && Ctor->isCopyConstructor())
3519       IIK = IIK_Copy;
3520     else if (Generated && Ctor->isMoveConstructor())
3521       IIK = IIK_Move;
3522     else if (Ctor->getInheritedConstructor())
3523       IIK = IIK_Inherit;
3524     else
3525       IIK = IIK_Default;
3526   }
3527 
3528   bool isImplicitCopyOrMove() const {
3529     switch (IIK) {
3530     case IIK_Copy:
3531     case IIK_Move:
3532       return true;
3533 
3534     case IIK_Default:
3535     case IIK_Inherit:
3536       return false;
3537     }
3538 
3539     llvm_unreachable("Invalid ImplicitInitializerKind!");
3540   }
3541 
3542   bool addFieldInitializer(CXXCtorInitializer *Init) {
3543     AllToInit.push_back(Init);
3544 
3545     // Check whether this initializer makes the field "used".
3546     if (Init->getInit()->HasSideEffects(S.Context))
3547       S.UnusedPrivateFields.remove(Init->getAnyMember());
3548 
3549     return false;
3550   }
3551 
3552   bool isInactiveUnionMember(FieldDecl *Field) {
3553     RecordDecl *Record = Field->getParent();
3554     if (!Record->isUnion())
3555       return false;
3556 
3557     if (FieldDecl *Active =
3558             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3559       return Active != Field->getCanonicalDecl();
3560 
3561     // In an implicit copy or move constructor, ignore any in-class initializer.
3562     if (isImplicitCopyOrMove())
3563       return true;
3564 
3565     // If there's no explicit initialization, the field is active only if it
3566     // has an in-class initializer...
3567     if (Field->hasInClassInitializer())
3568       return false;
3569     // ... or it's an anonymous struct or union whose class has an in-class
3570     // initializer.
3571     if (!Field->isAnonymousStructOrUnion())
3572       return true;
3573     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3574     return !FieldRD->hasInClassInitializer();
3575   }
3576 
3577   /// \brief Determine whether the given field is, or is within, a union member
3578   /// that is inactive (because there was an initializer given for a different
3579   /// member of the union, or because the union was not initialized at all).
3580   bool isWithinInactiveUnionMember(FieldDecl *Field,
3581                                    IndirectFieldDecl *Indirect) {
3582     if (!Indirect)
3583       return isInactiveUnionMember(Field);
3584 
3585     for (auto *C : Indirect->chain()) {
3586       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3587       if (Field && isInactiveUnionMember(Field))
3588         return true;
3589     }
3590     return false;
3591   }
3592 };
3593 }
3594 
3595 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3596 /// array type.
3597 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3598   if (T->isIncompleteArrayType())
3599     return true;
3600 
3601   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3602     if (!ArrayT->getSize())
3603       return true;
3604 
3605     T = ArrayT->getElementType();
3606   }
3607 
3608   return false;
3609 }
3610 
3611 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3612                                     FieldDecl *Field,
3613                                     IndirectFieldDecl *Indirect = nullptr) {
3614   if (Field->isInvalidDecl())
3615     return false;
3616 
3617   // Overwhelmingly common case: we have a direct initializer for this field.
3618   if (CXXCtorInitializer *Init =
3619           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3620     return Info.addFieldInitializer(Init);
3621 
3622   // C++11 [class.base.init]p8:
3623   //   if the entity is a non-static data member that has a
3624   //   brace-or-equal-initializer and either
3625   //   -- the constructor's class is a union and no other variant member of that
3626   //      union is designated by a mem-initializer-id or
3627   //   -- the constructor's class is not a union, and, if the entity is a member
3628   //      of an anonymous union, no other member of that union is designated by
3629   //      a mem-initializer-id,
3630   //   the entity is initialized as specified in [dcl.init].
3631   //
3632   // We also apply the same rules to handle anonymous structs within anonymous
3633   // unions.
3634   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3635     return false;
3636 
3637   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3638     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3639                                            Info.Ctor->getLocation(), Field);
3640     CXXCtorInitializer *Init;
3641     if (Indirect)
3642       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3643                                                       SourceLocation(),
3644                                                       SourceLocation(), DIE,
3645                                                       SourceLocation());
3646     else
3647       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3648                                                       SourceLocation(),
3649                                                       SourceLocation(), DIE,
3650                                                       SourceLocation());
3651     return Info.addFieldInitializer(Init);
3652   }
3653 
3654   // Don't initialize incomplete or zero-length arrays.
3655   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3656     return false;
3657 
3658   // Don't try to build an implicit initializer if there were semantic
3659   // errors in any of the initializers (and therefore we might be
3660   // missing some that the user actually wrote).
3661   if (Info.AnyErrorsInInits)
3662     return false;
3663 
3664   CXXCtorInitializer *Init = nullptr;
3665   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3666                                      Indirect, Init))
3667     return true;
3668 
3669   if (!Init)
3670     return false;
3671 
3672   return Info.addFieldInitializer(Init);
3673 }
3674 
3675 bool
3676 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3677                                CXXCtorInitializer *Initializer) {
3678   assert(Initializer->isDelegatingInitializer());
3679   Constructor->setNumCtorInitializers(1);
3680   CXXCtorInitializer **initializer =
3681     new (Context) CXXCtorInitializer*[1];
3682   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3683   Constructor->setCtorInitializers(initializer);
3684 
3685   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3686     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3687     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3688   }
3689 
3690   DelegatingCtorDecls.push_back(Constructor);
3691 
3692   DiagnoseUninitializedFields(*this, Constructor);
3693 
3694   return false;
3695 }
3696 
3697 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3698                                ArrayRef<CXXCtorInitializer *> Initializers) {
3699   if (Constructor->isDependentContext()) {
3700     // Just store the initializers as written, they will be checked during
3701     // instantiation.
3702     if (!Initializers.empty()) {
3703       Constructor->setNumCtorInitializers(Initializers.size());
3704       CXXCtorInitializer **baseOrMemberInitializers =
3705         new (Context) CXXCtorInitializer*[Initializers.size()];
3706       memcpy(baseOrMemberInitializers, Initializers.data(),
3707              Initializers.size() * sizeof(CXXCtorInitializer*));
3708       Constructor->setCtorInitializers(baseOrMemberInitializers);
3709     }
3710 
3711     // Let template instantiation know whether we had errors.
3712     if (AnyErrors)
3713       Constructor->setInvalidDecl();
3714 
3715     return false;
3716   }
3717 
3718   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3719 
3720   // We need to build the initializer AST according to order of construction
3721   // and not what user specified in the Initializers list.
3722   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3723   if (!ClassDecl)
3724     return true;
3725 
3726   bool HadError = false;
3727 
3728   for (unsigned i = 0; i < Initializers.size(); i++) {
3729     CXXCtorInitializer *Member = Initializers[i];
3730 
3731     if (Member->isBaseInitializer())
3732       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3733     else {
3734       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3735 
3736       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3737         for (auto *C : F->chain()) {
3738           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3739           if (FD && FD->getParent()->isUnion())
3740             Info.ActiveUnionMember.insert(std::make_pair(
3741                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3742         }
3743       } else if (FieldDecl *FD = Member->getMember()) {
3744         if (FD->getParent()->isUnion())
3745           Info.ActiveUnionMember.insert(std::make_pair(
3746               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3747       }
3748     }
3749   }
3750 
3751   // Keep track of the direct virtual bases.
3752   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3753   for (auto &I : ClassDecl->bases()) {
3754     if (I.isVirtual())
3755       DirectVBases.insert(&I);
3756   }
3757 
3758   // Push virtual bases before others.
3759   for (auto &VBase : ClassDecl->vbases()) {
3760     if (CXXCtorInitializer *Value
3761         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3762       // [class.base.init]p7, per DR257:
3763       //   A mem-initializer where the mem-initializer-id names a virtual base
3764       //   class is ignored during execution of a constructor of any class that
3765       //   is not the most derived class.
3766       if (ClassDecl->isAbstract()) {
3767         // FIXME: Provide a fixit to remove the base specifier. This requires
3768         // tracking the location of the associated comma for a base specifier.
3769         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3770           << VBase.getType() << ClassDecl;
3771         DiagnoseAbstractType(ClassDecl);
3772       }
3773 
3774       Info.AllToInit.push_back(Value);
3775     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3776       // [class.base.init]p8, per DR257:
3777       //   If a given [...] base class is not named by a mem-initializer-id
3778       //   [...] and the entity is not a virtual base class of an abstract
3779       //   class, then [...] the entity is default-initialized.
3780       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3781       CXXCtorInitializer *CXXBaseInit;
3782       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3783                                        &VBase, IsInheritedVirtualBase,
3784                                        CXXBaseInit)) {
3785         HadError = true;
3786         continue;
3787       }
3788 
3789       Info.AllToInit.push_back(CXXBaseInit);
3790     }
3791   }
3792 
3793   // Non-virtual bases.
3794   for (auto &Base : ClassDecl->bases()) {
3795     // Virtuals are in the virtual base list and already constructed.
3796     if (Base.isVirtual())
3797       continue;
3798 
3799     if (CXXCtorInitializer *Value
3800           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3801       Info.AllToInit.push_back(Value);
3802     } else if (!AnyErrors) {
3803       CXXCtorInitializer *CXXBaseInit;
3804       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3805                                        &Base, /*IsInheritedVirtualBase=*/false,
3806                                        CXXBaseInit)) {
3807         HadError = true;
3808         continue;
3809       }
3810 
3811       Info.AllToInit.push_back(CXXBaseInit);
3812     }
3813   }
3814 
3815   // Fields.
3816   for (auto *Mem : ClassDecl->decls()) {
3817     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3818       // C++ [class.bit]p2:
3819       //   A declaration for a bit-field that omits the identifier declares an
3820       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3821       //   initialized.
3822       if (F->isUnnamedBitfield())
3823         continue;
3824 
3825       // If we're not generating the implicit copy/move constructor, then we'll
3826       // handle anonymous struct/union fields based on their individual
3827       // indirect fields.
3828       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3829         continue;
3830 
3831       if (CollectFieldInitializer(*this, Info, F))
3832         HadError = true;
3833       continue;
3834     }
3835 
3836     // Beyond this point, we only consider default initialization.
3837     if (Info.isImplicitCopyOrMove())
3838       continue;
3839 
3840     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
3841       if (F->getType()->isIncompleteArrayType()) {
3842         assert(ClassDecl->hasFlexibleArrayMember() &&
3843                "Incomplete array type is not valid");
3844         continue;
3845       }
3846 
3847       // Initialize each field of an anonymous struct individually.
3848       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3849         HadError = true;
3850 
3851       continue;
3852     }
3853   }
3854 
3855   unsigned NumInitializers = Info.AllToInit.size();
3856   if (NumInitializers > 0) {
3857     Constructor->setNumCtorInitializers(NumInitializers);
3858     CXXCtorInitializer **baseOrMemberInitializers =
3859       new (Context) CXXCtorInitializer*[NumInitializers];
3860     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3861            NumInitializers * sizeof(CXXCtorInitializer*));
3862     Constructor->setCtorInitializers(baseOrMemberInitializers);
3863 
3864     // Constructors implicitly reference the base and member
3865     // destructors.
3866     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3867                                            Constructor->getParent());
3868   }
3869 
3870   return HadError;
3871 }
3872 
3873 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3874   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3875     const RecordDecl *RD = RT->getDecl();
3876     if (RD->isAnonymousStructOrUnion()) {
3877       for (auto *Field : RD->fields())
3878         PopulateKeysForFields(Field, IdealInits);
3879       return;
3880     }
3881   }
3882   IdealInits.push_back(Field->getCanonicalDecl());
3883 }
3884 
3885 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3886   return Context.getCanonicalType(BaseType).getTypePtr();
3887 }
3888 
3889 static const void *GetKeyForMember(ASTContext &Context,
3890                                    CXXCtorInitializer *Member) {
3891   if (!Member->isAnyMemberInitializer())
3892     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3893 
3894   return Member->getAnyMember()->getCanonicalDecl();
3895 }
3896 
3897 static void DiagnoseBaseOrMemInitializerOrder(
3898     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3899     ArrayRef<CXXCtorInitializer *> Inits) {
3900   if (Constructor->getDeclContext()->isDependentContext())
3901     return;
3902 
3903   // Don't check initializers order unless the warning is enabled at the
3904   // location of at least one initializer.
3905   bool ShouldCheckOrder = false;
3906   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3907     CXXCtorInitializer *Init = Inits[InitIndex];
3908     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3909                                  Init->getSourceLocation())) {
3910       ShouldCheckOrder = true;
3911       break;
3912     }
3913   }
3914   if (!ShouldCheckOrder)
3915     return;
3916 
3917   // Build the list of bases and members in the order that they'll
3918   // actually be initialized.  The explicit initializers should be in
3919   // this same order but may be missing things.
3920   SmallVector<const void*, 32> IdealInitKeys;
3921 
3922   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3923 
3924   // 1. Virtual bases.
3925   for (const auto &VBase : ClassDecl->vbases())
3926     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
3927 
3928   // 2. Non-virtual bases.
3929   for (const auto &Base : ClassDecl->bases()) {
3930     if (Base.isVirtual())
3931       continue;
3932     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
3933   }
3934 
3935   // 3. Direct fields.
3936   for (auto *Field : ClassDecl->fields()) {
3937     if (Field->isUnnamedBitfield())
3938       continue;
3939 
3940     PopulateKeysForFields(Field, IdealInitKeys);
3941   }
3942 
3943   unsigned NumIdealInits = IdealInitKeys.size();
3944   unsigned IdealIndex = 0;
3945 
3946   CXXCtorInitializer *PrevInit = nullptr;
3947   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3948     CXXCtorInitializer *Init = Inits[InitIndex];
3949     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3950 
3951     // Scan forward to try to find this initializer in the idealized
3952     // initializers list.
3953     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3954       if (InitKey == IdealInitKeys[IdealIndex])
3955         break;
3956 
3957     // If we didn't find this initializer, it must be because we
3958     // scanned past it on a previous iteration.  That can only
3959     // happen if we're out of order;  emit a warning.
3960     if (IdealIndex == NumIdealInits && PrevInit) {
3961       Sema::SemaDiagnosticBuilder D =
3962         SemaRef.Diag(PrevInit->getSourceLocation(),
3963                      diag::warn_initializer_out_of_order);
3964 
3965       if (PrevInit->isAnyMemberInitializer())
3966         D << 0 << PrevInit->getAnyMember()->getDeclName();
3967       else
3968         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3969 
3970       if (Init->isAnyMemberInitializer())
3971         D << 0 << Init->getAnyMember()->getDeclName();
3972       else
3973         D << 1 << Init->getTypeSourceInfo()->getType();
3974 
3975       // Move back to the initializer's location in the ideal list.
3976       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3977         if (InitKey == IdealInitKeys[IdealIndex])
3978           break;
3979 
3980       assert(IdealIndex != NumIdealInits &&
3981              "initializer not found in initializer list");
3982     }
3983 
3984     PrevInit = Init;
3985   }
3986 }
3987 
3988 namespace {
3989 bool CheckRedundantInit(Sema &S,
3990                         CXXCtorInitializer *Init,
3991                         CXXCtorInitializer *&PrevInit) {
3992   if (!PrevInit) {
3993     PrevInit = Init;
3994     return false;
3995   }
3996 
3997   if (FieldDecl *Field = Init->getAnyMember())
3998     S.Diag(Init->getSourceLocation(),
3999            diag::err_multiple_mem_initialization)
4000       << Field->getDeclName()
4001       << Init->getSourceRange();
4002   else {
4003     const Type *BaseClass = Init->getBaseClass();
4004     assert(BaseClass && "neither field nor base");
4005     S.Diag(Init->getSourceLocation(),
4006            diag::err_multiple_base_initialization)
4007       << QualType(BaseClass, 0)
4008       << Init->getSourceRange();
4009   }
4010   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4011     << 0 << PrevInit->getSourceRange();
4012 
4013   return true;
4014 }
4015 
4016 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4017 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4018 
4019 bool CheckRedundantUnionInit(Sema &S,
4020                              CXXCtorInitializer *Init,
4021                              RedundantUnionMap &Unions) {
4022   FieldDecl *Field = Init->getAnyMember();
4023   RecordDecl *Parent = Field->getParent();
4024   NamedDecl *Child = Field;
4025 
4026   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4027     if (Parent->isUnion()) {
4028       UnionEntry &En = Unions[Parent];
4029       if (En.first && En.first != Child) {
4030         S.Diag(Init->getSourceLocation(),
4031                diag::err_multiple_mem_union_initialization)
4032           << Field->getDeclName()
4033           << Init->getSourceRange();
4034         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4035           << 0 << En.second->getSourceRange();
4036         return true;
4037       }
4038       if (!En.first) {
4039         En.first = Child;
4040         En.second = Init;
4041       }
4042       if (!Parent->isAnonymousStructOrUnion())
4043         return false;
4044     }
4045 
4046     Child = Parent;
4047     Parent = cast<RecordDecl>(Parent->getDeclContext());
4048   }
4049 
4050   return false;
4051 }
4052 }
4053 
4054 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4055 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4056                                 SourceLocation ColonLoc,
4057                                 ArrayRef<CXXCtorInitializer*> MemInits,
4058                                 bool AnyErrors) {
4059   if (!ConstructorDecl)
4060     return;
4061 
4062   AdjustDeclIfTemplate(ConstructorDecl);
4063 
4064   CXXConstructorDecl *Constructor
4065     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4066 
4067   if (!Constructor) {
4068     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4069     return;
4070   }
4071 
4072   // Mapping for the duplicate initializers check.
4073   // For member initializers, this is keyed with a FieldDecl*.
4074   // For base initializers, this is keyed with a Type*.
4075   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4076 
4077   // Mapping for the inconsistent anonymous-union initializers check.
4078   RedundantUnionMap MemberUnions;
4079 
4080   bool HadError = false;
4081   for (unsigned i = 0; i < MemInits.size(); i++) {
4082     CXXCtorInitializer *Init = MemInits[i];
4083 
4084     // Set the source order index.
4085     Init->setSourceOrder(i);
4086 
4087     if (Init->isAnyMemberInitializer()) {
4088       const void *Key = GetKeyForMember(Context, Init);
4089       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4090           CheckRedundantUnionInit(*this, Init, MemberUnions))
4091         HadError = true;
4092     } else if (Init->isBaseInitializer()) {
4093       const void *Key = GetKeyForMember(Context, Init);
4094       if (CheckRedundantInit(*this, Init, Members[Key]))
4095         HadError = true;
4096     } else {
4097       assert(Init->isDelegatingInitializer());
4098       // This must be the only initializer
4099       if (MemInits.size() != 1) {
4100         Diag(Init->getSourceLocation(),
4101              diag::err_delegating_initializer_alone)
4102           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4103         // We will treat this as being the only initializer.
4104       }
4105       SetDelegatingInitializer(Constructor, MemInits[i]);
4106       // Return immediately as the initializer is set.
4107       return;
4108     }
4109   }
4110 
4111   if (HadError)
4112     return;
4113 
4114   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4115 
4116   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4117 
4118   DiagnoseUninitializedFields(*this, Constructor);
4119 }
4120 
4121 void
4122 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4123                                              CXXRecordDecl *ClassDecl) {
4124   // Ignore dependent contexts. Also ignore unions, since their members never
4125   // have destructors implicitly called.
4126   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4127     return;
4128 
4129   // FIXME: all the access-control diagnostics are positioned on the
4130   // field/base declaration.  That's probably good; that said, the
4131   // user might reasonably want to know why the destructor is being
4132   // emitted, and we currently don't say.
4133 
4134   // Non-static data members.
4135   for (auto *Field : ClassDecl->fields()) {
4136     if (Field->isInvalidDecl())
4137       continue;
4138 
4139     // Don't destroy incomplete or zero-length arrays.
4140     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4141       continue;
4142 
4143     QualType FieldType = Context.getBaseElementType(Field->getType());
4144 
4145     const RecordType* RT = FieldType->getAs<RecordType>();
4146     if (!RT)
4147       continue;
4148 
4149     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4150     if (FieldClassDecl->isInvalidDecl())
4151       continue;
4152     if (FieldClassDecl->hasIrrelevantDestructor())
4153       continue;
4154     // The destructor for an implicit anonymous union member is never invoked.
4155     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4156       continue;
4157 
4158     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4159     assert(Dtor && "No dtor found for FieldClassDecl!");
4160     CheckDestructorAccess(Field->getLocation(), Dtor,
4161                           PDiag(diag::err_access_dtor_field)
4162                             << Field->getDeclName()
4163                             << FieldType);
4164 
4165     MarkFunctionReferenced(Location, Dtor);
4166     DiagnoseUseOfDecl(Dtor, Location);
4167   }
4168 
4169   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4170 
4171   // Bases.
4172   for (const auto &Base : ClassDecl->bases()) {
4173     // Bases are always records in a well-formed non-dependent class.
4174     const RecordType *RT = Base.getType()->getAs<RecordType>();
4175 
4176     // Remember direct virtual bases.
4177     if (Base.isVirtual())
4178       DirectVirtualBases.insert(RT);
4179 
4180     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4181     // If our base class is invalid, we probably can't get its dtor anyway.
4182     if (BaseClassDecl->isInvalidDecl())
4183       continue;
4184     if (BaseClassDecl->hasIrrelevantDestructor())
4185       continue;
4186 
4187     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4188     assert(Dtor && "No dtor found for BaseClassDecl!");
4189 
4190     // FIXME: caret should be on the start of the class name
4191     CheckDestructorAccess(Base.getLocStart(), Dtor,
4192                           PDiag(diag::err_access_dtor_base)
4193                             << Base.getType()
4194                             << Base.getSourceRange(),
4195                           Context.getTypeDeclType(ClassDecl));
4196 
4197     MarkFunctionReferenced(Location, Dtor);
4198     DiagnoseUseOfDecl(Dtor, Location);
4199   }
4200 
4201   // Virtual bases.
4202   for (const auto &VBase : ClassDecl->vbases()) {
4203     // Bases are always records in a well-formed non-dependent class.
4204     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4205 
4206     // Ignore direct virtual bases.
4207     if (DirectVirtualBases.count(RT))
4208       continue;
4209 
4210     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4211     // If our base class is invalid, we probably can't get its dtor anyway.
4212     if (BaseClassDecl->isInvalidDecl())
4213       continue;
4214     if (BaseClassDecl->hasIrrelevantDestructor())
4215       continue;
4216 
4217     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4218     assert(Dtor && "No dtor found for BaseClassDecl!");
4219     if (CheckDestructorAccess(
4220             ClassDecl->getLocation(), Dtor,
4221             PDiag(diag::err_access_dtor_vbase)
4222                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4223             Context.getTypeDeclType(ClassDecl)) ==
4224         AR_accessible) {
4225       CheckDerivedToBaseConversion(
4226           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4227           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4228           SourceRange(), DeclarationName(), nullptr);
4229     }
4230 
4231     MarkFunctionReferenced(Location, Dtor);
4232     DiagnoseUseOfDecl(Dtor, Location);
4233   }
4234 }
4235 
4236 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4237   if (!CDtorDecl)
4238     return;
4239 
4240   if (CXXConstructorDecl *Constructor
4241       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4242     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4243     DiagnoseUninitializedFields(*this, Constructor);
4244   }
4245 }
4246 
4247 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4248                                   unsigned DiagID, AbstractDiagSelID SelID) {
4249   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4250     unsigned DiagID;
4251     AbstractDiagSelID SelID;
4252 
4253   public:
4254     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4255       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4256 
4257     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4258       if (Suppressed) return;
4259       if (SelID == -1)
4260         S.Diag(Loc, DiagID) << T;
4261       else
4262         S.Diag(Loc, DiagID) << SelID << T;
4263     }
4264   } Diagnoser(DiagID, SelID);
4265 
4266   return RequireNonAbstractType(Loc, T, Diagnoser);
4267 }
4268 
4269 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4270                                   TypeDiagnoser &Diagnoser) {
4271   if (!getLangOpts().CPlusPlus)
4272     return false;
4273 
4274   if (const ArrayType *AT = Context.getAsArrayType(T))
4275     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4276 
4277   if (const PointerType *PT = T->getAs<PointerType>()) {
4278     // Find the innermost pointer type.
4279     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4280       PT = T;
4281 
4282     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4283       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4284   }
4285 
4286   const RecordType *RT = T->getAs<RecordType>();
4287   if (!RT)
4288     return false;
4289 
4290   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4291 
4292   // We can't answer whether something is abstract until it has a
4293   // definition.  If it's currently being defined, we'll walk back
4294   // over all the declarations when we have a full definition.
4295   const CXXRecordDecl *Def = RD->getDefinition();
4296   if (!Def || Def->isBeingDefined())
4297     return false;
4298 
4299   if (!RD->isAbstract())
4300     return false;
4301 
4302   Diagnoser.diagnose(*this, Loc, T);
4303   DiagnoseAbstractType(RD);
4304 
4305   return true;
4306 }
4307 
4308 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4309   // Check if we've already emitted the list of pure virtual functions
4310   // for this class.
4311   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4312     return;
4313 
4314   // If the diagnostic is suppressed, don't emit the notes. We're only
4315   // going to emit them once, so try to attach them to a diagnostic we're
4316   // actually going to show.
4317   if (Diags.isLastDiagnosticIgnored())
4318     return;
4319 
4320   CXXFinalOverriderMap FinalOverriders;
4321   RD->getFinalOverriders(FinalOverriders);
4322 
4323   // Keep a set of seen pure methods so we won't diagnose the same method
4324   // more than once.
4325   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4326 
4327   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4328                                    MEnd = FinalOverriders.end();
4329        M != MEnd;
4330        ++M) {
4331     for (OverridingMethods::iterator SO = M->second.begin(),
4332                                   SOEnd = M->second.end();
4333          SO != SOEnd; ++SO) {
4334       // C++ [class.abstract]p4:
4335       //   A class is abstract if it contains or inherits at least one
4336       //   pure virtual function for which the final overrider is pure
4337       //   virtual.
4338 
4339       //
4340       if (SO->second.size() != 1)
4341         continue;
4342 
4343       if (!SO->second.front().Method->isPure())
4344         continue;
4345 
4346       if (!SeenPureMethods.insert(SO->second.front().Method))
4347         continue;
4348 
4349       Diag(SO->second.front().Method->getLocation(),
4350            diag::note_pure_virtual_function)
4351         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4352     }
4353   }
4354 
4355   if (!PureVirtualClassDiagSet)
4356     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4357   PureVirtualClassDiagSet->insert(RD);
4358 }
4359 
4360 namespace {
4361 struct AbstractUsageInfo {
4362   Sema &S;
4363   CXXRecordDecl *Record;
4364   CanQualType AbstractType;
4365   bool Invalid;
4366 
4367   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4368     : S(S), Record(Record),
4369       AbstractType(S.Context.getCanonicalType(
4370                    S.Context.getTypeDeclType(Record))),
4371       Invalid(false) {}
4372 
4373   void DiagnoseAbstractType() {
4374     if (Invalid) return;
4375     S.DiagnoseAbstractType(Record);
4376     Invalid = true;
4377   }
4378 
4379   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4380 };
4381 
4382 struct CheckAbstractUsage {
4383   AbstractUsageInfo &Info;
4384   const NamedDecl *Ctx;
4385 
4386   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4387     : Info(Info), Ctx(Ctx) {}
4388 
4389   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4390     switch (TL.getTypeLocClass()) {
4391 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4392 #define TYPELOC(CLASS, PARENT) \
4393     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4394 #include "clang/AST/TypeLocNodes.def"
4395     }
4396   }
4397 
4398   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4399     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4400     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4401       if (!TL.getParam(I))
4402         continue;
4403 
4404       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4405       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4406     }
4407   }
4408 
4409   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4410     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4411   }
4412 
4413   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4414     // Visit the type parameters from a permissive context.
4415     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4416       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4417       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4418         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4419           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4420       // TODO: other template argument types?
4421     }
4422   }
4423 
4424   // Visit pointee types from a permissive context.
4425 #define CheckPolymorphic(Type) \
4426   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4427     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4428   }
4429   CheckPolymorphic(PointerTypeLoc)
4430   CheckPolymorphic(ReferenceTypeLoc)
4431   CheckPolymorphic(MemberPointerTypeLoc)
4432   CheckPolymorphic(BlockPointerTypeLoc)
4433   CheckPolymorphic(AtomicTypeLoc)
4434 
4435   /// Handle all the types we haven't given a more specific
4436   /// implementation for above.
4437   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4438     // Every other kind of type that we haven't called out already
4439     // that has an inner type is either (1) sugar or (2) contains that
4440     // inner type in some way as a subobject.
4441     if (TypeLoc Next = TL.getNextTypeLoc())
4442       return Visit(Next, Sel);
4443 
4444     // If there's no inner type and we're in a permissive context,
4445     // don't diagnose.
4446     if (Sel == Sema::AbstractNone) return;
4447 
4448     // Check whether the type matches the abstract type.
4449     QualType T = TL.getType();
4450     if (T->isArrayType()) {
4451       Sel = Sema::AbstractArrayType;
4452       T = Info.S.Context.getBaseElementType(T);
4453     }
4454     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4455     if (CT != Info.AbstractType) return;
4456 
4457     // It matched; do some magic.
4458     if (Sel == Sema::AbstractArrayType) {
4459       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4460         << T << TL.getSourceRange();
4461     } else {
4462       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4463         << Sel << T << TL.getSourceRange();
4464     }
4465     Info.DiagnoseAbstractType();
4466   }
4467 };
4468 
4469 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4470                                   Sema::AbstractDiagSelID Sel) {
4471   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4472 }
4473 
4474 }
4475 
4476 /// Check for invalid uses of an abstract type in a method declaration.
4477 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4478                                     CXXMethodDecl *MD) {
4479   // No need to do the check on definitions, which require that
4480   // the return/param types be complete.
4481   if (MD->doesThisDeclarationHaveABody())
4482     return;
4483 
4484   // For safety's sake, just ignore it if we don't have type source
4485   // information.  This should never happen for non-implicit methods,
4486   // but...
4487   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4488     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4489 }
4490 
4491 /// Check for invalid uses of an abstract type within a class definition.
4492 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4493                                     CXXRecordDecl *RD) {
4494   for (auto *D : RD->decls()) {
4495     if (D->isImplicit()) continue;
4496 
4497     // Methods and method templates.
4498     if (isa<CXXMethodDecl>(D)) {
4499       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4500     } else if (isa<FunctionTemplateDecl>(D)) {
4501       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4502       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4503 
4504     // Fields and static variables.
4505     } else if (isa<FieldDecl>(D)) {
4506       FieldDecl *FD = cast<FieldDecl>(D);
4507       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4508         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4509     } else if (isa<VarDecl>(D)) {
4510       VarDecl *VD = cast<VarDecl>(D);
4511       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4512         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4513 
4514     // Nested classes and class templates.
4515     } else if (isa<CXXRecordDecl>(D)) {
4516       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4517     } else if (isa<ClassTemplateDecl>(D)) {
4518       CheckAbstractClassUsage(Info,
4519                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4520     }
4521   }
4522 }
4523 
4524 /// \brief Check class-level dllimport/dllexport attribute.
4525 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4526   Attr *ClassAttr = getDLLAttr(Class);
4527 
4528   // MSVC inherits DLL attributes to partial class template specializations.
4529   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4530     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4531       if (Attr *TemplateAttr =
4532               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4533         auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4534         A->setInherited(true);
4535         ClassAttr = A;
4536       }
4537     }
4538   }
4539 
4540   if (!ClassAttr)
4541     return;
4542 
4543   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4544       !ClassAttr->isInherited()) {
4545     // Diagnose dll attributes on members of class with dll attribute.
4546     for (Decl *Member : Class->decls()) {
4547       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4548         continue;
4549       InheritableAttr *MemberAttr = getDLLAttr(Member);
4550       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4551         continue;
4552 
4553       S.Diag(MemberAttr->getLocation(),
4554              diag::err_attribute_dll_member_of_dll_class)
4555           << MemberAttr << ClassAttr;
4556       S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4557       Member->setInvalidDecl();
4558     }
4559   }
4560 
4561   if (Class->getDescribedClassTemplate())
4562     // Don't inherit dll attribute until the template is instantiated.
4563     return;
4564 
4565   bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4566 
4567   // Force declaration of implicit members so they can inherit the attribute.
4568   S.ForceDeclarationOfImplicitMembers(Class);
4569 
4570   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4571   // seem to be true in practice?
4572 
4573   TemplateSpecializationKind TSK =
4574     Class->getTemplateSpecializationKind();
4575 
4576   for (Decl *Member : Class->decls()) {
4577     VarDecl *VD = dyn_cast<VarDecl>(Member);
4578     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4579 
4580     // Only methods and static fields inherit the attributes.
4581     if (!VD && !MD)
4582       continue;
4583 
4584     // Don't process deleted methods.
4585     if (MD && MD->isDeleted())
4586       continue;
4587 
4588     if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4589         MD->isInlined()) {
4590       // Current MSVC versions don't export the move assignment operators, so
4591       // don't attempt to import them if we have a definition.
4592       continue;
4593     }
4594 
4595     if (!getDLLAttr(Member)) {
4596       auto *NewAttr =
4597           cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4598       NewAttr->setInherited(true);
4599       Member->addAttr(NewAttr);
4600     }
4601 
4602     if (MD && ClassExported) {
4603       if (MD->isUserProvided()) {
4604         // Instantiate non-default methods..
4605 
4606         // .. except for certain kinds of template specializations.
4607         if (TSK == TSK_ExplicitInstantiationDeclaration)
4608           continue;
4609         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4610           continue;
4611 
4612         S.MarkFunctionReferenced(Class->getLocation(), MD);
4613       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4614                  MD->isCopyAssignmentOperator() ||
4615                  MD->isMoveAssignmentOperator()) {
4616         // Instantiate non-trivial or explicitly defaulted methods, and the
4617         // copy assignment / move assignment operators.
4618         S.MarkFunctionReferenced(Class->getLocation(), MD);
4619         // Resolve its exception specification; CodeGen needs it.
4620         auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4621         S.ResolveExceptionSpec(Class->getLocation(), FPT);
4622         S.ActOnFinishInlineMethodDef(MD);
4623       }
4624     }
4625   }
4626 }
4627 
4628 /// \brief Perform semantic checks on a class definition that has been
4629 /// completing, introducing implicitly-declared members, checking for
4630 /// abstract types, etc.
4631 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4632   if (!Record)
4633     return;
4634 
4635   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4636     AbstractUsageInfo Info(*this, Record);
4637     CheckAbstractClassUsage(Info, Record);
4638   }
4639 
4640   // If this is not an aggregate type and has no user-declared constructor,
4641   // complain about any non-static data members of reference or const scalar
4642   // type, since they will never get initializers.
4643   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4644       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4645       !Record->isLambda()) {
4646     bool Complained = false;
4647     for (const auto *F : Record->fields()) {
4648       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4649         continue;
4650 
4651       if (F->getType()->isReferenceType() ||
4652           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4653         if (!Complained) {
4654           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4655             << Record->getTagKind() << Record;
4656           Complained = true;
4657         }
4658 
4659         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4660           << F->getType()->isReferenceType()
4661           << F->getDeclName();
4662       }
4663     }
4664   }
4665 
4666   if (Record->isDynamicClass() && !Record->isDependentType())
4667     DynamicClasses.push_back(Record);
4668 
4669   if (Record->getIdentifier()) {
4670     // C++ [class.mem]p13:
4671     //   If T is the name of a class, then each of the following shall have a
4672     //   name different from T:
4673     //     - every member of every anonymous union that is a member of class T.
4674     //
4675     // C++ [class.mem]p14:
4676     //   In addition, if class T has a user-declared constructor (12.1), every
4677     //   non-static data member of class T shall have a name different from T.
4678     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4679     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4680          ++I) {
4681       NamedDecl *D = *I;
4682       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4683           isa<IndirectFieldDecl>(D)) {
4684         Diag(D->getLocation(), diag::err_member_name_of_class)
4685           << D->getDeclName();
4686         break;
4687       }
4688     }
4689   }
4690 
4691   // Warn if the class has virtual methods but non-virtual public destructor.
4692   if (Record->isPolymorphic() && !Record->isDependentType()) {
4693     CXXDestructorDecl *dtor = Record->getDestructor();
4694     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4695         !Record->hasAttr<FinalAttr>())
4696       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4697            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4698   }
4699 
4700   if (Record->isAbstract()) {
4701     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4702       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4703         << FA->isSpelledAsSealed();
4704       DiagnoseAbstractType(Record);
4705     }
4706   }
4707 
4708   bool HasMethodWithOverrideControl = false,
4709        HasOverridingMethodWithoutOverrideControl = false;
4710   if (!Record->isDependentType()) {
4711     for (auto *M : Record->methods()) {
4712       // See if a method overloads virtual methods in a base
4713       // class without overriding any.
4714       if (!M->isStatic())
4715         DiagnoseHiddenVirtualMethods(M);
4716       if (M->hasAttr<OverrideAttr>())
4717         HasMethodWithOverrideControl = true;
4718       else if (M->begin_overridden_methods() != M->end_overridden_methods())
4719         HasOverridingMethodWithoutOverrideControl = true;
4720       // Check whether the explicitly-defaulted special members are valid.
4721       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4722         CheckExplicitlyDefaultedSpecialMember(M);
4723 
4724       // For an explicitly defaulted or deleted special member, we defer
4725       // determining triviality until the class is complete. That time is now!
4726       if (!M->isImplicit() && !M->isUserProvided()) {
4727         CXXSpecialMember CSM = getSpecialMember(M);
4728         if (CSM != CXXInvalid) {
4729           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4730 
4731           // Inform the class that we've finished declaring this member.
4732           Record->finishedDefaultedOrDeletedMember(M);
4733         }
4734       }
4735     }
4736   }
4737 
4738   if (HasMethodWithOverrideControl
4739       && HasOverridingMethodWithoutOverrideControl) {
4740     // At least one method has the 'override' control declared.
4741     // Diagnose all other overridden methods which do not have 'override' specified on them.
4742     for (auto *M : Record->methods())
4743       if (!M->hasAttr<OverrideAttr>())
4744         DiagnoseAbsenseOfOverrideControl(M);
4745   }
4746   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4747   // function that is not a constructor declares that member function to be
4748   // const. [...] The class of which that function is a member shall be
4749   // a literal type.
4750   //
4751   // If the class has virtual bases, any constexpr members will already have
4752   // been diagnosed by the checks performed on the member declaration, so
4753   // suppress this (less useful) diagnostic.
4754   //
4755   // We delay this until we know whether an explicitly-defaulted (or deleted)
4756   // destructor for the class is trivial.
4757   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4758       !Record->isLiteral() && !Record->getNumVBases()) {
4759     for (const auto *M : Record->methods()) {
4760       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
4761         switch (Record->getTemplateSpecializationKind()) {
4762         case TSK_ImplicitInstantiation:
4763         case TSK_ExplicitInstantiationDeclaration:
4764         case TSK_ExplicitInstantiationDefinition:
4765           // If a template instantiates to a non-literal type, but its members
4766           // instantiate to constexpr functions, the template is technically
4767           // ill-formed, but we allow it for sanity.
4768           continue;
4769 
4770         case TSK_Undeclared:
4771         case TSK_ExplicitSpecialization:
4772           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4773                              diag::err_constexpr_method_non_literal);
4774           break;
4775         }
4776 
4777         // Only produce one error per class.
4778         break;
4779       }
4780     }
4781   }
4782 
4783   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4784   // whether this class uses any C++ features that are implemented
4785   // completely differently in MSVC, and if so, emit a diagnostic.
4786   // That diagnostic defaults to an error, but we allow projects to
4787   // map it down to a warning (or ignore it).  It's a fairly common
4788   // practice among users of the ms_struct pragma to mass-annotate
4789   // headers, sweeping up a bunch of types that the project doesn't
4790   // really rely on MSVC-compatible layout for.  We must therefore
4791   // support "ms_struct except for C++ stuff" as a secondary ABI.
4792   if (Record->isMsStruct(Context) &&
4793       (Record->isPolymorphic() || Record->getNumBases())) {
4794     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4795   }
4796 
4797   // Declare inheriting constructors. We do this eagerly here because:
4798   // - The standard requires an eager diagnostic for conflicting inheriting
4799   //   constructors from different classes.
4800   // - The lazy declaration of the other implicit constructors is so as to not
4801   //   waste space and performance on classes that are not meant to be
4802   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4803   //   have inheriting constructors.
4804   DeclareInheritingConstructors(Record);
4805 
4806   checkDLLAttribute(*this, Record);
4807 }
4808 
4809 /// Look up the special member function that would be called by a special
4810 /// member function for a subobject of class type.
4811 ///
4812 /// \param Class The class type of the subobject.
4813 /// \param CSM The kind of special member function.
4814 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4815 /// \param ConstRHS True if this is a copy operation with a const object
4816 ///        on its RHS, that is, if the argument to the outer special member
4817 ///        function is 'const' and this is not a field marked 'mutable'.
4818 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4819     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4820     unsigned FieldQuals, bool ConstRHS) {
4821   unsigned LHSQuals = 0;
4822   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4823     LHSQuals = FieldQuals;
4824 
4825   unsigned RHSQuals = FieldQuals;
4826   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4827     RHSQuals = 0;
4828   else if (ConstRHS)
4829     RHSQuals |= Qualifiers::Const;
4830 
4831   return S.LookupSpecialMember(Class, CSM,
4832                                RHSQuals & Qualifiers::Const,
4833                                RHSQuals & Qualifiers::Volatile,
4834                                false,
4835                                LHSQuals & Qualifiers::Const,
4836                                LHSQuals & Qualifiers::Volatile);
4837 }
4838 
4839 /// Is the special member function which would be selected to perform the
4840 /// specified operation on the specified class type a constexpr constructor?
4841 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4842                                      Sema::CXXSpecialMember CSM,
4843                                      unsigned Quals, bool ConstRHS) {
4844   Sema::SpecialMemberOverloadResult *SMOR =
4845       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
4846   if (!SMOR || !SMOR->getMethod())
4847     // A constructor we wouldn't select can't be "involved in initializing"
4848     // anything.
4849     return true;
4850   return SMOR->getMethod()->isConstexpr();
4851 }
4852 
4853 /// Determine whether the specified special member function would be constexpr
4854 /// if it were implicitly defined.
4855 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4856                                               Sema::CXXSpecialMember CSM,
4857                                               bool ConstArg) {
4858   if (!S.getLangOpts().CPlusPlus11)
4859     return false;
4860 
4861   // C++11 [dcl.constexpr]p4:
4862   // In the definition of a constexpr constructor [...]
4863   bool Ctor = true;
4864   switch (CSM) {
4865   case Sema::CXXDefaultConstructor:
4866     // Since default constructor lookup is essentially trivial (and cannot
4867     // involve, for instance, template instantiation), we compute whether a
4868     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4869     //
4870     // This is important for performance; we need to know whether the default
4871     // constructor is constexpr to determine whether the type is a literal type.
4872     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4873 
4874   case Sema::CXXCopyConstructor:
4875   case Sema::CXXMoveConstructor:
4876     // For copy or move constructors, we need to perform overload resolution.
4877     break;
4878 
4879   case Sema::CXXCopyAssignment:
4880   case Sema::CXXMoveAssignment:
4881     if (!S.getLangOpts().CPlusPlus14)
4882       return false;
4883     // In C++1y, we need to perform overload resolution.
4884     Ctor = false;
4885     break;
4886 
4887   case Sema::CXXDestructor:
4888   case Sema::CXXInvalid:
4889     return false;
4890   }
4891 
4892   //   -- if the class is a non-empty union, or for each non-empty anonymous
4893   //      union member of a non-union class, exactly one non-static data member
4894   //      shall be initialized; [DR1359]
4895   //
4896   // If we squint, this is guaranteed, since exactly one non-static data member
4897   // will be initialized (if the constructor isn't deleted), we just don't know
4898   // which one.
4899   if (Ctor && ClassDecl->isUnion())
4900     return true;
4901 
4902   //   -- the class shall not have any virtual base classes;
4903   if (Ctor && ClassDecl->getNumVBases())
4904     return false;
4905 
4906   // C++1y [class.copy]p26:
4907   //   -- [the class] is a literal type, and
4908   if (!Ctor && !ClassDecl->isLiteral())
4909     return false;
4910 
4911   //   -- every constructor involved in initializing [...] base class
4912   //      sub-objects shall be a constexpr constructor;
4913   //   -- the assignment operator selected to copy/move each direct base
4914   //      class is a constexpr function, and
4915   for (const auto &B : ClassDecl->bases()) {
4916     const RecordType *BaseType = B.getType()->getAs<RecordType>();
4917     if (!BaseType) continue;
4918 
4919     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4920     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
4921       return false;
4922   }
4923 
4924   //   -- every constructor involved in initializing non-static data members
4925   //      [...] shall be a constexpr constructor;
4926   //   -- every non-static data member and base class sub-object shall be
4927   //      initialized
4928   //   -- for each non-static data member of X that is of class type (or array
4929   //      thereof), the assignment operator selected to copy/move that member is
4930   //      a constexpr function
4931   for (const auto *F : ClassDecl->fields()) {
4932     if (F->isInvalidDecl())
4933       continue;
4934     QualType BaseType = S.Context.getBaseElementType(F->getType());
4935     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
4936       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4937       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4938                                     BaseType.getCVRQualifiers(),
4939                                     ConstArg && !F->isMutable()))
4940         return false;
4941     }
4942   }
4943 
4944   // All OK, it's constexpr!
4945   return true;
4946 }
4947 
4948 static Sema::ImplicitExceptionSpecification
4949 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4950   switch (S.getSpecialMember(MD)) {
4951   case Sema::CXXDefaultConstructor:
4952     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4953   case Sema::CXXCopyConstructor:
4954     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4955   case Sema::CXXCopyAssignment:
4956     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4957   case Sema::CXXMoveConstructor:
4958     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4959   case Sema::CXXMoveAssignment:
4960     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4961   case Sema::CXXDestructor:
4962     return S.ComputeDefaultedDtorExceptionSpec(MD);
4963   case Sema::CXXInvalid:
4964     break;
4965   }
4966   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4967          "only special members have implicit exception specs");
4968   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4969 }
4970 
4971 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4972                                                             CXXMethodDecl *MD) {
4973   FunctionProtoType::ExtProtoInfo EPI;
4974 
4975   // Build an exception specification pointing back at this member.
4976   EPI.ExceptionSpec.Type = EST_Unevaluated;
4977   EPI.ExceptionSpec.SourceDecl = MD;
4978 
4979   // Set the calling convention to the default for C++ instance methods.
4980   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4981       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4982                                             /*IsCXXMethod=*/true));
4983   return EPI;
4984 }
4985 
4986 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4987   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4988   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4989     return;
4990 
4991   // Evaluate the exception specification.
4992   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
4993 
4994   // Update the type of the special member to use it.
4995   UpdateExceptionSpec(MD, ESI);
4996 
4997   // A user-provided destructor can be defined outside the class. When that
4998   // happens, be sure to update the exception specification on both
4999   // declarations.
5000   const FunctionProtoType *CanonicalFPT =
5001     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5002   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5003     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5004 }
5005 
5006 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5007   CXXRecordDecl *RD = MD->getParent();
5008   CXXSpecialMember CSM = getSpecialMember(MD);
5009 
5010   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5011          "not an explicitly-defaulted special member");
5012 
5013   // Whether this was the first-declared instance of the constructor.
5014   // This affects whether we implicitly add an exception spec and constexpr.
5015   bool First = MD == MD->getCanonicalDecl();
5016 
5017   bool HadError = false;
5018 
5019   // C++11 [dcl.fct.def.default]p1:
5020   //   A function that is explicitly defaulted shall
5021   //     -- be a special member function (checked elsewhere),
5022   //     -- have the same type (except for ref-qualifiers, and except that a
5023   //        copy operation can take a non-const reference) as an implicit
5024   //        declaration, and
5025   //     -- not have default arguments.
5026   unsigned ExpectedParams = 1;
5027   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5028     ExpectedParams = 0;
5029   if (MD->getNumParams() != ExpectedParams) {
5030     // This also checks for default arguments: a copy or move constructor with a
5031     // default argument is classified as a default constructor, and assignment
5032     // operations and destructors can't have default arguments.
5033     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5034       << CSM << MD->getSourceRange();
5035     HadError = true;
5036   } else if (MD->isVariadic()) {
5037     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5038       << CSM << MD->getSourceRange();
5039     HadError = true;
5040   }
5041 
5042   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5043 
5044   bool CanHaveConstParam = false;
5045   if (CSM == CXXCopyConstructor)
5046     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5047   else if (CSM == CXXCopyAssignment)
5048     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5049 
5050   QualType ReturnType = Context.VoidTy;
5051   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5052     // Check for return type matching.
5053     ReturnType = Type->getReturnType();
5054     QualType ExpectedReturnType =
5055         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5056     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5057       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5058         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5059       HadError = true;
5060     }
5061 
5062     // A defaulted special member cannot have cv-qualifiers.
5063     if (Type->getTypeQuals()) {
5064       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5065         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5066       HadError = true;
5067     }
5068   }
5069 
5070   // Check for parameter type matching.
5071   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5072   bool HasConstParam = false;
5073   if (ExpectedParams && ArgType->isReferenceType()) {
5074     // Argument must be reference to possibly-const T.
5075     QualType ReferentType = ArgType->getPointeeType();
5076     HasConstParam = ReferentType.isConstQualified();
5077 
5078     if (ReferentType.isVolatileQualified()) {
5079       Diag(MD->getLocation(),
5080            diag::err_defaulted_special_member_volatile_param) << CSM;
5081       HadError = true;
5082     }
5083 
5084     if (HasConstParam && !CanHaveConstParam) {
5085       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5086         Diag(MD->getLocation(),
5087              diag::err_defaulted_special_member_copy_const_param)
5088           << (CSM == CXXCopyAssignment);
5089         // FIXME: Explain why this special member can't be const.
5090       } else {
5091         Diag(MD->getLocation(),
5092              diag::err_defaulted_special_member_move_const_param)
5093           << (CSM == CXXMoveAssignment);
5094       }
5095       HadError = true;
5096     }
5097   } else if (ExpectedParams) {
5098     // A copy assignment operator can take its argument by value, but a
5099     // defaulted one cannot.
5100     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5101     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5102     HadError = true;
5103   }
5104 
5105   // C++11 [dcl.fct.def.default]p2:
5106   //   An explicitly-defaulted function may be declared constexpr only if it
5107   //   would have been implicitly declared as constexpr,
5108   // Do not apply this rule to members of class templates, since core issue 1358
5109   // makes such functions always instantiate to constexpr functions. For
5110   // functions which cannot be constexpr (for non-constructors in C++11 and for
5111   // destructors in C++1y), this is checked elsewhere.
5112   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5113                                                      HasConstParam);
5114   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5115                                  : isa<CXXConstructorDecl>(MD)) &&
5116       MD->isConstexpr() && !Constexpr &&
5117       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5118     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5119     // FIXME: Explain why the special member can't be constexpr.
5120     HadError = true;
5121   }
5122 
5123   //   and may have an explicit exception-specification only if it is compatible
5124   //   with the exception-specification on the implicit declaration.
5125   if (Type->hasExceptionSpec()) {
5126     // Delay the check if this is the first declaration of the special member,
5127     // since we may not have parsed some necessary in-class initializers yet.
5128     if (First) {
5129       // If the exception specification needs to be instantiated, do so now,
5130       // before we clobber it with an EST_Unevaluated specification below.
5131       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5132         InstantiateExceptionSpec(MD->getLocStart(), MD);
5133         Type = MD->getType()->getAs<FunctionProtoType>();
5134       }
5135       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5136     } else
5137       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5138   }
5139 
5140   //   If a function is explicitly defaulted on its first declaration,
5141   if (First) {
5142     //  -- it is implicitly considered to be constexpr if the implicit
5143     //     definition would be,
5144     MD->setConstexpr(Constexpr);
5145 
5146     //  -- it is implicitly considered to have the same exception-specification
5147     //     as if it had been implicitly declared,
5148     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5149     EPI.ExceptionSpec.Type = EST_Unevaluated;
5150     EPI.ExceptionSpec.SourceDecl = MD;
5151     MD->setType(Context.getFunctionType(ReturnType,
5152                                         llvm::makeArrayRef(&ArgType,
5153                                                            ExpectedParams),
5154                                         EPI));
5155   }
5156 
5157   if (ShouldDeleteSpecialMember(MD, CSM)) {
5158     if (First) {
5159       SetDeclDeleted(MD, MD->getLocation());
5160     } else {
5161       // C++11 [dcl.fct.def.default]p4:
5162       //   [For a] user-provided explicitly-defaulted function [...] if such a
5163       //   function is implicitly defined as deleted, the program is ill-formed.
5164       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5165       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5166       HadError = true;
5167     }
5168   }
5169 
5170   if (HadError)
5171     MD->setInvalidDecl();
5172 }
5173 
5174 /// Check whether the exception specification provided for an
5175 /// explicitly-defaulted special member matches the exception specification
5176 /// that would have been generated for an implicit special member, per
5177 /// C++11 [dcl.fct.def.default]p2.
5178 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5179     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5180   // Compute the implicit exception specification.
5181   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5182                                                        /*IsCXXMethod=*/true);
5183   FunctionProtoType::ExtProtoInfo EPI(CC);
5184   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5185                           .getExceptionSpec();
5186   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5187     Context.getFunctionType(Context.VoidTy, None, EPI));
5188 
5189   // Ensure that it matches.
5190   CheckEquivalentExceptionSpec(
5191     PDiag(diag::err_incorrect_defaulted_exception_spec)
5192       << getSpecialMember(MD), PDiag(),
5193     ImplicitType, SourceLocation(),
5194     SpecifiedType, MD->getLocation());
5195 }
5196 
5197 void Sema::CheckDelayedMemberExceptionSpecs() {
5198   SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5199               2> Checks;
5200   SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
5201 
5202   std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5203   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5204 
5205   // Perform any deferred checking of exception specifications for virtual
5206   // destructors.
5207   for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5208     const CXXDestructorDecl *Dtor = Checks[i].first;
5209     assert(!Dtor->getParent()->isDependentType() &&
5210            "Should not ever add destructors of templates into the list.");
5211     CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5212   }
5213 
5214   // Check that any explicitly-defaulted methods have exception specifications
5215   // compatible with their implicit exception specifications.
5216   for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5217     CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5218                                                 Specs[I].second);
5219 }
5220 
5221 namespace {
5222 struct SpecialMemberDeletionInfo {
5223   Sema &S;
5224   CXXMethodDecl *MD;
5225   Sema::CXXSpecialMember CSM;
5226   bool Diagnose;
5227 
5228   // Properties of the special member, computed for convenience.
5229   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5230   SourceLocation Loc;
5231 
5232   bool AllFieldsAreConst;
5233 
5234   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5235                             Sema::CXXSpecialMember CSM, bool Diagnose)
5236     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5237       IsConstructor(false), IsAssignment(false), IsMove(false),
5238       ConstArg(false), Loc(MD->getLocation()),
5239       AllFieldsAreConst(true) {
5240     switch (CSM) {
5241       case Sema::CXXDefaultConstructor:
5242       case Sema::CXXCopyConstructor:
5243         IsConstructor = true;
5244         break;
5245       case Sema::CXXMoveConstructor:
5246         IsConstructor = true;
5247         IsMove = true;
5248         break;
5249       case Sema::CXXCopyAssignment:
5250         IsAssignment = true;
5251         break;
5252       case Sema::CXXMoveAssignment:
5253         IsAssignment = true;
5254         IsMove = true;
5255         break;
5256       case Sema::CXXDestructor:
5257         break;
5258       case Sema::CXXInvalid:
5259         llvm_unreachable("invalid special member kind");
5260     }
5261 
5262     if (MD->getNumParams()) {
5263       if (const ReferenceType *RT =
5264               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5265         ConstArg = RT->getPointeeType().isConstQualified();
5266     }
5267   }
5268 
5269   bool inUnion() const { return MD->getParent()->isUnion(); }
5270 
5271   /// Look up the corresponding special member in the given class.
5272   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5273                                               unsigned Quals, bool IsMutable) {
5274     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5275                                        ConstArg && !IsMutable);
5276   }
5277 
5278   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5279 
5280   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5281   bool shouldDeleteForField(FieldDecl *FD);
5282   bool shouldDeleteForAllConstMembers();
5283 
5284   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5285                                      unsigned Quals);
5286   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5287                                     Sema::SpecialMemberOverloadResult *SMOR,
5288                                     bool IsDtorCallInCtor);
5289 
5290   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5291 };
5292 }
5293 
5294 /// Is the given special member inaccessible when used on the given
5295 /// sub-object.
5296 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5297                                              CXXMethodDecl *target) {
5298   /// If we're operating on a base class, the object type is the
5299   /// type of this special member.
5300   QualType objectTy;
5301   AccessSpecifier access = target->getAccess();
5302   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5303     objectTy = S.Context.getTypeDeclType(MD->getParent());
5304     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5305 
5306   // If we're operating on a field, the object type is the type of the field.
5307   } else {
5308     objectTy = S.Context.getTypeDeclType(target->getParent());
5309   }
5310 
5311   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5312 }
5313 
5314 /// Check whether we should delete a special member due to the implicit
5315 /// definition containing a call to a special member of a subobject.
5316 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5317     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5318     bool IsDtorCallInCtor) {
5319   CXXMethodDecl *Decl = SMOR->getMethod();
5320   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5321 
5322   int DiagKind = -1;
5323 
5324   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5325     DiagKind = !Decl ? 0 : 1;
5326   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5327     DiagKind = 2;
5328   else if (!isAccessible(Subobj, Decl))
5329     DiagKind = 3;
5330   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5331            !Decl->isTrivial()) {
5332     // A member of a union must have a trivial corresponding special member.
5333     // As a weird special case, a destructor call from a union's constructor
5334     // must be accessible and non-deleted, but need not be trivial. Such a
5335     // destructor is never actually called, but is semantically checked as
5336     // if it were.
5337     DiagKind = 4;
5338   }
5339 
5340   if (DiagKind == -1)
5341     return false;
5342 
5343   if (Diagnose) {
5344     if (Field) {
5345       S.Diag(Field->getLocation(),
5346              diag::note_deleted_special_member_class_subobject)
5347         << CSM << MD->getParent() << /*IsField*/true
5348         << Field << DiagKind << IsDtorCallInCtor;
5349     } else {
5350       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5351       S.Diag(Base->getLocStart(),
5352              diag::note_deleted_special_member_class_subobject)
5353         << CSM << MD->getParent() << /*IsField*/false
5354         << Base->getType() << DiagKind << IsDtorCallInCtor;
5355     }
5356 
5357     if (DiagKind == 1)
5358       S.NoteDeletedFunction(Decl);
5359     // FIXME: Explain inaccessibility if DiagKind == 3.
5360   }
5361 
5362   return true;
5363 }
5364 
5365 /// Check whether we should delete a special member function due to having a
5366 /// direct or virtual base class or non-static data member of class type M.
5367 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5368     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5369   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5370   bool IsMutable = Field && Field->isMutable();
5371 
5372   // C++11 [class.ctor]p5:
5373   // -- any direct or virtual base class, or non-static data member with no
5374   //    brace-or-equal-initializer, has class type M (or array thereof) and
5375   //    either M has no default constructor or overload resolution as applied
5376   //    to M's default constructor results in an ambiguity or in a function
5377   //    that is deleted or inaccessible
5378   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5379   // -- a direct or virtual base class B that cannot be copied/moved because
5380   //    overload resolution, as applied to B's corresponding special member,
5381   //    results in an ambiguity or a function that is deleted or inaccessible
5382   //    from the defaulted special member
5383   // C++11 [class.dtor]p5:
5384   // -- any direct or virtual base class [...] has a type with a destructor
5385   //    that is deleted or inaccessible
5386   if (!(CSM == Sema::CXXDefaultConstructor &&
5387         Field && Field->hasInClassInitializer()) &&
5388       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5389                                    false))
5390     return true;
5391 
5392   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5393   // -- any direct or virtual base class or non-static data member has a
5394   //    type with a destructor that is deleted or inaccessible
5395   if (IsConstructor) {
5396     Sema::SpecialMemberOverloadResult *SMOR =
5397         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5398                               false, false, false, false, false);
5399     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5400       return true;
5401   }
5402 
5403   return false;
5404 }
5405 
5406 /// Check whether we should delete a special member function due to the class
5407 /// having a particular direct or virtual base class.
5408 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5409   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5410   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5411 }
5412 
5413 /// Check whether we should delete a special member function due to the class
5414 /// having a particular non-static data member.
5415 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5416   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5417   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5418 
5419   if (CSM == Sema::CXXDefaultConstructor) {
5420     // For a default constructor, all references must be initialized in-class
5421     // and, if a union, it must have a non-const member.
5422     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5423       if (Diagnose)
5424         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5425           << MD->getParent() << FD << FieldType << /*Reference*/0;
5426       return true;
5427     }
5428     // C++11 [class.ctor]p5: any non-variant non-static data member of
5429     // const-qualified type (or array thereof) with no
5430     // brace-or-equal-initializer does not have a user-provided default
5431     // constructor.
5432     if (!inUnion() && FieldType.isConstQualified() &&
5433         !FD->hasInClassInitializer() &&
5434         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5435       if (Diagnose)
5436         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5437           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5438       return true;
5439     }
5440 
5441     if (inUnion() && !FieldType.isConstQualified())
5442       AllFieldsAreConst = false;
5443   } else if (CSM == Sema::CXXCopyConstructor) {
5444     // For a copy constructor, data members must not be of rvalue reference
5445     // type.
5446     if (FieldType->isRValueReferenceType()) {
5447       if (Diagnose)
5448         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5449           << MD->getParent() << FD << FieldType;
5450       return true;
5451     }
5452   } else if (IsAssignment) {
5453     // For an assignment operator, data members must not be of reference type.
5454     if (FieldType->isReferenceType()) {
5455       if (Diagnose)
5456         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5457           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5458       return true;
5459     }
5460     if (!FieldRecord && FieldType.isConstQualified()) {
5461       // C++11 [class.copy]p23:
5462       // -- a non-static data member of const non-class type (or array thereof)
5463       if (Diagnose)
5464         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5465           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5466       return true;
5467     }
5468   }
5469 
5470   if (FieldRecord) {
5471     // Some additional restrictions exist on the variant members.
5472     if (!inUnion() && FieldRecord->isUnion() &&
5473         FieldRecord->isAnonymousStructOrUnion()) {
5474       bool AllVariantFieldsAreConst = true;
5475 
5476       // FIXME: Handle anonymous unions declared within anonymous unions.
5477       for (auto *UI : FieldRecord->fields()) {
5478         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5479 
5480         if (!UnionFieldType.isConstQualified())
5481           AllVariantFieldsAreConst = false;
5482 
5483         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5484         if (UnionFieldRecord &&
5485             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5486                                           UnionFieldType.getCVRQualifiers()))
5487           return true;
5488       }
5489 
5490       // At least one member in each anonymous union must be non-const
5491       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5492           !FieldRecord->field_empty()) {
5493         if (Diagnose)
5494           S.Diag(FieldRecord->getLocation(),
5495                  diag::note_deleted_default_ctor_all_const)
5496             << MD->getParent() << /*anonymous union*/1;
5497         return true;
5498       }
5499 
5500       // Don't check the implicit member of the anonymous union type.
5501       // This is technically non-conformant, but sanity demands it.
5502       return false;
5503     }
5504 
5505     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5506                                       FieldType.getCVRQualifiers()))
5507       return true;
5508   }
5509 
5510   return false;
5511 }
5512 
5513 /// C++11 [class.ctor] p5:
5514 ///   A defaulted default constructor for a class X is defined as deleted if
5515 /// X is a union and all of its variant members are of const-qualified type.
5516 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5517   // This is a silly definition, because it gives an empty union a deleted
5518   // default constructor. Don't do that.
5519   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5520       !MD->getParent()->field_empty()) {
5521     if (Diagnose)
5522       S.Diag(MD->getParent()->getLocation(),
5523              diag::note_deleted_default_ctor_all_const)
5524         << MD->getParent() << /*not anonymous union*/0;
5525     return true;
5526   }
5527   return false;
5528 }
5529 
5530 /// Determine whether a defaulted special member function should be defined as
5531 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5532 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5533 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5534                                      bool Diagnose) {
5535   if (MD->isInvalidDecl())
5536     return false;
5537   CXXRecordDecl *RD = MD->getParent();
5538   assert(!RD->isDependentType() && "do deletion after instantiation");
5539   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5540     return false;
5541 
5542   // C++11 [expr.lambda.prim]p19:
5543   //   The closure type associated with a lambda-expression has a
5544   //   deleted (8.4.3) default constructor and a deleted copy
5545   //   assignment operator.
5546   if (RD->isLambda() &&
5547       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5548     if (Diagnose)
5549       Diag(RD->getLocation(), diag::note_lambda_decl);
5550     return true;
5551   }
5552 
5553   // For an anonymous struct or union, the copy and assignment special members
5554   // will never be used, so skip the check. For an anonymous union declared at
5555   // namespace scope, the constructor and destructor are used.
5556   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5557       RD->isAnonymousStructOrUnion())
5558     return false;
5559 
5560   // C++11 [class.copy]p7, p18:
5561   //   If the class definition declares a move constructor or move assignment
5562   //   operator, an implicitly declared copy constructor or copy assignment
5563   //   operator is defined as deleted.
5564   if (MD->isImplicit() &&
5565       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5566     CXXMethodDecl *UserDeclaredMove = nullptr;
5567 
5568     // In Microsoft mode, a user-declared move only causes the deletion of the
5569     // corresponding copy operation, not both copy operations.
5570     if (RD->hasUserDeclaredMoveConstructor() &&
5571         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5572       if (!Diagnose) return true;
5573 
5574       // Find any user-declared move constructor.
5575       for (auto *I : RD->ctors()) {
5576         if (I->isMoveConstructor()) {
5577           UserDeclaredMove = I;
5578           break;
5579         }
5580       }
5581       assert(UserDeclaredMove);
5582     } else if (RD->hasUserDeclaredMoveAssignment() &&
5583                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5584       if (!Diagnose) return true;
5585 
5586       // Find any user-declared move assignment operator.
5587       for (auto *I : RD->methods()) {
5588         if (I->isMoveAssignmentOperator()) {
5589           UserDeclaredMove = I;
5590           break;
5591         }
5592       }
5593       assert(UserDeclaredMove);
5594     }
5595 
5596     if (UserDeclaredMove) {
5597       Diag(UserDeclaredMove->getLocation(),
5598            diag::note_deleted_copy_user_declared_move)
5599         << (CSM == CXXCopyAssignment) << RD
5600         << UserDeclaredMove->isMoveAssignmentOperator();
5601       return true;
5602     }
5603   }
5604 
5605   // Do access control from the special member function
5606   ContextRAII MethodContext(*this, MD);
5607 
5608   // C++11 [class.dtor]p5:
5609   // -- for a virtual destructor, lookup of the non-array deallocation function
5610   //    results in an ambiguity or in a function that is deleted or inaccessible
5611   if (CSM == CXXDestructor && MD->isVirtual()) {
5612     FunctionDecl *OperatorDelete = nullptr;
5613     DeclarationName Name =
5614       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5615     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5616                                  OperatorDelete, false)) {
5617       if (Diagnose)
5618         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5619       return true;
5620     }
5621   }
5622 
5623   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5624 
5625   for (auto &BI : RD->bases())
5626     if (!BI.isVirtual() &&
5627         SMI.shouldDeleteForBase(&BI))
5628       return true;
5629 
5630   // Per DR1611, do not consider virtual bases of constructors of abstract
5631   // classes, since we are not going to construct them.
5632   if (!RD->isAbstract() || !SMI.IsConstructor) {
5633     for (auto &BI : RD->vbases())
5634       if (SMI.shouldDeleteForBase(&BI))
5635         return true;
5636   }
5637 
5638   for (auto *FI : RD->fields())
5639     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5640         SMI.shouldDeleteForField(FI))
5641       return true;
5642 
5643   if (SMI.shouldDeleteForAllConstMembers())
5644     return true;
5645 
5646   if (getLangOpts().CUDA) {
5647     // We should delete the special member in CUDA mode if target inference
5648     // failed.
5649     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5650                                                    Diagnose);
5651   }
5652 
5653   return false;
5654 }
5655 
5656 /// Perform lookup for a special member of the specified kind, and determine
5657 /// whether it is trivial. If the triviality can be determined without the
5658 /// lookup, skip it. This is intended for use when determining whether a
5659 /// special member of a containing object is trivial, and thus does not ever
5660 /// perform overload resolution for default constructors.
5661 ///
5662 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5663 /// member that was most likely to be intended to be trivial, if any.
5664 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5665                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5666                                      bool ConstRHS, CXXMethodDecl **Selected) {
5667   if (Selected)
5668     *Selected = nullptr;
5669 
5670   switch (CSM) {
5671   case Sema::CXXInvalid:
5672     llvm_unreachable("not a special member");
5673 
5674   case Sema::CXXDefaultConstructor:
5675     // C++11 [class.ctor]p5:
5676     //   A default constructor is trivial if:
5677     //    - all the [direct subobjects] have trivial default constructors
5678     //
5679     // Note, no overload resolution is performed in this case.
5680     if (RD->hasTrivialDefaultConstructor())
5681       return true;
5682 
5683     if (Selected) {
5684       // If there's a default constructor which could have been trivial, dig it
5685       // out. Otherwise, if there's any user-provided default constructor, point
5686       // to that as an example of why there's not a trivial one.
5687       CXXConstructorDecl *DefCtor = nullptr;
5688       if (RD->needsImplicitDefaultConstructor())
5689         S.DeclareImplicitDefaultConstructor(RD);
5690       for (auto *CI : RD->ctors()) {
5691         if (!CI->isDefaultConstructor())
5692           continue;
5693         DefCtor = CI;
5694         if (!DefCtor->isUserProvided())
5695           break;
5696       }
5697 
5698       *Selected = DefCtor;
5699     }
5700 
5701     return false;
5702 
5703   case Sema::CXXDestructor:
5704     // C++11 [class.dtor]p5:
5705     //   A destructor is trivial if:
5706     //    - all the direct [subobjects] have trivial destructors
5707     if (RD->hasTrivialDestructor())
5708       return true;
5709 
5710     if (Selected) {
5711       if (RD->needsImplicitDestructor())
5712         S.DeclareImplicitDestructor(RD);
5713       *Selected = RD->getDestructor();
5714     }
5715 
5716     return false;
5717 
5718   case Sema::CXXCopyConstructor:
5719     // C++11 [class.copy]p12:
5720     //   A copy constructor is trivial if:
5721     //    - the constructor selected to copy each direct [subobject] is trivial
5722     if (RD->hasTrivialCopyConstructor()) {
5723       if (Quals == Qualifiers::Const)
5724         // We must either select the trivial copy constructor or reach an
5725         // ambiguity; no need to actually perform overload resolution.
5726         return true;
5727     } else if (!Selected) {
5728       return false;
5729     }
5730     // In C++98, we are not supposed to perform overload resolution here, but we
5731     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5732     // cases like B as having a non-trivial copy constructor:
5733     //   struct A { template<typename T> A(T&); };
5734     //   struct B { mutable A a; };
5735     goto NeedOverloadResolution;
5736 
5737   case Sema::CXXCopyAssignment:
5738     // C++11 [class.copy]p25:
5739     //   A copy assignment operator is trivial if:
5740     //    - the assignment operator selected to copy each direct [subobject] is
5741     //      trivial
5742     if (RD->hasTrivialCopyAssignment()) {
5743       if (Quals == Qualifiers::Const)
5744         return true;
5745     } else if (!Selected) {
5746       return false;
5747     }
5748     // In C++98, we are not supposed to perform overload resolution here, but we
5749     // treat that as a language defect.
5750     goto NeedOverloadResolution;
5751 
5752   case Sema::CXXMoveConstructor:
5753   case Sema::CXXMoveAssignment:
5754   NeedOverloadResolution:
5755     Sema::SpecialMemberOverloadResult *SMOR =
5756         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5757 
5758     // The standard doesn't describe how to behave if the lookup is ambiguous.
5759     // We treat it as not making the member non-trivial, just like the standard
5760     // mandates for the default constructor. This should rarely matter, because
5761     // the member will also be deleted.
5762     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5763       return true;
5764 
5765     if (!SMOR->getMethod()) {
5766       assert(SMOR->getKind() ==
5767              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5768       return false;
5769     }
5770 
5771     // We deliberately don't check if we found a deleted special member. We're
5772     // not supposed to!
5773     if (Selected)
5774       *Selected = SMOR->getMethod();
5775     return SMOR->getMethod()->isTrivial();
5776   }
5777 
5778   llvm_unreachable("unknown special method kind");
5779 }
5780 
5781 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5782   for (auto *CI : RD->ctors())
5783     if (!CI->isImplicit())
5784       return CI;
5785 
5786   // Look for constructor templates.
5787   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5788   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5789     if (CXXConstructorDecl *CD =
5790           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5791       return CD;
5792   }
5793 
5794   return nullptr;
5795 }
5796 
5797 /// The kind of subobject we are checking for triviality. The values of this
5798 /// enumeration are used in diagnostics.
5799 enum TrivialSubobjectKind {
5800   /// The subobject is a base class.
5801   TSK_BaseClass,
5802   /// The subobject is a non-static data member.
5803   TSK_Field,
5804   /// The object is actually the complete object.
5805   TSK_CompleteObject
5806 };
5807 
5808 /// Check whether the special member selected for a given type would be trivial.
5809 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5810                                       QualType SubType, bool ConstRHS,
5811                                       Sema::CXXSpecialMember CSM,
5812                                       TrivialSubobjectKind Kind,
5813                                       bool Diagnose) {
5814   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5815   if (!SubRD)
5816     return true;
5817 
5818   CXXMethodDecl *Selected;
5819   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5820                                ConstRHS, Diagnose ? &Selected : nullptr))
5821     return true;
5822 
5823   if (Diagnose) {
5824     if (ConstRHS)
5825       SubType.addConst();
5826 
5827     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5828       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5829         << Kind << SubType.getUnqualifiedType();
5830       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5831         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5832     } else if (!Selected)
5833       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5834         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5835     else if (Selected->isUserProvided()) {
5836       if (Kind == TSK_CompleteObject)
5837         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5838           << Kind << SubType.getUnqualifiedType() << CSM;
5839       else {
5840         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5841           << Kind << SubType.getUnqualifiedType() << CSM;
5842         S.Diag(Selected->getLocation(), diag::note_declared_at);
5843       }
5844     } else {
5845       if (Kind != TSK_CompleteObject)
5846         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5847           << Kind << SubType.getUnqualifiedType() << CSM;
5848 
5849       // Explain why the defaulted or deleted special member isn't trivial.
5850       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5851     }
5852   }
5853 
5854   return false;
5855 }
5856 
5857 /// Check whether the members of a class type allow a special member to be
5858 /// trivial.
5859 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5860                                      Sema::CXXSpecialMember CSM,
5861                                      bool ConstArg, bool Diagnose) {
5862   for (const auto *FI : RD->fields()) {
5863     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5864       continue;
5865 
5866     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5867 
5868     // Pretend anonymous struct or union members are members of this class.
5869     if (FI->isAnonymousStructOrUnion()) {
5870       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5871                                     CSM, ConstArg, Diagnose))
5872         return false;
5873       continue;
5874     }
5875 
5876     // C++11 [class.ctor]p5:
5877     //   A default constructor is trivial if [...]
5878     //    -- no non-static data member of its class has a
5879     //       brace-or-equal-initializer
5880     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5881       if (Diagnose)
5882         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
5883       return false;
5884     }
5885 
5886     // Objective C ARC 4.3.5:
5887     //   [...] nontrivally ownership-qualified types are [...] not trivially
5888     //   default constructible, copy constructible, move constructible, copy
5889     //   assignable, move assignable, or destructible [...]
5890     if (S.getLangOpts().ObjCAutoRefCount &&
5891         FieldType.hasNonTrivialObjCLifetime()) {
5892       if (Diagnose)
5893         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5894           << RD << FieldType.getObjCLifetime();
5895       return false;
5896     }
5897 
5898     bool ConstRHS = ConstArg && !FI->isMutable();
5899     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5900                                    CSM, TSK_Field, Diagnose))
5901       return false;
5902   }
5903 
5904   return true;
5905 }
5906 
5907 /// Diagnose why the specified class does not have a trivial special member of
5908 /// the given kind.
5909 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5910   QualType Ty = Context.getRecordType(RD);
5911 
5912   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5913   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
5914                             TSK_CompleteObject, /*Diagnose*/true);
5915 }
5916 
5917 /// Determine whether a defaulted or deleted special member function is trivial,
5918 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5919 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5920 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5921                                   bool Diagnose) {
5922   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5923 
5924   CXXRecordDecl *RD = MD->getParent();
5925 
5926   bool ConstArg = false;
5927 
5928   // C++11 [class.copy]p12, p25: [DR1593]
5929   //   A [special member] is trivial if [...] its parameter-type-list is
5930   //   equivalent to the parameter-type-list of an implicit declaration [...]
5931   switch (CSM) {
5932   case CXXDefaultConstructor:
5933   case CXXDestructor:
5934     // Trivial default constructors and destructors cannot have parameters.
5935     break;
5936 
5937   case CXXCopyConstructor:
5938   case CXXCopyAssignment: {
5939     // Trivial copy operations always have const, non-volatile parameter types.
5940     ConstArg = true;
5941     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5942     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5943     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5944       if (Diagnose)
5945         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5946           << Param0->getSourceRange() << Param0->getType()
5947           << Context.getLValueReferenceType(
5948                Context.getRecordType(RD).withConst());
5949       return false;
5950     }
5951     break;
5952   }
5953 
5954   case CXXMoveConstructor:
5955   case CXXMoveAssignment: {
5956     // Trivial move operations always have non-cv-qualified parameters.
5957     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5958     const RValueReferenceType *RT =
5959       Param0->getType()->getAs<RValueReferenceType>();
5960     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5961       if (Diagnose)
5962         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5963           << Param0->getSourceRange() << Param0->getType()
5964           << Context.getRValueReferenceType(Context.getRecordType(RD));
5965       return false;
5966     }
5967     break;
5968   }
5969 
5970   case CXXInvalid:
5971     llvm_unreachable("not a special member");
5972   }
5973 
5974   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5975     if (Diagnose)
5976       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5977            diag::note_nontrivial_default_arg)
5978         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5979     return false;
5980   }
5981   if (MD->isVariadic()) {
5982     if (Diagnose)
5983       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5984     return false;
5985   }
5986 
5987   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5988   //   A copy/move [constructor or assignment operator] is trivial if
5989   //    -- the [member] selected to copy/move each direct base class subobject
5990   //       is trivial
5991   //
5992   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5993   //   A [default constructor or destructor] is trivial if
5994   //    -- all the direct base classes have trivial [default constructors or
5995   //       destructors]
5996   for (const auto &BI : RD->bases())
5997     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
5998                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
5999       return false;
6000 
6001   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6002   //   A copy/move [constructor or assignment operator] for a class X is
6003   //   trivial if
6004   //    -- for each non-static data member of X that is of class type (or array
6005   //       thereof), the constructor selected to copy/move that member is
6006   //       trivial
6007   //
6008   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6009   //   A [default constructor or destructor] is trivial if
6010   //    -- for all of the non-static data members of its class that are of class
6011   //       type (or array thereof), each such class has a trivial [default
6012   //       constructor or destructor]
6013   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6014     return false;
6015 
6016   // C++11 [class.dtor]p5:
6017   //   A destructor is trivial if [...]
6018   //    -- the destructor is not virtual
6019   if (CSM == CXXDestructor && MD->isVirtual()) {
6020     if (Diagnose)
6021       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6022     return false;
6023   }
6024 
6025   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6026   //   A [special member] for class X is trivial if [...]
6027   //    -- class X has no virtual functions and no virtual base classes
6028   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6029     if (!Diagnose)
6030       return false;
6031 
6032     if (RD->getNumVBases()) {
6033       // Check for virtual bases. We already know that the corresponding
6034       // member in all bases is trivial, so vbases must all be direct.
6035       CXXBaseSpecifier &BS = *RD->vbases_begin();
6036       assert(BS.isVirtual());
6037       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6038       return false;
6039     }
6040 
6041     // Must have a virtual method.
6042     for (const auto *MI : RD->methods()) {
6043       if (MI->isVirtual()) {
6044         SourceLocation MLoc = MI->getLocStart();
6045         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6046         return false;
6047       }
6048     }
6049 
6050     llvm_unreachable("dynamic class with no vbases and no virtual functions");
6051   }
6052 
6053   // Looks like it's trivial!
6054   return true;
6055 }
6056 
6057 /// \brief Data used with FindHiddenVirtualMethod
6058 namespace {
6059   struct FindHiddenVirtualMethodData {
6060     Sema *S;
6061     CXXMethodDecl *Method;
6062     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6063     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6064   };
6065 }
6066 
6067 /// \brief Check whether any most overriden method from MD in Methods
6068 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
6069                   const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6070   if (MD->size_overridden_methods() == 0)
6071     return Methods.count(MD->getCanonicalDecl());
6072   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6073                                       E = MD->end_overridden_methods();
6074        I != E; ++I)
6075     if (CheckMostOverridenMethods(*I, Methods))
6076       return true;
6077   return false;
6078 }
6079 
6080 /// \brief Member lookup function that determines whether a given C++
6081 /// method overloads virtual methods in a base class without overriding any,
6082 /// to be used with CXXRecordDecl::lookupInBases().
6083 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6084                                     CXXBasePath &Path,
6085                                     void *UserData) {
6086   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6087 
6088   FindHiddenVirtualMethodData &Data
6089     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6090 
6091   DeclarationName Name = Data.Method->getDeclName();
6092   assert(Name.getNameKind() == DeclarationName::Identifier);
6093 
6094   bool foundSameNameMethod = false;
6095   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6096   for (Path.Decls = BaseRecord->lookup(Name);
6097        !Path.Decls.empty();
6098        Path.Decls = Path.Decls.slice(1)) {
6099     NamedDecl *D = Path.Decls.front();
6100     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6101       MD = MD->getCanonicalDecl();
6102       foundSameNameMethod = true;
6103       // Interested only in hidden virtual methods.
6104       if (!MD->isVirtual())
6105         continue;
6106       // If the method we are checking overrides a method from its base
6107       // don't warn about the other overloaded methods. Clang deviates from GCC
6108       // by only diagnosing overloads of inherited virtual functions that do not
6109       // override any other virtual functions in the base. GCC's
6110       // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6111       // function from a base class. These cases may be better served by a
6112       // warning (not specific to virtual functions) on call sites when the call
6113       // would select a different function from the base class, were it visible.
6114       // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6115       if (!Data.S->IsOverload(Data.Method, MD, false))
6116         return true;
6117       // Collect the overload only if its hidden.
6118       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
6119         overloadedMethods.push_back(MD);
6120     }
6121   }
6122 
6123   if (foundSameNameMethod)
6124     Data.OverloadedMethods.append(overloadedMethods.begin(),
6125                                    overloadedMethods.end());
6126   return foundSameNameMethod;
6127 }
6128 
6129 /// \brief Add the most overriden methods from MD to Methods
6130 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6131                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6132   if (MD->size_overridden_methods() == 0)
6133     Methods.insert(MD->getCanonicalDecl());
6134   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6135                                       E = MD->end_overridden_methods();
6136        I != E; ++I)
6137     AddMostOverridenMethods(*I, Methods);
6138 }
6139 
6140 /// \brief Check if a method overloads virtual methods in a base class without
6141 /// overriding any.
6142 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6143                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6144   if (!MD->getDeclName().isIdentifier())
6145     return;
6146 
6147   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6148                      /*bool RecordPaths=*/false,
6149                      /*bool DetectVirtual=*/false);
6150   FindHiddenVirtualMethodData Data;
6151   Data.Method = MD;
6152   Data.S = this;
6153 
6154   // Keep the base methods that were overriden or introduced in the subclass
6155   // by 'using' in a set. A base method not in this set is hidden.
6156   CXXRecordDecl *DC = MD->getParent();
6157   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6158   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6159     NamedDecl *ND = *I;
6160     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6161       ND = shad->getTargetDecl();
6162     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6163       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
6164   }
6165 
6166   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6167     OverloadedMethods = Data.OverloadedMethods;
6168 }
6169 
6170 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6171                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6172   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6173     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6174     PartialDiagnostic PD = PDiag(
6175          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6176     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6177     Diag(overloadedMD->getLocation(), PD);
6178   }
6179 }
6180 
6181 /// \brief Diagnose methods which overload virtual methods in a base class
6182 /// without overriding any.
6183 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6184   if (MD->isInvalidDecl())
6185     return;
6186 
6187   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6188     return;
6189 
6190   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6191   FindHiddenVirtualMethods(MD, OverloadedMethods);
6192   if (!OverloadedMethods.empty()) {
6193     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6194       << MD << (OverloadedMethods.size() > 1);
6195 
6196     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6197   }
6198 }
6199 
6200 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6201                                              Decl *TagDecl,
6202                                              SourceLocation LBrac,
6203                                              SourceLocation RBrac,
6204                                              AttributeList *AttrList) {
6205   if (!TagDecl)
6206     return;
6207 
6208   AdjustDeclIfTemplate(TagDecl);
6209 
6210   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6211     if (l->getKind() != AttributeList::AT_Visibility)
6212       continue;
6213     l->setInvalid();
6214     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6215       l->getName();
6216   }
6217 
6218   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6219               // strict aliasing violation!
6220               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6221               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6222 
6223   CheckCompletedCXXClass(
6224                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6225 }
6226 
6227 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6228 /// special functions, such as the default constructor, copy
6229 /// constructor, or destructor, to the given C++ class (C++
6230 /// [special]p1).  This routine can only be executed just before the
6231 /// definition of the class is complete.
6232 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6233   if (!ClassDecl->hasUserDeclaredConstructor())
6234     ++ASTContext::NumImplicitDefaultConstructors;
6235 
6236   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6237     ++ASTContext::NumImplicitCopyConstructors;
6238 
6239     // If the properties or semantics of the copy constructor couldn't be
6240     // determined while the class was being declared, force a declaration
6241     // of it now.
6242     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6243       DeclareImplicitCopyConstructor(ClassDecl);
6244   }
6245 
6246   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6247     ++ASTContext::NumImplicitMoveConstructors;
6248 
6249     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6250       DeclareImplicitMoveConstructor(ClassDecl);
6251   }
6252 
6253   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6254     ++ASTContext::NumImplicitCopyAssignmentOperators;
6255 
6256     // If we have a dynamic class, then the copy assignment operator may be
6257     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6258     // it shows up in the right place in the vtable and that we diagnose
6259     // problems with the implicit exception specification.
6260     if (ClassDecl->isDynamicClass() ||
6261         ClassDecl->needsOverloadResolutionForCopyAssignment())
6262       DeclareImplicitCopyAssignment(ClassDecl);
6263   }
6264 
6265   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6266     ++ASTContext::NumImplicitMoveAssignmentOperators;
6267 
6268     // Likewise for the move assignment operator.
6269     if (ClassDecl->isDynamicClass() ||
6270         ClassDecl->needsOverloadResolutionForMoveAssignment())
6271       DeclareImplicitMoveAssignment(ClassDecl);
6272   }
6273 
6274   if (!ClassDecl->hasUserDeclaredDestructor()) {
6275     ++ASTContext::NumImplicitDestructors;
6276 
6277     // If we have a dynamic class, then the destructor may be virtual, so we
6278     // have to declare the destructor immediately. This ensures that, e.g., it
6279     // shows up in the right place in the vtable and that we diagnose problems
6280     // with the implicit exception specification.
6281     if (ClassDecl->isDynamicClass() ||
6282         ClassDecl->needsOverloadResolutionForDestructor())
6283       DeclareImplicitDestructor(ClassDecl);
6284   }
6285 }
6286 
6287 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6288   if (!D)
6289     return 0;
6290 
6291   // The order of template parameters is not important here. All names
6292   // get added to the same scope.
6293   SmallVector<TemplateParameterList *, 4> ParameterLists;
6294 
6295   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6296     D = TD->getTemplatedDecl();
6297 
6298   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6299     ParameterLists.push_back(PSD->getTemplateParameters());
6300 
6301   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6302     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6303       ParameterLists.push_back(DD->getTemplateParameterList(i));
6304 
6305     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6306       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6307         ParameterLists.push_back(FTD->getTemplateParameters());
6308     }
6309   }
6310 
6311   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6312     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6313       ParameterLists.push_back(TD->getTemplateParameterList(i));
6314 
6315     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6316       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6317         ParameterLists.push_back(CTD->getTemplateParameters());
6318     }
6319   }
6320 
6321   unsigned Count = 0;
6322   for (TemplateParameterList *Params : ParameterLists) {
6323     if (Params->size() > 0)
6324       // Ignore explicit specializations; they don't contribute to the template
6325       // depth.
6326       ++Count;
6327     for (NamedDecl *Param : *Params) {
6328       if (Param->getDeclName()) {
6329         S->AddDecl(Param);
6330         IdResolver.AddDecl(Param);
6331       }
6332     }
6333   }
6334 
6335   return Count;
6336 }
6337 
6338 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6339   if (!RecordD) return;
6340   AdjustDeclIfTemplate(RecordD);
6341   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6342   PushDeclContext(S, Record);
6343 }
6344 
6345 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6346   if (!RecordD) return;
6347   PopDeclContext();
6348 }
6349 
6350 /// This is used to implement the constant expression evaluation part of the
6351 /// attribute enable_if extension. There is nothing in standard C++ which would
6352 /// require reentering parameters.
6353 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6354   if (!Param)
6355     return;
6356 
6357   S->AddDecl(Param);
6358   if (Param->getDeclName())
6359     IdResolver.AddDecl(Param);
6360 }
6361 
6362 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6363 /// parsing a top-level (non-nested) C++ class, and we are now
6364 /// parsing those parts of the given Method declaration that could
6365 /// not be parsed earlier (C++ [class.mem]p2), such as default
6366 /// arguments. This action should enter the scope of the given
6367 /// Method declaration as if we had just parsed the qualified method
6368 /// name. However, it should not bring the parameters into scope;
6369 /// that will be performed by ActOnDelayedCXXMethodParameter.
6370 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6371 }
6372 
6373 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6374 /// C++ method declaration. We're (re-)introducing the given
6375 /// function parameter into scope for use in parsing later parts of
6376 /// the method declaration. For example, we could see an
6377 /// ActOnParamDefaultArgument event for this parameter.
6378 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6379   if (!ParamD)
6380     return;
6381 
6382   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6383 
6384   // If this parameter has an unparsed default argument, clear it out
6385   // to make way for the parsed default argument.
6386   if (Param->hasUnparsedDefaultArg())
6387     Param->setDefaultArg(nullptr);
6388 
6389   S->AddDecl(Param);
6390   if (Param->getDeclName())
6391     IdResolver.AddDecl(Param);
6392 }
6393 
6394 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6395 /// processing the delayed method declaration for Method. The method
6396 /// declaration is now considered finished. There may be a separate
6397 /// ActOnStartOfFunctionDef action later (not necessarily
6398 /// immediately!) for this method, if it was also defined inside the
6399 /// class body.
6400 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6401   if (!MethodD)
6402     return;
6403 
6404   AdjustDeclIfTemplate(MethodD);
6405 
6406   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6407 
6408   // Now that we have our default arguments, check the constructor
6409   // again. It could produce additional diagnostics or affect whether
6410   // the class has implicitly-declared destructors, among other
6411   // things.
6412   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6413     CheckConstructor(Constructor);
6414 
6415   // Check the default arguments, which we may have added.
6416   if (!Method->isInvalidDecl())
6417     CheckCXXDefaultArguments(Method);
6418 }
6419 
6420 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6421 /// the well-formedness of the constructor declarator @p D with type @p
6422 /// R. If there are any errors in the declarator, this routine will
6423 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6424 /// will be updated to reflect a well-formed type for the constructor and
6425 /// returned.
6426 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6427                                           StorageClass &SC) {
6428   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6429 
6430   // C++ [class.ctor]p3:
6431   //   A constructor shall not be virtual (10.3) or static (9.4). A
6432   //   constructor can be invoked for a const, volatile or const
6433   //   volatile object. A constructor shall not be declared const,
6434   //   volatile, or const volatile (9.3.2).
6435   if (isVirtual) {
6436     if (!D.isInvalidType())
6437       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6438         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6439         << SourceRange(D.getIdentifierLoc());
6440     D.setInvalidType();
6441   }
6442   if (SC == SC_Static) {
6443     if (!D.isInvalidType())
6444       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6445         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6446         << SourceRange(D.getIdentifierLoc());
6447     D.setInvalidType();
6448     SC = SC_None;
6449   }
6450 
6451   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6452     diagnoseIgnoredQualifiers(
6453         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6454         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6455         D.getDeclSpec().getRestrictSpecLoc(),
6456         D.getDeclSpec().getAtomicSpecLoc());
6457     D.setInvalidType();
6458   }
6459 
6460   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6461   if (FTI.TypeQuals != 0) {
6462     if (FTI.TypeQuals & Qualifiers::Const)
6463       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6464         << "const" << SourceRange(D.getIdentifierLoc());
6465     if (FTI.TypeQuals & Qualifiers::Volatile)
6466       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6467         << "volatile" << SourceRange(D.getIdentifierLoc());
6468     if (FTI.TypeQuals & Qualifiers::Restrict)
6469       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6470         << "restrict" << SourceRange(D.getIdentifierLoc());
6471     D.setInvalidType();
6472   }
6473 
6474   // C++0x [class.ctor]p4:
6475   //   A constructor shall not be declared with a ref-qualifier.
6476   if (FTI.hasRefQualifier()) {
6477     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6478       << FTI.RefQualifierIsLValueRef
6479       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6480     D.setInvalidType();
6481   }
6482 
6483   // Rebuild the function type "R" without any type qualifiers (in
6484   // case any of the errors above fired) and with "void" as the
6485   // return type, since constructors don't have return types.
6486   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6487   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6488     return R;
6489 
6490   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6491   EPI.TypeQuals = 0;
6492   EPI.RefQualifier = RQ_None;
6493 
6494   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6495 }
6496 
6497 /// CheckConstructor - Checks a fully-formed constructor for
6498 /// well-formedness, issuing any diagnostics required. Returns true if
6499 /// the constructor declarator is invalid.
6500 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6501   CXXRecordDecl *ClassDecl
6502     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6503   if (!ClassDecl)
6504     return Constructor->setInvalidDecl();
6505 
6506   // C++ [class.copy]p3:
6507   //   A declaration of a constructor for a class X is ill-formed if
6508   //   its first parameter is of type (optionally cv-qualified) X and
6509   //   either there are no other parameters or else all other
6510   //   parameters have default arguments.
6511   if (!Constructor->isInvalidDecl() &&
6512       ((Constructor->getNumParams() == 1) ||
6513        (Constructor->getNumParams() > 1 &&
6514         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6515       Constructor->getTemplateSpecializationKind()
6516                                               != TSK_ImplicitInstantiation) {
6517     QualType ParamType = Constructor->getParamDecl(0)->getType();
6518     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6519     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6520       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6521       const char *ConstRef
6522         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6523                                                         : " const &";
6524       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6525         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6526 
6527       // FIXME: Rather that making the constructor invalid, we should endeavor
6528       // to fix the type.
6529       Constructor->setInvalidDecl();
6530     }
6531   }
6532 }
6533 
6534 /// CheckDestructor - Checks a fully-formed destructor definition for
6535 /// well-formedness, issuing any diagnostics required.  Returns true
6536 /// on error.
6537 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6538   CXXRecordDecl *RD = Destructor->getParent();
6539 
6540   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6541     SourceLocation Loc;
6542 
6543     if (!Destructor->isImplicit())
6544       Loc = Destructor->getLocation();
6545     else
6546       Loc = RD->getLocation();
6547 
6548     // If we have a virtual destructor, look up the deallocation function
6549     FunctionDecl *OperatorDelete = nullptr;
6550     DeclarationName Name =
6551     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6552     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6553       return true;
6554     // If there's no class-specific operator delete, look up the global
6555     // non-array delete.
6556     if (!OperatorDelete)
6557       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6558 
6559     MarkFunctionReferenced(Loc, OperatorDelete);
6560 
6561     Destructor->setOperatorDelete(OperatorDelete);
6562   }
6563 
6564   return false;
6565 }
6566 
6567 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6568 /// the well-formednes of the destructor declarator @p D with type @p
6569 /// R. If there are any errors in the declarator, this routine will
6570 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6571 /// will be updated to reflect a well-formed type for the destructor and
6572 /// returned.
6573 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6574                                          StorageClass& SC) {
6575   // C++ [class.dtor]p1:
6576   //   [...] A typedef-name that names a class is a class-name
6577   //   (7.1.3); however, a typedef-name that names a class shall not
6578   //   be used as the identifier in the declarator for a destructor
6579   //   declaration.
6580   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6581   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6582     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6583       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6584   else if (const TemplateSpecializationType *TST =
6585              DeclaratorType->getAs<TemplateSpecializationType>())
6586     if (TST->isTypeAlias())
6587       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6588         << DeclaratorType << 1;
6589 
6590   // C++ [class.dtor]p2:
6591   //   A destructor is used to destroy objects of its class type. A
6592   //   destructor takes no parameters, and no return type can be
6593   //   specified for it (not even void). The address of a destructor
6594   //   shall not be taken. A destructor shall not be static. A
6595   //   destructor can be invoked for a const, volatile or const
6596   //   volatile object. A destructor shall not be declared const,
6597   //   volatile or const volatile (9.3.2).
6598   if (SC == SC_Static) {
6599     if (!D.isInvalidType())
6600       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6601         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6602         << SourceRange(D.getIdentifierLoc())
6603         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6604 
6605     SC = SC_None;
6606   }
6607   if (!D.isInvalidType()) {
6608     // Destructors don't have return types, but the parser will
6609     // happily parse something like:
6610     //
6611     //   class X {
6612     //     float ~X();
6613     //   };
6614     //
6615     // The return type will be eliminated later.
6616     if (D.getDeclSpec().hasTypeSpecifier())
6617       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6618         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6619         << SourceRange(D.getIdentifierLoc());
6620     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6621       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6622                                 SourceLocation(),
6623                                 D.getDeclSpec().getConstSpecLoc(),
6624                                 D.getDeclSpec().getVolatileSpecLoc(),
6625                                 D.getDeclSpec().getRestrictSpecLoc(),
6626                                 D.getDeclSpec().getAtomicSpecLoc());
6627       D.setInvalidType();
6628     }
6629   }
6630 
6631   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6632   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6633     if (FTI.TypeQuals & Qualifiers::Const)
6634       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6635         << "const" << SourceRange(D.getIdentifierLoc());
6636     if (FTI.TypeQuals & Qualifiers::Volatile)
6637       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6638         << "volatile" << SourceRange(D.getIdentifierLoc());
6639     if (FTI.TypeQuals & Qualifiers::Restrict)
6640       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6641         << "restrict" << SourceRange(D.getIdentifierLoc());
6642     D.setInvalidType();
6643   }
6644 
6645   // C++0x [class.dtor]p2:
6646   //   A destructor shall not be declared with a ref-qualifier.
6647   if (FTI.hasRefQualifier()) {
6648     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6649       << FTI.RefQualifierIsLValueRef
6650       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6651     D.setInvalidType();
6652   }
6653 
6654   // Make sure we don't have any parameters.
6655   if (FTIHasNonVoidParameters(FTI)) {
6656     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6657 
6658     // Delete the parameters.
6659     FTI.freeParams();
6660     D.setInvalidType();
6661   }
6662 
6663   // Make sure the destructor isn't variadic.
6664   if (FTI.isVariadic) {
6665     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6666     D.setInvalidType();
6667   }
6668 
6669   // Rebuild the function type "R" without any type qualifiers or
6670   // parameters (in case any of the errors above fired) and with
6671   // "void" as the return type, since destructors don't have return
6672   // types.
6673   if (!D.isInvalidType())
6674     return R;
6675 
6676   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6677   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6678   EPI.Variadic = false;
6679   EPI.TypeQuals = 0;
6680   EPI.RefQualifier = RQ_None;
6681   return Context.getFunctionType(Context.VoidTy, None, EPI);
6682 }
6683 
6684 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6685 /// well-formednes of the conversion function declarator @p D with
6686 /// type @p R. If there are any errors in the declarator, this routine
6687 /// will emit diagnostics and return true. Otherwise, it will return
6688 /// false. Either way, the type @p R will be updated to reflect a
6689 /// well-formed type for the conversion operator.
6690 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6691                                      StorageClass& SC) {
6692   // C++ [class.conv.fct]p1:
6693   //   Neither parameter types nor return type can be specified. The
6694   //   type of a conversion function (8.3.5) is "function taking no
6695   //   parameter returning conversion-type-id."
6696   if (SC == SC_Static) {
6697     if (!D.isInvalidType())
6698       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6699         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6700         << D.getName().getSourceRange();
6701     D.setInvalidType();
6702     SC = SC_None;
6703   }
6704 
6705   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6706 
6707   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6708     // Conversion functions don't have return types, but the parser will
6709     // happily parse something like:
6710     //
6711     //   class X {
6712     //     float operator bool();
6713     //   };
6714     //
6715     // The return type will be changed later anyway.
6716     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6717       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6718       << SourceRange(D.getIdentifierLoc());
6719     D.setInvalidType();
6720   }
6721 
6722   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6723 
6724   // Make sure we don't have any parameters.
6725   if (Proto->getNumParams() > 0) {
6726     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6727 
6728     // Delete the parameters.
6729     D.getFunctionTypeInfo().freeParams();
6730     D.setInvalidType();
6731   } else if (Proto->isVariadic()) {
6732     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6733     D.setInvalidType();
6734   }
6735 
6736   // Diagnose "&operator bool()" and other such nonsense.  This
6737   // is actually a gcc extension which we don't support.
6738   if (Proto->getReturnType() != ConvType) {
6739     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6740         << Proto->getReturnType();
6741     D.setInvalidType();
6742     ConvType = Proto->getReturnType();
6743   }
6744 
6745   // C++ [class.conv.fct]p4:
6746   //   The conversion-type-id shall not represent a function type nor
6747   //   an array type.
6748   if (ConvType->isArrayType()) {
6749     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6750     ConvType = Context.getPointerType(ConvType);
6751     D.setInvalidType();
6752   } else if (ConvType->isFunctionType()) {
6753     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6754     ConvType = Context.getPointerType(ConvType);
6755     D.setInvalidType();
6756   }
6757 
6758   // Rebuild the function type "R" without any parameters (in case any
6759   // of the errors above fired) and with the conversion type as the
6760   // return type.
6761   if (D.isInvalidType())
6762     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6763 
6764   // C++0x explicit conversion operators.
6765   if (D.getDeclSpec().isExplicitSpecified())
6766     Diag(D.getDeclSpec().getExplicitSpecLoc(),
6767          getLangOpts().CPlusPlus11 ?
6768            diag::warn_cxx98_compat_explicit_conversion_functions :
6769            diag::ext_explicit_conversion_functions)
6770       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6771 }
6772 
6773 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6774 /// the declaration of the given C++ conversion function. This routine
6775 /// is responsible for recording the conversion function in the C++
6776 /// class, if possible.
6777 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6778   assert(Conversion && "Expected to receive a conversion function declaration");
6779 
6780   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6781 
6782   // Make sure we aren't redeclaring the conversion function.
6783   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6784 
6785   // C++ [class.conv.fct]p1:
6786   //   [...] A conversion function is never used to convert a
6787   //   (possibly cv-qualified) object to the (possibly cv-qualified)
6788   //   same object type (or a reference to it), to a (possibly
6789   //   cv-qualified) base class of that type (or a reference to it),
6790   //   or to (possibly cv-qualified) void.
6791   // FIXME: Suppress this warning if the conversion function ends up being a
6792   // virtual function that overrides a virtual function in a base class.
6793   QualType ClassType
6794     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6795   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6796     ConvType = ConvTypeRef->getPointeeType();
6797   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6798       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6799     /* Suppress diagnostics for instantiations. */;
6800   else if (ConvType->isRecordType()) {
6801     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6802     if (ConvType == ClassType)
6803       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6804         << ClassType;
6805     else if (IsDerivedFrom(ClassType, ConvType))
6806       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6807         <<  ClassType << ConvType;
6808   } else if (ConvType->isVoidType()) {
6809     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6810       << ClassType << ConvType;
6811   }
6812 
6813   if (FunctionTemplateDecl *ConversionTemplate
6814                                 = Conversion->getDescribedFunctionTemplate())
6815     return ConversionTemplate;
6816 
6817   return Conversion;
6818 }
6819 
6820 //===----------------------------------------------------------------------===//
6821 // Namespace Handling
6822 //===----------------------------------------------------------------------===//
6823 
6824 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6825 /// reopened.
6826 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6827                                             SourceLocation Loc,
6828                                             IdentifierInfo *II, bool *IsInline,
6829                                             NamespaceDecl *PrevNS) {
6830   assert(*IsInline != PrevNS->isInline());
6831 
6832   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6833   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6834   // inline namespaces, with the intention of bringing names into namespace std.
6835   //
6836   // We support this just well enough to get that case working; this is not
6837   // sufficient to support reopening namespaces as inline in general.
6838   if (*IsInline && II && II->getName().startswith("__atomic") &&
6839       S.getSourceManager().isInSystemHeader(Loc)) {
6840     // Mark all prior declarations of the namespace as inline.
6841     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6842          NS = NS->getPreviousDecl())
6843       NS->setInline(*IsInline);
6844     // Patch up the lookup table for the containing namespace. This isn't really
6845     // correct, but it's good enough for this particular case.
6846     for (auto *I : PrevNS->decls())
6847       if (auto *ND = dyn_cast<NamedDecl>(I))
6848         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6849     return;
6850   }
6851 
6852   if (PrevNS->isInline())
6853     // The user probably just forgot the 'inline', so suggest that it
6854     // be added back.
6855     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6856       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6857   else
6858     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
6859 
6860   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6861   *IsInline = PrevNS->isInline();
6862 }
6863 
6864 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6865 /// definition.
6866 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6867                                    SourceLocation InlineLoc,
6868                                    SourceLocation NamespaceLoc,
6869                                    SourceLocation IdentLoc,
6870                                    IdentifierInfo *II,
6871                                    SourceLocation LBrace,
6872                                    AttributeList *AttrList) {
6873   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6874   // For anonymous namespace, take the location of the left brace.
6875   SourceLocation Loc = II ? IdentLoc : LBrace;
6876   bool IsInline = InlineLoc.isValid();
6877   bool IsInvalid = false;
6878   bool IsStd = false;
6879   bool AddToKnown = false;
6880   Scope *DeclRegionScope = NamespcScope->getParent();
6881 
6882   NamespaceDecl *PrevNS = nullptr;
6883   if (II) {
6884     // C++ [namespace.def]p2:
6885     //   The identifier in an original-namespace-definition shall not
6886     //   have been previously defined in the declarative region in
6887     //   which the original-namespace-definition appears. The
6888     //   identifier in an original-namespace-definition is the name of
6889     //   the namespace. Subsequently in that declarative region, it is
6890     //   treated as an original-namespace-name.
6891     //
6892     // Since namespace names are unique in their scope, and we don't
6893     // look through using directives, just look for any ordinary names.
6894 
6895     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6896     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6897     Decl::IDNS_Namespace;
6898     NamedDecl *PrevDecl = nullptr;
6899     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6900     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6901          ++I) {
6902       if ((*I)->getIdentifierNamespace() & IDNS) {
6903         PrevDecl = *I;
6904         break;
6905       }
6906     }
6907 
6908     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6909 
6910     if (PrevNS) {
6911       // This is an extended namespace definition.
6912       if (IsInline != PrevNS->isInline())
6913         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6914                                         &IsInline, PrevNS);
6915     } else if (PrevDecl) {
6916       // This is an invalid name redefinition.
6917       Diag(Loc, diag::err_redefinition_different_kind)
6918         << II;
6919       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6920       IsInvalid = true;
6921       // Continue on to push Namespc as current DeclContext and return it.
6922     } else if (II->isStr("std") &&
6923                CurContext->getRedeclContext()->isTranslationUnit()) {
6924       // This is the first "real" definition of the namespace "std", so update
6925       // our cache of the "std" namespace to point at this definition.
6926       PrevNS = getStdNamespace();
6927       IsStd = true;
6928       AddToKnown = !IsInline;
6929     } else {
6930       // We've seen this namespace for the first time.
6931       AddToKnown = !IsInline;
6932     }
6933   } else {
6934     // Anonymous namespaces.
6935 
6936     // Determine whether the parent already has an anonymous namespace.
6937     DeclContext *Parent = CurContext->getRedeclContext();
6938     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6939       PrevNS = TU->getAnonymousNamespace();
6940     } else {
6941       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6942       PrevNS = ND->getAnonymousNamespace();
6943     }
6944 
6945     if (PrevNS && IsInline != PrevNS->isInline())
6946       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6947                                       &IsInline, PrevNS);
6948   }
6949 
6950   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6951                                                  StartLoc, Loc, II, PrevNS);
6952   if (IsInvalid)
6953     Namespc->setInvalidDecl();
6954 
6955   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6956 
6957   // FIXME: Should we be merging attributes?
6958   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6959     PushNamespaceVisibilityAttr(Attr, Loc);
6960 
6961   if (IsStd)
6962     StdNamespace = Namespc;
6963   if (AddToKnown)
6964     KnownNamespaces[Namespc] = false;
6965 
6966   if (II) {
6967     PushOnScopeChains(Namespc, DeclRegionScope);
6968   } else {
6969     // Link the anonymous namespace into its parent.
6970     DeclContext *Parent = CurContext->getRedeclContext();
6971     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6972       TU->setAnonymousNamespace(Namespc);
6973     } else {
6974       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6975     }
6976 
6977     CurContext->addDecl(Namespc);
6978 
6979     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6980     //   behaves as if it were replaced by
6981     //     namespace unique { /* empty body */ }
6982     //     using namespace unique;
6983     //     namespace unique { namespace-body }
6984     //   where all occurrences of 'unique' in a translation unit are
6985     //   replaced by the same identifier and this identifier differs
6986     //   from all other identifiers in the entire program.
6987 
6988     // We just create the namespace with an empty name and then add an
6989     // implicit using declaration, just like the standard suggests.
6990     //
6991     // CodeGen enforces the "universally unique" aspect by giving all
6992     // declarations semantically contained within an anonymous
6993     // namespace internal linkage.
6994 
6995     if (!PrevNS) {
6996       UsingDirectiveDecl* UD
6997         = UsingDirectiveDecl::Create(Context, Parent,
6998                                      /* 'using' */ LBrace,
6999                                      /* 'namespace' */ SourceLocation(),
7000                                      /* qualifier */ NestedNameSpecifierLoc(),
7001                                      /* identifier */ SourceLocation(),
7002                                      Namespc,
7003                                      /* Ancestor */ Parent);
7004       UD->setImplicit();
7005       Parent->addDecl(UD);
7006     }
7007   }
7008 
7009   ActOnDocumentableDecl(Namespc);
7010 
7011   // Although we could have an invalid decl (i.e. the namespace name is a
7012   // redefinition), push it as current DeclContext and try to continue parsing.
7013   // FIXME: We should be able to push Namespc here, so that the each DeclContext
7014   // for the namespace has the declarations that showed up in that particular
7015   // namespace definition.
7016   PushDeclContext(NamespcScope, Namespc);
7017   return Namespc;
7018 }
7019 
7020 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7021 /// is a namespace alias, returns the namespace it points to.
7022 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7023   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7024     return AD->getNamespace();
7025   return dyn_cast_or_null<NamespaceDecl>(D);
7026 }
7027 
7028 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7029 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7030 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7031   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7032   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7033   Namespc->setRBraceLoc(RBrace);
7034   PopDeclContext();
7035   if (Namespc->hasAttr<VisibilityAttr>())
7036     PopPragmaVisibility(true, RBrace);
7037 }
7038 
7039 CXXRecordDecl *Sema::getStdBadAlloc() const {
7040   return cast_or_null<CXXRecordDecl>(
7041                                   StdBadAlloc.get(Context.getExternalSource()));
7042 }
7043 
7044 NamespaceDecl *Sema::getStdNamespace() const {
7045   return cast_or_null<NamespaceDecl>(
7046                                  StdNamespace.get(Context.getExternalSource()));
7047 }
7048 
7049 /// \brief Retrieve the special "std" namespace, which may require us to
7050 /// implicitly define the namespace.
7051 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7052   if (!StdNamespace) {
7053     // The "std" namespace has not yet been defined, so build one implicitly.
7054     StdNamespace = NamespaceDecl::Create(Context,
7055                                          Context.getTranslationUnitDecl(),
7056                                          /*Inline=*/false,
7057                                          SourceLocation(), SourceLocation(),
7058                                          &PP.getIdentifierTable().get("std"),
7059                                          /*PrevDecl=*/nullptr);
7060     getStdNamespace()->setImplicit(true);
7061   }
7062 
7063   return getStdNamespace();
7064 }
7065 
7066 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7067   assert(getLangOpts().CPlusPlus &&
7068          "Looking for std::initializer_list outside of C++.");
7069 
7070   // We're looking for implicit instantiations of
7071   // template <typename E> class std::initializer_list.
7072 
7073   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7074     return false;
7075 
7076   ClassTemplateDecl *Template = nullptr;
7077   const TemplateArgument *Arguments = nullptr;
7078 
7079   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7080 
7081     ClassTemplateSpecializationDecl *Specialization =
7082         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7083     if (!Specialization)
7084       return false;
7085 
7086     Template = Specialization->getSpecializedTemplate();
7087     Arguments = Specialization->getTemplateArgs().data();
7088   } else if (const TemplateSpecializationType *TST =
7089                  Ty->getAs<TemplateSpecializationType>()) {
7090     Template = dyn_cast_or_null<ClassTemplateDecl>(
7091         TST->getTemplateName().getAsTemplateDecl());
7092     Arguments = TST->getArgs();
7093   }
7094   if (!Template)
7095     return false;
7096 
7097   if (!StdInitializerList) {
7098     // Haven't recognized std::initializer_list yet, maybe this is it.
7099     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7100     if (TemplateClass->getIdentifier() !=
7101             &PP.getIdentifierTable().get("initializer_list") ||
7102         !getStdNamespace()->InEnclosingNamespaceSetOf(
7103             TemplateClass->getDeclContext()))
7104       return false;
7105     // This is a template called std::initializer_list, but is it the right
7106     // template?
7107     TemplateParameterList *Params = Template->getTemplateParameters();
7108     if (Params->getMinRequiredArguments() != 1)
7109       return false;
7110     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7111       return false;
7112 
7113     // It's the right template.
7114     StdInitializerList = Template;
7115   }
7116 
7117   if (Template != StdInitializerList)
7118     return false;
7119 
7120   // This is an instance of std::initializer_list. Find the argument type.
7121   if (Element)
7122     *Element = Arguments[0].getAsType();
7123   return true;
7124 }
7125 
7126 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7127   NamespaceDecl *Std = S.getStdNamespace();
7128   if (!Std) {
7129     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7130     return nullptr;
7131   }
7132 
7133   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7134                       Loc, Sema::LookupOrdinaryName);
7135   if (!S.LookupQualifiedName(Result, Std)) {
7136     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7137     return nullptr;
7138   }
7139   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7140   if (!Template) {
7141     Result.suppressDiagnostics();
7142     // We found something weird. Complain about the first thing we found.
7143     NamedDecl *Found = *Result.begin();
7144     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7145     return nullptr;
7146   }
7147 
7148   // We found some template called std::initializer_list. Now verify that it's
7149   // correct.
7150   TemplateParameterList *Params = Template->getTemplateParameters();
7151   if (Params->getMinRequiredArguments() != 1 ||
7152       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7153     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7154     return nullptr;
7155   }
7156 
7157   return Template;
7158 }
7159 
7160 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7161   if (!StdInitializerList) {
7162     StdInitializerList = LookupStdInitializerList(*this, Loc);
7163     if (!StdInitializerList)
7164       return QualType();
7165   }
7166 
7167   TemplateArgumentListInfo Args(Loc, Loc);
7168   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7169                                        Context.getTrivialTypeSourceInfo(Element,
7170                                                                         Loc)));
7171   return Context.getCanonicalType(
7172       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7173 }
7174 
7175 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7176   // C++ [dcl.init.list]p2:
7177   //   A constructor is an initializer-list constructor if its first parameter
7178   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7179   //   std::initializer_list<E> for some type E, and either there are no other
7180   //   parameters or else all other parameters have default arguments.
7181   if (Ctor->getNumParams() < 1 ||
7182       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7183     return false;
7184 
7185   QualType ArgType = Ctor->getParamDecl(0)->getType();
7186   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7187     ArgType = RT->getPointeeType().getUnqualifiedType();
7188 
7189   return isStdInitializerList(ArgType, nullptr);
7190 }
7191 
7192 /// \brief Determine whether a using statement is in a context where it will be
7193 /// apply in all contexts.
7194 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7195   switch (CurContext->getDeclKind()) {
7196     case Decl::TranslationUnit:
7197       return true;
7198     case Decl::LinkageSpec:
7199       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7200     default:
7201       return false;
7202   }
7203 }
7204 
7205 namespace {
7206 
7207 // Callback to only accept typo corrections that are namespaces.
7208 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7209 public:
7210   bool ValidateCandidate(const TypoCorrection &candidate) override {
7211     if (NamedDecl *ND = candidate.getCorrectionDecl())
7212       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7213     return false;
7214   }
7215 };
7216 
7217 }
7218 
7219 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7220                                        CXXScopeSpec &SS,
7221                                        SourceLocation IdentLoc,
7222                                        IdentifierInfo *Ident) {
7223   NamespaceValidatorCCC Validator;
7224   R.clear();
7225   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
7226                                                R.getLookupKind(), Sc, &SS,
7227                                                Validator,
7228                                                Sema::CTK_ErrorRecovery)) {
7229     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7230       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7231       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7232                               Ident->getName().equals(CorrectedStr);
7233       S.diagnoseTypo(Corrected,
7234                      S.PDiag(diag::err_using_directive_member_suggest)
7235                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7236                      S.PDiag(diag::note_namespace_defined_here));
7237     } else {
7238       S.diagnoseTypo(Corrected,
7239                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7240                      S.PDiag(diag::note_namespace_defined_here));
7241     }
7242     R.addDecl(Corrected.getCorrectionDecl());
7243     return true;
7244   }
7245   return false;
7246 }
7247 
7248 Decl *Sema::ActOnUsingDirective(Scope *S,
7249                                           SourceLocation UsingLoc,
7250                                           SourceLocation NamespcLoc,
7251                                           CXXScopeSpec &SS,
7252                                           SourceLocation IdentLoc,
7253                                           IdentifierInfo *NamespcName,
7254                                           AttributeList *AttrList) {
7255   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7256   assert(NamespcName && "Invalid NamespcName.");
7257   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7258 
7259   // This can only happen along a recovery path.
7260   while (S->getFlags() & Scope::TemplateParamScope)
7261     S = S->getParent();
7262   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7263 
7264   UsingDirectiveDecl *UDir = nullptr;
7265   NestedNameSpecifier *Qualifier = nullptr;
7266   if (SS.isSet())
7267     Qualifier = SS.getScopeRep();
7268 
7269   // Lookup namespace name.
7270   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7271   LookupParsedName(R, S, &SS);
7272   if (R.isAmbiguous())
7273     return nullptr;
7274 
7275   if (R.empty()) {
7276     R.clear();
7277     // Allow "using namespace std;" or "using namespace ::std;" even if
7278     // "std" hasn't been defined yet, for GCC compatibility.
7279     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7280         NamespcName->isStr("std")) {
7281       Diag(IdentLoc, diag::ext_using_undefined_std);
7282       R.addDecl(getOrCreateStdNamespace());
7283       R.resolveKind();
7284     }
7285     // Otherwise, attempt typo correction.
7286     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7287   }
7288 
7289   if (!R.empty()) {
7290     NamedDecl *Named = R.getFoundDecl();
7291     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7292         && "expected namespace decl");
7293     // C++ [namespace.udir]p1:
7294     //   A using-directive specifies that the names in the nominated
7295     //   namespace can be used in the scope in which the
7296     //   using-directive appears after the using-directive. During
7297     //   unqualified name lookup (3.4.1), the names appear as if they
7298     //   were declared in the nearest enclosing namespace which
7299     //   contains both the using-directive and the nominated
7300     //   namespace. [Note: in this context, "contains" means "contains
7301     //   directly or indirectly". ]
7302 
7303     // Find enclosing context containing both using-directive and
7304     // nominated namespace.
7305     NamespaceDecl *NS = getNamespaceDecl(Named);
7306     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7307     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7308       CommonAncestor = CommonAncestor->getParent();
7309 
7310     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7311                                       SS.getWithLocInContext(Context),
7312                                       IdentLoc, Named, CommonAncestor);
7313 
7314     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7315         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7316       Diag(IdentLoc, diag::warn_using_directive_in_header);
7317     }
7318 
7319     PushUsingDirective(S, UDir);
7320   } else {
7321     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7322   }
7323 
7324   if (UDir)
7325     ProcessDeclAttributeList(S, UDir, AttrList);
7326 
7327   return UDir;
7328 }
7329 
7330 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7331   // If the scope has an associated entity and the using directive is at
7332   // namespace or translation unit scope, add the UsingDirectiveDecl into
7333   // its lookup structure so qualified name lookup can find it.
7334   DeclContext *Ctx = S->getEntity();
7335   if (Ctx && !Ctx->isFunctionOrMethod())
7336     Ctx->addDecl(UDir);
7337   else
7338     // Otherwise, it is at block scope. The using-directives will affect lookup
7339     // only to the end of the scope.
7340     S->PushUsingDirective(UDir);
7341 }
7342 
7343 
7344 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7345                                   AccessSpecifier AS,
7346                                   bool HasUsingKeyword,
7347                                   SourceLocation UsingLoc,
7348                                   CXXScopeSpec &SS,
7349                                   UnqualifiedId &Name,
7350                                   AttributeList *AttrList,
7351                                   bool HasTypenameKeyword,
7352                                   SourceLocation TypenameLoc) {
7353   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7354 
7355   switch (Name.getKind()) {
7356   case UnqualifiedId::IK_ImplicitSelfParam:
7357   case UnqualifiedId::IK_Identifier:
7358   case UnqualifiedId::IK_OperatorFunctionId:
7359   case UnqualifiedId::IK_LiteralOperatorId:
7360   case UnqualifiedId::IK_ConversionFunctionId:
7361     break;
7362 
7363   case UnqualifiedId::IK_ConstructorName:
7364   case UnqualifiedId::IK_ConstructorTemplateId:
7365     // C++11 inheriting constructors.
7366     Diag(Name.getLocStart(),
7367          getLangOpts().CPlusPlus11 ?
7368            diag::warn_cxx98_compat_using_decl_constructor :
7369            diag::err_using_decl_constructor)
7370       << SS.getRange();
7371 
7372     if (getLangOpts().CPlusPlus11) break;
7373 
7374     return nullptr;
7375 
7376   case UnqualifiedId::IK_DestructorName:
7377     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7378       << SS.getRange();
7379     return nullptr;
7380 
7381   case UnqualifiedId::IK_TemplateId:
7382     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7383       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7384     return nullptr;
7385   }
7386 
7387   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7388   DeclarationName TargetName = TargetNameInfo.getName();
7389   if (!TargetName)
7390     return nullptr;
7391 
7392   // Warn about access declarations.
7393   if (!HasUsingKeyword) {
7394     Diag(Name.getLocStart(),
7395          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7396                                    : diag::warn_access_decl_deprecated)
7397       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7398   }
7399 
7400   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7401       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7402     return nullptr;
7403 
7404   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7405                                         TargetNameInfo, AttrList,
7406                                         /* IsInstantiation */ false,
7407                                         HasTypenameKeyword, TypenameLoc);
7408   if (UD)
7409     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7410 
7411   return UD;
7412 }
7413 
7414 /// \brief Determine whether a using declaration considers the given
7415 /// declarations as "equivalent", e.g., if they are redeclarations of
7416 /// the same entity or are both typedefs of the same type.
7417 static bool
7418 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7419   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7420     return true;
7421 
7422   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7423     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7424       return Context.hasSameType(TD1->getUnderlyingType(),
7425                                  TD2->getUnderlyingType());
7426 
7427   return false;
7428 }
7429 
7430 
7431 /// Determines whether to create a using shadow decl for a particular
7432 /// decl, given the set of decls existing prior to this using lookup.
7433 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7434                                 const LookupResult &Previous,
7435                                 UsingShadowDecl *&PrevShadow) {
7436   // Diagnose finding a decl which is not from a base class of the
7437   // current class.  We do this now because there are cases where this
7438   // function will silently decide not to build a shadow decl, which
7439   // will pre-empt further diagnostics.
7440   //
7441   // We don't need to do this in C++0x because we do the check once on
7442   // the qualifier.
7443   //
7444   // FIXME: diagnose the following if we care enough:
7445   //   struct A { int foo; };
7446   //   struct B : A { using A::foo; };
7447   //   template <class T> struct C : A {};
7448   //   template <class T> struct D : C<T> { using B::foo; } // <---
7449   // This is invalid (during instantiation) in C++03 because B::foo
7450   // resolves to the using decl in B, which is not a base class of D<T>.
7451   // We can't diagnose it immediately because C<T> is an unknown
7452   // specialization.  The UsingShadowDecl in D<T> then points directly
7453   // to A::foo, which will look well-formed when we instantiate.
7454   // The right solution is to not collapse the shadow-decl chain.
7455   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7456     DeclContext *OrigDC = Orig->getDeclContext();
7457 
7458     // Handle enums and anonymous structs.
7459     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7460     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7461     while (OrigRec->isAnonymousStructOrUnion())
7462       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7463 
7464     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7465       if (OrigDC == CurContext) {
7466         Diag(Using->getLocation(),
7467              diag::err_using_decl_nested_name_specifier_is_current_class)
7468           << Using->getQualifierLoc().getSourceRange();
7469         Diag(Orig->getLocation(), diag::note_using_decl_target);
7470         return true;
7471       }
7472 
7473       Diag(Using->getQualifierLoc().getBeginLoc(),
7474            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7475         << Using->getQualifier()
7476         << cast<CXXRecordDecl>(CurContext)
7477         << Using->getQualifierLoc().getSourceRange();
7478       Diag(Orig->getLocation(), diag::note_using_decl_target);
7479       return true;
7480     }
7481   }
7482 
7483   if (Previous.empty()) return false;
7484 
7485   NamedDecl *Target = Orig;
7486   if (isa<UsingShadowDecl>(Target))
7487     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7488 
7489   // If the target happens to be one of the previous declarations, we
7490   // don't have a conflict.
7491   //
7492   // FIXME: but we might be increasing its access, in which case we
7493   // should redeclare it.
7494   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7495   bool FoundEquivalentDecl = false;
7496   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7497          I != E; ++I) {
7498     NamedDecl *D = (*I)->getUnderlyingDecl();
7499     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7500       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7501         PrevShadow = Shadow;
7502       FoundEquivalentDecl = true;
7503     }
7504 
7505     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7506   }
7507 
7508   if (FoundEquivalentDecl)
7509     return false;
7510 
7511   if (FunctionDecl *FD = Target->getAsFunction()) {
7512     NamedDecl *OldDecl = nullptr;
7513     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7514                           /*IsForUsingDecl*/ true)) {
7515     case Ovl_Overload:
7516       return false;
7517 
7518     case Ovl_NonFunction:
7519       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7520       break;
7521 
7522     // We found a decl with the exact signature.
7523     case Ovl_Match:
7524       // If we're in a record, we want to hide the target, so we
7525       // return true (without a diagnostic) to tell the caller not to
7526       // build a shadow decl.
7527       if (CurContext->isRecord())
7528         return true;
7529 
7530       // If we're not in a record, this is an error.
7531       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7532       break;
7533     }
7534 
7535     Diag(Target->getLocation(), diag::note_using_decl_target);
7536     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7537     return true;
7538   }
7539 
7540   // Target is not a function.
7541 
7542   if (isa<TagDecl>(Target)) {
7543     // No conflict between a tag and a non-tag.
7544     if (!Tag) return false;
7545 
7546     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7547     Diag(Target->getLocation(), diag::note_using_decl_target);
7548     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7549     return true;
7550   }
7551 
7552   // No conflict between a tag and a non-tag.
7553   if (!NonTag) return false;
7554 
7555   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7556   Diag(Target->getLocation(), diag::note_using_decl_target);
7557   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7558   return true;
7559 }
7560 
7561 /// Builds a shadow declaration corresponding to a 'using' declaration.
7562 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7563                                             UsingDecl *UD,
7564                                             NamedDecl *Orig,
7565                                             UsingShadowDecl *PrevDecl) {
7566 
7567   // If we resolved to another shadow declaration, just coalesce them.
7568   NamedDecl *Target = Orig;
7569   if (isa<UsingShadowDecl>(Target)) {
7570     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7571     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7572   }
7573 
7574   UsingShadowDecl *Shadow
7575     = UsingShadowDecl::Create(Context, CurContext,
7576                               UD->getLocation(), UD, Target);
7577   UD->addShadowDecl(Shadow);
7578 
7579   Shadow->setAccess(UD->getAccess());
7580   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7581     Shadow->setInvalidDecl();
7582 
7583   Shadow->setPreviousDecl(PrevDecl);
7584 
7585   if (S)
7586     PushOnScopeChains(Shadow, S);
7587   else
7588     CurContext->addDecl(Shadow);
7589 
7590 
7591   return Shadow;
7592 }
7593 
7594 /// Hides a using shadow declaration.  This is required by the current
7595 /// using-decl implementation when a resolvable using declaration in a
7596 /// class is followed by a declaration which would hide or override
7597 /// one or more of the using decl's targets; for example:
7598 ///
7599 ///   struct Base { void foo(int); };
7600 ///   struct Derived : Base {
7601 ///     using Base::foo;
7602 ///     void foo(int);
7603 ///   };
7604 ///
7605 /// The governing language is C++03 [namespace.udecl]p12:
7606 ///
7607 ///   When a using-declaration brings names from a base class into a
7608 ///   derived class scope, member functions in the derived class
7609 ///   override and/or hide member functions with the same name and
7610 ///   parameter types in a base class (rather than conflicting).
7611 ///
7612 /// There are two ways to implement this:
7613 ///   (1) optimistically create shadow decls when they're not hidden
7614 ///       by existing declarations, or
7615 ///   (2) don't create any shadow decls (or at least don't make them
7616 ///       visible) until we've fully parsed/instantiated the class.
7617 /// The problem with (1) is that we might have to retroactively remove
7618 /// a shadow decl, which requires several O(n) operations because the
7619 /// decl structures are (very reasonably) not designed for removal.
7620 /// (2) avoids this but is very fiddly and phase-dependent.
7621 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7622   if (Shadow->getDeclName().getNameKind() ==
7623         DeclarationName::CXXConversionFunctionName)
7624     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7625 
7626   // Remove it from the DeclContext...
7627   Shadow->getDeclContext()->removeDecl(Shadow);
7628 
7629   // ...and the scope, if applicable...
7630   if (S) {
7631     S->RemoveDecl(Shadow);
7632     IdResolver.RemoveDecl(Shadow);
7633   }
7634 
7635   // ...and the using decl.
7636   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7637 
7638   // TODO: complain somehow if Shadow was used.  It shouldn't
7639   // be possible for this to happen, because...?
7640 }
7641 
7642 /// Find the base specifier for a base class with the given type.
7643 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7644                                                 QualType DesiredBase,
7645                                                 bool &AnyDependentBases) {
7646   // Check whether the named type is a direct base class.
7647   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7648   for (auto &Base : Derived->bases()) {
7649     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7650     if (CanonicalDesiredBase == BaseType)
7651       return &Base;
7652     if (BaseType->isDependentType())
7653       AnyDependentBases = true;
7654   }
7655   return nullptr;
7656 }
7657 
7658 namespace {
7659 class UsingValidatorCCC : public CorrectionCandidateCallback {
7660 public:
7661   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7662                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7663       : HasTypenameKeyword(HasTypenameKeyword),
7664         IsInstantiation(IsInstantiation), OldNNS(NNS),
7665         RequireMemberOf(RequireMemberOf) {}
7666 
7667   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7668     NamedDecl *ND = Candidate.getCorrectionDecl();
7669 
7670     // Keywords are not valid here.
7671     if (!ND || isa<NamespaceDecl>(ND))
7672       return false;
7673 
7674     // Completely unqualified names are invalid for a 'using' declaration.
7675     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7676       return false;
7677 
7678     if (RequireMemberOf) {
7679       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7680       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7681         // No-one ever wants a using-declaration to name an injected-class-name
7682         // of a base class, unless they're declaring an inheriting constructor.
7683         ASTContext &Ctx = ND->getASTContext();
7684         if (!Ctx.getLangOpts().CPlusPlus11)
7685           return false;
7686         QualType FoundType = Ctx.getRecordType(FoundRecord);
7687 
7688         // Check that the injected-class-name is named as a member of its own
7689         // type; we don't want to suggest 'using Derived::Base;', since that
7690         // means something else.
7691         NestedNameSpecifier *Specifier =
7692             Candidate.WillReplaceSpecifier()
7693                 ? Candidate.getCorrectionSpecifier()
7694                 : OldNNS;
7695         if (!Specifier->getAsType() ||
7696             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7697           return false;
7698 
7699         // Check that this inheriting constructor declaration actually names a
7700         // direct base class of the current class.
7701         bool AnyDependentBases = false;
7702         if (!findDirectBaseWithType(RequireMemberOf,
7703                                     Ctx.getRecordType(FoundRecord),
7704                                     AnyDependentBases) &&
7705             !AnyDependentBases)
7706           return false;
7707       } else {
7708         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7709         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7710           return false;
7711 
7712         // FIXME: Check that the base class member is accessible?
7713       }
7714     }
7715 
7716     if (isa<TypeDecl>(ND))
7717       return HasTypenameKeyword || !IsInstantiation;
7718 
7719     return !HasTypenameKeyword;
7720   }
7721 
7722 private:
7723   bool HasTypenameKeyword;
7724   bool IsInstantiation;
7725   NestedNameSpecifier *OldNNS;
7726   CXXRecordDecl *RequireMemberOf;
7727 };
7728 } // end anonymous namespace
7729 
7730 /// Builds a using declaration.
7731 ///
7732 /// \param IsInstantiation - Whether this call arises from an
7733 ///   instantiation of an unresolved using declaration.  We treat
7734 ///   the lookup differently for these declarations.
7735 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7736                                        SourceLocation UsingLoc,
7737                                        CXXScopeSpec &SS,
7738                                        DeclarationNameInfo NameInfo,
7739                                        AttributeList *AttrList,
7740                                        bool IsInstantiation,
7741                                        bool HasTypenameKeyword,
7742                                        SourceLocation TypenameLoc) {
7743   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7744   SourceLocation IdentLoc = NameInfo.getLoc();
7745   assert(IdentLoc.isValid() && "Invalid TargetName location.");
7746 
7747   // FIXME: We ignore attributes for now.
7748 
7749   if (SS.isEmpty()) {
7750     Diag(IdentLoc, diag::err_using_requires_qualname);
7751     return nullptr;
7752   }
7753 
7754   // Do the redeclaration lookup in the current scope.
7755   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7756                         ForRedeclaration);
7757   Previous.setHideTags(false);
7758   if (S) {
7759     LookupName(Previous, S);
7760 
7761     // It is really dumb that we have to do this.
7762     LookupResult::Filter F = Previous.makeFilter();
7763     while (F.hasNext()) {
7764       NamedDecl *D = F.next();
7765       if (!isDeclInScope(D, CurContext, S))
7766         F.erase();
7767       // If we found a local extern declaration that's not ordinarily visible,
7768       // and this declaration is being added to a non-block scope, ignore it.
7769       // We're only checking for scope conflicts here, not also for violations
7770       // of the linkage rules.
7771       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7772                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7773         F.erase();
7774     }
7775     F.done();
7776   } else {
7777     assert(IsInstantiation && "no scope in non-instantiation");
7778     assert(CurContext->isRecord() && "scope not record in instantiation");
7779     LookupQualifiedName(Previous, CurContext);
7780   }
7781 
7782   // Check for invalid redeclarations.
7783   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7784                                   SS, IdentLoc, Previous))
7785     return nullptr;
7786 
7787   // Check for bad qualifiers.
7788   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
7789     return nullptr;
7790 
7791   DeclContext *LookupContext = computeDeclContext(SS);
7792   NamedDecl *D;
7793   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7794   if (!LookupContext) {
7795     if (HasTypenameKeyword) {
7796       // FIXME: not all declaration name kinds are legal here
7797       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7798                                               UsingLoc, TypenameLoc,
7799                                               QualifierLoc,
7800                                               IdentLoc, NameInfo.getName());
7801     } else {
7802       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7803                                            QualifierLoc, NameInfo);
7804     }
7805     D->setAccess(AS);
7806     CurContext->addDecl(D);
7807     return D;
7808   }
7809 
7810   auto Build = [&](bool Invalid) {
7811     UsingDecl *UD =
7812         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7813                           HasTypenameKeyword);
7814     UD->setAccess(AS);
7815     CurContext->addDecl(UD);
7816     UD->setInvalidDecl(Invalid);
7817     return UD;
7818   };
7819   auto BuildInvalid = [&]{ return Build(true); };
7820   auto BuildValid = [&]{ return Build(false); };
7821 
7822   if (RequireCompleteDeclContext(SS, LookupContext))
7823     return BuildInvalid();
7824 
7825   // The normal rules do not apply to inheriting constructor declarations.
7826   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7827     UsingDecl *UD = BuildValid();
7828     CheckInheritingConstructorUsingDecl(UD);
7829     return UD;
7830   }
7831 
7832   // Otherwise, look up the target name.
7833 
7834   LookupResult R(*this, NameInfo, LookupOrdinaryName);
7835 
7836   // Unlike most lookups, we don't always want to hide tag
7837   // declarations: tag names are visible through the using declaration
7838   // even if hidden by ordinary names, *except* in a dependent context
7839   // where it's important for the sanity of two-phase lookup.
7840   if (!IsInstantiation)
7841     R.setHideTags(false);
7842 
7843   // For the purposes of this lookup, we have a base object type
7844   // equal to that of the current context.
7845   if (CurContext->isRecord()) {
7846     R.setBaseObjectType(
7847                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7848   }
7849 
7850   LookupQualifiedName(R, LookupContext);
7851 
7852   // Try to correct typos if possible.
7853   if (R.empty()) {
7854     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
7855                           dyn_cast<CXXRecordDecl>(CurContext));
7856     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7857                                                R.getLookupKind(), S, &SS, CCC,
7858                                                CTK_ErrorRecovery)){
7859       // We reject any correction for which ND would be NULL.
7860       NamedDecl *ND = Corrected.getCorrectionDecl();
7861 
7862       // We reject candidates where DroppedSpecifier == true, hence the
7863       // literal '0' below.
7864       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7865                                 << NameInfo.getName() << LookupContext << 0
7866                                 << SS.getRange());
7867 
7868       // If we corrected to an inheriting constructor, handle it as one.
7869       auto *RD = dyn_cast<CXXRecordDecl>(ND);
7870       if (RD && RD->isInjectedClassName()) {
7871         // Fix up the information we'll use to build the using declaration.
7872         if (Corrected.WillReplaceSpecifier()) {
7873           NestedNameSpecifierLocBuilder Builder;
7874           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7875                               QualifierLoc.getSourceRange());
7876           QualifierLoc = Builder.getWithLocInContext(Context);
7877         }
7878 
7879         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7880             Context.getCanonicalType(Context.getRecordType(RD))));
7881         NameInfo.setNamedTypeInfo(nullptr);
7882 
7883         // Build it and process it as an inheriting constructor.
7884         UsingDecl *UD = BuildValid();
7885         CheckInheritingConstructorUsingDecl(UD);
7886         return UD;
7887       }
7888 
7889       // FIXME: Pick up all the declarations if we found an overloaded function.
7890       R.setLookupName(Corrected.getCorrection());
7891       R.addDecl(ND);
7892     } else {
7893       Diag(IdentLoc, diag::err_no_member)
7894         << NameInfo.getName() << LookupContext << SS.getRange();
7895       return BuildInvalid();
7896     }
7897   }
7898 
7899   if (R.isAmbiguous())
7900     return BuildInvalid();
7901 
7902   if (HasTypenameKeyword) {
7903     // If we asked for a typename and got a non-type decl, error out.
7904     if (!R.getAsSingle<TypeDecl>()) {
7905       Diag(IdentLoc, diag::err_using_typename_non_type);
7906       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7907         Diag((*I)->getUnderlyingDecl()->getLocation(),
7908              diag::note_using_decl_target);
7909       return BuildInvalid();
7910     }
7911   } else {
7912     // If we asked for a non-typename and we got a type, error out,
7913     // but only if this is an instantiation of an unresolved using
7914     // decl.  Otherwise just silently find the type name.
7915     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7916       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7917       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7918       return BuildInvalid();
7919     }
7920   }
7921 
7922   // C++0x N2914 [namespace.udecl]p6:
7923   // A using-declaration shall not name a namespace.
7924   if (R.getAsSingle<NamespaceDecl>()) {
7925     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7926       << SS.getRange();
7927     return BuildInvalid();
7928   }
7929 
7930   UsingDecl *UD = BuildValid();
7931   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7932     UsingShadowDecl *PrevDecl = nullptr;
7933     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7934       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7935   }
7936 
7937   return UD;
7938 }
7939 
7940 /// Additional checks for a using declaration referring to a constructor name.
7941 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7942   assert(!UD->hasTypename() && "expecting a constructor name");
7943 
7944   const Type *SourceType = UD->getQualifier()->getAsType();
7945   assert(SourceType &&
7946          "Using decl naming constructor doesn't have type in scope spec.");
7947   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7948 
7949   // Check whether the named type is a direct base class.
7950   bool AnyDependentBases = false;
7951   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7952                                       AnyDependentBases);
7953   if (!Base && !AnyDependentBases) {
7954     Diag(UD->getUsingLoc(),
7955          diag::err_using_decl_constructor_not_in_direct_base)
7956       << UD->getNameInfo().getSourceRange()
7957       << QualType(SourceType, 0) << TargetClass;
7958     UD->setInvalidDecl();
7959     return true;
7960   }
7961 
7962   if (Base)
7963     Base->setInheritConstructors();
7964 
7965   return false;
7966 }
7967 
7968 /// Checks that the given using declaration is not an invalid
7969 /// redeclaration.  Note that this is checking only for the using decl
7970 /// itself, not for any ill-formedness among the UsingShadowDecls.
7971 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7972                                        bool HasTypenameKeyword,
7973                                        const CXXScopeSpec &SS,
7974                                        SourceLocation NameLoc,
7975                                        const LookupResult &Prev) {
7976   // C++03 [namespace.udecl]p8:
7977   // C++0x [namespace.udecl]p10:
7978   //   A using-declaration is a declaration and can therefore be used
7979   //   repeatedly where (and only where) multiple declarations are
7980   //   allowed.
7981   //
7982   // That's in non-member contexts.
7983   if (!CurContext->getRedeclContext()->isRecord())
7984     return false;
7985 
7986   NestedNameSpecifier *Qual = SS.getScopeRep();
7987 
7988   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7989     NamedDecl *D = *I;
7990 
7991     bool DTypename;
7992     NestedNameSpecifier *DQual;
7993     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7994       DTypename = UD->hasTypename();
7995       DQual = UD->getQualifier();
7996     } else if (UnresolvedUsingValueDecl *UD
7997                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7998       DTypename = false;
7999       DQual = UD->getQualifier();
8000     } else if (UnresolvedUsingTypenameDecl *UD
8001                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8002       DTypename = true;
8003       DQual = UD->getQualifier();
8004     } else continue;
8005 
8006     // using decls differ if one says 'typename' and the other doesn't.
8007     // FIXME: non-dependent using decls?
8008     if (HasTypenameKeyword != DTypename) continue;
8009 
8010     // using decls differ if they name different scopes (but note that
8011     // template instantiation can cause this check to trigger when it
8012     // didn't before instantiation).
8013     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8014         Context.getCanonicalNestedNameSpecifier(DQual))
8015       continue;
8016 
8017     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8018     Diag(D->getLocation(), diag::note_using_decl) << 1;
8019     return true;
8020   }
8021 
8022   return false;
8023 }
8024 
8025 
8026 /// Checks that the given nested-name qualifier used in a using decl
8027 /// in the current context is appropriately related to the current
8028 /// scope.  If an error is found, diagnoses it and returns true.
8029 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8030                                    const CXXScopeSpec &SS,
8031                                    const DeclarationNameInfo &NameInfo,
8032                                    SourceLocation NameLoc) {
8033   DeclContext *NamedContext = computeDeclContext(SS);
8034 
8035   if (!CurContext->isRecord()) {
8036     // C++03 [namespace.udecl]p3:
8037     // C++0x [namespace.udecl]p8:
8038     //   A using-declaration for a class member shall be a member-declaration.
8039 
8040     // If we weren't able to compute a valid scope, it must be a
8041     // dependent class scope.
8042     if (!NamedContext || NamedContext->isRecord()) {
8043       auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
8044       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8045         RD = nullptr;
8046 
8047       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8048         << SS.getRange();
8049 
8050       // If we have a complete, non-dependent source type, try to suggest a
8051       // way to get the same effect.
8052       if (!RD)
8053         return true;
8054 
8055       // Find what this using-declaration was referring to.
8056       LookupResult R(*this, NameInfo, LookupOrdinaryName);
8057       R.setHideTags(false);
8058       R.suppressDiagnostics();
8059       LookupQualifiedName(R, RD);
8060 
8061       if (R.getAsSingle<TypeDecl>()) {
8062         if (getLangOpts().CPlusPlus11) {
8063           // Convert 'using X::Y;' to 'using Y = X::Y;'.
8064           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8065             << 0 // alias declaration
8066             << FixItHint::CreateInsertion(SS.getBeginLoc(),
8067                                           NameInfo.getName().getAsString() +
8068                                               " = ");
8069         } else {
8070           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8071           SourceLocation InsertLoc =
8072               PP.getLocForEndOfToken(NameInfo.getLocEnd());
8073           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8074             << 1 // typedef declaration
8075             << FixItHint::CreateReplacement(UsingLoc, "typedef")
8076             << FixItHint::CreateInsertion(
8077                    InsertLoc, " " + NameInfo.getName().getAsString());
8078         }
8079       } else if (R.getAsSingle<VarDecl>()) {
8080         // Don't provide a fixit outside C++11 mode; we don't want to suggest
8081         // repeating the type of the static data member here.
8082         FixItHint FixIt;
8083         if (getLangOpts().CPlusPlus11) {
8084           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8085           FixIt = FixItHint::CreateReplacement(
8086               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8087         }
8088 
8089         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8090           << 2 // reference declaration
8091           << FixIt;
8092       }
8093       return true;
8094     }
8095 
8096     // Otherwise, everything is known to be fine.
8097     return false;
8098   }
8099 
8100   // The current scope is a record.
8101 
8102   // If the named context is dependent, we can't decide much.
8103   if (!NamedContext) {
8104     // FIXME: in C++0x, we can diagnose if we can prove that the
8105     // nested-name-specifier does not refer to a base class, which is
8106     // still possible in some cases.
8107 
8108     // Otherwise we have to conservatively report that things might be
8109     // okay.
8110     return false;
8111   }
8112 
8113   if (!NamedContext->isRecord()) {
8114     // Ideally this would point at the last name in the specifier,
8115     // but we don't have that level of source info.
8116     Diag(SS.getRange().getBegin(),
8117          diag::err_using_decl_nested_name_specifier_is_not_class)
8118       << SS.getScopeRep() << SS.getRange();
8119     return true;
8120   }
8121 
8122   if (!NamedContext->isDependentContext() &&
8123       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8124     return true;
8125 
8126   if (getLangOpts().CPlusPlus11) {
8127     // C++0x [namespace.udecl]p3:
8128     //   In a using-declaration used as a member-declaration, the
8129     //   nested-name-specifier shall name a base class of the class
8130     //   being defined.
8131 
8132     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8133                                  cast<CXXRecordDecl>(NamedContext))) {
8134       if (CurContext == NamedContext) {
8135         Diag(NameLoc,
8136              diag::err_using_decl_nested_name_specifier_is_current_class)
8137           << SS.getRange();
8138         return true;
8139       }
8140 
8141       Diag(SS.getRange().getBegin(),
8142            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8143         << SS.getScopeRep()
8144         << cast<CXXRecordDecl>(CurContext)
8145         << SS.getRange();
8146       return true;
8147     }
8148 
8149     return false;
8150   }
8151 
8152   // C++03 [namespace.udecl]p4:
8153   //   A using-declaration used as a member-declaration shall refer
8154   //   to a member of a base class of the class being defined [etc.].
8155 
8156   // Salient point: SS doesn't have to name a base class as long as
8157   // lookup only finds members from base classes.  Therefore we can
8158   // diagnose here only if we can prove that that can't happen,
8159   // i.e. if the class hierarchies provably don't intersect.
8160 
8161   // TODO: it would be nice if "definitely valid" results were cached
8162   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8163   // need to be repeated.
8164 
8165   struct UserData {
8166     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8167 
8168     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8169       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8170       Data->Bases.insert(Base);
8171       return true;
8172     }
8173 
8174     bool hasDependentBases(const CXXRecordDecl *Class) {
8175       return !Class->forallBases(collect, this);
8176     }
8177 
8178     /// Returns true if the base is dependent or is one of the
8179     /// accumulated base classes.
8180     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8181       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8182       return !Data->Bases.count(Base);
8183     }
8184 
8185     bool mightShareBases(const CXXRecordDecl *Class) {
8186       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8187     }
8188   };
8189 
8190   UserData Data;
8191 
8192   // Returns false if we find a dependent base.
8193   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8194     return false;
8195 
8196   // Returns false if the class has a dependent base or if it or one
8197   // of its bases is present in the base set of the current context.
8198   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8199     return false;
8200 
8201   Diag(SS.getRange().getBegin(),
8202        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8203     << SS.getScopeRep()
8204     << cast<CXXRecordDecl>(CurContext)
8205     << SS.getRange();
8206 
8207   return true;
8208 }
8209 
8210 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8211                                   AccessSpecifier AS,
8212                                   MultiTemplateParamsArg TemplateParamLists,
8213                                   SourceLocation UsingLoc,
8214                                   UnqualifiedId &Name,
8215                                   AttributeList *AttrList,
8216                                   TypeResult Type) {
8217   // Skip up to the relevant declaration scope.
8218   while (S->getFlags() & Scope::TemplateParamScope)
8219     S = S->getParent();
8220   assert((S->getFlags() & Scope::DeclScope) &&
8221          "got alias-declaration outside of declaration scope");
8222 
8223   if (Type.isInvalid())
8224     return nullptr;
8225 
8226   bool Invalid = false;
8227   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8228   TypeSourceInfo *TInfo = nullptr;
8229   GetTypeFromParser(Type.get(), &TInfo);
8230 
8231   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8232     return nullptr;
8233 
8234   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8235                                       UPPC_DeclarationType)) {
8236     Invalid = true;
8237     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8238                                              TInfo->getTypeLoc().getBeginLoc());
8239   }
8240 
8241   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8242   LookupName(Previous, S);
8243 
8244   // Warn about shadowing the name of a template parameter.
8245   if (Previous.isSingleResult() &&
8246       Previous.getFoundDecl()->isTemplateParameter()) {
8247     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8248     Previous.clear();
8249   }
8250 
8251   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8252          "name in alias declaration must be an identifier");
8253   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8254                                                Name.StartLocation,
8255                                                Name.Identifier, TInfo);
8256 
8257   NewTD->setAccess(AS);
8258 
8259   if (Invalid)
8260     NewTD->setInvalidDecl();
8261 
8262   ProcessDeclAttributeList(S, NewTD, AttrList);
8263 
8264   CheckTypedefForVariablyModifiedType(S, NewTD);
8265   Invalid |= NewTD->isInvalidDecl();
8266 
8267   bool Redeclaration = false;
8268 
8269   NamedDecl *NewND;
8270   if (TemplateParamLists.size()) {
8271     TypeAliasTemplateDecl *OldDecl = nullptr;
8272     TemplateParameterList *OldTemplateParams = nullptr;
8273 
8274     if (TemplateParamLists.size() != 1) {
8275       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8276         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8277          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8278     }
8279     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8280 
8281     // Only consider previous declarations in the same scope.
8282     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8283                          /*ExplicitInstantiationOrSpecialization*/false);
8284     if (!Previous.empty()) {
8285       Redeclaration = true;
8286 
8287       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8288       if (!OldDecl && !Invalid) {
8289         Diag(UsingLoc, diag::err_redefinition_different_kind)
8290           << Name.Identifier;
8291 
8292         NamedDecl *OldD = Previous.getRepresentativeDecl();
8293         if (OldD->getLocation().isValid())
8294           Diag(OldD->getLocation(), diag::note_previous_definition);
8295 
8296         Invalid = true;
8297       }
8298 
8299       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8300         if (TemplateParameterListsAreEqual(TemplateParams,
8301                                            OldDecl->getTemplateParameters(),
8302                                            /*Complain=*/true,
8303                                            TPL_TemplateMatch))
8304           OldTemplateParams = OldDecl->getTemplateParameters();
8305         else
8306           Invalid = true;
8307 
8308         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8309         if (!Invalid &&
8310             !Context.hasSameType(OldTD->getUnderlyingType(),
8311                                  NewTD->getUnderlyingType())) {
8312           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8313           // but we can't reasonably accept it.
8314           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8315             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8316           if (OldTD->getLocation().isValid())
8317             Diag(OldTD->getLocation(), diag::note_previous_definition);
8318           Invalid = true;
8319         }
8320       }
8321     }
8322 
8323     // Merge any previous default template arguments into our parameters,
8324     // and check the parameter list.
8325     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8326                                    TPC_TypeAliasTemplate))
8327       return nullptr;
8328 
8329     TypeAliasTemplateDecl *NewDecl =
8330       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8331                                     Name.Identifier, TemplateParams,
8332                                     NewTD);
8333     NewTD->setDescribedAliasTemplate(NewDecl);
8334 
8335     NewDecl->setAccess(AS);
8336 
8337     if (Invalid)
8338       NewDecl->setInvalidDecl();
8339     else if (OldDecl)
8340       NewDecl->setPreviousDecl(OldDecl);
8341 
8342     NewND = NewDecl;
8343   } else {
8344     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8345     NewND = NewTD;
8346   }
8347 
8348   if (!Redeclaration)
8349     PushOnScopeChains(NewND, S);
8350 
8351   ActOnDocumentableDecl(NewND);
8352   return NewND;
8353 }
8354 
8355 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8356                                    SourceLocation AliasLoc,
8357                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
8358                                    SourceLocation IdentLoc,
8359                                    IdentifierInfo *Ident) {
8360 
8361   // Lookup the namespace name.
8362   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8363   LookupParsedName(R, S, &SS);
8364 
8365   if (R.isAmbiguous())
8366     return nullptr;
8367 
8368   if (R.empty()) {
8369     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8370       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8371       return nullptr;
8372     }
8373   }
8374   assert(!R.isAmbiguous() && !R.empty());
8375 
8376   // Check if we have a previous declaration with the same name.
8377   NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8378                                          ForRedeclaration);
8379   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8380     PrevDecl = nullptr;
8381 
8382   if (PrevDecl) {
8383     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8384       // We already have an alias with the same name that points to the same
8385       // namespace; check that it matches.
8386       if (!AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) {
8387         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8388           << Alias;
8389         Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8390           << AD->getNamespace();
8391         return nullptr;
8392       }
8393     } else {
8394       unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8395                             ? diag::err_redefinition
8396                             : diag::err_redefinition_different_kind;
8397       Diag(AliasLoc, DiagID) << Alias;
8398       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8399       return nullptr;
8400     }
8401   }
8402 
8403   NamespaceAliasDecl *AliasDecl =
8404     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8405                                Alias, SS.getWithLocInContext(Context),
8406                                IdentLoc, R.getFoundDecl());
8407   if (PrevDecl)
8408     AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
8409 
8410   PushOnScopeChains(AliasDecl, S);
8411   return AliasDecl;
8412 }
8413 
8414 Sema::ImplicitExceptionSpecification
8415 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8416                                                CXXMethodDecl *MD) {
8417   CXXRecordDecl *ClassDecl = MD->getParent();
8418 
8419   // C++ [except.spec]p14:
8420   //   An implicitly declared special member function (Clause 12) shall have an
8421   //   exception-specification. [...]
8422   ImplicitExceptionSpecification ExceptSpec(*this);
8423   if (ClassDecl->isInvalidDecl())
8424     return ExceptSpec;
8425 
8426   // Direct base-class constructors.
8427   for (const auto &B : ClassDecl->bases()) {
8428     if (B.isVirtual()) // Handled below.
8429       continue;
8430 
8431     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8432       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8433       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8434       // If this is a deleted function, add it anyway. This might be conformant
8435       // with the standard. This might not. I'm not sure. It might not matter.
8436       if (Constructor)
8437         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8438     }
8439   }
8440 
8441   // Virtual base-class constructors.
8442   for (const auto &B : ClassDecl->vbases()) {
8443     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8444       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8445       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8446       // If this is a deleted function, add it anyway. This might be conformant
8447       // with the standard. This might not. I'm not sure. It might not matter.
8448       if (Constructor)
8449         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8450     }
8451   }
8452 
8453   // Field constructors.
8454   for (const auto *F : ClassDecl->fields()) {
8455     if (F->hasInClassInitializer()) {
8456       if (Expr *E = F->getInClassInitializer())
8457         ExceptSpec.CalledExpr(E);
8458       else if (!F->isInvalidDecl())
8459         // DR1351:
8460         //   If the brace-or-equal-initializer of a non-static data member
8461         //   invokes a defaulted default constructor of its class or of an
8462         //   enclosing class in a potentially evaluated subexpression, the
8463         //   program is ill-formed.
8464         //
8465         // This resolution is unworkable: the exception specification of the
8466         // default constructor can be needed in an unevaluated context, in
8467         // particular, in the operand of a noexcept-expression, and we can be
8468         // unable to compute an exception specification for an enclosed class.
8469         //
8470         // We do not allow an in-class initializer to require the evaluation
8471         // of the exception specification for any in-class initializer whose
8472         // definition is not lexically complete.
8473         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
8474     } else if (const RecordType *RecordTy
8475               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8476       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8477       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8478       // If this is a deleted function, add it anyway. This might be conformant
8479       // with the standard. This might not. I'm not sure. It might not matter.
8480       // In particular, the problem is that this function never gets called. It
8481       // might just be ill-formed because this function attempts to refer to
8482       // a deleted function here.
8483       if (Constructor)
8484         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8485     }
8486   }
8487 
8488   return ExceptSpec;
8489 }
8490 
8491 Sema::ImplicitExceptionSpecification
8492 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8493   CXXRecordDecl *ClassDecl = CD->getParent();
8494 
8495   // C++ [except.spec]p14:
8496   //   An inheriting constructor [...] shall have an exception-specification. [...]
8497   ImplicitExceptionSpecification ExceptSpec(*this);
8498   if (ClassDecl->isInvalidDecl())
8499     return ExceptSpec;
8500 
8501   // Inherited constructor.
8502   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8503   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8504   // FIXME: Copying or moving the parameters could add extra exceptions to the
8505   // set, as could the default arguments for the inherited constructor. This
8506   // will be addressed when we implement the resolution of core issue 1351.
8507   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8508 
8509   // Direct base-class constructors.
8510   for (const auto &B : ClassDecl->bases()) {
8511     if (B.isVirtual()) // Handled below.
8512       continue;
8513 
8514     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8515       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8516       if (BaseClassDecl == InheritedDecl)
8517         continue;
8518       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8519       if (Constructor)
8520         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8521     }
8522   }
8523 
8524   // Virtual base-class constructors.
8525   for (const auto &B : ClassDecl->vbases()) {
8526     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8527       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8528       if (BaseClassDecl == InheritedDecl)
8529         continue;
8530       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8531       if (Constructor)
8532         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8533     }
8534   }
8535 
8536   // Field constructors.
8537   for (const auto *F : ClassDecl->fields()) {
8538     if (F->hasInClassInitializer()) {
8539       if (Expr *E = F->getInClassInitializer())
8540         ExceptSpec.CalledExpr(E);
8541       else if (!F->isInvalidDecl())
8542         Diag(CD->getLocation(),
8543              diag::err_in_class_initializer_references_def_ctor) << CD;
8544     } else if (const RecordType *RecordTy
8545               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8546       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8547       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8548       if (Constructor)
8549         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8550     }
8551   }
8552 
8553   return ExceptSpec;
8554 }
8555 
8556 namespace {
8557 /// RAII object to register a special member as being currently declared.
8558 struct DeclaringSpecialMember {
8559   Sema &S;
8560   Sema::SpecialMemberDecl D;
8561   bool WasAlreadyBeingDeclared;
8562 
8563   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8564     : S(S), D(RD, CSM) {
8565     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8566     if (WasAlreadyBeingDeclared)
8567       // This almost never happens, but if it does, ensure that our cache
8568       // doesn't contain a stale result.
8569       S.SpecialMemberCache.clear();
8570 
8571     // FIXME: Register a note to be produced if we encounter an error while
8572     // declaring the special member.
8573   }
8574   ~DeclaringSpecialMember() {
8575     if (!WasAlreadyBeingDeclared)
8576       S.SpecialMembersBeingDeclared.erase(D);
8577   }
8578 
8579   /// \brief Are we already trying to declare this special member?
8580   bool isAlreadyBeingDeclared() const {
8581     return WasAlreadyBeingDeclared;
8582   }
8583 };
8584 }
8585 
8586 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8587                                                      CXXRecordDecl *ClassDecl) {
8588   // C++ [class.ctor]p5:
8589   //   A default constructor for a class X is a constructor of class X
8590   //   that can be called without an argument. If there is no
8591   //   user-declared constructor for class X, a default constructor is
8592   //   implicitly declared. An implicitly-declared default constructor
8593   //   is an inline public member of its class.
8594   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8595          "Should not build implicit default constructor!");
8596 
8597   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8598   if (DSM.isAlreadyBeingDeclared())
8599     return nullptr;
8600 
8601   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8602                                                      CXXDefaultConstructor,
8603                                                      false);
8604 
8605   // Create the actual constructor declaration.
8606   CanQualType ClassType
8607     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8608   SourceLocation ClassLoc = ClassDecl->getLocation();
8609   DeclarationName Name
8610     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8611   DeclarationNameInfo NameInfo(Name, ClassLoc);
8612   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8613       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8614       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8615       /*isImplicitlyDeclared=*/true, Constexpr);
8616   DefaultCon->setAccess(AS_public);
8617   DefaultCon->setDefaulted();
8618 
8619   if (getLangOpts().CUDA) {
8620     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8621                                             DefaultCon,
8622                                             /* ConstRHS */ false,
8623                                             /* Diagnose */ false);
8624   }
8625 
8626   // Build an exception specification pointing back at this constructor.
8627   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8628   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8629 
8630   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8631   // constructors is easy to compute.
8632   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8633 
8634   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8635     SetDeclDeleted(DefaultCon, ClassLoc);
8636 
8637   // Note that we have declared this constructor.
8638   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8639 
8640   if (Scope *S = getScopeForContext(ClassDecl))
8641     PushOnScopeChains(DefaultCon, S, false);
8642   ClassDecl->addDecl(DefaultCon);
8643 
8644   return DefaultCon;
8645 }
8646 
8647 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8648                                             CXXConstructorDecl *Constructor) {
8649   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8650           !Constructor->doesThisDeclarationHaveABody() &&
8651           !Constructor->isDeleted()) &&
8652     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8653 
8654   CXXRecordDecl *ClassDecl = Constructor->getParent();
8655   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8656 
8657   SynthesizedFunctionScope Scope(*this, Constructor);
8658   DiagnosticErrorTrap Trap(Diags);
8659   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8660       Trap.hasErrorOccurred()) {
8661     Diag(CurrentLocation, diag::note_member_synthesized_at)
8662       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8663     Constructor->setInvalidDecl();
8664     return;
8665   }
8666 
8667   // The exception specification is needed because we are defining the
8668   // function.
8669   ResolveExceptionSpec(CurrentLocation,
8670                        Constructor->getType()->castAs<FunctionProtoType>());
8671 
8672   SourceLocation Loc = Constructor->getLocEnd().isValid()
8673                            ? Constructor->getLocEnd()
8674                            : Constructor->getLocation();
8675   Constructor->setBody(new (Context) CompoundStmt(Loc));
8676 
8677   Constructor->markUsed(Context);
8678   MarkVTableUsed(CurrentLocation, ClassDecl);
8679 
8680   if (ASTMutationListener *L = getASTMutationListener()) {
8681     L->CompletedImplicitDefinition(Constructor);
8682   }
8683 
8684   DiagnoseUninitializedFields(*this, Constructor);
8685 }
8686 
8687 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8688   // Perform any delayed checks on exception specifications.
8689   CheckDelayedMemberExceptionSpecs();
8690 }
8691 
8692 namespace {
8693 /// Information on inheriting constructors to declare.
8694 class InheritingConstructorInfo {
8695 public:
8696   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8697       : SemaRef(SemaRef), Derived(Derived) {
8698     // Mark the constructors that we already have in the derived class.
8699     //
8700     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8701     //   unless there is a user-declared constructor with the same signature in
8702     //   the class where the using-declaration appears.
8703     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8704   }
8705 
8706   void inheritAll(CXXRecordDecl *RD) {
8707     visitAll(RD, &InheritingConstructorInfo::inherit);
8708   }
8709 
8710 private:
8711   /// Information about an inheriting constructor.
8712   struct InheritingConstructor {
8713     InheritingConstructor()
8714       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
8715 
8716     /// If \c true, a constructor with this signature is already declared
8717     /// in the derived class.
8718     bool DeclaredInDerived;
8719 
8720     /// The constructor which is inherited.
8721     const CXXConstructorDecl *BaseCtor;
8722 
8723     /// The derived constructor we declared.
8724     CXXConstructorDecl *DerivedCtor;
8725   };
8726 
8727   /// Inheriting constructors with a given canonical type. There can be at
8728   /// most one such non-template constructor, and any number of templated
8729   /// constructors.
8730   struct InheritingConstructorsForType {
8731     InheritingConstructor NonTemplate;
8732     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8733         Templates;
8734 
8735     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8736       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8737         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8738         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8739           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8740                                                false, S.TPL_TemplateMatch))
8741             return Templates[I].second;
8742         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8743         return Templates.back().second;
8744       }
8745 
8746       return NonTemplate;
8747     }
8748   };
8749 
8750   /// Get or create the inheriting constructor record for a constructor.
8751   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8752                                   QualType CtorType) {
8753     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8754         .getEntry(SemaRef, Ctor);
8755   }
8756 
8757   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8758 
8759   /// Process all constructors for a class.
8760   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8761     for (const auto *Ctor : RD->ctors())
8762       (this->*Callback)(Ctor);
8763     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8764              I(RD->decls_begin()), E(RD->decls_end());
8765          I != E; ++I) {
8766       const FunctionDecl *FD = (*I)->getTemplatedDecl();
8767       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8768         (this->*Callback)(CD);
8769     }
8770   }
8771 
8772   /// Note that a constructor (or constructor template) was declared in Derived.
8773   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8774     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8775   }
8776 
8777   /// Inherit a single constructor.
8778   void inherit(const CXXConstructorDecl *Ctor) {
8779     const FunctionProtoType *CtorType =
8780         Ctor->getType()->castAs<FunctionProtoType>();
8781     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
8782     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8783 
8784     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8785 
8786     // Core issue (no number yet): the ellipsis is always discarded.
8787     if (EPI.Variadic) {
8788       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8789       SemaRef.Diag(Ctor->getLocation(),
8790                    diag::note_using_decl_constructor_ellipsis);
8791       EPI.Variadic = false;
8792     }
8793 
8794     // Declare a constructor for each number of parameters.
8795     //
8796     // C++11 [class.inhctor]p1:
8797     //   The candidate set of inherited constructors from the class X named in
8798     //   the using-declaration consists of [... modulo defects ...] for each
8799     //   constructor or constructor template of X, the set of constructors or
8800     //   constructor templates that results from omitting any ellipsis parameter
8801     //   specification and successively omitting parameters with a default
8802     //   argument from the end of the parameter-type-list
8803     unsigned MinParams = minParamsToInherit(Ctor);
8804     unsigned Params = Ctor->getNumParams();
8805     if (Params >= MinParams) {
8806       do
8807         declareCtor(UsingLoc, Ctor,
8808                     SemaRef.Context.getFunctionType(
8809                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
8810       while (Params > MinParams &&
8811              Ctor->getParamDecl(--Params)->hasDefaultArg());
8812     }
8813   }
8814 
8815   /// Find the using-declaration which specified that we should inherit the
8816   /// constructors of \p Base.
8817   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8818     // No fancy lookup required; just look for the base constructor name
8819     // directly within the derived class.
8820     ASTContext &Context = SemaRef.Context;
8821     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8822         Context.getCanonicalType(Context.getRecordType(Base)));
8823     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8824     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8825   }
8826 
8827   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8828     // C++11 [class.inhctor]p3:
8829     //   [F]or each constructor template in the candidate set of inherited
8830     //   constructors, a constructor template is implicitly declared
8831     if (Ctor->getDescribedFunctionTemplate())
8832       return 0;
8833 
8834     //   For each non-template constructor in the candidate set of inherited
8835     //   constructors other than a constructor having no parameters or a
8836     //   copy/move constructor having a single parameter, a constructor is
8837     //   implicitly declared [...]
8838     if (Ctor->getNumParams() == 0)
8839       return 1;
8840     if (Ctor->isCopyOrMoveConstructor())
8841       return 2;
8842 
8843     // Per discussion on core reflector, never inherit a constructor which
8844     // would become a default, copy, or move constructor of Derived either.
8845     const ParmVarDecl *PD = Ctor->getParamDecl(0);
8846     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8847     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8848   }
8849 
8850   /// Declare a single inheriting constructor, inheriting the specified
8851   /// constructor, with the given type.
8852   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8853                    QualType DerivedType) {
8854     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8855 
8856     // C++11 [class.inhctor]p3:
8857     //   ... a constructor is implicitly declared with the same constructor
8858     //   characteristics unless there is a user-declared constructor with
8859     //   the same signature in the class where the using-declaration appears
8860     if (Entry.DeclaredInDerived)
8861       return;
8862 
8863     // C++11 [class.inhctor]p7:
8864     //   If two using-declarations declare inheriting constructors with the
8865     //   same signature, the program is ill-formed
8866     if (Entry.DerivedCtor) {
8867       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8868         // Only diagnose this once per constructor.
8869         if (Entry.DerivedCtor->isInvalidDecl())
8870           return;
8871         Entry.DerivedCtor->setInvalidDecl();
8872 
8873         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8874         SemaRef.Diag(BaseCtor->getLocation(),
8875                      diag::note_using_decl_constructor_conflict_current_ctor);
8876         SemaRef.Diag(Entry.BaseCtor->getLocation(),
8877                      diag::note_using_decl_constructor_conflict_previous_ctor);
8878         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8879                      diag::note_using_decl_constructor_conflict_previous_using);
8880       } else {
8881         // Core issue (no number): if the same inheriting constructor is
8882         // produced by multiple base class constructors from the same base
8883         // class, the inheriting constructor is defined as deleted.
8884         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8885       }
8886 
8887       return;
8888     }
8889 
8890     ASTContext &Context = SemaRef.Context;
8891     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8892         Context.getCanonicalType(Context.getRecordType(Derived)));
8893     DeclarationNameInfo NameInfo(Name, UsingLoc);
8894 
8895     TemplateParameterList *TemplateParams = nullptr;
8896     if (const FunctionTemplateDecl *FTD =
8897             BaseCtor->getDescribedFunctionTemplate()) {
8898       TemplateParams = FTD->getTemplateParameters();
8899       // We're reusing template parameters from a different DeclContext. This
8900       // is questionable at best, but works out because the template depth in
8901       // both places is guaranteed to be 0.
8902       // FIXME: Rebuild the template parameters in the new context, and
8903       // transform the function type to refer to them.
8904     }
8905 
8906     // Build type source info pointing at the using-declaration. This is
8907     // required by template instantiation.
8908     TypeSourceInfo *TInfo =
8909         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8910     FunctionProtoTypeLoc ProtoLoc =
8911         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8912 
8913     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8914         Context, Derived, UsingLoc, NameInfo, DerivedType,
8915         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8916         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8917 
8918     // Build an unevaluated exception specification for this constructor.
8919     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8920     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8921     EPI.ExceptionSpec.Type = EST_Unevaluated;
8922     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
8923     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
8924                                                  FPT->getParamTypes(), EPI));
8925 
8926     // Build the parameter declarations.
8927     SmallVector<ParmVarDecl *, 16> ParamDecls;
8928     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
8929       TypeSourceInfo *TInfo =
8930           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
8931       ParmVarDecl *PD = ParmVarDecl::Create(
8932           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8933           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
8934       PD->setScopeInfo(0, I);
8935       PD->setImplicit();
8936       ParamDecls.push_back(PD);
8937       ProtoLoc.setParam(I, PD);
8938     }
8939 
8940     // Set up the new constructor.
8941     DerivedCtor->setAccess(BaseCtor->getAccess());
8942     DerivedCtor->setParams(ParamDecls);
8943     DerivedCtor->setInheritedConstructor(BaseCtor);
8944     if (BaseCtor->isDeleted())
8945       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8946 
8947     // If this is a constructor template, build the template declaration.
8948     if (TemplateParams) {
8949       FunctionTemplateDecl *DerivedTemplate =
8950           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8951                                        TemplateParams, DerivedCtor);
8952       DerivedTemplate->setAccess(BaseCtor->getAccess());
8953       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8954       Derived->addDecl(DerivedTemplate);
8955     } else {
8956       Derived->addDecl(DerivedCtor);
8957     }
8958 
8959     Entry.BaseCtor = BaseCtor;
8960     Entry.DerivedCtor = DerivedCtor;
8961   }
8962 
8963   Sema &SemaRef;
8964   CXXRecordDecl *Derived;
8965   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8966   MapType Map;
8967 };
8968 }
8969 
8970 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8971   // Defer declaring the inheriting constructors until the class is
8972   // instantiated.
8973   if (ClassDecl->isDependentContext())
8974     return;
8975 
8976   // Find base classes from which we might inherit constructors.
8977   SmallVector<CXXRecordDecl*, 4> InheritedBases;
8978   for (const auto &BaseIt : ClassDecl->bases())
8979     if (BaseIt.getInheritConstructors())
8980       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
8981 
8982   // Go no further if we're not inheriting any constructors.
8983   if (InheritedBases.empty())
8984     return;
8985 
8986   // Declare the inherited constructors.
8987   InheritingConstructorInfo ICI(*this, ClassDecl);
8988   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8989     ICI.inheritAll(InheritedBases[I]);
8990 }
8991 
8992 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8993                                        CXXConstructorDecl *Constructor) {
8994   CXXRecordDecl *ClassDecl = Constructor->getParent();
8995   assert(Constructor->getInheritedConstructor() &&
8996          !Constructor->doesThisDeclarationHaveABody() &&
8997          !Constructor->isDeleted());
8998 
8999   SynthesizedFunctionScope Scope(*this, Constructor);
9000   DiagnosticErrorTrap Trap(Diags);
9001   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9002       Trap.hasErrorOccurred()) {
9003     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9004       << Context.getTagDeclType(ClassDecl);
9005     Constructor->setInvalidDecl();
9006     return;
9007   }
9008 
9009   SourceLocation Loc = Constructor->getLocation();
9010   Constructor->setBody(new (Context) CompoundStmt(Loc));
9011 
9012   Constructor->markUsed(Context);
9013   MarkVTableUsed(CurrentLocation, ClassDecl);
9014 
9015   if (ASTMutationListener *L = getASTMutationListener()) {
9016     L->CompletedImplicitDefinition(Constructor);
9017   }
9018 }
9019 
9020 
9021 Sema::ImplicitExceptionSpecification
9022 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9023   CXXRecordDecl *ClassDecl = MD->getParent();
9024 
9025   // C++ [except.spec]p14:
9026   //   An implicitly declared special member function (Clause 12) shall have
9027   //   an exception-specification.
9028   ImplicitExceptionSpecification ExceptSpec(*this);
9029   if (ClassDecl->isInvalidDecl())
9030     return ExceptSpec;
9031 
9032   // Direct base-class destructors.
9033   for (const auto &B : ClassDecl->bases()) {
9034     if (B.isVirtual()) // Handled below.
9035       continue;
9036 
9037     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9038       ExceptSpec.CalledDecl(B.getLocStart(),
9039                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9040   }
9041 
9042   // Virtual base-class destructors.
9043   for (const auto &B : ClassDecl->vbases()) {
9044     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9045       ExceptSpec.CalledDecl(B.getLocStart(),
9046                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9047   }
9048 
9049   // Field destructors.
9050   for (const auto *F : ClassDecl->fields()) {
9051     if (const RecordType *RecordTy
9052         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9053       ExceptSpec.CalledDecl(F->getLocation(),
9054                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9055   }
9056 
9057   return ExceptSpec;
9058 }
9059 
9060 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9061   // C++ [class.dtor]p2:
9062   //   If a class has no user-declared destructor, a destructor is
9063   //   declared implicitly. An implicitly-declared destructor is an
9064   //   inline public member of its class.
9065   assert(ClassDecl->needsImplicitDestructor());
9066 
9067   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9068   if (DSM.isAlreadyBeingDeclared())
9069     return nullptr;
9070 
9071   // Create the actual destructor declaration.
9072   CanQualType ClassType
9073     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9074   SourceLocation ClassLoc = ClassDecl->getLocation();
9075   DeclarationName Name
9076     = Context.DeclarationNames.getCXXDestructorName(ClassType);
9077   DeclarationNameInfo NameInfo(Name, ClassLoc);
9078   CXXDestructorDecl *Destructor
9079       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9080                                   QualType(), nullptr, /*isInline=*/true,
9081                                   /*isImplicitlyDeclared=*/true);
9082   Destructor->setAccess(AS_public);
9083   Destructor->setDefaulted();
9084 
9085   if (getLangOpts().CUDA) {
9086     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9087                                             Destructor,
9088                                             /* ConstRHS */ false,
9089                                             /* Diagnose */ false);
9090   }
9091 
9092   // Build an exception specification pointing back at this destructor.
9093   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9094   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9095 
9096   AddOverriddenMethods(ClassDecl, Destructor);
9097 
9098   // We don't need to use SpecialMemberIsTrivial here; triviality for
9099   // destructors is easy to compute.
9100   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9101 
9102   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9103     SetDeclDeleted(Destructor, ClassLoc);
9104 
9105   // Note that we have declared this destructor.
9106   ++ASTContext::NumImplicitDestructorsDeclared;
9107 
9108   // Introduce this destructor into its scope.
9109   if (Scope *S = getScopeForContext(ClassDecl))
9110     PushOnScopeChains(Destructor, S, false);
9111   ClassDecl->addDecl(Destructor);
9112 
9113   return Destructor;
9114 }
9115 
9116 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9117                                     CXXDestructorDecl *Destructor) {
9118   assert((Destructor->isDefaulted() &&
9119           !Destructor->doesThisDeclarationHaveABody() &&
9120           !Destructor->isDeleted()) &&
9121          "DefineImplicitDestructor - call it for implicit default dtor");
9122   CXXRecordDecl *ClassDecl = Destructor->getParent();
9123   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9124 
9125   if (Destructor->isInvalidDecl())
9126     return;
9127 
9128   SynthesizedFunctionScope Scope(*this, Destructor);
9129 
9130   DiagnosticErrorTrap Trap(Diags);
9131   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9132                                          Destructor->getParent());
9133 
9134   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9135     Diag(CurrentLocation, diag::note_member_synthesized_at)
9136       << CXXDestructor << Context.getTagDeclType(ClassDecl);
9137 
9138     Destructor->setInvalidDecl();
9139     return;
9140   }
9141 
9142   // The exception specification is needed because we are defining the
9143   // function.
9144   ResolveExceptionSpec(CurrentLocation,
9145                        Destructor->getType()->castAs<FunctionProtoType>());
9146 
9147   SourceLocation Loc = Destructor->getLocEnd().isValid()
9148                            ? Destructor->getLocEnd()
9149                            : Destructor->getLocation();
9150   Destructor->setBody(new (Context) CompoundStmt(Loc));
9151   Destructor->markUsed(Context);
9152   MarkVTableUsed(CurrentLocation, ClassDecl);
9153 
9154   if (ASTMutationListener *L = getASTMutationListener()) {
9155     L->CompletedImplicitDefinition(Destructor);
9156   }
9157 }
9158 
9159 /// \brief Perform any semantic analysis which needs to be delayed until all
9160 /// pending class member declarations have been parsed.
9161 void Sema::ActOnFinishCXXMemberDecls() {
9162   // If the context is an invalid C++ class, just suppress these checks.
9163   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9164     if (Record->isInvalidDecl()) {
9165       DelayedDefaultedMemberExceptionSpecs.clear();
9166       DelayedDestructorExceptionSpecChecks.clear();
9167       return;
9168     }
9169   }
9170 }
9171 
9172 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9173                                          CXXDestructorDecl *Destructor) {
9174   assert(getLangOpts().CPlusPlus11 &&
9175          "adjusting dtor exception specs was introduced in c++11");
9176 
9177   // C++11 [class.dtor]p3:
9178   //   A declaration of a destructor that does not have an exception-
9179   //   specification is implicitly considered to have the same exception-
9180   //   specification as an implicit declaration.
9181   const FunctionProtoType *DtorType = Destructor->getType()->
9182                                         getAs<FunctionProtoType>();
9183   if (DtorType->hasExceptionSpec())
9184     return;
9185 
9186   // Replace the destructor's type, building off the existing one. Fortunately,
9187   // the only thing of interest in the destructor type is its extended info.
9188   // The return and arguments are fixed.
9189   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9190   EPI.ExceptionSpec.Type = EST_Unevaluated;
9191   EPI.ExceptionSpec.SourceDecl = Destructor;
9192   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9193 
9194   // FIXME: If the destructor has a body that could throw, and the newly created
9195   // spec doesn't allow exceptions, we should emit a warning, because this
9196   // change in behavior can break conforming C++03 programs at runtime.
9197   // However, we don't have a body or an exception specification yet, so it
9198   // needs to be done somewhere else.
9199 }
9200 
9201 namespace {
9202 /// \brief An abstract base class for all helper classes used in building the
9203 //  copy/move operators. These classes serve as factory functions and help us
9204 //  avoid using the same Expr* in the AST twice.
9205 class ExprBuilder {
9206   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9207   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9208 
9209 protected:
9210   static Expr *assertNotNull(Expr *E) {
9211     assert(E && "Expression construction must not fail.");
9212     return E;
9213   }
9214 
9215 public:
9216   ExprBuilder() {}
9217   virtual ~ExprBuilder() {}
9218 
9219   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9220 };
9221 
9222 class RefBuilder: public ExprBuilder {
9223   VarDecl *Var;
9224   QualType VarType;
9225 
9226 public:
9227   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9228     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9229   }
9230 
9231   RefBuilder(VarDecl *Var, QualType VarType)
9232       : Var(Var), VarType(VarType) {}
9233 };
9234 
9235 class ThisBuilder: public ExprBuilder {
9236 public:
9237   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9238     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9239   }
9240 };
9241 
9242 class CastBuilder: public ExprBuilder {
9243   const ExprBuilder &Builder;
9244   QualType Type;
9245   ExprValueKind Kind;
9246   const CXXCastPath &Path;
9247 
9248 public:
9249   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9250     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9251                                              CK_UncheckedDerivedToBase, Kind,
9252                                              &Path).get());
9253   }
9254 
9255   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9256               const CXXCastPath &Path)
9257       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9258 };
9259 
9260 class DerefBuilder: public ExprBuilder {
9261   const ExprBuilder &Builder;
9262 
9263 public:
9264   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9265     return assertNotNull(
9266         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9267   }
9268 
9269   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9270 };
9271 
9272 class MemberBuilder: public ExprBuilder {
9273   const ExprBuilder &Builder;
9274   QualType Type;
9275   CXXScopeSpec SS;
9276   bool IsArrow;
9277   LookupResult &MemberLookup;
9278 
9279 public:
9280   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9281     return assertNotNull(S.BuildMemberReferenceExpr(
9282         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9283         nullptr, MemberLookup, nullptr).get());
9284   }
9285 
9286   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9287                 LookupResult &MemberLookup)
9288       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9289         MemberLookup(MemberLookup) {}
9290 };
9291 
9292 class MoveCastBuilder: public ExprBuilder {
9293   const ExprBuilder &Builder;
9294 
9295 public:
9296   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9297     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9298   }
9299 
9300   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9301 };
9302 
9303 class LvalueConvBuilder: public ExprBuilder {
9304   const ExprBuilder &Builder;
9305 
9306 public:
9307   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9308     return assertNotNull(
9309         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9310   }
9311 
9312   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9313 };
9314 
9315 class SubscriptBuilder: public ExprBuilder {
9316   const ExprBuilder &Base;
9317   const ExprBuilder &Index;
9318 
9319 public:
9320   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9321     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9322         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9323   }
9324 
9325   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9326       : Base(Base), Index(Index) {}
9327 };
9328 
9329 } // end anonymous namespace
9330 
9331 /// When generating a defaulted copy or move assignment operator, if a field
9332 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9333 /// do so. This optimization only applies for arrays of scalars, and for arrays
9334 /// of class type where the selected copy/move-assignment operator is trivial.
9335 static StmtResult
9336 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9337                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9338   // Compute the size of the memory buffer to be copied.
9339   QualType SizeType = S.Context.getSizeType();
9340   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9341                    S.Context.getTypeSizeInChars(T).getQuantity());
9342 
9343   // Take the address of the field references for "from" and "to". We
9344   // directly construct UnaryOperators here because semantic analysis
9345   // does not permit us to take the address of an xvalue.
9346   Expr *From = FromB.build(S, Loc);
9347   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9348                          S.Context.getPointerType(From->getType()),
9349                          VK_RValue, OK_Ordinary, Loc);
9350   Expr *To = ToB.build(S, Loc);
9351   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9352                        S.Context.getPointerType(To->getType()),
9353                        VK_RValue, OK_Ordinary, Loc);
9354 
9355   const Type *E = T->getBaseElementTypeUnsafe();
9356   bool NeedsCollectableMemCpy =
9357     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9358 
9359   // Create a reference to the __builtin_objc_memmove_collectable function
9360   StringRef MemCpyName = NeedsCollectableMemCpy ?
9361     "__builtin_objc_memmove_collectable" :
9362     "__builtin_memcpy";
9363   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9364                  Sema::LookupOrdinaryName);
9365   S.LookupName(R, S.TUScope, true);
9366 
9367   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9368   if (!MemCpy)
9369     // Something went horribly wrong earlier, and we will have complained
9370     // about it.
9371     return StmtError();
9372 
9373   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9374                                             VK_RValue, Loc, nullptr);
9375   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9376 
9377   Expr *CallArgs[] = {
9378     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9379   };
9380   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9381                                     Loc, CallArgs, Loc);
9382 
9383   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9384   return Call.getAs<Stmt>();
9385 }
9386 
9387 /// \brief Builds a statement that copies/moves the given entity from \p From to
9388 /// \c To.
9389 ///
9390 /// This routine is used to copy/move the members of a class with an
9391 /// implicitly-declared copy/move assignment operator. When the entities being
9392 /// copied are arrays, this routine builds for loops to copy them.
9393 ///
9394 /// \param S The Sema object used for type-checking.
9395 ///
9396 /// \param Loc The location where the implicit copy/move is being generated.
9397 ///
9398 /// \param T The type of the expressions being copied/moved. Both expressions
9399 /// must have this type.
9400 ///
9401 /// \param To The expression we are copying/moving to.
9402 ///
9403 /// \param From The expression we are copying/moving from.
9404 ///
9405 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9406 /// Otherwise, it's a non-static member subobject.
9407 ///
9408 /// \param Copying Whether we're copying or moving.
9409 ///
9410 /// \param Depth Internal parameter recording the depth of the recursion.
9411 ///
9412 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9413 /// if a memcpy should be used instead.
9414 static StmtResult
9415 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9416                                  const ExprBuilder &To, const ExprBuilder &From,
9417                                  bool CopyingBaseSubobject, bool Copying,
9418                                  unsigned Depth = 0) {
9419   // C++11 [class.copy]p28:
9420   //   Each subobject is assigned in the manner appropriate to its type:
9421   //
9422   //     - if the subobject is of class type, as if by a call to operator= with
9423   //       the subobject as the object expression and the corresponding
9424   //       subobject of x as a single function argument (as if by explicit
9425   //       qualification; that is, ignoring any possible virtual overriding
9426   //       functions in more derived classes);
9427   //
9428   // C++03 [class.copy]p13:
9429   //     - if the subobject is of class type, the copy assignment operator for
9430   //       the class is used (as if by explicit qualification; that is,
9431   //       ignoring any possible virtual overriding functions in more derived
9432   //       classes);
9433   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9434     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9435 
9436     // Look for operator=.
9437     DeclarationName Name
9438       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9439     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9440     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9441 
9442     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9443     // operator.
9444     if (!S.getLangOpts().CPlusPlus11) {
9445       LookupResult::Filter F = OpLookup.makeFilter();
9446       while (F.hasNext()) {
9447         NamedDecl *D = F.next();
9448         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9449           if (Method->isCopyAssignmentOperator() ||
9450               (!Copying && Method->isMoveAssignmentOperator()))
9451             continue;
9452 
9453         F.erase();
9454       }
9455       F.done();
9456     }
9457 
9458     // Suppress the protected check (C++ [class.protected]) for each of the
9459     // assignment operators we found. This strange dance is required when
9460     // we're assigning via a base classes's copy-assignment operator. To
9461     // ensure that we're getting the right base class subobject (without
9462     // ambiguities), we need to cast "this" to that subobject type; to
9463     // ensure that we don't go through the virtual call mechanism, we need
9464     // to qualify the operator= name with the base class (see below). However,
9465     // this means that if the base class has a protected copy assignment
9466     // operator, the protected member access check will fail. So, we
9467     // rewrite "protected" access to "public" access in this case, since we
9468     // know by construction that we're calling from a derived class.
9469     if (CopyingBaseSubobject) {
9470       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9471            L != LEnd; ++L) {
9472         if (L.getAccess() == AS_protected)
9473           L.setAccess(AS_public);
9474       }
9475     }
9476 
9477     // Create the nested-name-specifier that will be used to qualify the
9478     // reference to operator=; this is required to suppress the virtual
9479     // call mechanism.
9480     CXXScopeSpec SS;
9481     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9482     SS.MakeTrivial(S.Context,
9483                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9484                                                CanonicalT),
9485                    Loc);
9486 
9487     // Create the reference to operator=.
9488     ExprResult OpEqualRef
9489       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9490                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9491                                    /*FirstQualifierInScope=*/nullptr,
9492                                    OpLookup,
9493                                    /*TemplateArgs=*/nullptr,
9494                                    /*SuppressQualifierCheck=*/true);
9495     if (OpEqualRef.isInvalid())
9496       return StmtError();
9497 
9498     // Build the call to the assignment operator.
9499 
9500     Expr *FromInst = From.build(S, Loc);
9501     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9502                                                   OpEqualRef.getAs<Expr>(),
9503                                                   Loc, FromInst, Loc);
9504     if (Call.isInvalid())
9505       return StmtError();
9506 
9507     // If we built a call to a trivial 'operator=' while copying an array,
9508     // bail out. We'll replace the whole shebang with a memcpy.
9509     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9510     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9511       return StmtResult((Stmt*)nullptr);
9512 
9513     // Convert to an expression-statement, and clean up any produced
9514     // temporaries.
9515     return S.ActOnExprStmt(Call);
9516   }
9517 
9518   //     - if the subobject is of scalar type, the built-in assignment
9519   //       operator is used.
9520   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9521   if (!ArrayTy) {
9522     ExprResult Assignment = S.CreateBuiltinBinOp(
9523         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9524     if (Assignment.isInvalid())
9525       return StmtError();
9526     return S.ActOnExprStmt(Assignment);
9527   }
9528 
9529   //     - if the subobject is an array, each element is assigned, in the
9530   //       manner appropriate to the element type;
9531 
9532   // Construct a loop over the array bounds, e.g.,
9533   //
9534   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9535   //
9536   // that will copy each of the array elements.
9537   QualType SizeType = S.Context.getSizeType();
9538 
9539   // Create the iteration variable.
9540   IdentifierInfo *IterationVarName = nullptr;
9541   {
9542     SmallString<8> Str;
9543     llvm::raw_svector_ostream OS(Str);
9544     OS << "__i" << Depth;
9545     IterationVarName = &S.Context.Idents.get(OS.str());
9546   }
9547   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9548                                           IterationVarName, SizeType,
9549                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9550                                           SC_None);
9551 
9552   // Initialize the iteration variable to zero.
9553   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9554   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9555 
9556   // Creates a reference to the iteration variable.
9557   RefBuilder IterationVarRef(IterationVar, SizeType);
9558   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9559 
9560   // Create the DeclStmt that holds the iteration variable.
9561   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9562 
9563   // Subscript the "from" and "to" expressions with the iteration variable.
9564   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9565   MoveCastBuilder FromIndexMove(FromIndexCopy);
9566   const ExprBuilder *FromIndex;
9567   if (Copying)
9568     FromIndex = &FromIndexCopy;
9569   else
9570     FromIndex = &FromIndexMove;
9571 
9572   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9573 
9574   // Build the copy/move for an individual element of the array.
9575   StmtResult Copy =
9576     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9577                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9578                                      Copying, Depth + 1);
9579   // Bail out if copying fails or if we determined that we should use memcpy.
9580   if (Copy.isInvalid() || !Copy.get())
9581     return Copy;
9582 
9583   // Create the comparison against the array bound.
9584   llvm::APInt Upper
9585     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9586   Expr *Comparison
9587     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9588                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9589                                      BO_NE, S.Context.BoolTy,
9590                                      VK_RValue, OK_Ordinary, Loc, false);
9591 
9592   // Create the pre-increment of the iteration variable.
9593   Expr *Increment
9594     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9595                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9596 
9597   // Construct the loop that copies all elements of this array.
9598   return S.ActOnForStmt(Loc, Loc, InitStmt,
9599                         S.MakeFullExpr(Comparison),
9600                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9601                         Loc, Copy.get());
9602 }
9603 
9604 static StmtResult
9605 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9606                       const ExprBuilder &To, const ExprBuilder &From,
9607                       bool CopyingBaseSubobject, bool Copying) {
9608   // Maybe we should use a memcpy?
9609   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9610       T.isTriviallyCopyableType(S.Context))
9611     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9612 
9613   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9614                                                      CopyingBaseSubobject,
9615                                                      Copying, 0));
9616 
9617   // If we ended up picking a trivial assignment operator for an array of a
9618   // non-trivially-copyable class type, just emit a memcpy.
9619   if (!Result.isInvalid() && !Result.get())
9620     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9621 
9622   return Result;
9623 }
9624 
9625 Sema::ImplicitExceptionSpecification
9626 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9627   CXXRecordDecl *ClassDecl = MD->getParent();
9628 
9629   ImplicitExceptionSpecification ExceptSpec(*this);
9630   if (ClassDecl->isInvalidDecl())
9631     return ExceptSpec;
9632 
9633   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9634   assert(T->getNumParams() == 1 && "not a copy assignment op");
9635   unsigned ArgQuals =
9636       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9637 
9638   // C++ [except.spec]p14:
9639   //   An implicitly declared special member function (Clause 12) shall have an
9640   //   exception-specification. [...]
9641 
9642   // It is unspecified whether or not an implicit copy assignment operator
9643   // attempts to deduplicate calls to assignment operators of virtual bases are
9644   // made. As such, this exception specification is effectively unspecified.
9645   // Based on a similar decision made for constness in C++0x, we're erring on
9646   // the side of assuming such calls to be made regardless of whether they
9647   // actually happen.
9648   for (const auto &Base : ClassDecl->bases()) {
9649     if (Base.isVirtual())
9650       continue;
9651 
9652     CXXRecordDecl *BaseClassDecl
9653       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9654     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9655                                                             ArgQuals, false, 0))
9656       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9657   }
9658 
9659   for (const auto &Base : ClassDecl->vbases()) {
9660     CXXRecordDecl *BaseClassDecl
9661       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9662     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9663                                                             ArgQuals, false, 0))
9664       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9665   }
9666 
9667   for (const auto *Field : ClassDecl->fields()) {
9668     QualType FieldType = Context.getBaseElementType(Field->getType());
9669     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9670       if (CXXMethodDecl *CopyAssign =
9671           LookupCopyingAssignment(FieldClassDecl,
9672                                   ArgQuals | FieldType.getCVRQualifiers(),
9673                                   false, 0))
9674         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9675     }
9676   }
9677 
9678   return ExceptSpec;
9679 }
9680 
9681 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9682   // Note: The following rules are largely analoguous to the copy
9683   // constructor rules. Note that virtual bases are not taken into account
9684   // for determining the argument type of the operator. Note also that
9685   // operators taking an object instead of a reference are allowed.
9686   assert(ClassDecl->needsImplicitCopyAssignment());
9687 
9688   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9689   if (DSM.isAlreadyBeingDeclared())
9690     return nullptr;
9691 
9692   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9693   QualType RetType = Context.getLValueReferenceType(ArgType);
9694   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9695   if (Const)
9696     ArgType = ArgType.withConst();
9697   ArgType = Context.getLValueReferenceType(ArgType);
9698 
9699   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9700                                                      CXXCopyAssignment,
9701                                                      Const);
9702 
9703   //   An implicitly-declared copy assignment operator is an inline public
9704   //   member of its class.
9705   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9706   SourceLocation ClassLoc = ClassDecl->getLocation();
9707   DeclarationNameInfo NameInfo(Name, ClassLoc);
9708   CXXMethodDecl *CopyAssignment =
9709       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9710                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9711                             /*isInline=*/true, Constexpr, SourceLocation());
9712   CopyAssignment->setAccess(AS_public);
9713   CopyAssignment->setDefaulted();
9714   CopyAssignment->setImplicit();
9715 
9716   if (getLangOpts().CUDA) {
9717     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
9718                                             CopyAssignment,
9719                                             /* ConstRHS */ Const,
9720                                             /* Diagnose */ false);
9721   }
9722 
9723   // Build an exception specification pointing back at this member.
9724   FunctionProtoType::ExtProtoInfo EPI =
9725       getImplicitMethodEPI(*this, CopyAssignment);
9726   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9727 
9728   // Add the parameter to the operator.
9729   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9730                                                ClassLoc, ClassLoc,
9731                                                /*Id=*/nullptr, ArgType,
9732                                                /*TInfo=*/nullptr, SC_None,
9733                                                nullptr);
9734   CopyAssignment->setParams(FromParam);
9735 
9736   AddOverriddenMethods(ClassDecl, CopyAssignment);
9737 
9738   CopyAssignment->setTrivial(
9739     ClassDecl->needsOverloadResolutionForCopyAssignment()
9740       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9741       : ClassDecl->hasTrivialCopyAssignment());
9742 
9743   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9744     SetDeclDeleted(CopyAssignment, ClassLoc);
9745 
9746   // Note that we have added this copy-assignment operator.
9747   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9748 
9749   if (Scope *S = getScopeForContext(ClassDecl))
9750     PushOnScopeChains(CopyAssignment, S, false);
9751   ClassDecl->addDecl(CopyAssignment);
9752 
9753   return CopyAssignment;
9754 }
9755 
9756 /// Diagnose an implicit copy operation for a class which is odr-used, but
9757 /// which is deprecated because the class has a user-declared copy constructor,
9758 /// copy assignment operator, or destructor.
9759 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9760                                             SourceLocation UseLoc) {
9761   assert(CopyOp->isImplicit());
9762 
9763   CXXRecordDecl *RD = CopyOp->getParent();
9764   CXXMethodDecl *UserDeclaredOperation = nullptr;
9765 
9766   // In Microsoft mode, assignment operations don't affect constructors and
9767   // vice versa.
9768   if (RD->hasUserDeclaredDestructor()) {
9769     UserDeclaredOperation = RD->getDestructor();
9770   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9771              RD->hasUserDeclaredCopyConstructor() &&
9772              !S.getLangOpts().MSVCCompat) {
9773     // Find any user-declared copy constructor.
9774     for (auto *I : RD->ctors()) {
9775       if (I->isCopyConstructor()) {
9776         UserDeclaredOperation = I;
9777         break;
9778       }
9779     }
9780     assert(UserDeclaredOperation);
9781   } else if (isa<CXXConstructorDecl>(CopyOp) &&
9782              RD->hasUserDeclaredCopyAssignment() &&
9783              !S.getLangOpts().MSVCCompat) {
9784     // Find any user-declared move assignment operator.
9785     for (auto *I : RD->methods()) {
9786       if (I->isCopyAssignmentOperator()) {
9787         UserDeclaredOperation = I;
9788         break;
9789       }
9790     }
9791     assert(UserDeclaredOperation);
9792   }
9793 
9794   if (UserDeclaredOperation) {
9795     S.Diag(UserDeclaredOperation->getLocation(),
9796          diag::warn_deprecated_copy_operation)
9797       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9798       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9799     S.Diag(UseLoc, diag::note_member_synthesized_at)
9800       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9801                                           : Sema::CXXCopyAssignment)
9802       << RD;
9803   }
9804 }
9805 
9806 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9807                                         CXXMethodDecl *CopyAssignOperator) {
9808   assert((CopyAssignOperator->isDefaulted() &&
9809           CopyAssignOperator->isOverloadedOperator() &&
9810           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9811           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9812           !CopyAssignOperator->isDeleted()) &&
9813          "DefineImplicitCopyAssignment called for wrong function");
9814 
9815   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9816 
9817   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9818     CopyAssignOperator->setInvalidDecl();
9819     return;
9820   }
9821 
9822   // C++11 [class.copy]p18:
9823   //   The [definition of an implicitly declared copy assignment operator] is
9824   //   deprecated if the class has a user-declared copy constructor or a
9825   //   user-declared destructor.
9826   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9827     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9828 
9829   CopyAssignOperator->markUsed(Context);
9830 
9831   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9832   DiagnosticErrorTrap Trap(Diags);
9833 
9834   // C++0x [class.copy]p30:
9835   //   The implicitly-defined or explicitly-defaulted copy assignment operator
9836   //   for a non-union class X performs memberwise copy assignment of its
9837   //   subobjects. The direct base classes of X are assigned first, in the
9838   //   order of their declaration in the base-specifier-list, and then the
9839   //   immediate non-static data members of X are assigned, in the order in
9840   //   which they were declared in the class definition.
9841 
9842   // The statements that form the synthesized function body.
9843   SmallVector<Stmt*, 8> Statements;
9844 
9845   // The parameter for the "other" object, which we are copying from.
9846   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9847   Qualifiers OtherQuals = Other->getType().getQualifiers();
9848   QualType OtherRefType = Other->getType();
9849   if (const LValueReferenceType *OtherRef
9850                                 = OtherRefType->getAs<LValueReferenceType>()) {
9851     OtherRefType = OtherRef->getPointeeType();
9852     OtherQuals = OtherRefType.getQualifiers();
9853   }
9854 
9855   // Our location for everything implicitly-generated.
9856   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9857                            ? CopyAssignOperator->getLocEnd()
9858                            : CopyAssignOperator->getLocation();
9859 
9860   // Builds a DeclRefExpr for the "other" object.
9861   RefBuilder OtherRef(Other, OtherRefType);
9862 
9863   // Builds the "this" pointer.
9864   ThisBuilder This;
9865 
9866   // Assign base classes.
9867   bool Invalid = false;
9868   for (auto &Base : ClassDecl->bases()) {
9869     // Form the assignment:
9870     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9871     QualType BaseType = Base.getType().getUnqualifiedType();
9872     if (!BaseType->isRecordType()) {
9873       Invalid = true;
9874       continue;
9875     }
9876 
9877     CXXCastPath BasePath;
9878     BasePath.push_back(&Base);
9879 
9880     // Construct the "from" expression, which is an implicit cast to the
9881     // appropriately-qualified base type.
9882     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9883                      VK_LValue, BasePath);
9884 
9885     // Dereference "this".
9886     DerefBuilder DerefThis(This);
9887     CastBuilder To(DerefThis,
9888                    Context.getCVRQualifiedType(
9889                        BaseType, CopyAssignOperator->getTypeQualifiers()),
9890                    VK_LValue, BasePath);
9891 
9892     // Build the copy.
9893     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9894                                             To, From,
9895                                             /*CopyingBaseSubobject=*/true,
9896                                             /*Copying=*/true);
9897     if (Copy.isInvalid()) {
9898       Diag(CurrentLocation, diag::note_member_synthesized_at)
9899         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9900       CopyAssignOperator->setInvalidDecl();
9901       return;
9902     }
9903 
9904     // Success! Record the copy.
9905     Statements.push_back(Copy.getAs<Expr>());
9906   }
9907 
9908   // Assign non-static members.
9909   for (auto *Field : ClassDecl->fields()) {
9910     if (Field->isUnnamedBitfield())
9911       continue;
9912 
9913     if (Field->isInvalidDecl()) {
9914       Invalid = true;
9915       continue;
9916     }
9917 
9918     // Check for members of reference type; we can't copy those.
9919     if (Field->getType()->isReferenceType()) {
9920       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9921         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9922       Diag(Field->getLocation(), diag::note_declared_at);
9923       Diag(CurrentLocation, diag::note_member_synthesized_at)
9924         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9925       Invalid = true;
9926       continue;
9927     }
9928 
9929     // Check for members of const-qualified, non-class type.
9930     QualType BaseType = Context.getBaseElementType(Field->getType());
9931     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9932       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9933         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9934       Diag(Field->getLocation(), diag::note_declared_at);
9935       Diag(CurrentLocation, diag::note_member_synthesized_at)
9936         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9937       Invalid = true;
9938       continue;
9939     }
9940 
9941     // Suppress assigning zero-width bitfields.
9942     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9943       continue;
9944 
9945     QualType FieldType = Field->getType().getNonReferenceType();
9946     if (FieldType->isIncompleteArrayType()) {
9947       assert(ClassDecl->hasFlexibleArrayMember() &&
9948              "Incomplete array type is not valid");
9949       continue;
9950     }
9951 
9952     // Build references to the field in the object we're copying from and to.
9953     CXXScopeSpec SS; // Intentionally empty
9954     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9955                               LookupMemberName);
9956     MemberLookup.addDecl(Field);
9957     MemberLookup.resolveKind();
9958 
9959     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9960 
9961     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9962 
9963     // Build the copy of this field.
9964     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9965                                             To, From,
9966                                             /*CopyingBaseSubobject=*/false,
9967                                             /*Copying=*/true);
9968     if (Copy.isInvalid()) {
9969       Diag(CurrentLocation, diag::note_member_synthesized_at)
9970         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9971       CopyAssignOperator->setInvalidDecl();
9972       return;
9973     }
9974 
9975     // Success! Record the copy.
9976     Statements.push_back(Copy.getAs<Stmt>());
9977   }
9978 
9979   if (!Invalid) {
9980     // Add a "return *this;"
9981     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9982 
9983     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
9984     if (Return.isInvalid())
9985       Invalid = true;
9986     else {
9987       Statements.push_back(Return.getAs<Stmt>());
9988 
9989       if (Trap.hasErrorOccurred()) {
9990         Diag(CurrentLocation, diag::note_member_synthesized_at)
9991           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9992         Invalid = true;
9993       }
9994     }
9995   }
9996 
9997   // The exception specification is needed because we are defining the
9998   // function.
9999   ResolveExceptionSpec(CurrentLocation,
10000                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10001 
10002   if (Invalid) {
10003     CopyAssignOperator->setInvalidDecl();
10004     return;
10005   }
10006 
10007   StmtResult Body;
10008   {
10009     CompoundScopeRAII CompoundScope(*this);
10010     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10011                              /*isStmtExpr=*/false);
10012     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10013   }
10014   CopyAssignOperator->setBody(Body.getAs<Stmt>());
10015 
10016   if (ASTMutationListener *L = getASTMutationListener()) {
10017     L->CompletedImplicitDefinition(CopyAssignOperator);
10018   }
10019 }
10020 
10021 Sema::ImplicitExceptionSpecification
10022 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10023   CXXRecordDecl *ClassDecl = MD->getParent();
10024 
10025   ImplicitExceptionSpecification ExceptSpec(*this);
10026   if (ClassDecl->isInvalidDecl())
10027     return ExceptSpec;
10028 
10029   // C++0x [except.spec]p14:
10030   //   An implicitly declared special member function (Clause 12) shall have an
10031   //   exception-specification. [...]
10032 
10033   // It is unspecified whether or not an implicit move assignment operator
10034   // attempts to deduplicate calls to assignment operators of virtual bases are
10035   // made. As such, this exception specification is effectively unspecified.
10036   // Based on a similar decision made for constness in C++0x, we're erring on
10037   // the side of assuming such calls to be made regardless of whether they
10038   // actually happen.
10039   // Note that a move constructor is not implicitly declared when there are
10040   // virtual bases, but it can still be user-declared and explicitly defaulted.
10041   for (const auto &Base : ClassDecl->bases()) {
10042     if (Base.isVirtual())
10043       continue;
10044 
10045     CXXRecordDecl *BaseClassDecl
10046       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10047     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10048                                                            0, false, 0))
10049       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10050   }
10051 
10052   for (const auto &Base : ClassDecl->vbases()) {
10053     CXXRecordDecl *BaseClassDecl
10054       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10055     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10056                                                            0, false, 0))
10057       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10058   }
10059 
10060   for (const auto *Field : ClassDecl->fields()) {
10061     QualType FieldType = Context.getBaseElementType(Field->getType());
10062     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10063       if (CXXMethodDecl *MoveAssign =
10064               LookupMovingAssignment(FieldClassDecl,
10065                                      FieldType.getCVRQualifiers(),
10066                                      false, 0))
10067         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10068     }
10069   }
10070 
10071   return ExceptSpec;
10072 }
10073 
10074 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10075   assert(ClassDecl->needsImplicitMoveAssignment());
10076 
10077   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10078   if (DSM.isAlreadyBeingDeclared())
10079     return nullptr;
10080 
10081   // Note: The following rules are largely analoguous to the move
10082   // constructor rules.
10083 
10084   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10085   QualType RetType = Context.getLValueReferenceType(ArgType);
10086   ArgType = Context.getRValueReferenceType(ArgType);
10087 
10088   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10089                                                      CXXMoveAssignment,
10090                                                      false);
10091 
10092   //   An implicitly-declared move assignment operator is an inline public
10093   //   member of its class.
10094   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10095   SourceLocation ClassLoc = ClassDecl->getLocation();
10096   DeclarationNameInfo NameInfo(Name, ClassLoc);
10097   CXXMethodDecl *MoveAssignment =
10098       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10099                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10100                             /*isInline=*/true, Constexpr, SourceLocation());
10101   MoveAssignment->setAccess(AS_public);
10102   MoveAssignment->setDefaulted();
10103   MoveAssignment->setImplicit();
10104 
10105   if (getLangOpts().CUDA) {
10106     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10107                                             MoveAssignment,
10108                                             /* ConstRHS */ false,
10109                                             /* Diagnose */ false);
10110   }
10111 
10112   // Build an exception specification pointing back at this member.
10113   FunctionProtoType::ExtProtoInfo EPI =
10114       getImplicitMethodEPI(*this, MoveAssignment);
10115   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10116 
10117   // Add the parameter to the operator.
10118   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10119                                                ClassLoc, ClassLoc,
10120                                                /*Id=*/nullptr, ArgType,
10121                                                /*TInfo=*/nullptr, SC_None,
10122                                                nullptr);
10123   MoveAssignment->setParams(FromParam);
10124 
10125   AddOverriddenMethods(ClassDecl, MoveAssignment);
10126 
10127   MoveAssignment->setTrivial(
10128     ClassDecl->needsOverloadResolutionForMoveAssignment()
10129       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10130       : ClassDecl->hasTrivialMoveAssignment());
10131 
10132   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10133     ClassDecl->setImplicitMoveAssignmentIsDeleted();
10134     SetDeclDeleted(MoveAssignment, ClassLoc);
10135   }
10136 
10137   // Note that we have added this copy-assignment operator.
10138   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10139 
10140   if (Scope *S = getScopeForContext(ClassDecl))
10141     PushOnScopeChains(MoveAssignment, S, false);
10142   ClassDecl->addDecl(MoveAssignment);
10143 
10144   return MoveAssignment;
10145 }
10146 
10147 /// Check if we're implicitly defining a move assignment operator for a class
10148 /// with virtual bases. Such a move assignment might move-assign the virtual
10149 /// base multiple times.
10150 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10151                                                SourceLocation CurrentLocation) {
10152   assert(!Class->isDependentContext() && "should not define dependent move");
10153 
10154   // Only a virtual base could get implicitly move-assigned multiple times.
10155   // Only a non-trivial move assignment can observe this. We only want to
10156   // diagnose if we implicitly define an assignment operator that assigns
10157   // two base classes, both of which move-assign the same virtual base.
10158   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10159       Class->getNumBases() < 2)
10160     return;
10161 
10162   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10163   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10164   VBaseMap VBases;
10165 
10166   for (auto &BI : Class->bases()) {
10167     Worklist.push_back(&BI);
10168     while (!Worklist.empty()) {
10169       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10170       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10171 
10172       // If the base has no non-trivial move assignment operators,
10173       // we don't care about moves from it.
10174       if (!Base->hasNonTrivialMoveAssignment())
10175         continue;
10176 
10177       // If there's nothing virtual here, skip it.
10178       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10179         continue;
10180 
10181       // If we're not actually going to call a move assignment for this base,
10182       // or the selected move assignment is trivial, skip it.
10183       Sema::SpecialMemberOverloadResult *SMOR =
10184         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10185                               /*ConstArg*/false, /*VolatileArg*/false,
10186                               /*RValueThis*/true, /*ConstThis*/false,
10187                               /*VolatileThis*/false);
10188       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10189           !SMOR->getMethod()->isMoveAssignmentOperator())
10190         continue;
10191 
10192       if (BaseSpec->isVirtual()) {
10193         // We're going to move-assign this virtual base, and its move
10194         // assignment operator is not trivial. If this can happen for
10195         // multiple distinct direct bases of Class, diagnose it. (If it
10196         // only happens in one base, we'll diagnose it when synthesizing
10197         // that base class's move assignment operator.)
10198         CXXBaseSpecifier *&Existing =
10199             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10200                 .first->second;
10201         if (Existing && Existing != &BI) {
10202           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10203             << Class << Base;
10204           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10205             << (Base->getCanonicalDecl() ==
10206                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10207             << Base << Existing->getType() << Existing->getSourceRange();
10208           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10209             << (Base->getCanonicalDecl() ==
10210                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10211             << Base << BI.getType() << BaseSpec->getSourceRange();
10212 
10213           // Only diagnose each vbase once.
10214           Existing = nullptr;
10215         }
10216       } else {
10217         // Only walk over bases that have defaulted move assignment operators.
10218         // We assume that any user-provided move assignment operator handles
10219         // the multiple-moves-of-vbase case itself somehow.
10220         if (!SMOR->getMethod()->isDefaulted())
10221           continue;
10222 
10223         // We're going to move the base classes of Base. Add them to the list.
10224         for (auto &BI : Base->bases())
10225           Worklist.push_back(&BI);
10226       }
10227     }
10228   }
10229 }
10230 
10231 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10232                                         CXXMethodDecl *MoveAssignOperator) {
10233   assert((MoveAssignOperator->isDefaulted() &&
10234           MoveAssignOperator->isOverloadedOperator() &&
10235           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10236           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10237           !MoveAssignOperator->isDeleted()) &&
10238          "DefineImplicitMoveAssignment called for wrong function");
10239 
10240   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10241 
10242   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10243     MoveAssignOperator->setInvalidDecl();
10244     return;
10245   }
10246 
10247   MoveAssignOperator->markUsed(Context);
10248 
10249   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10250   DiagnosticErrorTrap Trap(Diags);
10251 
10252   // C++0x [class.copy]p28:
10253   //   The implicitly-defined or move assignment operator for a non-union class
10254   //   X performs memberwise move assignment of its subobjects. The direct base
10255   //   classes of X are assigned first, in the order of their declaration in the
10256   //   base-specifier-list, and then the immediate non-static data members of X
10257   //   are assigned, in the order in which they were declared in the class
10258   //   definition.
10259 
10260   // Issue a warning if our implicit move assignment operator will move
10261   // from a virtual base more than once.
10262   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10263 
10264   // The statements that form the synthesized function body.
10265   SmallVector<Stmt*, 8> Statements;
10266 
10267   // The parameter for the "other" object, which we are move from.
10268   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10269   QualType OtherRefType = Other->getType()->
10270       getAs<RValueReferenceType>()->getPointeeType();
10271   assert(!OtherRefType.getQualifiers() &&
10272          "Bad argument type of defaulted move assignment");
10273 
10274   // Our location for everything implicitly-generated.
10275   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10276                            ? MoveAssignOperator->getLocEnd()
10277                            : MoveAssignOperator->getLocation();
10278 
10279   // Builds a reference to the "other" object.
10280   RefBuilder OtherRef(Other, OtherRefType);
10281   // Cast to rvalue.
10282   MoveCastBuilder MoveOther(OtherRef);
10283 
10284   // Builds the "this" pointer.
10285   ThisBuilder This;
10286 
10287   // Assign base classes.
10288   bool Invalid = false;
10289   for (auto &Base : ClassDecl->bases()) {
10290     // C++11 [class.copy]p28:
10291     //   It is unspecified whether subobjects representing virtual base classes
10292     //   are assigned more than once by the implicitly-defined copy assignment
10293     //   operator.
10294     // FIXME: Do not assign to a vbase that will be assigned by some other base
10295     // class. For a move-assignment, this can result in the vbase being moved
10296     // multiple times.
10297 
10298     // Form the assignment:
10299     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10300     QualType BaseType = Base.getType().getUnqualifiedType();
10301     if (!BaseType->isRecordType()) {
10302       Invalid = true;
10303       continue;
10304     }
10305 
10306     CXXCastPath BasePath;
10307     BasePath.push_back(&Base);
10308 
10309     // Construct the "from" expression, which is an implicit cast to the
10310     // appropriately-qualified base type.
10311     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10312 
10313     // Dereference "this".
10314     DerefBuilder DerefThis(This);
10315 
10316     // Implicitly cast "this" to the appropriately-qualified base type.
10317     CastBuilder To(DerefThis,
10318                    Context.getCVRQualifiedType(
10319                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10320                    VK_LValue, BasePath);
10321 
10322     // Build the move.
10323     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10324                                             To, From,
10325                                             /*CopyingBaseSubobject=*/true,
10326                                             /*Copying=*/false);
10327     if (Move.isInvalid()) {
10328       Diag(CurrentLocation, diag::note_member_synthesized_at)
10329         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10330       MoveAssignOperator->setInvalidDecl();
10331       return;
10332     }
10333 
10334     // Success! Record the move.
10335     Statements.push_back(Move.getAs<Expr>());
10336   }
10337 
10338   // Assign non-static members.
10339   for (auto *Field : ClassDecl->fields()) {
10340     if (Field->isUnnamedBitfield())
10341       continue;
10342 
10343     if (Field->isInvalidDecl()) {
10344       Invalid = true;
10345       continue;
10346     }
10347 
10348     // Check for members of reference type; we can't move those.
10349     if (Field->getType()->isReferenceType()) {
10350       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10351         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10352       Diag(Field->getLocation(), diag::note_declared_at);
10353       Diag(CurrentLocation, diag::note_member_synthesized_at)
10354         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10355       Invalid = true;
10356       continue;
10357     }
10358 
10359     // Check for members of const-qualified, non-class type.
10360     QualType BaseType = Context.getBaseElementType(Field->getType());
10361     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10362       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10363         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10364       Diag(Field->getLocation(), diag::note_declared_at);
10365       Diag(CurrentLocation, diag::note_member_synthesized_at)
10366         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10367       Invalid = true;
10368       continue;
10369     }
10370 
10371     // Suppress assigning zero-width bitfields.
10372     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10373       continue;
10374 
10375     QualType FieldType = Field->getType().getNonReferenceType();
10376     if (FieldType->isIncompleteArrayType()) {
10377       assert(ClassDecl->hasFlexibleArrayMember() &&
10378              "Incomplete array type is not valid");
10379       continue;
10380     }
10381 
10382     // Build references to the field in the object we're copying from and to.
10383     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10384                               LookupMemberName);
10385     MemberLookup.addDecl(Field);
10386     MemberLookup.resolveKind();
10387     MemberBuilder From(MoveOther, OtherRefType,
10388                        /*IsArrow=*/false, MemberLookup);
10389     MemberBuilder To(This, getCurrentThisType(),
10390                      /*IsArrow=*/true, MemberLookup);
10391 
10392     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10393         "Member reference with rvalue base must be rvalue except for reference "
10394         "members, which aren't allowed for move assignment.");
10395 
10396     // Build the move of this field.
10397     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10398                                             To, From,
10399                                             /*CopyingBaseSubobject=*/false,
10400                                             /*Copying=*/false);
10401     if (Move.isInvalid()) {
10402       Diag(CurrentLocation, diag::note_member_synthesized_at)
10403         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10404       MoveAssignOperator->setInvalidDecl();
10405       return;
10406     }
10407 
10408     // Success! Record the copy.
10409     Statements.push_back(Move.getAs<Stmt>());
10410   }
10411 
10412   if (!Invalid) {
10413     // Add a "return *this;"
10414     ExprResult ThisObj =
10415         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10416 
10417     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10418     if (Return.isInvalid())
10419       Invalid = true;
10420     else {
10421       Statements.push_back(Return.getAs<Stmt>());
10422 
10423       if (Trap.hasErrorOccurred()) {
10424         Diag(CurrentLocation, diag::note_member_synthesized_at)
10425           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10426         Invalid = true;
10427       }
10428     }
10429   }
10430 
10431   // The exception specification is needed because we are defining the
10432   // function.
10433   ResolveExceptionSpec(CurrentLocation,
10434                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10435 
10436   if (Invalid) {
10437     MoveAssignOperator->setInvalidDecl();
10438     return;
10439   }
10440 
10441   StmtResult Body;
10442   {
10443     CompoundScopeRAII CompoundScope(*this);
10444     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10445                              /*isStmtExpr=*/false);
10446     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10447   }
10448   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10449 
10450   if (ASTMutationListener *L = getASTMutationListener()) {
10451     L->CompletedImplicitDefinition(MoveAssignOperator);
10452   }
10453 }
10454 
10455 Sema::ImplicitExceptionSpecification
10456 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10457   CXXRecordDecl *ClassDecl = MD->getParent();
10458 
10459   ImplicitExceptionSpecification ExceptSpec(*this);
10460   if (ClassDecl->isInvalidDecl())
10461     return ExceptSpec;
10462 
10463   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10464   assert(T->getNumParams() >= 1 && "not a copy ctor");
10465   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10466 
10467   // C++ [except.spec]p14:
10468   //   An implicitly declared special member function (Clause 12) shall have an
10469   //   exception-specification. [...]
10470   for (const auto &Base : ClassDecl->bases()) {
10471     // Virtual bases are handled below.
10472     if (Base.isVirtual())
10473       continue;
10474 
10475     CXXRecordDecl *BaseClassDecl
10476       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10477     if (CXXConstructorDecl *CopyConstructor =
10478           LookupCopyingConstructor(BaseClassDecl, Quals))
10479       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10480   }
10481   for (const auto &Base : ClassDecl->vbases()) {
10482     CXXRecordDecl *BaseClassDecl
10483       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10484     if (CXXConstructorDecl *CopyConstructor =
10485           LookupCopyingConstructor(BaseClassDecl, Quals))
10486       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10487   }
10488   for (const auto *Field : ClassDecl->fields()) {
10489     QualType FieldType = Context.getBaseElementType(Field->getType());
10490     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10491       if (CXXConstructorDecl *CopyConstructor =
10492               LookupCopyingConstructor(FieldClassDecl,
10493                                        Quals | FieldType.getCVRQualifiers()))
10494       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10495     }
10496   }
10497 
10498   return ExceptSpec;
10499 }
10500 
10501 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10502                                                     CXXRecordDecl *ClassDecl) {
10503   // C++ [class.copy]p4:
10504   //   If the class definition does not explicitly declare a copy
10505   //   constructor, one is declared implicitly.
10506   assert(ClassDecl->needsImplicitCopyConstructor());
10507 
10508   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10509   if (DSM.isAlreadyBeingDeclared())
10510     return nullptr;
10511 
10512   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10513   QualType ArgType = ClassType;
10514   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10515   if (Const)
10516     ArgType = ArgType.withConst();
10517   ArgType = Context.getLValueReferenceType(ArgType);
10518 
10519   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10520                                                      CXXCopyConstructor,
10521                                                      Const);
10522 
10523   DeclarationName Name
10524     = Context.DeclarationNames.getCXXConstructorName(
10525                                            Context.getCanonicalType(ClassType));
10526   SourceLocation ClassLoc = ClassDecl->getLocation();
10527   DeclarationNameInfo NameInfo(Name, ClassLoc);
10528 
10529   //   An implicitly-declared copy constructor is an inline public
10530   //   member of its class.
10531   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10532       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10533       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10534       Constexpr);
10535   CopyConstructor->setAccess(AS_public);
10536   CopyConstructor->setDefaulted();
10537 
10538   if (getLangOpts().CUDA) {
10539     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10540                                             CopyConstructor,
10541                                             /* ConstRHS */ Const,
10542                                             /* Diagnose */ false);
10543   }
10544 
10545   // Build an exception specification pointing back at this member.
10546   FunctionProtoType::ExtProtoInfo EPI =
10547       getImplicitMethodEPI(*this, CopyConstructor);
10548   CopyConstructor->setType(
10549       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10550 
10551   // Add the parameter to the constructor.
10552   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10553                                                ClassLoc, ClassLoc,
10554                                                /*IdentifierInfo=*/nullptr,
10555                                                ArgType, /*TInfo=*/nullptr,
10556                                                SC_None, nullptr);
10557   CopyConstructor->setParams(FromParam);
10558 
10559   CopyConstructor->setTrivial(
10560     ClassDecl->needsOverloadResolutionForCopyConstructor()
10561       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10562       : ClassDecl->hasTrivialCopyConstructor());
10563 
10564   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10565     SetDeclDeleted(CopyConstructor, ClassLoc);
10566 
10567   // Note that we have declared this constructor.
10568   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10569 
10570   if (Scope *S = getScopeForContext(ClassDecl))
10571     PushOnScopeChains(CopyConstructor, S, false);
10572   ClassDecl->addDecl(CopyConstructor);
10573 
10574   return CopyConstructor;
10575 }
10576 
10577 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10578                                    CXXConstructorDecl *CopyConstructor) {
10579   assert((CopyConstructor->isDefaulted() &&
10580           CopyConstructor->isCopyConstructor() &&
10581           !CopyConstructor->doesThisDeclarationHaveABody() &&
10582           !CopyConstructor->isDeleted()) &&
10583          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10584 
10585   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10586   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10587 
10588   // C++11 [class.copy]p7:
10589   //   The [definition of an implicitly declared copy constructor] is
10590   //   deprecated if the class has a user-declared copy assignment operator
10591   //   or a user-declared destructor.
10592   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10593     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10594 
10595   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10596   DiagnosticErrorTrap Trap(Diags);
10597 
10598   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10599       Trap.hasErrorOccurred()) {
10600     Diag(CurrentLocation, diag::note_member_synthesized_at)
10601       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10602     CopyConstructor->setInvalidDecl();
10603   }  else {
10604     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10605                              ? CopyConstructor->getLocEnd()
10606                              : CopyConstructor->getLocation();
10607     Sema::CompoundScopeRAII CompoundScope(*this);
10608     CopyConstructor->setBody(
10609         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10610   }
10611 
10612   // The exception specification is needed because we are defining the
10613   // function.
10614   ResolveExceptionSpec(CurrentLocation,
10615                        CopyConstructor->getType()->castAs<FunctionProtoType>());
10616 
10617   CopyConstructor->markUsed(Context);
10618   MarkVTableUsed(CurrentLocation, ClassDecl);
10619 
10620   if (ASTMutationListener *L = getASTMutationListener()) {
10621     L->CompletedImplicitDefinition(CopyConstructor);
10622   }
10623 }
10624 
10625 Sema::ImplicitExceptionSpecification
10626 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10627   CXXRecordDecl *ClassDecl = MD->getParent();
10628 
10629   // C++ [except.spec]p14:
10630   //   An implicitly declared special member function (Clause 12) shall have an
10631   //   exception-specification. [...]
10632   ImplicitExceptionSpecification ExceptSpec(*this);
10633   if (ClassDecl->isInvalidDecl())
10634     return ExceptSpec;
10635 
10636   // Direct base-class constructors.
10637   for (const auto &B : ClassDecl->bases()) {
10638     if (B.isVirtual()) // Handled below.
10639       continue;
10640 
10641     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10642       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10643       CXXConstructorDecl *Constructor =
10644           LookupMovingConstructor(BaseClassDecl, 0);
10645       // If this is a deleted function, add it anyway. This might be conformant
10646       // with the standard. This might not. I'm not sure. It might not matter.
10647       if (Constructor)
10648         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10649     }
10650   }
10651 
10652   // Virtual base-class constructors.
10653   for (const auto &B : ClassDecl->vbases()) {
10654     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10655       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10656       CXXConstructorDecl *Constructor =
10657           LookupMovingConstructor(BaseClassDecl, 0);
10658       // If this is a deleted function, add it anyway. This might be conformant
10659       // with the standard. This might not. I'm not sure. It might not matter.
10660       if (Constructor)
10661         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10662     }
10663   }
10664 
10665   // Field constructors.
10666   for (const auto *F : ClassDecl->fields()) {
10667     QualType FieldType = Context.getBaseElementType(F->getType());
10668     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10669       CXXConstructorDecl *Constructor =
10670           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10671       // If this is a deleted function, add it anyway. This might be conformant
10672       // with the standard. This might not. I'm not sure. It might not matter.
10673       // In particular, the problem is that this function never gets called. It
10674       // might just be ill-formed because this function attempts to refer to
10675       // a deleted function here.
10676       if (Constructor)
10677         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10678     }
10679   }
10680 
10681   return ExceptSpec;
10682 }
10683 
10684 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10685                                                     CXXRecordDecl *ClassDecl) {
10686   assert(ClassDecl->needsImplicitMoveConstructor());
10687 
10688   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10689   if (DSM.isAlreadyBeingDeclared())
10690     return nullptr;
10691 
10692   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10693   QualType ArgType = Context.getRValueReferenceType(ClassType);
10694 
10695   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10696                                                      CXXMoveConstructor,
10697                                                      false);
10698 
10699   DeclarationName Name
10700     = Context.DeclarationNames.getCXXConstructorName(
10701                                            Context.getCanonicalType(ClassType));
10702   SourceLocation ClassLoc = ClassDecl->getLocation();
10703   DeclarationNameInfo NameInfo(Name, ClassLoc);
10704 
10705   // C++11 [class.copy]p11:
10706   //   An implicitly-declared copy/move constructor is an inline public
10707   //   member of its class.
10708   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10709       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10710       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10711       Constexpr);
10712   MoveConstructor->setAccess(AS_public);
10713   MoveConstructor->setDefaulted();
10714 
10715   if (getLangOpts().CUDA) {
10716     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10717                                             MoveConstructor,
10718                                             /* ConstRHS */ false,
10719                                             /* Diagnose */ false);
10720   }
10721 
10722   // Build an exception specification pointing back at this member.
10723   FunctionProtoType::ExtProtoInfo EPI =
10724       getImplicitMethodEPI(*this, MoveConstructor);
10725   MoveConstructor->setType(
10726       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10727 
10728   // Add the parameter to the constructor.
10729   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10730                                                ClassLoc, ClassLoc,
10731                                                /*IdentifierInfo=*/nullptr,
10732                                                ArgType, /*TInfo=*/nullptr,
10733                                                SC_None, nullptr);
10734   MoveConstructor->setParams(FromParam);
10735 
10736   MoveConstructor->setTrivial(
10737     ClassDecl->needsOverloadResolutionForMoveConstructor()
10738       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10739       : ClassDecl->hasTrivialMoveConstructor());
10740 
10741   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10742     ClassDecl->setImplicitMoveConstructorIsDeleted();
10743     SetDeclDeleted(MoveConstructor, ClassLoc);
10744   }
10745 
10746   // Note that we have declared this constructor.
10747   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10748 
10749   if (Scope *S = getScopeForContext(ClassDecl))
10750     PushOnScopeChains(MoveConstructor, S, false);
10751   ClassDecl->addDecl(MoveConstructor);
10752 
10753   return MoveConstructor;
10754 }
10755 
10756 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10757                                    CXXConstructorDecl *MoveConstructor) {
10758   assert((MoveConstructor->isDefaulted() &&
10759           MoveConstructor->isMoveConstructor() &&
10760           !MoveConstructor->doesThisDeclarationHaveABody() &&
10761           !MoveConstructor->isDeleted()) &&
10762          "DefineImplicitMoveConstructor - call it for implicit move ctor");
10763 
10764   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10765   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10766 
10767   SynthesizedFunctionScope Scope(*this, MoveConstructor);
10768   DiagnosticErrorTrap Trap(Diags);
10769 
10770   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10771       Trap.hasErrorOccurred()) {
10772     Diag(CurrentLocation, diag::note_member_synthesized_at)
10773       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10774     MoveConstructor->setInvalidDecl();
10775   }  else {
10776     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10777                              ? MoveConstructor->getLocEnd()
10778                              : MoveConstructor->getLocation();
10779     Sema::CompoundScopeRAII CompoundScope(*this);
10780     MoveConstructor->setBody(ActOnCompoundStmt(
10781         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
10782   }
10783 
10784   // The exception specification is needed because we are defining the
10785   // function.
10786   ResolveExceptionSpec(CurrentLocation,
10787                        MoveConstructor->getType()->castAs<FunctionProtoType>());
10788 
10789   MoveConstructor->markUsed(Context);
10790   MarkVTableUsed(CurrentLocation, ClassDecl);
10791 
10792   if (ASTMutationListener *L = getASTMutationListener()) {
10793     L->CompletedImplicitDefinition(MoveConstructor);
10794   }
10795 }
10796 
10797 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10798   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10799 }
10800 
10801 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10802                             SourceLocation CurrentLocation,
10803                             CXXConversionDecl *Conv) {
10804   CXXRecordDecl *Lambda = Conv->getParent();
10805   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10806   // If we are defining a specialization of a conversion to function-ptr
10807   // cache the deduced template arguments for this specialization
10808   // so that we can use them to retrieve the corresponding call-operator
10809   // and static-invoker.
10810   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10811 
10812   // Retrieve the corresponding call-operator specialization.
10813   if (Lambda->isGenericLambda()) {
10814     assert(Conv->isFunctionTemplateSpecialization());
10815     FunctionTemplateDecl *CallOpTemplate =
10816         CallOp->getDescribedFunctionTemplate();
10817     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10818     void *InsertPos = nullptr;
10819     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10820                                                 DeducedTemplateArgs->asArray(),
10821                                                 InsertPos);
10822     assert(CallOpSpec &&
10823           "Conversion operator must have a corresponding call operator");
10824     CallOp = cast<CXXMethodDecl>(CallOpSpec);
10825   }
10826   // Mark the call operator referenced (and add to pending instantiations
10827   // if necessary).
10828   // For both the conversion and static-invoker template specializations
10829   // we construct their body's in this function, so no need to add them
10830   // to the PendingInstantiations.
10831   MarkFunctionReferenced(CurrentLocation, CallOp);
10832 
10833   SynthesizedFunctionScope Scope(*this, Conv);
10834   DiagnosticErrorTrap Trap(Diags);
10835 
10836   // Retrieve the static invoker...
10837   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10838   // ... and get the corresponding specialization for a generic lambda.
10839   if (Lambda->isGenericLambda()) {
10840     assert(DeducedTemplateArgs &&
10841       "Must have deduced template arguments from Conversion Operator");
10842     FunctionTemplateDecl *InvokeTemplate =
10843                           Invoker->getDescribedFunctionTemplate();
10844     void *InsertPos = nullptr;
10845     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10846                                                 DeducedTemplateArgs->asArray(),
10847                                                 InsertPos);
10848     assert(InvokeSpec &&
10849       "Must have a corresponding static invoker specialization");
10850     Invoker = cast<CXXMethodDecl>(InvokeSpec);
10851   }
10852   // Construct the body of the conversion function { return __invoke; }.
10853   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10854                                         VK_LValue, Conv->getLocation()).get();
10855    assert(FunctionRef && "Can't refer to __invoke function?");
10856    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
10857    Conv->setBody(new (Context) CompoundStmt(Context, Return,
10858                                             Conv->getLocation(),
10859                                             Conv->getLocation()));
10860 
10861   Conv->markUsed(Context);
10862   Conv->setReferenced();
10863 
10864   // Fill in the __invoke function with a dummy implementation. IR generation
10865   // will fill in the actual details.
10866   Invoker->markUsed(Context);
10867   Invoker->setReferenced();
10868   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10869 
10870   if (ASTMutationListener *L = getASTMutationListener()) {
10871     L->CompletedImplicitDefinition(Conv);
10872     L->CompletedImplicitDefinition(Invoker);
10873    }
10874 }
10875 
10876 
10877 
10878 void Sema::DefineImplicitLambdaToBlockPointerConversion(
10879        SourceLocation CurrentLocation,
10880        CXXConversionDecl *Conv)
10881 {
10882   assert(!Conv->getParent()->isGenericLambda());
10883 
10884   Conv->markUsed(Context);
10885 
10886   SynthesizedFunctionScope Scope(*this, Conv);
10887   DiagnosticErrorTrap Trap(Diags);
10888 
10889   // Copy-initialize the lambda object as needed to capture it.
10890   Expr *This = ActOnCXXThis(CurrentLocation).get();
10891   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
10892 
10893   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10894                                                         Conv->getLocation(),
10895                                                         Conv, DerefThis);
10896 
10897   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10898   // behavior.  Note that only the general conversion function does this
10899   // (since it's unusable otherwise); in the case where we inline the
10900   // block literal, it has block literal lifetime semantics.
10901   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10902     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10903                                           CK_CopyAndAutoreleaseBlockObject,
10904                                           BuildBlock.get(), nullptr, VK_RValue);
10905 
10906   if (BuildBlock.isInvalid()) {
10907     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10908     Conv->setInvalidDecl();
10909     return;
10910   }
10911 
10912   // Create the return statement that returns the block from the conversion
10913   // function.
10914   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
10915   if (Return.isInvalid()) {
10916     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10917     Conv->setInvalidDecl();
10918     return;
10919   }
10920 
10921   // Set the body of the conversion function.
10922   Stmt *ReturnS = Return.get();
10923   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10924                                            Conv->getLocation(),
10925                                            Conv->getLocation()));
10926 
10927   // We're done; notify the mutation listener, if any.
10928   if (ASTMutationListener *L = getASTMutationListener()) {
10929     L->CompletedImplicitDefinition(Conv);
10930   }
10931 }
10932 
10933 /// \brief Determine whether the given list arguments contains exactly one
10934 /// "real" (non-default) argument.
10935 static bool hasOneRealArgument(MultiExprArg Args) {
10936   switch (Args.size()) {
10937   case 0:
10938     return false;
10939 
10940   default:
10941     if (!Args[1]->isDefaultArgument())
10942       return false;
10943 
10944     // fall through
10945   case 1:
10946     return !Args[0]->isDefaultArgument();
10947   }
10948 
10949   return false;
10950 }
10951 
10952 ExprResult
10953 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10954                             CXXConstructorDecl *Constructor,
10955                             MultiExprArg ExprArgs,
10956                             bool HadMultipleCandidates,
10957                             bool IsListInitialization,
10958                             bool IsStdInitListInitialization,
10959                             bool RequiresZeroInit,
10960                             unsigned ConstructKind,
10961                             SourceRange ParenRange) {
10962   bool Elidable = false;
10963 
10964   // C++0x [class.copy]p34:
10965   //   When certain criteria are met, an implementation is allowed to
10966   //   omit the copy/move construction of a class object, even if the
10967   //   copy/move constructor and/or destructor for the object have
10968   //   side effects. [...]
10969   //     - when a temporary class object that has not been bound to a
10970   //       reference (12.2) would be copied/moved to a class object
10971   //       with the same cv-unqualified type, the copy/move operation
10972   //       can be omitted by constructing the temporary object
10973   //       directly into the target of the omitted copy/move
10974   if (ConstructKind == CXXConstructExpr::CK_Complete &&
10975       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10976     Expr *SubExpr = ExprArgs[0];
10977     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10978   }
10979 
10980   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10981                                Elidable, ExprArgs, HadMultipleCandidates,
10982                                IsListInitialization,
10983                                IsStdInitListInitialization, RequiresZeroInit,
10984                                ConstructKind, ParenRange);
10985 }
10986 
10987 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
10988 /// including handling of its default argument expressions.
10989 ExprResult
10990 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10991                             CXXConstructorDecl *Constructor, bool Elidable,
10992                             MultiExprArg ExprArgs,
10993                             bool HadMultipleCandidates,
10994                             bool IsListInitialization,
10995                             bool IsStdInitListInitialization,
10996                             bool RequiresZeroInit,
10997                             unsigned ConstructKind,
10998                             SourceRange ParenRange) {
10999   MarkFunctionReferenced(ConstructLoc, Constructor);
11000   return CXXConstructExpr::Create(
11001       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11002       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11003       RequiresZeroInit,
11004       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11005       ParenRange);
11006 }
11007 
11008 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11009   if (VD->isInvalidDecl()) return;
11010 
11011   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11012   if (ClassDecl->isInvalidDecl()) return;
11013   if (ClassDecl->hasIrrelevantDestructor()) return;
11014   if (ClassDecl->isDependentContext()) return;
11015 
11016   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11017   MarkFunctionReferenced(VD->getLocation(), Destructor);
11018   CheckDestructorAccess(VD->getLocation(), Destructor,
11019                         PDiag(diag::err_access_dtor_var)
11020                         << VD->getDeclName()
11021                         << VD->getType());
11022   DiagnoseUseOfDecl(Destructor, VD->getLocation());
11023 
11024   if (Destructor->isTrivial()) return;
11025   if (!VD->hasGlobalStorage()) return;
11026 
11027   // Emit warning for non-trivial dtor in global scope (a real global,
11028   // class-static, function-static).
11029   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11030 
11031   // TODO: this should be re-enabled for static locals by !CXAAtExit
11032   if (!VD->isStaticLocal())
11033     Diag(VD->getLocation(), diag::warn_global_destructor);
11034 }
11035 
11036 /// \brief Given a constructor and the set of arguments provided for the
11037 /// constructor, convert the arguments and add any required default arguments
11038 /// to form a proper call to this constructor.
11039 ///
11040 /// \returns true if an error occurred, false otherwise.
11041 bool
11042 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11043                               MultiExprArg ArgsPtr,
11044                               SourceLocation Loc,
11045                               SmallVectorImpl<Expr*> &ConvertedArgs,
11046                               bool AllowExplicit,
11047                               bool IsListInitialization) {
11048   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11049   unsigned NumArgs = ArgsPtr.size();
11050   Expr **Args = ArgsPtr.data();
11051 
11052   const FunctionProtoType *Proto
11053     = Constructor->getType()->getAs<FunctionProtoType>();
11054   assert(Proto && "Constructor without a prototype?");
11055   unsigned NumParams = Proto->getNumParams();
11056 
11057   // If too few arguments are available, we'll fill in the rest with defaults.
11058   if (NumArgs < NumParams)
11059     ConvertedArgs.reserve(NumParams);
11060   else
11061     ConvertedArgs.reserve(NumArgs);
11062 
11063   VariadicCallType CallType =
11064     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11065   SmallVector<Expr *, 8> AllArgs;
11066   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11067                                         Proto, 0,
11068                                         llvm::makeArrayRef(Args, NumArgs),
11069                                         AllArgs,
11070                                         CallType, AllowExplicit,
11071                                         IsListInitialization);
11072   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11073 
11074   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11075 
11076   CheckConstructorCall(Constructor,
11077                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11078                        Proto, Loc);
11079 
11080   return Invalid;
11081 }
11082 
11083 static inline bool
11084 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11085                                        const FunctionDecl *FnDecl) {
11086   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11087   if (isa<NamespaceDecl>(DC)) {
11088     return SemaRef.Diag(FnDecl->getLocation(),
11089                         diag::err_operator_new_delete_declared_in_namespace)
11090       << FnDecl->getDeclName();
11091   }
11092 
11093   if (isa<TranslationUnitDecl>(DC) &&
11094       FnDecl->getStorageClass() == SC_Static) {
11095     return SemaRef.Diag(FnDecl->getLocation(),
11096                         diag::err_operator_new_delete_declared_static)
11097       << FnDecl->getDeclName();
11098   }
11099 
11100   return false;
11101 }
11102 
11103 static inline bool
11104 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11105                             CanQualType ExpectedResultType,
11106                             CanQualType ExpectedFirstParamType,
11107                             unsigned DependentParamTypeDiag,
11108                             unsigned InvalidParamTypeDiag) {
11109   QualType ResultType =
11110       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11111 
11112   // Check that the result type is not dependent.
11113   if (ResultType->isDependentType())
11114     return SemaRef.Diag(FnDecl->getLocation(),
11115                         diag::err_operator_new_delete_dependent_result_type)
11116     << FnDecl->getDeclName() << ExpectedResultType;
11117 
11118   // Check that the result type is what we expect.
11119   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11120     return SemaRef.Diag(FnDecl->getLocation(),
11121                         diag::err_operator_new_delete_invalid_result_type)
11122     << FnDecl->getDeclName() << ExpectedResultType;
11123 
11124   // A function template must have at least 2 parameters.
11125   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11126     return SemaRef.Diag(FnDecl->getLocation(),
11127                       diag::err_operator_new_delete_template_too_few_parameters)
11128         << FnDecl->getDeclName();
11129 
11130   // The function decl must have at least 1 parameter.
11131   if (FnDecl->getNumParams() == 0)
11132     return SemaRef.Diag(FnDecl->getLocation(),
11133                         diag::err_operator_new_delete_too_few_parameters)
11134       << FnDecl->getDeclName();
11135 
11136   // Check the first parameter type is not dependent.
11137   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11138   if (FirstParamType->isDependentType())
11139     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11140       << FnDecl->getDeclName() << ExpectedFirstParamType;
11141 
11142   // Check that the first parameter type is what we expect.
11143   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11144       ExpectedFirstParamType)
11145     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11146     << FnDecl->getDeclName() << ExpectedFirstParamType;
11147 
11148   return false;
11149 }
11150 
11151 static bool
11152 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11153   // C++ [basic.stc.dynamic.allocation]p1:
11154   //   A program is ill-formed if an allocation function is declared in a
11155   //   namespace scope other than global scope or declared static in global
11156   //   scope.
11157   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11158     return true;
11159 
11160   CanQualType SizeTy =
11161     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11162 
11163   // C++ [basic.stc.dynamic.allocation]p1:
11164   //  The return type shall be void*. The first parameter shall have type
11165   //  std::size_t.
11166   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11167                                   SizeTy,
11168                                   diag::err_operator_new_dependent_param_type,
11169                                   diag::err_operator_new_param_type))
11170     return true;
11171 
11172   // C++ [basic.stc.dynamic.allocation]p1:
11173   //  The first parameter shall not have an associated default argument.
11174   if (FnDecl->getParamDecl(0)->hasDefaultArg())
11175     return SemaRef.Diag(FnDecl->getLocation(),
11176                         diag::err_operator_new_default_arg)
11177       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11178 
11179   return false;
11180 }
11181 
11182 static bool
11183 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11184   // C++ [basic.stc.dynamic.deallocation]p1:
11185   //   A program is ill-formed if deallocation functions are declared in a
11186   //   namespace scope other than global scope or declared static in global
11187   //   scope.
11188   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11189     return true;
11190 
11191   // C++ [basic.stc.dynamic.deallocation]p2:
11192   //   Each deallocation function shall return void and its first parameter
11193   //   shall be void*.
11194   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11195                                   SemaRef.Context.VoidPtrTy,
11196                                  diag::err_operator_delete_dependent_param_type,
11197                                  diag::err_operator_delete_param_type))
11198     return true;
11199 
11200   return false;
11201 }
11202 
11203 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11204 /// of this overloaded operator is well-formed. If so, returns false;
11205 /// otherwise, emits appropriate diagnostics and returns true.
11206 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11207   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11208          "Expected an overloaded operator declaration");
11209 
11210   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11211 
11212   // C++ [over.oper]p5:
11213   //   The allocation and deallocation functions, operator new,
11214   //   operator new[], operator delete and operator delete[], are
11215   //   described completely in 3.7.3. The attributes and restrictions
11216   //   found in the rest of this subclause do not apply to them unless
11217   //   explicitly stated in 3.7.3.
11218   if (Op == OO_Delete || Op == OO_Array_Delete)
11219     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11220 
11221   if (Op == OO_New || Op == OO_Array_New)
11222     return CheckOperatorNewDeclaration(*this, FnDecl);
11223 
11224   // C++ [over.oper]p6:
11225   //   An operator function shall either be a non-static member
11226   //   function or be a non-member function and have at least one
11227   //   parameter whose type is a class, a reference to a class, an
11228   //   enumeration, or a reference to an enumeration.
11229   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11230     if (MethodDecl->isStatic())
11231       return Diag(FnDecl->getLocation(),
11232                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11233   } else {
11234     bool ClassOrEnumParam = false;
11235     for (auto Param : FnDecl->params()) {
11236       QualType ParamType = Param->getType().getNonReferenceType();
11237       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11238           ParamType->isEnumeralType()) {
11239         ClassOrEnumParam = true;
11240         break;
11241       }
11242     }
11243 
11244     if (!ClassOrEnumParam)
11245       return Diag(FnDecl->getLocation(),
11246                   diag::err_operator_overload_needs_class_or_enum)
11247         << FnDecl->getDeclName();
11248   }
11249 
11250   // C++ [over.oper]p8:
11251   //   An operator function cannot have default arguments (8.3.6),
11252   //   except where explicitly stated below.
11253   //
11254   // Only the function-call operator allows default arguments
11255   // (C++ [over.call]p1).
11256   if (Op != OO_Call) {
11257     for (auto Param : FnDecl->params()) {
11258       if (Param->hasDefaultArg())
11259         return Diag(Param->getLocation(),
11260                     diag::err_operator_overload_default_arg)
11261           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11262     }
11263   }
11264 
11265   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11266     { false, false, false }
11267 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11268     , { Unary, Binary, MemberOnly }
11269 #include "clang/Basic/OperatorKinds.def"
11270   };
11271 
11272   bool CanBeUnaryOperator = OperatorUses[Op][0];
11273   bool CanBeBinaryOperator = OperatorUses[Op][1];
11274   bool MustBeMemberOperator = OperatorUses[Op][2];
11275 
11276   // C++ [over.oper]p8:
11277   //   [...] Operator functions cannot have more or fewer parameters
11278   //   than the number required for the corresponding operator, as
11279   //   described in the rest of this subclause.
11280   unsigned NumParams = FnDecl->getNumParams()
11281                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11282   if (Op != OO_Call &&
11283       ((NumParams == 1 && !CanBeUnaryOperator) ||
11284        (NumParams == 2 && !CanBeBinaryOperator) ||
11285        (NumParams < 1) || (NumParams > 2))) {
11286     // We have the wrong number of parameters.
11287     unsigned ErrorKind;
11288     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11289       ErrorKind = 2;  // 2 -> unary or binary.
11290     } else if (CanBeUnaryOperator) {
11291       ErrorKind = 0;  // 0 -> unary
11292     } else {
11293       assert(CanBeBinaryOperator &&
11294              "All non-call overloaded operators are unary or binary!");
11295       ErrorKind = 1;  // 1 -> binary
11296     }
11297 
11298     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11299       << FnDecl->getDeclName() << NumParams << ErrorKind;
11300   }
11301 
11302   // Overloaded operators other than operator() cannot be variadic.
11303   if (Op != OO_Call &&
11304       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11305     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11306       << FnDecl->getDeclName();
11307   }
11308 
11309   // Some operators must be non-static member functions.
11310   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11311     return Diag(FnDecl->getLocation(),
11312                 diag::err_operator_overload_must_be_member)
11313       << FnDecl->getDeclName();
11314   }
11315 
11316   // C++ [over.inc]p1:
11317   //   The user-defined function called operator++ implements the
11318   //   prefix and postfix ++ operator. If this function is a member
11319   //   function with no parameters, or a non-member function with one
11320   //   parameter of class or enumeration type, it defines the prefix
11321   //   increment operator ++ for objects of that type. If the function
11322   //   is a member function with one parameter (which shall be of type
11323   //   int) or a non-member function with two parameters (the second
11324   //   of which shall be of type int), it defines the postfix
11325   //   increment operator ++ for objects of that type.
11326   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11327     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11328     QualType ParamType = LastParam->getType();
11329 
11330     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11331         !ParamType->isDependentType())
11332       return Diag(LastParam->getLocation(),
11333                   diag::err_operator_overload_post_incdec_must_be_int)
11334         << LastParam->getType() << (Op == OO_MinusMinus);
11335   }
11336 
11337   return false;
11338 }
11339 
11340 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11341 /// of this literal operator function is well-formed. If so, returns
11342 /// false; otherwise, emits appropriate diagnostics and returns true.
11343 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11344   if (isa<CXXMethodDecl>(FnDecl)) {
11345     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11346       << FnDecl->getDeclName();
11347     return true;
11348   }
11349 
11350   if (FnDecl->isExternC()) {
11351     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11352     return true;
11353   }
11354 
11355   bool Valid = false;
11356 
11357   // This might be the definition of a literal operator template.
11358   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11359   // This might be a specialization of a literal operator template.
11360   if (!TpDecl)
11361     TpDecl = FnDecl->getPrimaryTemplate();
11362 
11363   // template <char...> type operator "" name() and
11364   // template <class T, T...> type operator "" name() are the only valid
11365   // template signatures, and the only valid signatures with no parameters.
11366   if (TpDecl) {
11367     if (FnDecl->param_size() == 0) {
11368       // Must have one or two template parameters
11369       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11370       if (Params->size() == 1) {
11371         NonTypeTemplateParmDecl *PmDecl =
11372           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11373 
11374         // The template parameter must be a char parameter pack.
11375         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11376             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11377           Valid = true;
11378       } else if (Params->size() == 2) {
11379         TemplateTypeParmDecl *PmType =
11380           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11381         NonTypeTemplateParmDecl *PmArgs =
11382           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11383 
11384         // The second template parameter must be a parameter pack with the
11385         // first template parameter as its type.
11386         if (PmType && PmArgs &&
11387             !PmType->isTemplateParameterPack() &&
11388             PmArgs->isTemplateParameterPack()) {
11389           const TemplateTypeParmType *TArgs =
11390             PmArgs->getType()->getAs<TemplateTypeParmType>();
11391           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11392               TArgs->getIndex() == PmType->getIndex()) {
11393             Valid = true;
11394             if (ActiveTemplateInstantiations.empty())
11395               Diag(FnDecl->getLocation(),
11396                    diag::ext_string_literal_operator_template);
11397           }
11398         }
11399       }
11400     }
11401   } else if (FnDecl->param_size()) {
11402     // Check the first parameter
11403     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11404 
11405     QualType T = (*Param)->getType().getUnqualifiedType();
11406 
11407     // unsigned long long int, long double, and any character type are allowed
11408     // as the only parameters.
11409     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11410         Context.hasSameType(T, Context.LongDoubleTy) ||
11411         Context.hasSameType(T, Context.CharTy) ||
11412         Context.hasSameType(T, Context.WideCharTy) ||
11413         Context.hasSameType(T, Context.Char16Ty) ||
11414         Context.hasSameType(T, Context.Char32Ty)) {
11415       if (++Param == FnDecl->param_end())
11416         Valid = true;
11417       goto FinishedParams;
11418     }
11419 
11420     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11421     const PointerType *PT = T->getAs<PointerType>();
11422     if (!PT)
11423       goto FinishedParams;
11424     T = PT->getPointeeType();
11425     if (!T.isConstQualified() || T.isVolatileQualified())
11426       goto FinishedParams;
11427     T = T.getUnqualifiedType();
11428 
11429     // Move on to the second parameter;
11430     ++Param;
11431 
11432     // If there is no second parameter, the first must be a const char *
11433     if (Param == FnDecl->param_end()) {
11434       if (Context.hasSameType(T, Context.CharTy))
11435         Valid = true;
11436       goto FinishedParams;
11437     }
11438 
11439     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11440     // are allowed as the first parameter to a two-parameter function
11441     if (!(Context.hasSameType(T, Context.CharTy) ||
11442           Context.hasSameType(T, Context.WideCharTy) ||
11443           Context.hasSameType(T, Context.Char16Ty) ||
11444           Context.hasSameType(T, Context.Char32Ty)))
11445       goto FinishedParams;
11446 
11447     // The second and final parameter must be an std::size_t
11448     T = (*Param)->getType().getUnqualifiedType();
11449     if (Context.hasSameType(T, Context.getSizeType()) &&
11450         ++Param == FnDecl->param_end())
11451       Valid = true;
11452   }
11453 
11454   // FIXME: This diagnostic is absolutely terrible.
11455 FinishedParams:
11456   if (!Valid) {
11457     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11458       << FnDecl->getDeclName();
11459     return true;
11460   }
11461 
11462   // A parameter-declaration-clause containing a default argument is not
11463   // equivalent to any of the permitted forms.
11464   for (auto Param : FnDecl->params()) {
11465     if (Param->hasDefaultArg()) {
11466       Diag(Param->getDefaultArgRange().getBegin(),
11467            diag::err_literal_operator_default_argument)
11468         << Param->getDefaultArgRange();
11469       break;
11470     }
11471   }
11472 
11473   StringRef LiteralName
11474     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11475   if (LiteralName[0] != '_') {
11476     // C++11 [usrlit.suffix]p1:
11477     //   Literal suffix identifiers that do not start with an underscore
11478     //   are reserved for future standardization.
11479     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11480       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11481   }
11482 
11483   return false;
11484 }
11485 
11486 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11487 /// linkage specification, including the language and (if present)
11488 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11489 /// language string literal. LBraceLoc, if valid, provides the location of
11490 /// the '{' brace. Otherwise, this linkage specification does not
11491 /// have any braces.
11492 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11493                                            Expr *LangStr,
11494                                            SourceLocation LBraceLoc) {
11495   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11496   if (!Lit->isAscii()) {
11497     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11498       << LangStr->getSourceRange();
11499     return nullptr;
11500   }
11501 
11502   StringRef Lang = Lit->getString();
11503   LinkageSpecDecl::LanguageIDs Language;
11504   if (Lang == "C")
11505     Language = LinkageSpecDecl::lang_c;
11506   else if (Lang == "C++")
11507     Language = LinkageSpecDecl::lang_cxx;
11508   else {
11509     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11510       << LangStr->getSourceRange();
11511     return nullptr;
11512   }
11513 
11514   // FIXME: Add all the various semantics of linkage specifications
11515 
11516   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11517                                                LangStr->getExprLoc(), Language,
11518                                                LBraceLoc.isValid());
11519   CurContext->addDecl(D);
11520   PushDeclContext(S, D);
11521   return D;
11522 }
11523 
11524 /// ActOnFinishLinkageSpecification - Complete the definition of
11525 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11526 /// valid, it's the position of the closing '}' brace in a linkage
11527 /// specification that uses braces.
11528 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11529                                             Decl *LinkageSpec,
11530                                             SourceLocation RBraceLoc) {
11531   if (RBraceLoc.isValid()) {
11532     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11533     LSDecl->setRBraceLoc(RBraceLoc);
11534   }
11535   PopDeclContext();
11536   return LinkageSpec;
11537 }
11538 
11539 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11540                                   AttributeList *AttrList,
11541                                   SourceLocation SemiLoc) {
11542   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11543   // Attribute declarations appertain to empty declaration so we handle
11544   // them here.
11545   if (AttrList)
11546     ProcessDeclAttributeList(S, ED, AttrList);
11547 
11548   CurContext->addDecl(ED);
11549   return ED;
11550 }
11551 
11552 /// \brief Perform semantic analysis for the variable declaration that
11553 /// occurs within a C++ catch clause, returning the newly-created
11554 /// variable.
11555 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11556                                          TypeSourceInfo *TInfo,
11557                                          SourceLocation StartLoc,
11558                                          SourceLocation Loc,
11559                                          IdentifierInfo *Name) {
11560   bool Invalid = false;
11561   QualType ExDeclType = TInfo->getType();
11562 
11563   // Arrays and functions decay.
11564   if (ExDeclType->isArrayType())
11565     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11566   else if (ExDeclType->isFunctionType())
11567     ExDeclType = Context.getPointerType(ExDeclType);
11568 
11569   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11570   // The exception-declaration shall not denote a pointer or reference to an
11571   // incomplete type, other than [cv] void*.
11572   // N2844 forbids rvalue references.
11573   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11574     Diag(Loc, diag::err_catch_rvalue_ref);
11575     Invalid = true;
11576   }
11577 
11578   QualType BaseType = ExDeclType;
11579   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11580   unsigned DK = diag::err_catch_incomplete;
11581   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11582     BaseType = Ptr->getPointeeType();
11583     Mode = 1;
11584     DK = diag::err_catch_incomplete_ptr;
11585   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11586     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11587     BaseType = Ref->getPointeeType();
11588     Mode = 2;
11589     DK = diag::err_catch_incomplete_ref;
11590   }
11591   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11592       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11593     Invalid = true;
11594 
11595   if (!Invalid && !ExDeclType->isDependentType() &&
11596       RequireNonAbstractType(Loc, ExDeclType,
11597                              diag::err_abstract_type_in_decl,
11598                              AbstractVariableType))
11599     Invalid = true;
11600 
11601   // Only the non-fragile NeXT runtime currently supports C++ catches
11602   // of ObjC types, and no runtime supports catching ObjC types by value.
11603   if (!Invalid && getLangOpts().ObjC1) {
11604     QualType T = ExDeclType;
11605     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11606       T = RT->getPointeeType();
11607 
11608     if (T->isObjCObjectType()) {
11609       Diag(Loc, diag::err_objc_object_catch);
11610       Invalid = true;
11611     } else if (T->isObjCObjectPointerType()) {
11612       // FIXME: should this be a test for macosx-fragile specifically?
11613       if (getLangOpts().ObjCRuntime.isFragile())
11614         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11615     }
11616   }
11617 
11618   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11619                                     ExDeclType, TInfo, SC_None);
11620   ExDecl->setExceptionVariable(true);
11621 
11622   // In ARC, infer 'retaining' for variables of retainable type.
11623   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11624     Invalid = true;
11625 
11626   if (!Invalid && !ExDeclType->isDependentType()) {
11627     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11628       // Insulate this from anything else we might currently be parsing.
11629       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11630 
11631       // C++ [except.handle]p16:
11632       //   The object declared in an exception-declaration or, if the
11633       //   exception-declaration does not specify a name, a temporary (12.2) is
11634       //   copy-initialized (8.5) from the exception object. [...]
11635       //   The object is destroyed when the handler exits, after the destruction
11636       //   of any automatic objects initialized within the handler.
11637       //
11638       // We just pretend to initialize the object with itself, then make sure
11639       // it can be destroyed later.
11640       QualType initType = ExDeclType;
11641 
11642       InitializedEntity entity =
11643         InitializedEntity::InitializeVariable(ExDecl);
11644       InitializationKind initKind =
11645         InitializationKind::CreateCopy(Loc, SourceLocation());
11646 
11647       Expr *opaqueValue =
11648         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11649       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11650       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11651       if (result.isInvalid())
11652         Invalid = true;
11653       else {
11654         // If the constructor used was non-trivial, set this as the
11655         // "initializer".
11656         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
11657         if (!construct->getConstructor()->isTrivial()) {
11658           Expr *init = MaybeCreateExprWithCleanups(construct);
11659           ExDecl->setInit(init);
11660         }
11661 
11662         // And make sure it's destructable.
11663         FinalizeVarWithDestructor(ExDecl, recordType);
11664       }
11665     }
11666   }
11667 
11668   if (Invalid)
11669     ExDecl->setInvalidDecl();
11670 
11671   return ExDecl;
11672 }
11673 
11674 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11675 /// handler.
11676 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11677   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11678   bool Invalid = D.isInvalidType();
11679 
11680   // Check for unexpanded parameter packs.
11681   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11682                                       UPPC_ExceptionType)) {
11683     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11684                                              D.getIdentifierLoc());
11685     Invalid = true;
11686   }
11687 
11688   IdentifierInfo *II = D.getIdentifier();
11689   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11690                                              LookupOrdinaryName,
11691                                              ForRedeclaration)) {
11692     // The scope should be freshly made just for us. There is just no way
11693     // it contains any previous declaration, except for function parameters in
11694     // a function-try-block's catch statement.
11695     assert(!S->isDeclScope(PrevDecl));
11696     if (isDeclInScope(PrevDecl, CurContext, S)) {
11697       Diag(D.getIdentifierLoc(), diag::err_redefinition)
11698         << D.getIdentifier();
11699       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11700       Invalid = true;
11701     } else if (PrevDecl->isTemplateParameter())
11702       // Maybe we will complain about the shadowed template parameter.
11703       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11704   }
11705 
11706   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11707     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11708       << D.getCXXScopeSpec().getRange();
11709     Invalid = true;
11710   }
11711 
11712   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11713                                               D.getLocStart(),
11714                                               D.getIdentifierLoc(),
11715                                               D.getIdentifier());
11716   if (Invalid)
11717     ExDecl->setInvalidDecl();
11718 
11719   // Add the exception declaration into this scope.
11720   if (II)
11721     PushOnScopeChains(ExDecl, S);
11722   else
11723     CurContext->addDecl(ExDecl);
11724 
11725   ProcessDeclAttributes(S, ExDecl, D);
11726   return ExDecl;
11727 }
11728 
11729 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11730                                          Expr *AssertExpr,
11731                                          Expr *AssertMessageExpr,
11732                                          SourceLocation RParenLoc) {
11733   StringLiteral *AssertMessage =
11734       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
11735 
11736   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11737     return nullptr;
11738 
11739   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11740                                       AssertMessage, RParenLoc, false);
11741 }
11742 
11743 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11744                                          Expr *AssertExpr,
11745                                          StringLiteral *AssertMessage,
11746                                          SourceLocation RParenLoc,
11747                                          bool Failed) {
11748   assert(AssertExpr != nullptr && "Expected non-null condition");
11749   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11750       !Failed) {
11751     // In a static_assert-declaration, the constant-expression shall be a
11752     // constant expression that can be contextually converted to bool.
11753     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11754     if (Converted.isInvalid())
11755       Failed = true;
11756 
11757     llvm::APSInt Cond;
11758     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11759           diag::err_static_assert_expression_is_not_constant,
11760           /*AllowFold=*/false).isInvalid())
11761       Failed = true;
11762 
11763     if (!Failed && !Cond) {
11764       SmallString<256> MsgBuffer;
11765       llvm::raw_svector_ostream Msg(MsgBuffer);
11766       if (AssertMessage)
11767         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
11768       Diag(StaticAssertLoc, diag::err_static_assert_failed)
11769         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
11770       Failed = true;
11771     }
11772   }
11773 
11774   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11775                                         AssertExpr, AssertMessage, RParenLoc,
11776                                         Failed);
11777 
11778   CurContext->addDecl(Decl);
11779   return Decl;
11780 }
11781 
11782 /// \brief Perform semantic analysis of the given friend type declaration.
11783 ///
11784 /// \returns A friend declaration that.
11785 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11786                                       SourceLocation FriendLoc,
11787                                       TypeSourceInfo *TSInfo) {
11788   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11789 
11790   QualType T = TSInfo->getType();
11791   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11792 
11793   // C++03 [class.friend]p2:
11794   //   An elaborated-type-specifier shall be used in a friend declaration
11795   //   for a class.*
11796   //
11797   //   * The class-key of the elaborated-type-specifier is required.
11798   if (!ActiveTemplateInstantiations.empty()) {
11799     // Do not complain about the form of friend template types during
11800     // template instantiation; we will already have complained when the
11801     // template was declared.
11802   } else {
11803     if (!T->isElaboratedTypeSpecifier()) {
11804       // If we evaluated the type to a record type, suggest putting
11805       // a tag in front.
11806       if (const RecordType *RT = T->getAs<RecordType>()) {
11807         RecordDecl *RD = RT->getDecl();
11808 
11809         SmallString<16> InsertionText(" ");
11810         InsertionText += RD->getKindName();
11811 
11812         Diag(TypeRange.getBegin(),
11813              getLangOpts().CPlusPlus11 ?
11814                diag::warn_cxx98_compat_unelaborated_friend_type :
11815                diag::ext_unelaborated_friend_type)
11816           << (unsigned) RD->getTagKind()
11817           << T
11818           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11819                                         InsertionText);
11820       } else {
11821         Diag(FriendLoc,
11822              getLangOpts().CPlusPlus11 ?
11823                diag::warn_cxx98_compat_nonclass_type_friend :
11824                diag::ext_nonclass_type_friend)
11825           << T
11826           << TypeRange;
11827       }
11828     } else if (T->getAs<EnumType>()) {
11829       Diag(FriendLoc,
11830            getLangOpts().CPlusPlus11 ?
11831              diag::warn_cxx98_compat_enum_friend :
11832              diag::ext_enum_friend)
11833         << T
11834         << TypeRange;
11835     }
11836 
11837     // C++11 [class.friend]p3:
11838     //   A friend declaration that does not declare a function shall have one
11839     //   of the following forms:
11840     //     friend elaborated-type-specifier ;
11841     //     friend simple-type-specifier ;
11842     //     friend typename-specifier ;
11843     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11844       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11845   }
11846 
11847   //   If the type specifier in a friend declaration designates a (possibly
11848   //   cv-qualified) class type, that class is declared as a friend; otherwise,
11849   //   the friend declaration is ignored.
11850   return FriendDecl::Create(Context, CurContext,
11851                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
11852                             FriendLoc);
11853 }
11854 
11855 /// Handle a friend tag declaration where the scope specifier was
11856 /// templated.
11857 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11858                                     unsigned TagSpec, SourceLocation TagLoc,
11859                                     CXXScopeSpec &SS,
11860                                     IdentifierInfo *Name,
11861                                     SourceLocation NameLoc,
11862                                     AttributeList *Attr,
11863                                     MultiTemplateParamsArg TempParamLists) {
11864   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11865 
11866   bool isExplicitSpecialization = false;
11867   bool Invalid = false;
11868 
11869   if (TemplateParameterList *TemplateParams =
11870           MatchTemplateParametersToScopeSpecifier(
11871               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
11872               isExplicitSpecialization, Invalid)) {
11873     if (TemplateParams->size() > 0) {
11874       // This is a declaration of a class template.
11875       if (Invalid)
11876         return nullptr;
11877 
11878       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
11879                                 NameLoc, Attr, TemplateParams, AS_public,
11880                                 /*ModulePrivateLoc=*/SourceLocation(),
11881                                 FriendLoc, TempParamLists.size() - 1,
11882                                 TempParamLists.data()).get();
11883     } else {
11884       // The "template<>" header is extraneous.
11885       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11886         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11887       isExplicitSpecialization = true;
11888     }
11889   }
11890 
11891   if (Invalid) return nullptr;
11892 
11893   bool isAllExplicitSpecializations = true;
11894   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11895     if (TempParamLists[I]->size()) {
11896       isAllExplicitSpecializations = false;
11897       break;
11898     }
11899   }
11900 
11901   // FIXME: don't ignore attributes.
11902 
11903   // If it's explicit specializations all the way down, just forget
11904   // about the template header and build an appropriate non-templated
11905   // friend.  TODO: for source fidelity, remember the headers.
11906   if (isAllExplicitSpecializations) {
11907     if (SS.isEmpty()) {
11908       bool Owned = false;
11909       bool IsDependent = false;
11910       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11911                       Attr, AS_public,
11912                       /*ModulePrivateLoc=*/SourceLocation(),
11913                       MultiTemplateParamsArg(), Owned, IsDependent,
11914                       /*ScopedEnumKWLoc=*/SourceLocation(),
11915                       /*ScopedEnumUsesClassTag=*/false,
11916                       /*UnderlyingType=*/TypeResult(),
11917                       /*IsTypeSpecifier=*/false);
11918     }
11919 
11920     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11921     ElaboratedTypeKeyword Keyword
11922       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11923     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11924                                    *Name, NameLoc);
11925     if (T.isNull())
11926       return nullptr;
11927 
11928     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11929     if (isa<DependentNameType>(T)) {
11930       DependentNameTypeLoc TL =
11931           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11932       TL.setElaboratedKeywordLoc(TagLoc);
11933       TL.setQualifierLoc(QualifierLoc);
11934       TL.setNameLoc(NameLoc);
11935     } else {
11936       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11937       TL.setElaboratedKeywordLoc(TagLoc);
11938       TL.setQualifierLoc(QualifierLoc);
11939       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11940     }
11941 
11942     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11943                                             TSI, FriendLoc, TempParamLists);
11944     Friend->setAccess(AS_public);
11945     CurContext->addDecl(Friend);
11946     return Friend;
11947   }
11948 
11949   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11950 
11951 
11952 
11953   // Handle the case of a templated-scope friend class.  e.g.
11954   //   template <class T> class A<T>::B;
11955   // FIXME: we don't support these right now.
11956   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11957     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
11958   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11959   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11960   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11961   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11962   TL.setElaboratedKeywordLoc(TagLoc);
11963   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11964   TL.setNameLoc(NameLoc);
11965 
11966   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11967                                           TSI, FriendLoc, TempParamLists);
11968   Friend->setAccess(AS_public);
11969   Friend->setUnsupportedFriend(true);
11970   CurContext->addDecl(Friend);
11971   return Friend;
11972 }
11973 
11974 
11975 /// Handle a friend type declaration.  This works in tandem with
11976 /// ActOnTag.
11977 ///
11978 /// Notes on friend class templates:
11979 ///
11980 /// We generally treat friend class declarations as if they were
11981 /// declaring a class.  So, for example, the elaborated type specifier
11982 /// in a friend declaration is required to obey the restrictions of a
11983 /// class-head (i.e. no typedefs in the scope chain), template
11984 /// parameters are required to match up with simple template-ids, &c.
11985 /// However, unlike when declaring a template specialization, it's
11986 /// okay to refer to a template specialization without an empty
11987 /// template parameter declaration, e.g.
11988 ///   friend class A<T>::B<unsigned>;
11989 /// We permit this as a special case; if there are any template
11990 /// parameters present at all, require proper matching, i.e.
11991 ///   template <> template \<class T> friend class A<int>::B;
11992 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11993                                 MultiTemplateParamsArg TempParams) {
11994   SourceLocation Loc = DS.getLocStart();
11995 
11996   assert(DS.isFriendSpecified());
11997   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11998 
11999   // Try to convert the decl specifier to a type.  This works for
12000   // friend templates because ActOnTag never produces a ClassTemplateDecl
12001   // for a TUK_Friend.
12002   Declarator TheDeclarator(DS, Declarator::MemberContext);
12003   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12004   QualType T = TSI->getType();
12005   if (TheDeclarator.isInvalidType())
12006     return nullptr;
12007 
12008   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12009     return nullptr;
12010 
12011   // This is definitely an error in C++98.  It's probably meant to
12012   // be forbidden in C++0x, too, but the specification is just
12013   // poorly written.
12014   //
12015   // The problem is with declarations like the following:
12016   //   template <T> friend A<T>::foo;
12017   // where deciding whether a class C is a friend or not now hinges
12018   // on whether there exists an instantiation of A that causes
12019   // 'foo' to equal C.  There are restrictions on class-heads
12020   // (which we declare (by fiat) elaborated friend declarations to
12021   // be) that makes this tractable.
12022   //
12023   // FIXME: handle "template <> friend class A<T>;", which
12024   // is possibly well-formed?  Who even knows?
12025   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12026     Diag(Loc, diag::err_tagless_friend_type_template)
12027       << DS.getSourceRange();
12028     return nullptr;
12029   }
12030 
12031   // C++98 [class.friend]p1: A friend of a class is a function
12032   //   or class that is not a member of the class . . .
12033   // This is fixed in DR77, which just barely didn't make the C++03
12034   // deadline.  It's also a very silly restriction that seriously
12035   // affects inner classes and which nobody else seems to implement;
12036   // thus we never diagnose it, not even in -pedantic.
12037   //
12038   // But note that we could warn about it: it's always useless to
12039   // friend one of your own members (it's not, however, worthless to
12040   // friend a member of an arbitrary specialization of your template).
12041 
12042   Decl *D;
12043   if (unsigned NumTempParamLists = TempParams.size())
12044     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12045                                    NumTempParamLists,
12046                                    TempParams.data(),
12047                                    TSI,
12048                                    DS.getFriendSpecLoc());
12049   else
12050     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12051 
12052   if (!D)
12053     return nullptr;
12054 
12055   D->setAccess(AS_public);
12056   CurContext->addDecl(D);
12057 
12058   return D;
12059 }
12060 
12061 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12062                                         MultiTemplateParamsArg TemplateParams) {
12063   const DeclSpec &DS = D.getDeclSpec();
12064 
12065   assert(DS.isFriendSpecified());
12066   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12067 
12068   SourceLocation Loc = D.getIdentifierLoc();
12069   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12070 
12071   // C++ [class.friend]p1
12072   //   A friend of a class is a function or class....
12073   // Note that this sees through typedefs, which is intended.
12074   // It *doesn't* see through dependent types, which is correct
12075   // according to [temp.arg.type]p3:
12076   //   If a declaration acquires a function type through a
12077   //   type dependent on a template-parameter and this causes
12078   //   a declaration that does not use the syntactic form of a
12079   //   function declarator to have a function type, the program
12080   //   is ill-formed.
12081   if (!TInfo->getType()->isFunctionType()) {
12082     Diag(Loc, diag::err_unexpected_friend);
12083 
12084     // It might be worthwhile to try to recover by creating an
12085     // appropriate declaration.
12086     return nullptr;
12087   }
12088 
12089   // C++ [namespace.memdef]p3
12090   //  - If a friend declaration in a non-local class first declares a
12091   //    class or function, the friend class or function is a member
12092   //    of the innermost enclosing namespace.
12093   //  - The name of the friend is not found by simple name lookup
12094   //    until a matching declaration is provided in that namespace
12095   //    scope (either before or after the class declaration granting
12096   //    friendship).
12097   //  - If a friend function is called, its name may be found by the
12098   //    name lookup that considers functions from namespaces and
12099   //    classes associated with the types of the function arguments.
12100   //  - When looking for a prior declaration of a class or a function
12101   //    declared as a friend, scopes outside the innermost enclosing
12102   //    namespace scope are not considered.
12103 
12104   CXXScopeSpec &SS = D.getCXXScopeSpec();
12105   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12106   DeclarationName Name = NameInfo.getName();
12107   assert(Name);
12108 
12109   // Check for unexpanded parameter packs.
12110   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12111       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12112       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12113     return nullptr;
12114 
12115   // The context we found the declaration in, or in which we should
12116   // create the declaration.
12117   DeclContext *DC;
12118   Scope *DCScope = S;
12119   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12120                         ForRedeclaration);
12121 
12122   // There are five cases here.
12123   //   - There's no scope specifier and we're in a local class. Only look
12124   //     for functions declared in the immediately-enclosing block scope.
12125   // We recover from invalid scope qualifiers as if they just weren't there.
12126   FunctionDecl *FunctionContainingLocalClass = nullptr;
12127   if ((SS.isInvalid() || !SS.isSet()) &&
12128       (FunctionContainingLocalClass =
12129            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12130     // C++11 [class.friend]p11:
12131     //   If a friend declaration appears in a local class and the name
12132     //   specified is an unqualified name, a prior declaration is
12133     //   looked up without considering scopes that are outside the
12134     //   innermost enclosing non-class scope. For a friend function
12135     //   declaration, if there is no prior declaration, the program is
12136     //   ill-formed.
12137 
12138     // Find the innermost enclosing non-class scope. This is the block
12139     // scope containing the local class definition (or for a nested class,
12140     // the outer local class).
12141     DCScope = S->getFnParent();
12142 
12143     // Look up the function name in the scope.
12144     Previous.clear(LookupLocalFriendName);
12145     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12146 
12147     if (!Previous.empty()) {
12148       // All possible previous declarations must have the same context:
12149       // either they were declared at block scope or they are members of
12150       // one of the enclosing local classes.
12151       DC = Previous.getRepresentativeDecl()->getDeclContext();
12152     } else {
12153       // This is ill-formed, but provide the context that we would have
12154       // declared the function in, if we were permitted to, for error recovery.
12155       DC = FunctionContainingLocalClass;
12156     }
12157     adjustContextForLocalExternDecl(DC);
12158 
12159     // C++ [class.friend]p6:
12160     //   A function can be defined in a friend declaration of a class if and
12161     //   only if the class is a non-local class (9.8), the function name is
12162     //   unqualified, and the function has namespace scope.
12163     if (D.isFunctionDefinition()) {
12164       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12165     }
12166 
12167   //   - There's no scope specifier, in which case we just go to the
12168   //     appropriate scope and look for a function or function template
12169   //     there as appropriate.
12170   } else if (SS.isInvalid() || !SS.isSet()) {
12171     // C++11 [namespace.memdef]p3:
12172     //   If the name in a friend declaration is neither qualified nor
12173     //   a template-id and the declaration is a function or an
12174     //   elaborated-type-specifier, the lookup to determine whether
12175     //   the entity has been previously declared shall not consider
12176     //   any scopes outside the innermost enclosing namespace.
12177     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12178 
12179     // Find the appropriate context according to the above.
12180     DC = CurContext;
12181 
12182     // Skip class contexts.  If someone can cite chapter and verse
12183     // for this behavior, that would be nice --- it's what GCC and
12184     // EDG do, and it seems like a reasonable intent, but the spec
12185     // really only says that checks for unqualified existing
12186     // declarations should stop at the nearest enclosing namespace,
12187     // not that they should only consider the nearest enclosing
12188     // namespace.
12189     while (DC->isRecord())
12190       DC = DC->getParent();
12191 
12192     DeclContext *LookupDC = DC;
12193     while (LookupDC->isTransparentContext())
12194       LookupDC = LookupDC->getParent();
12195 
12196     while (true) {
12197       LookupQualifiedName(Previous, LookupDC);
12198 
12199       if (!Previous.empty()) {
12200         DC = LookupDC;
12201         break;
12202       }
12203 
12204       if (isTemplateId) {
12205         if (isa<TranslationUnitDecl>(LookupDC)) break;
12206       } else {
12207         if (LookupDC->isFileContext()) break;
12208       }
12209       LookupDC = LookupDC->getParent();
12210     }
12211 
12212     DCScope = getScopeForDeclContext(S, DC);
12213 
12214   //   - There's a non-dependent scope specifier, in which case we
12215   //     compute it and do a previous lookup there for a function
12216   //     or function template.
12217   } else if (!SS.getScopeRep()->isDependent()) {
12218     DC = computeDeclContext(SS);
12219     if (!DC) return nullptr;
12220 
12221     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12222 
12223     LookupQualifiedName(Previous, DC);
12224 
12225     // Ignore things found implicitly in the wrong scope.
12226     // TODO: better diagnostics for this case.  Suggesting the right
12227     // qualified scope would be nice...
12228     LookupResult::Filter F = Previous.makeFilter();
12229     while (F.hasNext()) {
12230       NamedDecl *D = F.next();
12231       if (!DC->InEnclosingNamespaceSetOf(
12232               D->getDeclContext()->getRedeclContext()))
12233         F.erase();
12234     }
12235     F.done();
12236 
12237     if (Previous.empty()) {
12238       D.setInvalidType();
12239       Diag(Loc, diag::err_qualified_friend_not_found)
12240           << Name << TInfo->getType();
12241       return nullptr;
12242     }
12243 
12244     // C++ [class.friend]p1: A friend of a class is a function or
12245     //   class that is not a member of the class . . .
12246     if (DC->Equals(CurContext))
12247       Diag(DS.getFriendSpecLoc(),
12248            getLangOpts().CPlusPlus11 ?
12249              diag::warn_cxx98_compat_friend_is_member :
12250              diag::err_friend_is_member);
12251 
12252     if (D.isFunctionDefinition()) {
12253       // C++ [class.friend]p6:
12254       //   A function can be defined in a friend declaration of a class if and
12255       //   only if the class is a non-local class (9.8), the function name is
12256       //   unqualified, and the function has namespace scope.
12257       SemaDiagnosticBuilder DB
12258         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12259 
12260       DB << SS.getScopeRep();
12261       if (DC->isFileContext())
12262         DB << FixItHint::CreateRemoval(SS.getRange());
12263       SS.clear();
12264     }
12265 
12266   //   - There's a scope specifier that does not match any template
12267   //     parameter lists, in which case we use some arbitrary context,
12268   //     create a method or method template, and wait for instantiation.
12269   //   - There's a scope specifier that does match some template
12270   //     parameter lists, which we don't handle right now.
12271   } else {
12272     if (D.isFunctionDefinition()) {
12273       // C++ [class.friend]p6:
12274       //   A function can be defined in a friend declaration of a class if and
12275       //   only if the class is a non-local class (9.8), the function name is
12276       //   unqualified, and the function has namespace scope.
12277       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12278         << SS.getScopeRep();
12279     }
12280 
12281     DC = CurContext;
12282     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12283   }
12284 
12285   if (!DC->isRecord()) {
12286     // This implies that it has to be an operator or function.
12287     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12288         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12289         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12290       Diag(Loc, diag::err_introducing_special_friend) <<
12291         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12292          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12293       return nullptr;
12294     }
12295   }
12296 
12297   // FIXME: This is an egregious hack to cope with cases where the scope stack
12298   // does not contain the declaration context, i.e., in an out-of-line
12299   // definition of a class.
12300   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12301   if (!DCScope) {
12302     FakeDCScope.setEntity(DC);
12303     DCScope = &FakeDCScope;
12304   }
12305 
12306   bool AddToScope = true;
12307   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12308                                           TemplateParams, AddToScope);
12309   if (!ND) return nullptr;
12310 
12311   assert(ND->getLexicalDeclContext() == CurContext);
12312 
12313   // If we performed typo correction, we might have added a scope specifier
12314   // and changed the decl context.
12315   DC = ND->getDeclContext();
12316 
12317   // Add the function declaration to the appropriate lookup tables,
12318   // adjusting the redeclarations list as necessary.  We don't
12319   // want to do this yet if the friending class is dependent.
12320   //
12321   // Also update the scope-based lookup if the target context's
12322   // lookup context is in lexical scope.
12323   if (!CurContext->isDependentContext()) {
12324     DC = DC->getRedeclContext();
12325     DC->makeDeclVisibleInContext(ND);
12326     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12327       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12328   }
12329 
12330   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12331                                        D.getIdentifierLoc(), ND,
12332                                        DS.getFriendSpecLoc());
12333   FrD->setAccess(AS_public);
12334   CurContext->addDecl(FrD);
12335 
12336   if (ND->isInvalidDecl()) {
12337     FrD->setInvalidDecl();
12338   } else {
12339     if (DC->isRecord()) CheckFriendAccess(ND);
12340 
12341     FunctionDecl *FD;
12342     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12343       FD = FTD->getTemplatedDecl();
12344     else
12345       FD = cast<FunctionDecl>(ND);
12346 
12347     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12348     // default argument expression, that declaration shall be a definition
12349     // and shall be the only declaration of the function or function
12350     // template in the translation unit.
12351     if (functionDeclHasDefaultArgument(FD)) {
12352       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12353         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12354         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12355       } else if (!D.isFunctionDefinition())
12356         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12357     }
12358 
12359     // Mark templated-scope function declarations as unsupported.
12360     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12361       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12362         << SS.getScopeRep() << SS.getRange()
12363         << cast<CXXRecordDecl>(CurContext);
12364       FrD->setUnsupportedFriend(true);
12365     }
12366   }
12367 
12368   return ND;
12369 }
12370 
12371 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12372   AdjustDeclIfTemplate(Dcl);
12373 
12374   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12375   if (!Fn) {
12376     Diag(DelLoc, diag::err_deleted_non_function);
12377     return;
12378   }
12379 
12380   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12381     // Don't consider the implicit declaration we generate for explicit
12382     // specializations. FIXME: Do not generate these implicit declarations.
12383     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12384          Prev->getPreviousDecl()) &&
12385         !Prev->isDefined()) {
12386       Diag(DelLoc, diag::err_deleted_decl_not_first);
12387       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12388            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12389                               : diag::note_previous_declaration);
12390     }
12391     // If the declaration wasn't the first, we delete the function anyway for
12392     // recovery.
12393     Fn = Fn->getCanonicalDecl();
12394   }
12395 
12396   // dllimport/dllexport cannot be deleted.
12397   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12398     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12399     Fn->setInvalidDecl();
12400   }
12401 
12402   if (Fn->isDeleted())
12403     return;
12404 
12405   // See if we're deleting a function which is already known to override a
12406   // non-deleted virtual function.
12407   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12408     bool IssuedDiagnostic = false;
12409     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12410                                         E = MD->end_overridden_methods();
12411          I != E; ++I) {
12412       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12413         if (!IssuedDiagnostic) {
12414           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12415           IssuedDiagnostic = true;
12416         }
12417         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12418       }
12419     }
12420   }
12421 
12422   // C++11 [basic.start.main]p3:
12423   //   A program that defines main as deleted [...] is ill-formed.
12424   if (Fn->isMain())
12425     Diag(DelLoc, diag::err_deleted_main);
12426 
12427   Fn->setDeletedAsWritten();
12428 }
12429 
12430 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12431   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12432 
12433   if (MD) {
12434     if (MD->getParent()->isDependentType()) {
12435       MD->setDefaulted();
12436       MD->setExplicitlyDefaulted();
12437       return;
12438     }
12439 
12440     CXXSpecialMember Member = getSpecialMember(MD);
12441     if (Member == CXXInvalid) {
12442       if (!MD->isInvalidDecl())
12443         Diag(DefaultLoc, diag::err_default_special_members);
12444       return;
12445     }
12446 
12447     MD->setDefaulted();
12448     MD->setExplicitlyDefaulted();
12449 
12450     // If this definition appears within the record, do the checking when
12451     // the record is complete.
12452     const FunctionDecl *Primary = MD;
12453     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12454       // Find the uninstantiated declaration that actually had the '= default'
12455       // on it.
12456       Pattern->isDefined(Primary);
12457 
12458     // If the method was defaulted on its first declaration, we will have
12459     // already performed the checking in CheckCompletedCXXClass. Such a
12460     // declaration doesn't trigger an implicit definition.
12461     if (Primary == Primary->getCanonicalDecl())
12462       return;
12463 
12464     CheckExplicitlyDefaultedSpecialMember(MD);
12465 
12466     if (MD->isInvalidDecl())
12467       return;
12468 
12469     switch (Member) {
12470     case CXXDefaultConstructor:
12471       DefineImplicitDefaultConstructor(DefaultLoc,
12472                                        cast<CXXConstructorDecl>(MD));
12473       break;
12474     case CXXCopyConstructor:
12475       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12476       break;
12477     case CXXCopyAssignment:
12478       DefineImplicitCopyAssignment(DefaultLoc, MD);
12479       break;
12480     case CXXDestructor:
12481       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12482       break;
12483     case CXXMoveConstructor:
12484       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12485       break;
12486     case CXXMoveAssignment:
12487       DefineImplicitMoveAssignment(DefaultLoc, MD);
12488       break;
12489     case CXXInvalid:
12490       llvm_unreachable("Invalid special member.");
12491     }
12492   } else {
12493     Diag(DefaultLoc, diag::err_default_special_members);
12494   }
12495 }
12496 
12497 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12498   for (Stmt::child_range CI = S->children(); CI; ++CI) {
12499     Stmt *SubStmt = *CI;
12500     if (!SubStmt)
12501       continue;
12502     if (isa<ReturnStmt>(SubStmt))
12503       Self.Diag(SubStmt->getLocStart(),
12504            diag::err_return_in_constructor_handler);
12505     if (!isa<Expr>(SubStmt))
12506       SearchForReturnInStmt(Self, SubStmt);
12507   }
12508 }
12509 
12510 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12511   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12512     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12513     SearchForReturnInStmt(*this, Handler);
12514   }
12515 }
12516 
12517 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12518                                              const CXXMethodDecl *Old) {
12519   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12520   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12521 
12522   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12523 
12524   // If the calling conventions match, everything is fine
12525   if (NewCC == OldCC)
12526     return false;
12527 
12528   // If the calling conventions mismatch because the new function is static,
12529   // suppress the calling convention mismatch error; the error about static
12530   // function override (err_static_overrides_virtual from
12531   // Sema::CheckFunctionDeclaration) is more clear.
12532   if (New->getStorageClass() == SC_Static)
12533     return false;
12534 
12535   Diag(New->getLocation(),
12536        diag::err_conflicting_overriding_cc_attributes)
12537     << New->getDeclName() << New->getType() << Old->getType();
12538   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12539   return true;
12540 }
12541 
12542 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12543                                              const CXXMethodDecl *Old) {
12544   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12545   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12546 
12547   if (Context.hasSameType(NewTy, OldTy) ||
12548       NewTy->isDependentType() || OldTy->isDependentType())
12549     return false;
12550 
12551   // Check if the return types are covariant
12552   QualType NewClassTy, OldClassTy;
12553 
12554   /// Both types must be pointers or references to classes.
12555   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12556     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12557       NewClassTy = NewPT->getPointeeType();
12558       OldClassTy = OldPT->getPointeeType();
12559     }
12560   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12561     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12562       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12563         NewClassTy = NewRT->getPointeeType();
12564         OldClassTy = OldRT->getPointeeType();
12565       }
12566     }
12567   }
12568 
12569   // The return types aren't either both pointers or references to a class type.
12570   if (NewClassTy.isNull()) {
12571     Diag(New->getLocation(),
12572          diag::err_different_return_type_for_overriding_virtual_function)
12573         << New->getDeclName() << NewTy << OldTy
12574         << New->getReturnTypeSourceRange();
12575     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12576         << Old->getReturnTypeSourceRange();
12577 
12578     return true;
12579   }
12580 
12581   // C++ [class.virtual]p6:
12582   //   If the return type of D::f differs from the return type of B::f, the
12583   //   class type in the return type of D::f shall be complete at the point of
12584   //   declaration of D::f or shall be the class type D.
12585   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12586     if (!RT->isBeingDefined() &&
12587         RequireCompleteType(New->getLocation(), NewClassTy,
12588                             diag::err_covariant_return_incomplete,
12589                             New->getDeclName()))
12590     return true;
12591   }
12592 
12593   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12594     // Check if the new class derives from the old class.
12595     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12596       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12597           << New->getDeclName() << NewTy << OldTy
12598           << New->getReturnTypeSourceRange();
12599       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12600           << Old->getReturnTypeSourceRange();
12601       return true;
12602     }
12603 
12604     // Check if we the conversion from derived to base is valid.
12605     if (CheckDerivedToBaseConversion(
12606             NewClassTy, OldClassTy,
12607             diag::err_covariant_return_inaccessible_base,
12608             diag::err_covariant_return_ambiguous_derived_to_base_conv,
12609             New->getLocation(), New->getReturnTypeSourceRange(),
12610             New->getDeclName(), nullptr)) {
12611       // FIXME: this note won't trigger for delayed access control
12612       // diagnostics, and it's impossible to get an undelayed error
12613       // here from access control during the original parse because
12614       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12615       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12616           << Old->getReturnTypeSourceRange();
12617       return true;
12618     }
12619   }
12620 
12621   // The qualifiers of the return types must be the same.
12622   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12623     Diag(New->getLocation(),
12624          diag::err_covariant_return_type_different_qualifications)
12625         << New->getDeclName() << NewTy << OldTy
12626         << New->getReturnTypeSourceRange();
12627     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12628         << Old->getReturnTypeSourceRange();
12629     return true;
12630   };
12631 
12632 
12633   // The new class type must have the same or less qualifiers as the old type.
12634   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12635     Diag(New->getLocation(),
12636          diag::err_covariant_return_type_class_type_more_qualified)
12637         << New->getDeclName() << NewTy << OldTy
12638         << New->getReturnTypeSourceRange();
12639     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12640         << Old->getReturnTypeSourceRange();
12641     return true;
12642   };
12643 
12644   return false;
12645 }
12646 
12647 /// \brief Mark the given method pure.
12648 ///
12649 /// \param Method the method to be marked pure.
12650 ///
12651 /// \param InitRange the source range that covers the "0" initializer.
12652 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12653   SourceLocation EndLoc = InitRange.getEnd();
12654   if (EndLoc.isValid())
12655     Method->setRangeEnd(EndLoc);
12656 
12657   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12658     Method->setPure();
12659     return false;
12660   }
12661 
12662   if (!Method->isInvalidDecl())
12663     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12664       << Method->getDeclName() << InitRange;
12665   return true;
12666 }
12667 
12668 /// \brief Determine whether the given declaration is a static data member.
12669 static bool isStaticDataMember(const Decl *D) {
12670   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12671     return Var->isStaticDataMember();
12672 
12673   return false;
12674 }
12675 
12676 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12677 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12678 /// is a fresh scope pushed for just this purpose.
12679 ///
12680 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12681 /// static data member of class X, names should be looked up in the scope of
12682 /// class X.
12683 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12684   // If there is no declaration, there was an error parsing it.
12685   if (!D || D->isInvalidDecl())
12686     return;
12687 
12688   // We will always have a nested name specifier here, but this declaration
12689   // might not be out of line if the specifier names the current namespace:
12690   //   extern int n;
12691   //   int ::n = 0;
12692   if (D->isOutOfLine())
12693     EnterDeclaratorContext(S, D->getDeclContext());
12694 
12695   // If we are parsing the initializer for a static data member, push a
12696   // new expression evaluation context that is associated with this static
12697   // data member.
12698   if (isStaticDataMember(D))
12699     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12700 }
12701 
12702 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12703 /// initializer for the out-of-line declaration 'D'.
12704 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12705   // If there is no declaration, there was an error parsing it.
12706   if (!D || D->isInvalidDecl())
12707     return;
12708 
12709   if (isStaticDataMember(D))
12710     PopExpressionEvaluationContext();
12711 
12712   if (D->isOutOfLine())
12713     ExitDeclaratorContext(S);
12714 }
12715 
12716 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12717 /// C++ if/switch/while/for statement.
12718 /// e.g: "if (int x = f()) {...}"
12719 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12720   // C++ 6.4p2:
12721   // The declarator shall not specify a function or an array.
12722   // The type-specifier-seq shall not contain typedef and shall not declare a
12723   // new class or enumeration.
12724   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12725          "Parser allowed 'typedef' as storage class of condition decl.");
12726 
12727   Decl *Dcl = ActOnDeclarator(S, D);
12728   if (!Dcl)
12729     return true;
12730 
12731   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12732     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12733       << D.getSourceRange();
12734     return true;
12735   }
12736 
12737   return Dcl;
12738 }
12739 
12740 void Sema::LoadExternalVTableUses() {
12741   if (!ExternalSource)
12742     return;
12743 
12744   SmallVector<ExternalVTableUse, 4> VTables;
12745   ExternalSource->ReadUsedVTables(VTables);
12746   SmallVector<VTableUse, 4> NewUses;
12747   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12748     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12749       = VTablesUsed.find(VTables[I].Record);
12750     // Even if a definition wasn't required before, it may be required now.
12751     if (Pos != VTablesUsed.end()) {
12752       if (!Pos->second && VTables[I].DefinitionRequired)
12753         Pos->second = true;
12754       continue;
12755     }
12756 
12757     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12758     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12759   }
12760 
12761   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12762 }
12763 
12764 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12765                           bool DefinitionRequired) {
12766   // Ignore any vtable uses in unevaluated operands or for classes that do
12767   // not have a vtable.
12768   if (!Class->isDynamicClass() || Class->isDependentContext() ||
12769       CurContext->isDependentContext() || isUnevaluatedContext())
12770     return;
12771 
12772   // Try to insert this class into the map.
12773   LoadExternalVTableUses();
12774   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12775   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12776     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12777   if (!Pos.second) {
12778     // If we already had an entry, check to see if we are promoting this vtable
12779     // to required a definition. If so, we need to reappend to the VTableUses
12780     // list, since we may have already processed the first entry.
12781     if (DefinitionRequired && !Pos.first->second) {
12782       Pos.first->second = true;
12783     } else {
12784       // Otherwise, we can early exit.
12785       return;
12786     }
12787   } else {
12788     // The Microsoft ABI requires that we perform the destructor body
12789     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12790     // the deleting destructor is emitted with the vtable, not with the
12791     // destructor definition as in the Itanium ABI.
12792     // If it has a definition, we do the check at that point instead.
12793     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12794         Class->hasUserDeclaredDestructor() &&
12795         !Class->getDestructor()->isDefined() &&
12796         !Class->getDestructor()->isDeleted()) {
12797       CXXDestructorDecl *DD = Class->getDestructor();
12798       ContextRAII SavedContext(*this, DD);
12799       CheckDestructor(DD);
12800     }
12801   }
12802 
12803   // Local classes need to have their virtual members marked
12804   // immediately. For all other classes, we mark their virtual members
12805   // at the end of the translation unit.
12806   if (Class->isLocalClass())
12807     MarkVirtualMembersReferenced(Loc, Class);
12808   else
12809     VTableUses.push_back(std::make_pair(Class, Loc));
12810 }
12811 
12812 bool Sema::DefineUsedVTables() {
12813   LoadExternalVTableUses();
12814   if (VTableUses.empty())
12815     return false;
12816 
12817   // Note: The VTableUses vector could grow as a result of marking
12818   // the members of a class as "used", so we check the size each
12819   // time through the loop and prefer indices (which are stable) to
12820   // iterators (which are not).
12821   bool DefinedAnything = false;
12822   for (unsigned I = 0; I != VTableUses.size(); ++I) {
12823     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12824     if (!Class)
12825       continue;
12826 
12827     SourceLocation Loc = VTableUses[I].second;
12828 
12829     bool DefineVTable = true;
12830 
12831     // If this class has a key function, but that key function is
12832     // defined in another translation unit, we don't need to emit the
12833     // vtable even though we're using it.
12834     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12835     if (KeyFunction && !KeyFunction->hasBody()) {
12836       // The key function is in another translation unit.
12837       DefineVTable = false;
12838       TemplateSpecializationKind TSK =
12839           KeyFunction->getTemplateSpecializationKind();
12840       assert(TSK != TSK_ExplicitInstantiationDefinition &&
12841              TSK != TSK_ImplicitInstantiation &&
12842              "Instantiations don't have key functions");
12843       (void)TSK;
12844     } else if (!KeyFunction) {
12845       // If we have a class with no key function that is the subject
12846       // of an explicit instantiation declaration, suppress the
12847       // vtable; it will live with the explicit instantiation
12848       // definition.
12849       bool IsExplicitInstantiationDeclaration
12850         = Class->getTemplateSpecializationKind()
12851                                       == TSK_ExplicitInstantiationDeclaration;
12852       for (auto R : Class->redecls()) {
12853         TemplateSpecializationKind TSK
12854           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
12855         if (TSK == TSK_ExplicitInstantiationDeclaration)
12856           IsExplicitInstantiationDeclaration = true;
12857         else if (TSK == TSK_ExplicitInstantiationDefinition) {
12858           IsExplicitInstantiationDeclaration = false;
12859           break;
12860         }
12861       }
12862 
12863       if (IsExplicitInstantiationDeclaration)
12864         DefineVTable = false;
12865     }
12866 
12867     // The exception specifications for all virtual members may be needed even
12868     // if we are not providing an authoritative form of the vtable in this TU.
12869     // We may choose to emit it available_externally anyway.
12870     if (!DefineVTable) {
12871       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12872       continue;
12873     }
12874 
12875     // Mark all of the virtual members of this class as referenced, so
12876     // that we can build a vtable. Then, tell the AST consumer that a
12877     // vtable for this class is required.
12878     DefinedAnything = true;
12879     MarkVirtualMembersReferenced(Loc, Class);
12880     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12881     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12882 
12883     // Optionally warn if we're emitting a weak vtable.
12884     if (Class->isExternallyVisible() &&
12885         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12886       const FunctionDecl *KeyFunctionDef = nullptr;
12887       if (!KeyFunction ||
12888           (KeyFunction->hasBody(KeyFunctionDef) &&
12889            KeyFunctionDef->isInlined()))
12890         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12891              TSK_ExplicitInstantiationDefinition
12892              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12893           << Class;
12894     }
12895   }
12896   VTableUses.clear();
12897 
12898   return DefinedAnything;
12899 }
12900 
12901 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12902                                                  const CXXRecordDecl *RD) {
12903   for (const auto *I : RD->methods())
12904     if (I->isVirtual() && !I->isPure())
12905       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
12906 }
12907 
12908 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12909                                         const CXXRecordDecl *RD) {
12910   // Mark all functions which will appear in RD's vtable as used.
12911   CXXFinalOverriderMap FinalOverriders;
12912   RD->getFinalOverriders(FinalOverriders);
12913   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12914                                             E = FinalOverriders.end();
12915        I != E; ++I) {
12916     for (OverridingMethods::const_iterator OI = I->second.begin(),
12917                                            OE = I->second.end();
12918          OI != OE; ++OI) {
12919       assert(OI->second.size() > 0 && "no final overrider");
12920       CXXMethodDecl *Overrider = OI->second.front().Method;
12921 
12922       // C++ [basic.def.odr]p2:
12923       //   [...] A virtual member function is used if it is not pure. [...]
12924       if (!Overrider->isPure())
12925         MarkFunctionReferenced(Loc, Overrider);
12926     }
12927   }
12928 
12929   // Only classes that have virtual bases need a VTT.
12930   if (RD->getNumVBases() == 0)
12931     return;
12932 
12933   for (const auto &I : RD->bases()) {
12934     const CXXRecordDecl *Base =
12935         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
12936     if (Base->getNumVBases() == 0)
12937       continue;
12938     MarkVirtualMembersReferenced(Loc, Base);
12939   }
12940 }
12941 
12942 /// SetIvarInitializers - This routine builds initialization ASTs for the
12943 /// Objective-C implementation whose ivars need be initialized.
12944 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12945   if (!getLangOpts().CPlusPlus)
12946     return;
12947   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12948     SmallVector<ObjCIvarDecl*, 8> ivars;
12949     CollectIvarsToConstructOrDestruct(OID, ivars);
12950     if (ivars.empty())
12951       return;
12952     SmallVector<CXXCtorInitializer*, 32> AllToInit;
12953     for (unsigned i = 0; i < ivars.size(); i++) {
12954       FieldDecl *Field = ivars[i];
12955       if (Field->isInvalidDecl())
12956         continue;
12957 
12958       CXXCtorInitializer *Member;
12959       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12960       InitializationKind InitKind =
12961         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12962 
12963       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12964       ExprResult MemberInit =
12965         InitSeq.Perform(*this, InitEntity, InitKind, None);
12966       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12967       // Note, MemberInit could actually come back empty if no initialization
12968       // is required (e.g., because it would call a trivial default constructor)
12969       if (!MemberInit.get() || MemberInit.isInvalid())
12970         continue;
12971 
12972       Member =
12973         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12974                                          SourceLocation(),
12975                                          MemberInit.getAs<Expr>(),
12976                                          SourceLocation());
12977       AllToInit.push_back(Member);
12978 
12979       // Be sure that the destructor is accessible and is marked as referenced.
12980       if (const RecordType *RecordTy
12981                   = Context.getBaseElementType(Field->getType())
12982                                                         ->getAs<RecordType>()) {
12983                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12984         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12985           MarkFunctionReferenced(Field->getLocation(), Destructor);
12986           CheckDestructorAccess(Field->getLocation(), Destructor,
12987                             PDiag(diag::err_access_dtor_ivar)
12988                               << Context.getBaseElementType(Field->getType()));
12989         }
12990       }
12991     }
12992     ObjCImplementation->setIvarInitializers(Context,
12993                                             AllToInit.data(), AllToInit.size());
12994   }
12995 }
12996 
12997 static
12998 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12999                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13000                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13001                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13002                            Sema &S) {
13003   if (Ctor->isInvalidDecl())
13004     return;
13005 
13006   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13007 
13008   // Target may not be determinable yet, for instance if this is a dependent
13009   // call in an uninstantiated template.
13010   if (Target) {
13011     const FunctionDecl *FNTarget = nullptr;
13012     (void)Target->hasBody(FNTarget);
13013     Target = const_cast<CXXConstructorDecl*>(
13014       cast_or_null<CXXConstructorDecl>(FNTarget));
13015   }
13016 
13017   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13018                      // Avoid dereferencing a null pointer here.
13019                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13020 
13021   if (!Current.insert(Canonical))
13022     return;
13023 
13024   // We know that beyond here, we aren't chaining into a cycle.
13025   if (!Target || !Target->isDelegatingConstructor() ||
13026       Target->isInvalidDecl() || Valid.count(TCanonical)) {
13027     Valid.insert(Current.begin(), Current.end());
13028     Current.clear();
13029   // We've hit a cycle.
13030   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13031              Current.count(TCanonical)) {
13032     // If we haven't diagnosed this cycle yet, do so now.
13033     if (!Invalid.count(TCanonical)) {
13034       S.Diag((*Ctor->init_begin())->getSourceLocation(),
13035              diag::warn_delegating_ctor_cycle)
13036         << Ctor;
13037 
13038       // Don't add a note for a function delegating directly to itself.
13039       if (TCanonical != Canonical)
13040         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13041 
13042       CXXConstructorDecl *C = Target;
13043       while (C->getCanonicalDecl() != Canonical) {
13044         const FunctionDecl *FNTarget = nullptr;
13045         (void)C->getTargetConstructor()->hasBody(FNTarget);
13046         assert(FNTarget && "Ctor cycle through bodiless function");
13047 
13048         C = const_cast<CXXConstructorDecl*>(
13049           cast<CXXConstructorDecl>(FNTarget));
13050         S.Diag(C->getLocation(), diag::note_which_delegates_to);
13051       }
13052     }
13053 
13054     Invalid.insert(Current.begin(), Current.end());
13055     Current.clear();
13056   } else {
13057     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13058   }
13059 }
13060 
13061 
13062 void Sema::CheckDelegatingCtorCycles() {
13063   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13064 
13065   for (DelegatingCtorDeclsType::iterator
13066          I = DelegatingCtorDecls.begin(ExternalSource),
13067          E = DelegatingCtorDecls.end();
13068        I != E; ++I)
13069     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13070 
13071   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13072                                                          CE = Invalid.end();
13073        CI != CE; ++CI)
13074     (*CI)->setInvalidDecl();
13075 }
13076 
13077 namespace {
13078   /// \brief AST visitor that finds references to the 'this' expression.
13079   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13080     Sema &S;
13081 
13082   public:
13083     explicit FindCXXThisExpr(Sema &S) : S(S) { }
13084 
13085     bool VisitCXXThisExpr(CXXThisExpr *E) {
13086       S.Diag(E->getLocation(), diag::err_this_static_member_func)
13087         << E->isImplicit();
13088       return false;
13089     }
13090   };
13091 }
13092 
13093 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13094   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13095   if (!TSInfo)
13096     return false;
13097 
13098   TypeLoc TL = TSInfo->getTypeLoc();
13099   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13100   if (!ProtoTL)
13101     return false;
13102 
13103   // C++11 [expr.prim.general]p3:
13104   //   [The expression this] shall not appear before the optional
13105   //   cv-qualifier-seq and it shall not appear within the declaration of a
13106   //   static member function (although its type and value category are defined
13107   //   within a static member function as they are within a non-static member
13108   //   function). [ Note: this is because declaration matching does not occur
13109   //  until the complete declarator is known. - end note ]
13110   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13111   FindCXXThisExpr Finder(*this);
13112 
13113   // If the return type came after the cv-qualifier-seq, check it now.
13114   if (Proto->hasTrailingReturn() &&
13115       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13116     return true;
13117 
13118   // Check the exception specification.
13119   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13120     return true;
13121 
13122   return checkThisInStaticMemberFunctionAttributes(Method);
13123 }
13124 
13125 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13126   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13127   if (!TSInfo)
13128     return false;
13129 
13130   TypeLoc TL = TSInfo->getTypeLoc();
13131   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13132   if (!ProtoTL)
13133     return false;
13134 
13135   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13136   FindCXXThisExpr Finder(*this);
13137 
13138   switch (Proto->getExceptionSpecType()) {
13139   case EST_Uninstantiated:
13140   case EST_Unevaluated:
13141   case EST_BasicNoexcept:
13142   case EST_DynamicNone:
13143   case EST_MSAny:
13144   case EST_None:
13145     break;
13146 
13147   case EST_ComputedNoexcept:
13148     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13149       return true;
13150 
13151   case EST_Dynamic:
13152     for (const auto &E : Proto->exceptions()) {
13153       if (!Finder.TraverseType(E))
13154         return true;
13155     }
13156     break;
13157   }
13158 
13159   return false;
13160 }
13161 
13162 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13163   FindCXXThisExpr Finder(*this);
13164 
13165   // Check attributes.
13166   for (const auto *A : Method->attrs()) {
13167     // FIXME: This should be emitted by tblgen.
13168     Expr *Arg = nullptr;
13169     ArrayRef<Expr *> Args;
13170     if (const auto *G = dyn_cast<GuardedByAttr>(A))
13171       Arg = G->getArg();
13172     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13173       Arg = G->getArg();
13174     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13175       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13176     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13177       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13178     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13179       Arg = ETLF->getSuccessValue();
13180       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13181     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13182       Arg = STLF->getSuccessValue();
13183       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13184     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13185       Arg = LR->getArg();
13186     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13187       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13188     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13189       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13190     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13191       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13192     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13193       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13194     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13195       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13196 
13197     if (Arg && !Finder.TraverseStmt(Arg))
13198       return true;
13199 
13200     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13201       if (!Finder.TraverseStmt(Args[I]))
13202         return true;
13203     }
13204   }
13205 
13206   return false;
13207 }
13208 
13209 void
13210 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
13211                                   ArrayRef<ParsedType> DynamicExceptions,
13212                                   ArrayRef<SourceRange> DynamicExceptionRanges,
13213                                   Expr *NoexceptExpr,
13214                                   SmallVectorImpl<QualType> &Exceptions,
13215                                   FunctionProtoType::ExceptionSpecInfo &ESI) {
13216   Exceptions.clear();
13217   ESI.Type = EST;
13218   if (EST == EST_Dynamic) {
13219     Exceptions.reserve(DynamicExceptions.size());
13220     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13221       // FIXME: Preserve type source info.
13222       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13223 
13224       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13225       collectUnexpandedParameterPacks(ET, Unexpanded);
13226       if (!Unexpanded.empty()) {
13227         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
13228                                          UPPC_ExceptionType,
13229                                          Unexpanded);
13230         continue;
13231       }
13232 
13233       // Check that the type is valid for an exception spec, and
13234       // drop it if not.
13235       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13236         Exceptions.push_back(ET);
13237     }
13238     ESI.Exceptions = Exceptions;
13239     return;
13240   }
13241 
13242   if (EST == EST_ComputedNoexcept) {
13243     // If an error occurred, there's no expression here.
13244     if (NoexceptExpr) {
13245       assert((NoexceptExpr->isTypeDependent() ||
13246               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13247               Context.BoolTy) &&
13248              "Parser should have made sure that the expression is boolean");
13249       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13250         ESI.Type = EST_BasicNoexcept;
13251         return;
13252       }
13253 
13254       if (!NoexceptExpr->isValueDependent())
13255         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13256                          diag::err_noexcept_needs_constant_expression,
13257                          /*AllowFold*/ false).get();
13258       ESI.NoexceptExpr = NoexceptExpr;
13259     }
13260     return;
13261   }
13262 }
13263 
13264 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13265 ///
13266 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13267                                        SourceLocation DeclStart,
13268                                        Declarator &D, Expr *BitWidth,
13269                                        InClassInitStyle InitStyle,
13270                                        AccessSpecifier AS,
13271                                        AttributeList *MSPropertyAttr) {
13272   IdentifierInfo *II = D.getIdentifier();
13273   if (!II) {
13274     Diag(DeclStart, diag::err_anonymous_property);
13275     return nullptr;
13276   }
13277   SourceLocation Loc = D.getIdentifierLoc();
13278 
13279   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13280   QualType T = TInfo->getType();
13281   if (getLangOpts().CPlusPlus) {
13282     CheckExtraCXXDefaultArguments(D);
13283 
13284     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13285                                         UPPC_DataMemberType)) {
13286       D.setInvalidType();
13287       T = Context.IntTy;
13288       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13289     }
13290   }
13291 
13292   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13293 
13294   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13295     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13296          diag::err_invalid_thread)
13297       << DeclSpec::getSpecifierName(TSCS);
13298 
13299   // Check to see if this name was declared as a member previously
13300   NamedDecl *PrevDecl = nullptr;
13301   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13302   LookupName(Previous, S);
13303   switch (Previous.getResultKind()) {
13304   case LookupResult::Found:
13305   case LookupResult::FoundUnresolvedValue:
13306     PrevDecl = Previous.getAsSingle<NamedDecl>();
13307     break;
13308 
13309   case LookupResult::FoundOverloaded:
13310     PrevDecl = Previous.getRepresentativeDecl();
13311     break;
13312 
13313   case LookupResult::NotFound:
13314   case LookupResult::NotFoundInCurrentInstantiation:
13315   case LookupResult::Ambiguous:
13316     break;
13317   }
13318 
13319   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13320     // Maybe we will complain about the shadowed template parameter.
13321     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13322     // Just pretend that we didn't see the previous declaration.
13323     PrevDecl = nullptr;
13324   }
13325 
13326   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13327     PrevDecl = nullptr;
13328 
13329   SourceLocation TSSL = D.getLocStart();
13330   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13331   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13332       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13333   ProcessDeclAttributes(TUScope, NewPD, D);
13334   NewPD->setAccess(AS);
13335 
13336   if (NewPD->isInvalidDecl())
13337     Record->setInvalidDecl();
13338 
13339   if (D.getDeclSpec().isModulePrivateSpecified())
13340     NewPD->setModulePrivate();
13341 
13342   if (NewPD->isInvalidDecl() && PrevDecl) {
13343     // Don't introduce NewFD into scope; there's already something
13344     // with the same name in the same scope.
13345   } else if (II) {
13346     PushOnScopeChains(NewPD, S);
13347   } else
13348     Record->addDecl(NewPD);
13349 
13350   return NewPD;
13351 }
13352