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 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1901 /// function overrides a virtual member function marked 'final', according to
1902 /// C++11 [class.virtual]p4.
1903 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1904                                                   const CXXMethodDecl *Old) {
1905   FinalAttr *FA = Old->getAttr<FinalAttr>();
1906   if (!FA)
1907     return false;
1908 
1909   Diag(New->getLocation(), diag::err_final_function_overridden)
1910     << New->getDeclName()
1911     << FA->isSpelledAsSealed();
1912   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1913   return true;
1914 }
1915 
1916 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1917   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1918   // FIXME: Destruction of ObjC lifetime types has side-effects.
1919   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1920     return !RD->isCompleteDefinition() ||
1921            !RD->hasTrivialDefaultConstructor() ||
1922            !RD->hasTrivialDestructor();
1923   return false;
1924 }
1925 
1926 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1927   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1928     if (it->isDeclspecPropertyAttribute())
1929       return it;
1930   return nullptr;
1931 }
1932 
1933 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1934 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1935 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1936 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1937 /// present (but parsing it has been deferred).
1938 NamedDecl *
1939 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1940                                MultiTemplateParamsArg TemplateParameterLists,
1941                                Expr *BW, const VirtSpecifiers &VS,
1942                                InClassInitStyle InitStyle) {
1943   const DeclSpec &DS = D.getDeclSpec();
1944   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1945   DeclarationName Name = NameInfo.getName();
1946   SourceLocation Loc = NameInfo.getLoc();
1947 
1948   // For anonymous bitfields, the location should point to the type.
1949   if (Loc.isInvalid())
1950     Loc = D.getLocStart();
1951 
1952   Expr *BitWidth = static_cast<Expr*>(BW);
1953 
1954   assert(isa<CXXRecordDecl>(CurContext));
1955   assert(!DS.isFriendSpecified());
1956 
1957   bool isFunc = D.isDeclarationOfFunction();
1958 
1959   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1960     // The Microsoft extension __interface only permits public member functions
1961     // and prohibits constructors, destructors, operators, non-public member
1962     // functions, static methods and data members.
1963     unsigned InvalidDecl;
1964     bool ShowDeclName = true;
1965     if (!isFunc)
1966       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1967     else if (AS != AS_public)
1968       InvalidDecl = 2;
1969     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1970       InvalidDecl = 3;
1971     else switch (Name.getNameKind()) {
1972       case DeclarationName::CXXConstructorName:
1973         InvalidDecl = 4;
1974         ShowDeclName = false;
1975         break;
1976 
1977       case DeclarationName::CXXDestructorName:
1978         InvalidDecl = 5;
1979         ShowDeclName = false;
1980         break;
1981 
1982       case DeclarationName::CXXOperatorName:
1983       case DeclarationName::CXXConversionFunctionName:
1984         InvalidDecl = 6;
1985         break;
1986 
1987       default:
1988         InvalidDecl = 0;
1989         break;
1990     }
1991 
1992     if (InvalidDecl) {
1993       if (ShowDeclName)
1994         Diag(Loc, diag::err_invalid_member_in_interface)
1995           << (InvalidDecl-1) << Name;
1996       else
1997         Diag(Loc, diag::err_invalid_member_in_interface)
1998           << (InvalidDecl-1) << "";
1999       return nullptr;
2000     }
2001   }
2002 
2003   // C++ 9.2p6: A member shall not be declared to have automatic storage
2004   // duration (auto, register) or with the extern storage-class-specifier.
2005   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2006   // data members and cannot be applied to names declared const or static,
2007   // and cannot be applied to reference members.
2008   switch (DS.getStorageClassSpec()) {
2009   case DeclSpec::SCS_unspecified:
2010   case DeclSpec::SCS_typedef:
2011   case DeclSpec::SCS_static:
2012     break;
2013   case DeclSpec::SCS_mutable:
2014     if (isFunc) {
2015       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2016 
2017       // FIXME: It would be nicer if the keyword was ignored only for this
2018       // declarator. Otherwise we could get follow-up errors.
2019       D.getMutableDeclSpec().ClearStorageClassSpecs();
2020     }
2021     break;
2022   default:
2023     Diag(DS.getStorageClassSpecLoc(),
2024          diag::err_storageclass_invalid_for_member);
2025     D.getMutableDeclSpec().ClearStorageClassSpecs();
2026     break;
2027   }
2028 
2029   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2030                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2031                       !isFunc);
2032 
2033   if (DS.isConstexprSpecified() && isInstField) {
2034     SemaDiagnosticBuilder B =
2035         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2036     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2037     if (InitStyle == ICIS_NoInit) {
2038       B << 0 << 0;
2039       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2040         B << FixItHint::CreateRemoval(ConstexprLoc);
2041       else {
2042         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2043         D.getMutableDeclSpec().ClearConstexprSpec();
2044         const char *PrevSpec;
2045         unsigned DiagID;
2046         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2047             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2048         (void)Failed;
2049         assert(!Failed && "Making a constexpr member const shouldn't fail");
2050       }
2051     } else {
2052       B << 1;
2053       const char *PrevSpec;
2054       unsigned DiagID;
2055       if (D.getMutableDeclSpec().SetStorageClassSpec(
2056           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2057           Context.getPrintingPolicy())) {
2058         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2059                "This is the only DeclSpec that should fail to be applied");
2060         B << 1;
2061       } else {
2062         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2063         isInstField = false;
2064       }
2065     }
2066   }
2067 
2068   NamedDecl *Member;
2069   if (isInstField) {
2070     CXXScopeSpec &SS = D.getCXXScopeSpec();
2071 
2072     // Data members must have identifiers for names.
2073     if (!Name.isIdentifier()) {
2074       Diag(Loc, diag::err_bad_variable_name)
2075         << Name;
2076       return nullptr;
2077     }
2078 
2079     IdentifierInfo *II = Name.getAsIdentifierInfo();
2080 
2081     // Member field could not be with "template" keyword.
2082     // So TemplateParameterLists should be empty in this case.
2083     if (TemplateParameterLists.size()) {
2084       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2085       if (TemplateParams->size()) {
2086         // There is no such thing as a member field template.
2087         Diag(D.getIdentifierLoc(), diag::err_template_member)
2088             << II
2089             << SourceRange(TemplateParams->getTemplateLoc(),
2090                 TemplateParams->getRAngleLoc());
2091       } else {
2092         // There is an extraneous 'template<>' for this member.
2093         Diag(TemplateParams->getTemplateLoc(),
2094             diag::err_template_member_noparams)
2095             << II
2096             << SourceRange(TemplateParams->getTemplateLoc(),
2097                 TemplateParams->getRAngleLoc());
2098       }
2099       return nullptr;
2100     }
2101 
2102     if (SS.isSet() && !SS.isInvalid()) {
2103       // The user provided a superfluous scope specifier inside a class
2104       // definition:
2105       //
2106       // class X {
2107       //   int X::member;
2108       // };
2109       if (DeclContext *DC = computeDeclContext(SS, false))
2110         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2111       else
2112         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2113           << Name << SS.getRange();
2114 
2115       SS.clear();
2116     }
2117 
2118     AttributeList *MSPropertyAttr =
2119       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2120     if (MSPropertyAttr) {
2121       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2122                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2123       if (!Member)
2124         return nullptr;
2125       isInstField = false;
2126     } else {
2127       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2128                                 BitWidth, InitStyle, AS);
2129       assert(Member && "HandleField never returns null");
2130     }
2131   } else {
2132     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2133 
2134     Member = HandleDeclarator(S, D, TemplateParameterLists);
2135     if (!Member)
2136       return nullptr;
2137 
2138     // Non-instance-fields can't have a bitfield.
2139     if (BitWidth) {
2140       if (Member->isInvalidDecl()) {
2141         // don't emit another diagnostic.
2142       } else if (isa<VarDecl>(Member)) {
2143         // C++ 9.6p3: A bit-field shall not be a static member.
2144         // "static member 'A' cannot be a bit-field"
2145         Diag(Loc, diag::err_static_not_bitfield)
2146           << Name << BitWidth->getSourceRange();
2147       } else if (isa<TypedefDecl>(Member)) {
2148         // "typedef member 'x' cannot be a bit-field"
2149         Diag(Loc, diag::err_typedef_not_bitfield)
2150           << Name << BitWidth->getSourceRange();
2151       } else {
2152         // A function typedef ("typedef int f(); f a;").
2153         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2154         Diag(Loc, diag::err_not_integral_type_bitfield)
2155           << Name << cast<ValueDecl>(Member)->getType()
2156           << BitWidth->getSourceRange();
2157       }
2158 
2159       BitWidth = nullptr;
2160       Member->setInvalidDecl();
2161     }
2162 
2163     Member->setAccess(AS);
2164 
2165     // If we have declared a member function template or static data member
2166     // template, set the access of the templated declaration as well.
2167     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2168       FunTmpl->getTemplatedDecl()->setAccess(AS);
2169     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2170       VarTmpl->getTemplatedDecl()->setAccess(AS);
2171   }
2172 
2173   if (VS.isOverrideSpecified())
2174     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2175   if (VS.isFinalSpecified())
2176     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2177                                             VS.isFinalSpelledSealed()));
2178 
2179   if (VS.getLastLocation().isValid()) {
2180     // Update the end location of a method that has a virt-specifiers.
2181     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2182       MD->setRangeEnd(VS.getLastLocation());
2183   }
2184 
2185   CheckOverrideControl(Member);
2186 
2187   assert((Name || isInstField) && "No identifier for non-field ?");
2188 
2189   if (isInstField) {
2190     FieldDecl *FD = cast<FieldDecl>(Member);
2191     FieldCollector->Add(FD);
2192 
2193     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2194       // Remember all explicit private FieldDecls that have a name, no side
2195       // effects and are not part of a dependent type declaration.
2196       if (!FD->isImplicit() && FD->getDeclName() &&
2197           FD->getAccess() == AS_private &&
2198           !FD->hasAttr<UnusedAttr>() &&
2199           !FD->getParent()->isDependentContext() &&
2200           !InitializationHasSideEffects(*FD))
2201         UnusedPrivateFields.insert(FD);
2202     }
2203   }
2204 
2205   return Member;
2206 }
2207 
2208 namespace {
2209   class UninitializedFieldVisitor
2210       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2211     Sema &S;
2212     // List of Decls to generate a warning on.  Also remove Decls that become
2213     // initialized.
2214     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2215     // Vector of decls to be removed from the Decl set prior to visiting the
2216     // nodes.  These Decls may have been initialized in the prior initializer.
2217     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2218     // If non-null, add a note to the warning pointing back to the constructor.
2219     const CXXConstructorDecl *Constructor;
2220     // Variables to hold state when processing an initializer list.  When
2221     // InitList is true, special case initialization of FieldDecls matching
2222     // InitListFieldDecl.
2223     bool InitList;
2224     FieldDecl *InitListFieldDecl;
2225     llvm::SmallVector<unsigned, 4> InitFieldIndex;
2226 
2227   public:
2228     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2229     UninitializedFieldVisitor(Sema &S,
2230                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls)
2231       : Inherited(S.Context), S(S), Decls(Decls), Constructor(nullptr),
2232         InitList(false), InitListFieldDecl(nullptr) {}
2233 
2234     // Returns true if the use of ME is not an uninitialized use.
2235     bool IsInitListMemberExprInitialized(MemberExpr *ME,
2236                                          bool CheckReferenceOnly) {
2237       llvm::SmallVector<FieldDecl*, 4> Fields;
2238       bool ReferenceField = false;
2239       while (ME) {
2240         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2241         if (!FD)
2242           return false;
2243         Fields.push_back(FD);
2244         if (FD->getType()->isReferenceType())
2245           ReferenceField = true;
2246         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2247       }
2248 
2249       // Binding a reference to an unintialized field is not an
2250       // uninitialized use.
2251       if (CheckReferenceOnly && !ReferenceField)
2252         return true;
2253 
2254       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2255       // Discard the first field since it is the field decl that is being
2256       // initialized.
2257       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2258         UsedFieldIndex.push_back((*I)->getFieldIndex());
2259       }
2260 
2261       for (auto UsedIter = UsedFieldIndex.begin(),
2262                 UsedEnd = UsedFieldIndex.end(),
2263                 OrigIter = InitFieldIndex.begin(),
2264                 OrigEnd = InitFieldIndex.end();
2265            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2266         if (*UsedIter < *OrigIter)
2267           return true;
2268         if (*UsedIter > *OrigIter)
2269           break;
2270       }
2271 
2272       return false;
2273     }
2274 
2275     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2276                           bool AddressOf) {
2277       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2278         return;
2279 
2280       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2281       // or union.
2282       MemberExpr *FieldME = ME;
2283 
2284       bool AllPODFields = FieldME->getType().isPODType(S.Context);
2285 
2286       Expr *Base = ME;
2287       while (MemberExpr *SubME = dyn_cast<MemberExpr>(Base)) {
2288 
2289         if (isa<VarDecl>(SubME->getMemberDecl()))
2290           return;
2291 
2292         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2293           if (!FD->isAnonymousStructOrUnion())
2294             FieldME = SubME;
2295 
2296         if (!FieldME->getType().isPODType(S.Context))
2297           AllPODFields = false;
2298 
2299         Base = SubME->getBase()->IgnoreParenImpCasts();
2300       }
2301 
2302       if (!isa<CXXThisExpr>(Base))
2303         return;
2304 
2305       if (AddressOf && AllPODFields)
2306         return;
2307 
2308       ValueDecl* FoundVD = FieldME->getMemberDecl();
2309 
2310       if (!Decls.count(FoundVD))
2311         return;
2312 
2313       const bool IsReference = FoundVD->getType()->isReferenceType();
2314 
2315       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2316         // Special checking for initializer lists.
2317         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2318           return;
2319         }
2320       } else {
2321         // Prevent double warnings on use of unbounded references.
2322         if (CheckReferenceOnly && !IsReference)
2323           return;
2324       }
2325 
2326       unsigned diag = IsReference
2327           ? diag::warn_reference_field_is_uninit
2328           : diag::warn_field_is_uninit;
2329       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2330       if (Constructor)
2331         S.Diag(Constructor->getLocation(),
2332                diag::note_uninit_in_this_constructor)
2333           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2334 
2335     }
2336 
2337     void HandleValue(Expr *E, bool AddressOf) {
2338       E = E->IgnoreParens();
2339 
2340       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2341         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2342                          AddressOf /*AddressOf*/);
2343         return;
2344       }
2345 
2346       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2347         Visit(CO->getCond());
2348         HandleValue(CO->getTrueExpr(), AddressOf);
2349         HandleValue(CO->getFalseExpr(), AddressOf);
2350         return;
2351       }
2352 
2353       if (BinaryConditionalOperator *BCO =
2354               dyn_cast<BinaryConditionalOperator>(E)) {
2355         Visit(BCO->getCond());
2356         HandleValue(BCO->getFalseExpr(), AddressOf);
2357         return;
2358       }
2359 
2360       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2361         HandleValue(OVE->getSourceExpr(), AddressOf);
2362         return;
2363       }
2364 
2365       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2366         switch (BO->getOpcode()) {
2367         default:
2368           break;
2369         case(BO_PtrMemD):
2370         case(BO_PtrMemI):
2371           HandleValue(BO->getLHS(), AddressOf);
2372           Visit(BO->getRHS());
2373           return;
2374         case(BO_Comma):
2375           Visit(BO->getLHS());
2376           HandleValue(BO->getRHS(), AddressOf);
2377           return;
2378         }
2379       }
2380 
2381       Visit(E);
2382     }
2383 
2384     void CheckInitListExpr(InitListExpr *ILE) {
2385       InitFieldIndex.push_back(0);
2386       for (auto Child : ILE->children()) {
2387         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2388           CheckInitListExpr(SubList);
2389         } else {
2390           Visit(Child);
2391         }
2392         ++InitFieldIndex.back();
2393       }
2394       InitFieldIndex.pop_back();
2395     }
2396 
2397     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2398                           FieldDecl *Field) {
2399       // Remove Decls that may have been initialized in the previous
2400       // initializer.
2401       for (ValueDecl* VD : DeclsToRemove)
2402         Decls.erase(VD);
2403       DeclsToRemove.clear();
2404 
2405       Constructor = FieldConstructor;
2406       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2407 
2408       if (ILE && Field) {
2409         InitList = true;
2410         InitListFieldDecl = Field;
2411         InitFieldIndex.clear();
2412         CheckInitListExpr(ILE);
2413       } else {
2414         InitList = false;
2415         Visit(E);
2416       }
2417 
2418       if (Field)
2419         Decls.erase(Field);
2420     }
2421 
2422     void VisitMemberExpr(MemberExpr *ME) {
2423       // All uses of unbounded reference fields will warn.
2424       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2425     }
2426 
2427     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2428       if (E->getCastKind() == CK_LValueToRValue) {
2429         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2430         return;
2431       }
2432 
2433       Inherited::VisitImplicitCastExpr(E);
2434     }
2435 
2436     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2437       if (E->getConstructor()->isCopyConstructor()) {
2438         Expr *ArgExpr = E->getArg(0);
2439         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2440           if (ILE->getNumInits() == 1)
2441             ArgExpr = ILE->getInit(0);
2442         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2443           if (ICE->getCastKind() == CK_NoOp)
2444             ArgExpr = ICE->getSubExpr();
2445         HandleValue(ArgExpr, false /*AddressOf*/);
2446         return;
2447       }
2448       Inherited::VisitCXXConstructExpr(E);
2449     }
2450 
2451     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2452       Expr *Callee = E->getCallee();
2453       if (isa<MemberExpr>(Callee)) {
2454         HandleValue(Callee, false /*AddressOf*/);
2455         return;
2456       }
2457 
2458       Inherited::VisitCXXMemberCallExpr(E);
2459     }
2460 
2461     void VisitCallExpr(CallExpr *E) {
2462       // Treat std::move as a use.
2463       if (E->getNumArgs() == 1) {
2464         if (FunctionDecl *FD = E->getDirectCallee()) {
2465           if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
2466             HandleValue(E->getArg(0), false /*AddressOf*/);
2467             return;
2468           }
2469         }
2470       }
2471 
2472       Inherited::VisitCallExpr(E);
2473     }
2474 
2475     void VisitBinaryOperator(BinaryOperator *E) {
2476       // If a field assignment is detected, remove the field from the
2477       // uninitiailized field set.
2478       if (E->getOpcode() == BO_Assign)
2479         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2480           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2481             if (!FD->getType()->isReferenceType())
2482               DeclsToRemove.push_back(FD);
2483 
2484       if (E->isCompoundAssignmentOp()) {
2485         HandleValue(E->getLHS(), false /*AddressOf*/);
2486         Visit(E->getRHS());
2487         return;
2488       }
2489 
2490       Inherited::VisitBinaryOperator(E);
2491     }
2492 
2493     void VisitUnaryOperator(UnaryOperator *E) {
2494       if (E->isIncrementDecrementOp()) {
2495         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2496         return;
2497       }
2498       if (E->getOpcode() == UO_AddrOf) {
2499         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2500           HandleValue(ME->getBase(), true /*AddressOf*/);
2501           return;
2502         }
2503       }
2504 
2505       Inherited::VisitUnaryOperator(E);
2506     }
2507   };
2508 
2509   // Diagnose value-uses of fields to initialize themselves, e.g.
2510   //   foo(foo)
2511   // where foo is not also a parameter to the constructor.
2512   // Also diagnose across field uninitialized use such as
2513   //   x(y), y(x)
2514   // TODO: implement -Wuninitialized and fold this into that framework.
2515   static void DiagnoseUninitializedFields(
2516       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2517 
2518     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2519                                            Constructor->getLocation())) {
2520       return;
2521     }
2522 
2523     if (Constructor->isInvalidDecl())
2524       return;
2525 
2526     const CXXRecordDecl *RD = Constructor->getParent();
2527 
2528     // Holds fields that are uninitialized.
2529     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2530 
2531     // At the beginning, all fields are uninitialized.
2532     for (auto *I : RD->decls()) {
2533       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2534         UninitializedFields.insert(FD);
2535       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2536         UninitializedFields.insert(IFD->getAnonField());
2537       }
2538     }
2539 
2540     if (UninitializedFields.empty())
2541       return;
2542 
2543     UninitializedFieldVisitor UninitializedChecker(SemaRef,
2544                                                    UninitializedFields);
2545 
2546     for (const auto *FieldInit : Constructor->inits()) {
2547       if (UninitializedFields.empty())
2548         break;
2549 
2550       Expr *InitExpr = FieldInit->getInit();
2551       if (!InitExpr)
2552         continue;
2553 
2554       if (CXXDefaultInitExpr *Default =
2555               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2556         InitExpr = Default->getExpr();
2557         if (!InitExpr)
2558           continue;
2559         // In class initializers will point to the constructor.
2560         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2561                                               FieldInit->getAnyMember());
2562       } else {
2563         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2564                                               FieldInit->getAnyMember());
2565       }
2566     }
2567   }
2568 } // namespace
2569 
2570 /// \brief Enter a new C++ default initializer scope. After calling this, the
2571 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2572 /// parsing or instantiating the initializer failed.
2573 void Sema::ActOnStartCXXInClassMemberInitializer() {
2574   // Create a synthetic function scope to represent the call to the constructor
2575   // that notionally surrounds a use of this initializer.
2576   PushFunctionScope();
2577 }
2578 
2579 /// \brief This is invoked after parsing an in-class initializer for a
2580 /// non-static C++ class member, and after instantiating an in-class initializer
2581 /// in a class template. Such actions are deferred until the class is complete.
2582 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2583                                                   SourceLocation InitLoc,
2584                                                   Expr *InitExpr) {
2585   // Pop the notional constructor scope we created earlier.
2586   PopFunctionScopeInfo(nullptr, D);
2587 
2588   FieldDecl *FD = cast<FieldDecl>(D);
2589   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2590          "must set init style when field is created");
2591 
2592   if (!InitExpr) {
2593     FD->setInvalidDecl();
2594     FD->removeInClassInitializer();
2595     return;
2596   }
2597 
2598   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2599     FD->setInvalidDecl();
2600     FD->removeInClassInitializer();
2601     return;
2602   }
2603 
2604   ExprResult Init = InitExpr;
2605   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2606     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2607     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2608         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2609         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2610     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2611     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2612     if (Init.isInvalid()) {
2613       FD->setInvalidDecl();
2614       return;
2615     }
2616   }
2617 
2618   // C++11 [class.base.init]p7:
2619   //   The initialization of each base and member constitutes a
2620   //   full-expression.
2621   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2622   if (Init.isInvalid()) {
2623     FD->setInvalidDecl();
2624     return;
2625   }
2626 
2627   InitExpr = Init.get();
2628 
2629   FD->setInClassInitializer(InitExpr);
2630 }
2631 
2632 /// \brief Find the direct and/or virtual base specifiers that
2633 /// correspond to the given base type, for use in base initialization
2634 /// within a constructor.
2635 static bool FindBaseInitializer(Sema &SemaRef,
2636                                 CXXRecordDecl *ClassDecl,
2637                                 QualType BaseType,
2638                                 const CXXBaseSpecifier *&DirectBaseSpec,
2639                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2640   // First, check for a direct base class.
2641   DirectBaseSpec = nullptr;
2642   for (const auto &Base : ClassDecl->bases()) {
2643     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2644       // We found a direct base of this type. That's what we're
2645       // initializing.
2646       DirectBaseSpec = &Base;
2647       break;
2648     }
2649   }
2650 
2651   // Check for a virtual base class.
2652   // FIXME: We might be able to short-circuit this if we know in advance that
2653   // there are no virtual bases.
2654   VirtualBaseSpec = nullptr;
2655   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2656     // We haven't found a base yet; search the class hierarchy for a
2657     // virtual base class.
2658     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2659                        /*DetectVirtual=*/false);
2660     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2661                               BaseType, Paths)) {
2662       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2663            Path != Paths.end(); ++Path) {
2664         if (Path->back().Base->isVirtual()) {
2665           VirtualBaseSpec = Path->back().Base;
2666           break;
2667         }
2668       }
2669     }
2670   }
2671 
2672   return DirectBaseSpec || VirtualBaseSpec;
2673 }
2674 
2675 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2676 MemInitResult
2677 Sema::ActOnMemInitializer(Decl *ConstructorD,
2678                           Scope *S,
2679                           CXXScopeSpec &SS,
2680                           IdentifierInfo *MemberOrBase,
2681                           ParsedType TemplateTypeTy,
2682                           const DeclSpec &DS,
2683                           SourceLocation IdLoc,
2684                           Expr *InitList,
2685                           SourceLocation EllipsisLoc) {
2686   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2687                              DS, IdLoc, InitList,
2688                              EllipsisLoc);
2689 }
2690 
2691 /// \brief Handle a C++ member initializer using parentheses syntax.
2692 MemInitResult
2693 Sema::ActOnMemInitializer(Decl *ConstructorD,
2694                           Scope *S,
2695                           CXXScopeSpec &SS,
2696                           IdentifierInfo *MemberOrBase,
2697                           ParsedType TemplateTypeTy,
2698                           const DeclSpec &DS,
2699                           SourceLocation IdLoc,
2700                           SourceLocation LParenLoc,
2701                           ArrayRef<Expr *> Args,
2702                           SourceLocation RParenLoc,
2703                           SourceLocation EllipsisLoc) {
2704   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2705                                            Args, RParenLoc);
2706   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2707                              DS, IdLoc, List, EllipsisLoc);
2708 }
2709 
2710 namespace {
2711 
2712 // Callback to only accept typo corrections that can be a valid C++ member
2713 // intializer: either a non-static field member or a base class.
2714 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2715 public:
2716   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2717       : ClassDecl(ClassDecl) {}
2718 
2719   bool ValidateCandidate(const TypoCorrection &candidate) override {
2720     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2721       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2722         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2723       return isa<TypeDecl>(ND);
2724     }
2725     return false;
2726   }
2727 
2728 private:
2729   CXXRecordDecl *ClassDecl;
2730 };
2731 
2732 }
2733 
2734 /// \brief Handle a C++ member initializer.
2735 MemInitResult
2736 Sema::BuildMemInitializer(Decl *ConstructorD,
2737                           Scope *S,
2738                           CXXScopeSpec &SS,
2739                           IdentifierInfo *MemberOrBase,
2740                           ParsedType TemplateTypeTy,
2741                           const DeclSpec &DS,
2742                           SourceLocation IdLoc,
2743                           Expr *Init,
2744                           SourceLocation EllipsisLoc) {
2745   if (!ConstructorD)
2746     return true;
2747 
2748   AdjustDeclIfTemplate(ConstructorD);
2749 
2750   CXXConstructorDecl *Constructor
2751     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2752   if (!Constructor) {
2753     // The user wrote a constructor initializer on a function that is
2754     // not a C++ constructor. Ignore the error for now, because we may
2755     // have more member initializers coming; we'll diagnose it just
2756     // once in ActOnMemInitializers.
2757     return true;
2758   }
2759 
2760   CXXRecordDecl *ClassDecl = Constructor->getParent();
2761 
2762   // C++ [class.base.init]p2:
2763   //   Names in a mem-initializer-id are looked up in the scope of the
2764   //   constructor's class and, if not found in that scope, are looked
2765   //   up in the scope containing the constructor's definition.
2766   //   [Note: if the constructor's class contains a member with the
2767   //   same name as a direct or virtual base class of the class, a
2768   //   mem-initializer-id naming the member or base class and composed
2769   //   of a single identifier refers to the class member. A
2770   //   mem-initializer-id for the hidden base class may be specified
2771   //   using a qualified name. ]
2772   if (!SS.getScopeRep() && !TemplateTypeTy) {
2773     // Look for a member, first.
2774     DeclContext::lookup_result Result
2775       = ClassDecl->lookup(MemberOrBase);
2776     if (!Result.empty()) {
2777       ValueDecl *Member;
2778       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2779           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2780         if (EllipsisLoc.isValid())
2781           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2782             << MemberOrBase
2783             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2784 
2785         return BuildMemberInitializer(Member, Init, IdLoc);
2786       }
2787     }
2788   }
2789   // It didn't name a member, so see if it names a class.
2790   QualType BaseType;
2791   TypeSourceInfo *TInfo = nullptr;
2792 
2793   if (TemplateTypeTy) {
2794     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2795   } else if (DS.getTypeSpecType() == TST_decltype) {
2796     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2797   } else {
2798     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2799     LookupParsedName(R, S, &SS);
2800 
2801     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2802     if (!TyD) {
2803       if (R.isAmbiguous()) return true;
2804 
2805       // We don't want access-control diagnostics here.
2806       R.suppressDiagnostics();
2807 
2808       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2809         bool NotUnknownSpecialization = false;
2810         DeclContext *DC = computeDeclContext(SS, false);
2811         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2812           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2813 
2814         if (!NotUnknownSpecialization) {
2815           // When the scope specifier can refer to a member of an unknown
2816           // specialization, we take it as a type name.
2817           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2818                                        SS.getWithLocInContext(Context),
2819                                        *MemberOrBase, IdLoc);
2820           if (BaseType.isNull())
2821             return true;
2822 
2823           R.clear();
2824           R.setLookupName(MemberOrBase);
2825         }
2826       }
2827 
2828       // If no results were found, try to correct typos.
2829       TypoCorrection Corr;
2830       MemInitializerValidatorCCC Validator(ClassDecl);
2831       if (R.empty() && BaseType.isNull() &&
2832           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2833                               Validator, CTK_ErrorRecovery, ClassDecl))) {
2834         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2835           // We have found a non-static data member with a similar
2836           // name to what was typed; complain and initialize that
2837           // member.
2838           diagnoseTypo(Corr,
2839                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2840                          << MemberOrBase << true);
2841           return BuildMemberInitializer(Member, Init, IdLoc);
2842         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2843           const CXXBaseSpecifier *DirectBaseSpec;
2844           const CXXBaseSpecifier *VirtualBaseSpec;
2845           if (FindBaseInitializer(*this, ClassDecl,
2846                                   Context.getTypeDeclType(Type),
2847                                   DirectBaseSpec, VirtualBaseSpec)) {
2848             // We have found a direct or virtual base class with a
2849             // similar name to what was typed; complain and initialize
2850             // that base class.
2851             diagnoseTypo(Corr,
2852                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2853                            << MemberOrBase << false,
2854                          PDiag() /*Suppress note, we provide our own.*/);
2855 
2856             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2857                                                               : VirtualBaseSpec;
2858             Diag(BaseSpec->getLocStart(),
2859                  diag::note_base_class_specified_here)
2860               << BaseSpec->getType()
2861               << BaseSpec->getSourceRange();
2862 
2863             TyD = Type;
2864           }
2865         }
2866       }
2867 
2868       if (!TyD && BaseType.isNull()) {
2869         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2870           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2871         return true;
2872       }
2873     }
2874 
2875     if (BaseType.isNull()) {
2876       BaseType = Context.getTypeDeclType(TyD);
2877       if (SS.isSet())
2878         // FIXME: preserve source range information
2879         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2880                                              BaseType);
2881     }
2882   }
2883 
2884   if (!TInfo)
2885     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2886 
2887   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2888 }
2889 
2890 /// Checks a member initializer expression for cases where reference (or
2891 /// pointer) members are bound to by-value parameters (or their addresses).
2892 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2893                                                Expr *Init,
2894                                                SourceLocation IdLoc) {
2895   QualType MemberTy = Member->getType();
2896 
2897   // We only handle pointers and references currently.
2898   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2899   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2900     return;
2901 
2902   const bool IsPointer = MemberTy->isPointerType();
2903   if (IsPointer) {
2904     if (const UnaryOperator *Op
2905           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2906       // The only case we're worried about with pointers requires taking the
2907       // address.
2908       if (Op->getOpcode() != UO_AddrOf)
2909         return;
2910 
2911       Init = Op->getSubExpr();
2912     } else {
2913       // We only handle address-of expression initializers for pointers.
2914       return;
2915     }
2916   }
2917 
2918   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2919     // We only warn when referring to a non-reference parameter declaration.
2920     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2921     if (!Parameter || Parameter->getType()->isReferenceType())
2922       return;
2923 
2924     S.Diag(Init->getExprLoc(),
2925            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2926                      : diag::warn_bind_ref_member_to_parameter)
2927       << Member << Parameter << Init->getSourceRange();
2928   } else {
2929     // Other initializers are fine.
2930     return;
2931   }
2932 
2933   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2934     << (unsigned)IsPointer;
2935 }
2936 
2937 MemInitResult
2938 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2939                              SourceLocation IdLoc) {
2940   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2941   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2942   assert((DirectMember || IndirectMember) &&
2943          "Member must be a FieldDecl or IndirectFieldDecl");
2944 
2945   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2946     return true;
2947 
2948   if (Member->isInvalidDecl())
2949     return true;
2950 
2951   MultiExprArg Args;
2952   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2953     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2954   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2955     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2956   } else {
2957     // Template instantiation doesn't reconstruct ParenListExprs for us.
2958     Args = Init;
2959   }
2960 
2961   SourceRange InitRange = Init->getSourceRange();
2962 
2963   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2964     // Can't check initialization for a member of dependent type or when
2965     // any of the arguments are type-dependent expressions.
2966     DiscardCleanupsInEvaluationContext();
2967   } else {
2968     bool InitList = false;
2969     if (isa<InitListExpr>(Init)) {
2970       InitList = true;
2971       Args = Init;
2972     }
2973 
2974     // Initialize the member.
2975     InitializedEntity MemberEntity =
2976       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2977                    : InitializedEntity::InitializeMember(IndirectMember,
2978                                                          nullptr);
2979     InitializationKind Kind =
2980       InitList ? InitializationKind::CreateDirectList(IdLoc)
2981                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2982                                                   InitRange.getEnd());
2983 
2984     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2985     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2986                                             nullptr);
2987     if (MemberInit.isInvalid())
2988       return true;
2989 
2990     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2991 
2992     // C++11 [class.base.init]p7:
2993     //   The initialization of each base and member constitutes a
2994     //   full-expression.
2995     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2996     if (MemberInit.isInvalid())
2997       return true;
2998 
2999     Init = MemberInit.get();
3000   }
3001 
3002   if (DirectMember) {
3003     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3004                                             InitRange.getBegin(), Init,
3005                                             InitRange.getEnd());
3006   } else {
3007     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3008                                             InitRange.getBegin(), Init,
3009                                             InitRange.getEnd());
3010   }
3011 }
3012 
3013 MemInitResult
3014 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3015                                  CXXRecordDecl *ClassDecl) {
3016   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3017   if (!LangOpts.CPlusPlus11)
3018     return Diag(NameLoc, diag::err_delegating_ctor)
3019       << TInfo->getTypeLoc().getLocalSourceRange();
3020   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3021 
3022   bool InitList = true;
3023   MultiExprArg Args = Init;
3024   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3025     InitList = false;
3026     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3027   }
3028 
3029   SourceRange InitRange = Init->getSourceRange();
3030   // Initialize the object.
3031   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3032                                      QualType(ClassDecl->getTypeForDecl(), 0));
3033   InitializationKind Kind =
3034     InitList ? InitializationKind::CreateDirectList(NameLoc)
3035              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3036                                                 InitRange.getEnd());
3037   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3038   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3039                                               Args, nullptr);
3040   if (DelegationInit.isInvalid())
3041     return true;
3042 
3043   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3044          "Delegating constructor with no target?");
3045 
3046   // C++11 [class.base.init]p7:
3047   //   The initialization of each base and member constitutes a
3048   //   full-expression.
3049   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3050                                        InitRange.getBegin());
3051   if (DelegationInit.isInvalid())
3052     return true;
3053 
3054   // If we are in a dependent context, template instantiation will
3055   // perform this type-checking again. Just save the arguments that we
3056   // received in a ParenListExpr.
3057   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3058   // of the information that we have about the base
3059   // initializer. However, deconstructing the ASTs is a dicey process,
3060   // and this approach is far more likely to get the corner cases right.
3061   if (CurContext->isDependentContext())
3062     DelegationInit = Init;
3063 
3064   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3065                                           DelegationInit.getAs<Expr>(),
3066                                           InitRange.getEnd());
3067 }
3068 
3069 MemInitResult
3070 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3071                            Expr *Init, CXXRecordDecl *ClassDecl,
3072                            SourceLocation EllipsisLoc) {
3073   SourceLocation BaseLoc
3074     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3075 
3076   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3077     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3078              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3079 
3080   // C++ [class.base.init]p2:
3081   //   [...] Unless the mem-initializer-id names a nonstatic data
3082   //   member of the constructor's class or a direct or virtual base
3083   //   of that class, the mem-initializer is ill-formed. A
3084   //   mem-initializer-list can initialize a base class using any
3085   //   name that denotes that base class type.
3086   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3087 
3088   SourceRange InitRange = Init->getSourceRange();
3089   if (EllipsisLoc.isValid()) {
3090     // This is a pack expansion.
3091     if (!BaseType->containsUnexpandedParameterPack())  {
3092       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3093         << SourceRange(BaseLoc, InitRange.getEnd());
3094 
3095       EllipsisLoc = SourceLocation();
3096     }
3097   } else {
3098     // Check for any unexpanded parameter packs.
3099     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3100       return true;
3101 
3102     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3103       return true;
3104   }
3105 
3106   // Check for direct and virtual base classes.
3107   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3108   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3109   if (!Dependent) {
3110     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3111                                        BaseType))
3112       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3113 
3114     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3115                         VirtualBaseSpec);
3116 
3117     // C++ [base.class.init]p2:
3118     // Unless the mem-initializer-id names a nonstatic data member of the
3119     // constructor's class or a direct or virtual base of that class, the
3120     // mem-initializer is ill-formed.
3121     if (!DirectBaseSpec && !VirtualBaseSpec) {
3122       // If the class has any dependent bases, then it's possible that
3123       // one of those types will resolve to the same type as
3124       // BaseType. Therefore, just treat this as a dependent base
3125       // class initialization.  FIXME: Should we try to check the
3126       // initialization anyway? It seems odd.
3127       if (ClassDecl->hasAnyDependentBases())
3128         Dependent = true;
3129       else
3130         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3131           << BaseType << Context.getTypeDeclType(ClassDecl)
3132           << BaseTInfo->getTypeLoc().getLocalSourceRange();
3133     }
3134   }
3135 
3136   if (Dependent) {
3137     DiscardCleanupsInEvaluationContext();
3138 
3139     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3140                                             /*IsVirtual=*/false,
3141                                             InitRange.getBegin(), Init,
3142                                             InitRange.getEnd(), EllipsisLoc);
3143   }
3144 
3145   // C++ [base.class.init]p2:
3146   //   If a mem-initializer-id is ambiguous because it designates both
3147   //   a direct non-virtual base class and an inherited virtual base
3148   //   class, the mem-initializer is ill-formed.
3149   if (DirectBaseSpec && VirtualBaseSpec)
3150     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3151       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3152 
3153   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3154   if (!BaseSpec)
3155     BaseSpec = VirtualBaseSpec;
3156 
3157   // Initialize the base.
3158   bool InitList = true;
3159   MultiExprArg Args = Init;
3160   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3161     InitList = false;
3162     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3163   }
3164 
3165   InitializedEntity BaseEntity =
3166     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3167   InitializationKind Kind =
3168     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3169              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3170                                                 InitRange.getEnd());
3171   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3172   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3173   if (BaseInit.isInvalid())
3174     return true;
3175 
3176   // C++11 [class.base.init]p7:
3177   //   The initialization of each base and member constitutes a
3178   //   full-expression.
3179   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3180   if (BaseInit.isInvalid())
3181     return true;
3182 
3183   // If we are in a dependent context, template instantiation will
3184   // perform this type-checking again. Just save the arguments that we
3185   // received in a ParenListExpr.
3186   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3187   // of the information that we have about the base
3188   // initializer. However, deconstructing the ASTs is a dicey process,
3189   // and this approach is far more likely to get the corner cases right.
3190   if (CurContext->isDependentContext())
3191     BaseInit = Init;
3192 
3193   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3194                                           BaseSpec->isVirtual(),
3195                                           InitRange.getBegin(),
3196                                           BaseInit.getAs<Expr>(),
3197                                           InitRange.getEnd(), EllipsisLoc);
3198 }
3199 
3200 // Create a static_cast\<T&&>(expr).
3201 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3202   if (T.isNull()) T = E->getType();
3203   QualType TargetType = SemaRef.BuildReferenceType(
3204       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3205   SourceLocation ExprLoc = E->getLocStart();
3206   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3207       TargetType, ExprLoc);
3208 
3209   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3210                                    SourceRange(ExprLoc, ExprLoc),
3211                                    E->getSourceRange()).get();
3212 }
3213 
3214 /// ImplicitInitializerKind - How an implicit base or member initializer should
3215 /// initialize its base or member.
3216 enum ImplicitInitializerKind {
3217   IIK_Default,
3218   IIK_Copy,
3219   IIK_Move,
3220   IIK_Inherit
3221 };
3222 
3223 static bool
3224 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3225                              ImplicitInitializerKind ImplicitInitKind,
3226                              CXXBaseSpecifier *BaseSpec,
3227                              bool IsInheritedVirtualBase,
3228                              CXXCtorInitializer *&CXXBaseInit) {
3229   InitializedEntity InitEntity
3230     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3231                                         IsInheritedVirtualBase);
3232 
3233   ExprResult BaseInit;
3234 
3235   switch (ImplicitInitKind) {
3236   case IIK_Inherit: {
3237     const CXXRecordDecl *Inherited =
3238         Constructor->getInheritedConstructor()->getParent();
3239     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3240     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3241       // C++11 [class.inhctor]p8:
3242       //   Each expression in the expression-list is of the form
3243       //   static_cast<T&&>(p), where p is the name of the corresponding
3244       //   constructor parameter and T is the declared type of p.
3245       SmallVector<Expr*, 16> Args;
3246       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3247         ParmVarDecl *PD = Constructor->getParamDecl(I);
3248         ExprResult ArgExpr =
3249             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3250                                      VK_LValue, SourceLocation());
3251         if (ArgExpr.isInvalid())
3252           return true;
3253         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3254       }
3255 
3256       InitializationKind InitKind = InitializationKind::CreateDirect(
3257           Constructor->getLocation(), SourceLocation(), SourceLocation());
3258       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3259       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3260       break;
3261     }
3262   }
3263   // Fall through.
3264   case IIK_Default: {
3265     InitializationKind InitKind
3266       = InitializationKind::CreateDefault(Constructor->getLocation());
3267     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3268     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3269     break;
3270   }
3271 
3272   case IIK_Move:
3273   case IIK_Copy: {
3274     bool Moving = ImplicitInitKind == IIK_Move;
3275     ParmVarDecl *Param = Constructor->getParamDecl(0);
3276     QualType ParamType = Param->getType().getNonReferenceType();
3277 
3278     Expr *CopyCtorArg =
3279       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3280                           SourceLocation(), Param, false,
3281                           Constructor->getLocation(), ParamType,
3282                           VK_LValue, nullptr);
3283 
3284     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3285 
3286     // Cast to the base class to avoid ambiguities.
3287     QualType ArgTy =
3288       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3289                                        ParamType.getQualifiers());
3290 
3291     if (Moving) {
3292       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3293     }
3294 
3295     CXXCastPath BasePath;
3296     BasePath.push_back(BaseSpec);
3297     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3298                                             CK_UncheckedDerivedToBase,
3299                                             Moving ? VK_XValue : VK_LValue,
3300                                             &BasePath).get();
3301 
3302     InitializationKind InitKind
3303       = InitializationKind::CreateDirect(Constructor->getLocation(),
3304                                          SourceLocation(), SourceLocation());
3305     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3306     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3307     break;
3308   }
3309   }
3310 
3311   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3312   if (BaseInit.isInvalid())
3313     return true;
3314 
3315   CXXBaseInit =
3316     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3317                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3318                                                         SourceLocation()),
3319                                              BaseSpec->isVirtual(),
3320                                              SourceLocation(),
3321                                              BaseInit.getAs<Expr>(),
3322                                              SourceLocation(),
3323                                              SourceLocation());
3324 
3325   return false;
3326 }
3327 
3328 static bool RefersToRValueRef(Expr *MemRef) {
3329   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3330   return Referenced->getType()->isRValueReferenceType();
3331 }
3332 
3333 static bool
3334 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3335                                ImplicitInitializerKind ImplicitInitKind,
3336                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3337                                CXXCtorInitializer *&CXXMemberInit) {
3338   if (Field->isInvalidDecl())
3339     return true;
3340 
3341   SourceLocation Loc = Constructor->getLocation();
3342 
3343   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3344     bool Moving = ImplicitInitKind == IIK_Move;
3345     ParmVarDecl *Param = Constructor->getParamDecl(0);
3346     QualType ParamType = Param->getType().getNonReferenceType();
3347 
3348     // Suppress copying zero-width bitfields.
3349     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3350       return false;
3351 
3352     Expr *MemberExprBase =
3353       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3354                           SourceLocation(), Param, false,
3355                           Loc, ParamType, VK_LValue, nullptr);
3356 
3357     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3358 
3359     if (Moving) {
3360       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3361     }
3362 
3363     // Build a reference to this field within the parameter.
3364     CXXScopeSpec SS;
3365     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3366                               Sema::LookupMemberName);
3367     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3368                                   : cast<ValueDecl>(Field), AS_public);
3369     MemberLookup.resolveKind();
3370     ExprResult CtorArg
3371       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3372                                          ParamType, Loc,
3373                                          /*IsArrow=*/false,
3374                                          SS,
3375                                          /*TemplateKWLoc=*/SourceLocation(),
3376                                          /*FirstQualifierInScope=*/nullptr,
3377                                          MemberLookup,
3378                                          /*TemplateArgs=*/nullptr);
3379     if (CtorArg.isInvalid())
3380       return true;
3381 
3382     // C++11 [class.copy]p15:
3383     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3384     //     with static_cast<T&&>(x.m);
3385     if (RefersToRValueRef(CtorArg.get())) {
3386       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3387     }
3388 
3389     // When the field we are copying is an array, create index variables for
3390     // each dimension of the array. We use these index variables to subscript
3391     // the source array, and other clients (e.g., CodeGen) will perform the
3392     // necessary iteration with these index variables.
3393     SmallVector<VarDecl *, 4> IndexVariables;
3394     QualType BaseType = Field->getType();
3395     QualType SizeType = SemaRef.Context.getSizeType();
3396     bool InitializingArray = false;
3397     while (const ConstantArrayType *Array
3398                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3399       InitializingArray = true;
3400       // Create the iteration variable for this array index.
3401       IdentifierInfo *IterationVarName = nullptr;
3402       {
3403         SmallString<8> Str;
3404         llvm::raw_svector_ostream OS(Str);
3405         OS << "__i" << IndexVariables.size();
3406         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3407       }
3408       VarDecl *IterationVar
3409         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3410                           IterationVarName, SizeType,
3411                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3412                           SC_None);
3413       IndexVariables.push_back(IterationVar);
3414 
3415       // Create a reference to the iteration variable.
3416       ExprResult IterationVarRef
3417         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3418       assert(!IterationVarRef.isInvalid() &&
3419              "Reference to invented variable cannot fail!");
3420       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3421       assert(!IterationVarRef.isInvalid() &&
3422              "Conversion of invented variable cannot fail!");
3423 
3424       // Subscript the array with this iteration variable.
3425       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3426                                                         IterationVarRef.get(),
3427                                                         Loc);
3428       if (CtorArg.isInvalid())
3429         return true;
3430 
3431       BaseType = Array->getElementType();
3432     }
3433 
3434     // The array subscript expression is an lvalue, which is wrong for moving.
3435     if (Moving && InitializingArray)
3436       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3437 
3438     // Construct the entity that we will be initializing. For an array, this
3439     // will be first element in the array, which may require several levels
3440     // of array-subscript entities.
3441     SmallVector<InitializedEntity, 4> Entities;
3442     Entities.reserve(1 + IndexVariables.size());
3443     if (Indirect)
3444       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3445     else
3446       Entities.push_back(InitializedEntity::InitializeMember(Field));
3447     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3448       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3449                                                               0,
3450                                                               Entities.back()));
3451 
3452     // Direct-initialize to use the copy constructor.
3453     InitializationKind InitKind =
3454       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3455 
3456     Expr *CtorArgE = CtorArg.getAs<Expr>();
3457     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3458 
3459     ExprResult MemberInit
3460       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3461                         MultiExprArg(&CtorArgE, 1));
3462     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3463     if (MemberInit.isInvalid())
3464       return true;
3465 
3466     if (Indirect) {
3467       assert(IndexVariables.size() == 0 &&
3468              "Indirect field improperly initialized");
3469       CXXMemberInit
3470         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3471                                                    Loc, Loc,
3472                                                    MemberInit.getAs<Expr>(),
3473                                                    Loc);
3474     } else
3475       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3476                                                  Loc, MemberInit.getAs<Expr>(),
3477                                                  Loc,
3478                                                  IndexVariables.data(),
3479                                                  IndexVariables.size());
3480     return false;
3481   }
3482 
3483   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3484          "Unhandled implicit init kind!");
3485 
3486   QualType FieldBaseElementType =
3487     SemaRef.Context.getBaseElementType(Field->getType());
3488 
3489   if (FieldBaseElementType->isRecordType()) {
3490     InitializedEntity InitEntity
3491       = Indirect? InitializedEntity::InitializeMember(Indirect)
3492                 : InitializedEntity::InitializeMember(Field);
3493     InitializationKind InitKind =
3494       InitializationKind::CreateDefault(Loc);
3495 
3496     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3497     ExprResult MemberInit =
3498       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3499 
3500     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3501     if (MemberInit.isInvalid())
3502       return true;
3503 
3504     if (Indirect)
3505       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3506                                                                Indirect, Loc,
3507                                                                Loc,
3508                                                                MemberInit.get(),
3509                                                                Loc);
3510     else
3511       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3512                                                                Field, Loc, Loc,
3513                                                                MemberInit.get(),
3514                                                                Loc);
3515     return false;
3516   }
3517 
3518   if (!Field->getParent()->isUnion()) {
3519     if (FieldBaseElementType->isReferenceType()) {
3520       SemaRef.Diag(Constructor->getLocation(),
3521                    diag::err_uninitialized_member_in_ctor)
3522       << (int)Constructor->isImplicit()
3523       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3524       << 0 << Field->getDeclName();
3525       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3526       return true;
3527     }
3528 
3529     if (FieldBaseElementType.isConstQualified()) {
3530       SemaRef.Diag(Constructor->getLocation(),
3531                    diag::err_uninitialized_member_in_ctor)
3532       << (int)Constructor->isImplicit()
3533       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3534       << 1 << Field->getDeclName();
3535       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3536       return true;
3537     }
3538   }
3539 
3540   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3541       FieldBaseElementType->isObjCRetainableType() &&
3542       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3543       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3544     // ARC:
3545     //   Default-initialize Objective-C pointers to NULL.
3546     CXXMemberInit
3547       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3548                                                  Loc, Loc,
3549                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3550                                                  Loc);
3551     return false;
3552   }
3553 
3554   // Nothing to initialize.
3555   CXXMemberInit = nullptr;
3556   return false;
3557 }
3558 
3559 namespace {
3560 struct BaseAndFieldInfo {
3561   Sema &S;
3562   CXXConstructorDecl *Ctor;
3563   bool AnyErrorsInInits;
3564   ImplicitInitializerKind IIK;
3565   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3566   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3567   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3568 
3569   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3570     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3571     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3572     if (Generated && Ctor->isCopyConstructor())
3573       IIK = IIK_Copy;
3574     else if (Generated && Ctor->isMoveConstructor())
3575       IIK = IIK_Move;
3576     else if (Ctor->getInheritedConstructor())
3577       IIK = IIK_Inherit;
3578     else
3579       IIK = IIK_Default;
3580   }
3581 
3582   bool isImplicitCopyOrMove() const {
3583     switch (IIK) {
3584     case IIK_Copy:
3585     case IIK_Move:
3586       return true;
3587 
3588     case IIK_Default:
3589     case IIK_Inherit:
3590       return false;
3591     }
3592 
3593     llvm_unreachable("Invalid ImplicitInitializerKind!");
3594   }
3595 
3596   bool addFieldInitializer(CXXCtorInitializer *Init) {
3597     AllToInit.push_back(Init);
3598 
3599     // Check whether this initializer makes the field "used".
3600     if (Init->getInit()->HasSideEffects(S.Context))
3601       S.UnusedPrivateFields.remove(Init->getAnyMember());
3602 
3603     return false;
3604   }
3605 
3606   bool isInactiveUnionMember(FieldDecl *Field) {
3607     RecordDecl *Record = Field->getParent();
3608     if (!Record->isUnion())
3609       return false;
3610 
3611     if (FieldDecl *Active =
3612             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3613       return Active != Field->getCanonicalDecl();
3614 
3615     // In an implicit copy or move constructor, ignore any in-class initializer.
3616     if (isImplicitCopyOrMove())
3617       return true;
3618 
3619     // If there's no explicit initialization, the field is active only if it
3620     // has an in-class initializer...
3621     if (Field->hasInClassInitializer())
3622       return false;
3623     // ... or it's an anonymous struct or union whose class has an in-class
3624     // initializer.
3625     if (!Field->isAnonymousStructOrUnion())
3626       return true;
3627     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3628     return !FieldRD->hasInClassInitializer();
3629   }
3630 
3631   /// \brief Determine whether the given field is, or is within, a union member
3632   /// that is inactive (because there was an initializer given for a different
3633   /// member of the union, or because the union was not initialized at all).
3634   bool isWithinInactiveUnionMember(FieldDecl *Field,
3635                                    IndirectFieldDecl *Indirect) {
3636     if (!Indirect)
3637       return isInactiveUnionMember(Field);
3638 
3639     for (auto *C : Indirect->chain()) {
3640       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3641       if (Field && isInactiveUnionMember(Field))
3642         return true;
3643     }
3644     return false;
3645   }
3646 };
3647 }
3648 
3649 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3650 /// array type.
3651 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3652   if (T->isIncompleteArrayType())
3653     return true;
3654 
3655   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3656     if (!ArrayT->getSize())
3657       return true;
3658 
3659     T = ArrayT->getElementType();
3660   }
3661 
3662   return false;
3663 }
3664 
3665 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3666                                     FieldDecl *Field,
3667                                     IndirectFieldDecl *Indirect = nullptr) {
3668   if (Field->isInvalidDecl())
3669     return false;
3670 
3671   // Overwhelmingly common case: we have a direct initializer for this field.
3672   if (CXXCtorInitializer *Init =
3673           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3674     return Info.addFieldInitializer(Init);
3675 
3676   // C++11 [class.base.init]p8:
3677   //   if the entity is a non-static data member that has a
3678   //   brace-or-equal-initializer and either
3679   //   -- the constructor's class is a union and no other variant member of that
3680   //      union is designated by a mem-initializer-id or
3681   //   -- the constructor's class is not a union, and, if the entity is a member
3682   //      of an anonymous union, no other member of that union is designated by
3683   //      a mem-initializer-id,
3684   //   the entity is initialized as specified in [dcl.init].
3685   //
3686   // We also apply the same rules to handle anonymous structs within anonymous
3687   // unions.
3688   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3689     return false;
3690 
3691   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3692     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3693                                            Info.Ctor->getLocation(), Field);
3694     CXXCtorInitializer *Init;
3695     if (Indirect)
3696       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3697                                                       SourceLocation(),
3698                                                       SourceLocation(), DIE,
3699                                                       SourceLocation());
3700     else
3701       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3702                                                       SourceLocation(),
3703                                                       SourceLocation(), DIE,
3704                                                       SourceLocation());
3705     return Info.addFieldInitializer(Init);
3706   }
3707 
3708   // Don't initialize incomplete or zero-length arrays.
3709   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3710     return false;
3711 
3712   // Don't try to build an implicit initializer if there were semantic
3713   // errors in any of the initializers (and therefore we might be
3714   // missing some that the user actually wrote).
3715   if (Info.AnyErrorsInInits)
3716     return false;
3717 
3718   CXXCtorInitializer *Init = nullptr;
3719   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3720                                      Indirect, Init))
3721     return true;
3722 
3723   if (!Init)
3724     return false;
3725 
3726   return Info.addFieldInitializer(Init);
3727 }
3728 
3729 bool
3730 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3731                                CXXCtorInitializer *Initializer) {
3732   assert(Initializer->isDelegatingInitializer());
3733   Constructor->setNumCtorInitializers(1);
3734   CXXCtorInitializer **initializer =
3735     new (Context) CXXCtorInitializer*[1];
3736   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3737   Constructor->setCtorInitializers(initializer);
3738 
3739   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3740     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3741     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3742   }
3743 
3744   DelegatingCtorDecls.push_back(Constructor);
3745 
3746   DiagnoseUninitializedFields(*this, Constructor);
3747 
3748   return false;
3749 }
3750 
3751 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3752                                ArrayRef<CXXCtorInitializer *> Initializers) {
3753   if (Constructor->isDependentContext()) {
3754     // Just store the initializers as written, they will be checked during
3755     // instantiation.
3756     if (!Initializers.empty()) {
3757       Constructor->setNumCtorInitializers(Initializers.size());
3758       CXXCtorInitializer **baseOrMemberInitializers =
3759         new (Context) CXXCtorInitializer*[Initializers.size()];
3760       memcpy(baseOrMemberInitializers, Initializers.data(),
3761              Initializers.size() * sizeof(CXXCtorInitializer*));
3762       Constructor->setCtorInitializers(baseOrMemberInitializers);
3763     }
3764 
3765     // Let template instantiation know whether we had errors.
3766     if (AnyErrors)
3767       Constructor->setInvalidDecl();
3768 
3769     return false;
3770   }
3771 
3772   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3773 
3774   // We need to build the initializer AST according to order of construction
3775   // and not what user specified in the Initializers list.
3776   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3777   if (!ClassDecl)
3778     return true;
3779 
3780   bool HadError = false;
3781 
3782   for (unsigned i = 0; i < Initializers.size(); i++) {
3783     CXXCtorInitializer *Member = Initializers[i];
3784 
3785     if (Member->isBaseInitializer())
3786       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3787     else {
3788       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3789 
3790       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3791         for (auto *C : F->chain()) {
3792           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3793           if (FD && FD->getParent()->isUnion())
3794             Info.ActiveUnionMember.insert(std::make_pair(
3795                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3796         }
3797       } else if (FieldDecl *FD = Member->getMember()) {
3798         if (FD->getParent()->isUnion())
3799           Info.ActiveUnionMember.insert(std::make_pair(
3800               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3801       }
3802     }
3803   }
3804 
3805   // Keep track of the direct virtual bases.
3806   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3807   for (auto &I : ClassDecl->bases()) {
3808     if (I.isVirtual())
3809       DirectVBases.insert(&I);
3810   }
3811 
3812   // Push virtual bases before others.
3813   for (auto &VBase : ClassDecl->vbases()) {
3814     if (CXXCtorInitializer *Value
3815         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3816       // [class.base.init]p7, per DR257:
3817       //   A mem-initializer where the mem-initializer-id names a virtual base
3818       //   class is ignored during execution of a constructor of any class that
3819       //   is not the most derived class.
3820       if (ClassDecl->isAbstract()) {
3821         // FIXME: Provide a fixit to remove the base specifier. This requires
3822         // tracking the location of the associated comma for a base specifier.
3823         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3824           << VBase.getType() << ClassDecl;
3825         DiagnoseAbstractType(ClassDecl);
3826       }
3827 
3828       Info.AllToInit.push_back(Value);
3829     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3830       // [class.base.init]p8, per DR257:
3831       //   If a given [...] base class is not named by a mem-initializer-id
3832       //   [...] and the entity is not a virtual base class of an abstract
3833       //   class, then [...] the entity is default-initialized.
3834       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3835       CXXCtorInitializer *CXXBaseInit;
3836       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3837                                        &VBase, IsInheritedVirtualBase,
3838                                        CXXBaseInit)) {
3839         HadError = true;
3840         continue;
3841       }
3842 
3843       Info.AllToInit.push_back(CXXBaseInit);
3844     }
3845   }
3846 
3847   // Non-virtual bases.
3848   for (auto &Base : ClassDecl->bases()) {
3849     // Virtuals are in the virtual base list and already constructed.
3850     if (Base.isVirtual())
3851       continue;
3852 
3853     if (CXXCtorInitializer *Value
3854           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3855       Info.AllToInit.push_back(Value);
3856     } else if (!AnyErrors) {
3857       CXXCtorInitializer *CXXBaseInit;
3858       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3859                                        &Base, /*IsInheritedVirtualBase=*/false,
3860                                        CXXBaseInit)) {
3861         HadError = true;
3862         continue;
3863       }
3864 
3865       Info.AllToInit.push_back(CXXBaseInit);
3866     }
3867   }
3868 
3869   // Fields.
3870   for (auto *Mem : ClassDecl->decls()) {
3871     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3872       // C++ [class.bit]p2:
3873       //   A declaration for a bit-field that omits the identifier declares an
3874       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3875       //   initialized.
3876       if (F->isUnnamedBitfield())
3877         continue;
3878 
3879       // If we're not generating the implicit copy/move constructor, then we'll
3880       // handle anonymous struct/union fields based on their individual
3881       // indirect fields.
3882       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3883         continue;
3884 
3885       if (CollectFieldInitializer(*this, Info, F))
3886         HadError = true;
3887       continue;
3888     }
3889 
3890     // Beyond this point, we only consider default initialization.
3891     if (Info.isImplicitCopyOrMove())
3892       continue;
3893 
3894     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
3895       if (F->getType()->isIncompleteArrayType()) {
3896         assert(ClassDecl->hasFlexibleArrayMember() &&
3897                "Incomplete array type is not valid");
3898         continue;
3899       }
3900 
3901       // Initialize each field of an anonymous struct individually.
3902       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3903         HadError = true;
3904 
3905       continue;
3906     }
3907   }
3908 
3909   unsigned NumInitializers = Info.AllToInit.size();
3910   if (NumInitializers > 0) {
3911     Constructor->setNumCtorInitializers(NumInitializers);
3912     CXXCtorInitializer **baseOrMemberInitializers =
3913       new (Context) CXXCtorInitializer*[NumInitializers];
3914     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3915            NumInitializers * sizeof(CXXCtorInitializer*));
3916     Constructor->setCtorInitializers(baseOrMemberInitializers);
3917 
3918     // Constructors implicitly reference the base and member
3919     // destructors.
3920     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3921                                            Constructor->getParent());
3922   }
3923 
3924   return HadError;
3925 }
3926 
3927 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3928   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3929     const RecordDecl *RD = RT->getDecl();
3930     if (RD->isAnonymousStructOrUnion()) {
3931       for (auto *Field : RD->fields())
3932         PopulateKeysForFields(Field, IdealInits);
3933       return;
3934     }
3935   }
3936   IdealInits.push_back(Field->getCanonicalDecl());
3937 }
3938 
3939 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3940   return Context.getCanonicalType(BaseType).getTypePtr();
3941 }
3942 
3943 static const void *GetKeyForMember(ASTContext &Context,
3944                                    CXXCtorInitializer *Member) {
3945   if (!Member->isAnyMemberInitializer())
3946     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3947 
3948   return Member->getAnyMember()->getCanonicalDecl();
3949 }
3950 
3951 static void DiagnoseBaseOrMemInitializerOrder(
3952     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3953     ArrayRef<CXXCtorInitializer *> Inits) {
3954   if (Constructor->getDeclContext()->isDependentContext())
3955     return;
3956 
3957   // Don't check initializers order unless the warning is enabled at the
3958   // location of at least one initializer.
3959   bool ShouldCheckOrder = false;
3960   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3961     CXXCtorInitializer *Init = Inits[InitIndex];
3962     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3963                                  Init->getSourceLocation())) {
3964       ShouldCheckOrder = true;
3965       break;
3966     }
3967   }
3968   if (!ShouldCheckOrder)
3969     return;
3970 
3971   // Build the list of bases and members in the order that they'll
3972   // actually be initialized.  The explicit initializers should be in
3973   // this same order but may be missing things.
3974   SmallVector<const void*, 32> IdealInitKeys;
3975 
3976   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3977 
3978   // 1. Virtual bases.
3979   for (const auto &VBase : ClassDecl->vbases())
3980     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
3981 
3982   // 2. Non-virtual bases.
3983   for (const auto &Base : ClassDecl->bases()) {
3984     if (Base.isVirtual())
3985       continue;
3986     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
3987   }
3988 
3989   // 3. Direct fields.
3990   for (auto *Field : ClassDecl->fields()) {
3991     if (Field->isUnnamedBitfield())
3992       continue;
3993 
3994     PopulateKeysForFields(Field, IdealInitKeys);
3995   }
3996 
3997   unsigned NumIdealInits = IdealInitKeys.size();
3998   unsigned IdealIndex = 0;
3999 
4000   CXXCtorInitializer *PrevInit = nullptr;
4001   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4002     CXXCtorInitializer *Init = Inits[InitIndex];
4003     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4004 
4005     // Scan forward to try to find this initializer in the idealized
4006     // initializers list.
4007     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4008       if (InitKey == IdealInitKeys[IdealIndex])
4009         break;
4010 
4011     // If we didn't find this initializer, it must be because we
4012     // scanned past it on a previous iteration.  That can only
4013     // happen if we're out of order;  emit a warning.
4014     if (IdealIndex == NumIdealInits && PrevInit) {
4015       Sema::SemaDiagnosticBuilder D =
4016         SemaRef.Diag(PrevInit->getSourceLocation(),
4017                      diag::warn_initializer_out_of_order);
4018 
4019       if (PrevInit->isAnyMemberInitializer())
4020         D << 0 << PrevInit->getAnyMember()->getDeclName();
4021       else
4022         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4023 
4024       if (Init->isAnyMemberInitializer())
4025         D << 0 << Init->getAnyMember()->getDeclName();
4026       else
4027         D << 1 << Init->getTypeSourceInfo()->getType();
4028 
4029       // Move back to the initializer's location in the ideal list.
4030       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4031         if (InitKey == IdealInitKeys[IdealIndex])
4032           break;
4033 
4034       assert(IdealIndex != NumIdealInits &&
4035              "initializer not found in initializer list");
4036     }
4037 
4038     PrevInit = Init;
4039   }
4040 }
4041 
4042 namespace {
4043 bool CheckRedundantInit(Sema &S,
4044                         CXXCtorInitializer *Init,
4045                         CXXCtorInitializer *&PrevInit) {
4046   if (!PrevInit) {
4047     PrevInit = Init;
4048     return false;
4049   }
4050 
4051   if (FieldDecl *Field = Init->getAnyMember())
4052     S.Diag(Init->getSourceLocation(),
4053            diag::err_multiple_mem_initialization)
4054       << Field->getDeclName()
4055       << Init->getSourceRange();
4056   else {
4057     const Type *BaseClass = Init->getBaseClass();
4058     assert(BaseClass && "neither field nor base");
4059     S.Diag(Init->getSourceLocation(),
4060            diag::err_multiple_base_initialization)
4061       << QualType(BaseClass, 0)
4062       << Init->getSourceRange();
4063   }
4064   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4065     << 0 << PrevInit->getSourceRange();
4066 
4067   return true;
4068 }
4069 
4070 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4071 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4072 
4073 bool CheckRedundantUnionInit(Sema &S,
4074                              CXXCtorInitializer *Init,
4075                              RedundantUnionMap &Unions) {
4076   FieldDecl *Field = Init->getAnyMember();
4077   RecordDecl *Parent = Field->getParent();
4078   NamedDecl *Child = Field;
4079 
4080   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4081     if (Parent->isUnion()) {
4082       UnionEntry &En = Unions[Parent];
4083       if (En.first && En.first != Child) {
4084         S.Diag(Init->getSourceLocation(),
4085                diag::err_multiple_mem_union_initialization)
4086           << Field->getDeclName()
4087           << Init->getSourceRange();
4088         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4089           << 0 << En.second->getSourceRange();
4090         return true;
4091       }
4092       if (!En.first) {
4093         En.first = Child;
4094         En.second = Init;
4095       }
4096       if (!Parent->isAnonymousStructOrUnion())
4097         return false;
4098     }
4099 
4100     Child = Parent;
4101     Parent = cast<RecordDecl>(Parent->getDeclContext());
4102   }
4103 
4104   return false;
4105 }
4106 }
4107 
4108 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4109 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4110                                 SourceLocation ColonLoc,
4111                                 ArrayRef<CXXCtorInitializer*> MemInits,
4112                                 bool AnyErrors) {
4113   if (!ConstructorDecl)
4114     return;
4115 
4116   AdjustDeclIfTemplate(ConstructorDecl);
4117 
4118   CXXConstructorDecl *Constructor
4119     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4120 
4121   if (!Constructor) {
4122     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4123     return;
4124   }
4125 
4126   // Mapping for the duplicate initializers check.
4127   // For member initializers, this is keyed with a FieldDecl*.
4128   // For base initializers, this is keyed with a Type*.
4129   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4130 
4131   // Mapping for the inconsistent anonymous-union initializers check.
4132   RedundantUnionMap MemberUnions;
4133 
4134   bool HadError = false;
4135   for (unsigned i = 0; i < MemInits.size(); i++) {
4136     CXXCtorInitializer *Init = MemInits[i];
4137 
4138     // Set the source order index.
4139     Init->setSourceOrder(i);
4140 
4141     if (Init->isAnyMemberInitializer()) {
4142       const void *Key = GetKeyForMember(Context, Init);
4143       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4144           CheckRedundantUnionInit(*this, Init, MemberUnions))
4145         HadError = true;
4146     } else if (Init->isBaseInitializer()) {
4147       const void *Key = GetKeyForMember(Context, Init);
4148       if (CheckRedundantInit(*this, Init, Members[Key]))
4149         HadError = true;
4150     } else {
4151       assert(Init->isDelegatingInitializer());
4152       // This must be the only initializer
4153       if (MemInits.size() != 1) {
4154         Diag(Init->getSourceLocation(),
4155              diag::err_delegating_initializer_alone)
4156           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4157         // We will treat this as being the only initializer.
4158       }
4159       SetDelegatingInitializer(Constructor, MemInits[i]);
4160       // Return immediately as the initializer is set.
4161       return;
4162     }
4163   }
4164 
4165   if (HadError)
4166     return;
4167 
4168   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4169 
4170   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4171 
4172   DiagnoseUninitializedFields(*this, Constructor);
4173 }
4174 
4175 void
4176 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4177                                              CXXRecordDecl *ClassDecl) {
4178   // Ignore dependent contexts. Also ignore unions, since their members never
4179   // have destructors implicitly called.
4180   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4181     return;
4182 
4183   // FIXME: all the access-control diagnostics are positioned on the
4184   // field/base declaration.  That's probably good; that said, the
4185   // user might reasonably want to know why the destructor is being
4186   // emitted, and we currently don't say.
4187 
4188   // Non-static data members.
4189   for (auto *Field : ClassDecl->fields()) {
4190     if (Field->isInvalidDecl())
4191       continue;
4192 
4193     // Don't destroy incomplete or zero-length arrays.
4194     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4195       continue;
4196 
4197     QualType FieldType = Context.getBaseElementType(Field->getType());
4198 
4199     const RecordType* RT = FieldType->getAs<RecordType>();
4200     if (!RT)
4201       continue;
4202 
4203     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4204     if (FieldClassDecl->isInvalidDecl())
4205       continue;
4206     if (FieldClassDecl->hasIrrelevantDestructor())
4207       continue;
4208     // The destructor for an implicit anonymous union member is never invoked.
4209     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4210       continue;
4211 
4212     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4213     assert(Dtor && "No dtor found for FieldClassDecl!");
4214     CheckDestructorAccess(Field->getLocation(), Dtor,
4215                           PDiag(diag::err_access_dtor_field)
4216                             << Field->getDeclName()
4217                             << FieldType);
4218 
4219     MarkFunctionReferenced(Location, Dtor);
4220     DiagnoseUseOfDecl(Dtor, Location);
4221   }
4222 
4223   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4224 
4225   // Bases.
4226   for (const auto &Base : ClassDecl->bases()) {
4227     // Bases are always records in a well-formed non-dependent class.
4228     const RecordType *RT = Base.getType()->getAs<RecordType>();
4229 
4230     // Remember direct virtual bases.
4231     if (Base.isVirtual())
4232       DirectVirtualBases.insert(RT);
4233 
4234     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4235     // If our base class is invalid, we probably can't get its dtor anyway.
4236     if (BaseClassDecl->isInvalidDecl())
4237       continue;
4238     if (BaseClassDecl->hasIrrelevantDestructor())
4239       continue;
4240 
4241     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4242     assert(Dtor && "No dtor found for BaseClassDecl!");
4243 
4244     // FIXME: caret should be on the start of the class name
4245     CheckDestructorAccess(Base.getLocStart(), Dtor,
4246                           PDiag(diag::err_access_dtor_base)
4247                             << Base.getType()
4248                             << Base.getSourceRange(),
4249                           Context.getTypeDeclType(ClassDecl));
4250 
4251     MarkFunctionReferenced(Location, Dtor);
4252     DiagnoseUseOfDecl(Dtor, Location);
4253   }
4254 
4255   // Virtual bases.
4256   for (const auto &VBase : ClassDecl->vbases()) {
4257     // Bases are always records in a well-formed non-dependent class.
4258     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4259 
4260     // Ignore direct virtual bases.
4261     if (DirectVirtualBases.count(RT))
4262       continue;
4263 
4264     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4265     // If our base class is invalid, we probably can't get its dtor anyway.
4266     if (BaseClassDecl->isInvalidDecl())
4267       continue;
4268     if (BaseClassDecl->hasIrrelevantDestructor())
4269       continue;
4270 
4271     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4272     assert(Dtor && "No dtor found for BaseClassDecl!");
4273     if (CheckDestructorAccess(
4274             ClassDecl->getLocation(), Dtor,
4275             PDiag(diag::err_access_dtor_vbase)
4276                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4277             Context.getTypeDeclType(ClassDecl)) ==
4278         AR_accessible) {
4279       CheckDerivedToBaseConversion(
4280           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4281           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4282           SourceRange(), DeclarationName(), nullptr);
4283     }
4284 
4285     MarkFunctionReferenced(Location, Dtor);
4286     DiagnoseUseOfDecl(Dtor, Location);
4287   }
4288 }
4289 
4290 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4291   if (!CDtorDecl)
4292     return;
4293 
4294   if (CXXConstructorDecl *Constructor
4295       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4296     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4297     DiagnoseUninitializedFields(*this, Constructor);
4298   }
4299 }
4300 
4301 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4302                                   unsigned DiagID, AbstractDiagSelID SelID) {
4303   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4304     unsigned DiagID;
4305     AbstractDiagSelID SelID;
4306 
4307   public:
4308     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4309       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4310 
4311     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4312       if (Suppressed) return;
4313       if (SelID == -1)
4314         S.Diag(Loc, DiagID) << T;
4315       else
4316         S.Diag(Loc, DiagID) << SelID << T;
4317     }
4318   } Diagnoser(DiagID, SelID);
4319 
4320   return RequireNonAbstractType(Loc, T, Diagnoser);
4321 }
4322 
4323 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4324                                   TypeDiagnoser &Diagnoser) {
4325   if (!getLangOpts().CPlusPlus)
4326     return false;
4327 
4328   if (const ArrayType *AT = Context.getAsArrayType(T))
4329     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4330 
4331   if (const PointerType *PT = T->getAs<PointerType>()) {
4332     // Find the innermost pointer type.
4333     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4334       PT = T;
4335 
4336     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4337       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4338   }
4339 
4340   const RecordType *RT = T->getAs<RecordType>();
4341   if (!RT)
4342     return false;
4343 
4344   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4345 
4346   // We can't answer whether something is abstract until it has a
4347   // definition.  If it's currently being defined, we'll walk back
4348   // over all the declarations when we have a full definition.
4349   const CXXRecordDecl *Def = RD->getDefinition();
4350   if (!Def || Def->isBeingDefined())
4351     return false;
4352 
4353   if (!RD->isAbstract())
4354     return false;
4355 
4356   Diagnoser.diagnose(*this, Loc, T);
4357   DiagnoseAbstractType(RD);
4358 
4359   return true;
4360 }
4361 
4362 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4363   // Check if we've already emitted the list of pure virtual functions
4364   // for this class.
4365   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4366     return;
4367 
4368   // If the diagnostic is suppressed, don't emit the notes. We're only
4369   // going to emit them once, so try to attach them to a diagnostic we're
4370   // actually going to show.
4371   if (Diags.isLastDiagnosticIgnored())
4372     return;
4373 
4374   CXXFinalOverriderMap FinalOverriders;
4375   RD->getFinalOverriders(FinalOverriders);
4376 
4377   // Keep a set of seen pure methods so we won't diagnose the same method
4378   // more than once.
4379   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4380 
4381   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4382                                    MEnd = FinalOverriders.end();
4383        M != MEnd;
4384        ++M) {
4385     for (OverridingMethods::iterator SO = M->second.begin(),
4386                                   SOEnd = M->second.end();
4387          SO != SOEnd; ++SO) {
4388       // C++ [class.abstract]p4:
4389       //   A class is abstract if it contains or inherits at least one
4390       //   pure virtual function for which the final overrider is pure
4391       //   virtual.
4392 
4393       //
4394       if (SO->second.size() != 1)
4395         continue;
4396 
4397       if (!SO->second.front().Method->isPure())
4398         continue;
4399 
4400       if (!SeenPureMethods.insert(SO->second.front().Method))
4401         continue;
4402 
4403       Diag(SO->second.front().Method->getLocation(),
4404            diag::note_pure_virtual_function)
4405         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4406     }
4407   }
4408 
4409   if (!PureVirtualClassDiagSet)
4410     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4411   PureVirtualClassDiagSet->insert(RD);
4412 }
4413 
4414 namespace {
4415 struct AbstractUsageInfo {
4416   Sema &S;
4417   CXXRecordDecl *Record;
4418   CanQualType AbstractType;
4419   bool Invalid;
4420 
4421   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4422     : S(S), Record(Record),
4423       AbstractType(S.Context.getCanonicalType(
4424                    S.Context.getTypeDeclType(Record))),
4425       Invalid(false) {}
4426 
4427   void DiagnoseAbstractType() {
4428     if (Invalid) return;
4429     S.DiagnoseAbstractType(Record);
4430     Invalid = true;
4431   }
4432 
4433   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4434 };
4435 
4436 struct CheckAbstractUsage {
4437   AbstractUsageInfo &Info;
4438   const NamedDecl *Ctx;
4439 
4440   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4441     : Info(Info), Ctx(Ctx) {}
4442 
4443   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4444     switch (TL.getTypeLocClass()) {
4445 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4446 #define TYPELOC(CLASS, PARENT) \
4447     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4448 #include "clang/AST/TypeLocNodes.def"
4449     }
4450   }
4451 
4452   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4453     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4454     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4455       if (!TL.getParam(I))
4456         continue;
4457 
4458       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4459       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4460     }
4461   }
4462 
4463   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4464     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4465   }
4466 
4467   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4468     // Visit the type parameters from a permissive context.
4469     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4470       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4471       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4472         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4473           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4474       // TODO: other template argument types?
4475     }
4476   }
4477 
4478   // Visit pointee types from a permissive context.
4479 #define CheckPolymorphic(Type) \
4480   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4481     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4482   }
4483   CheckPolymorphic(PointerTypeLoc)
4484   CheckPolymorphic(ReferenceTypeLoc)
4485   CheckPolymorphic(MemberPointerTypeLoc)
4486   CheckPolymorphic(BlockPointerTypeLoc)
4487   CheckPolymorphic(AtomicTypeLoc)
4488 
4489   /// Handle all the types we haven't given a more specific
4490   /// implementation for above.
4491   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4492     // Every other kind of type that we haven't called out already
4493     // that has an inner type is either (1) sugar or (2) contains that
4494     // inner type in some way as a subobject.
4495     if (TypeLoc Next = TL.getNextTypeLoc())
4496       return Visit(Next, Sel);
4497 
4498     // If there's no inner type and we're in a permissive context,
4499     // don't diagnose.
4500     if (Sel == Sema::AbstractNone) return;
4501 
4502     // Check whether the type matches the abstract type.
4503     QualType T = TL.getType();
4504     if (T->isArrayType()) {
4505       Sel = Sema::AbstractArrayType;
4506       T = Info.S.Context.getBaseElementType(T);
4507     }
4508     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4509     if (CT != Info.AbstractType) return;
4510 
4511     // It matched; do some magic.
4512     if (Sel == Sema::AbstractArrayType) {
4513       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4514         << T << TL.getSourceRange();
4515     } else {
4516       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4517         << Sel << T << TL.getSourceRange();
4518     }
4519     Info.DiagnoseAbstractType();
4520   }
4521 };
4522 
4523 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4524                                   Sema::AbstractDiagSelID Sel) {
4525   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4526 }
4527 
4528 }
4529 
4530 /// Check for invalid uses of an abstract type in a method declaration.
4531 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4532                                     CXXMethodDecl *MD) {
4533   // No need to do the check on definitions, which require that
4534   // the return/param types be complete.
4535   if (MD->doesThisDeclarationHaveABody())
4536     return;
4537 
4538   // For safety's sake, just ignore it if we don't have type source
4539   // information.  This should never happen for non-implicit methods,
4540   // but...
4541   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4542     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4543 }
4544 
4545 /// Check for invalid uses of an abstract type within a class definition.
4546 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4547                                     CXXRecordDecl *RD) {
4548   for (auto *D : RD->decls()) {
4549     if (D->isImplicit()) continue;
4550 
4551     // Methods and method templates.
4552     if (isa<CXXMethodDecl>(D)) {
4553       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4554     } else if (isa<FunctionTemplateDecl>(D)) {
4555       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4556       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4557 
4558     // Fields and static variables.
4559     } else if (isa<FieldDecl>(D)) {
4560       FieldDecl *FD = cast<FieldDecl>(D);
4561       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4562         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4563     } else if (isa<VarDecl>(D)) {
4564       VarDecl *VD = cast<VarDecl>(D);
4565       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4566         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4567 
4568     // Nested classes and class templates.
4569     } else if (isa<CXXRecordDecl>(D)) {
4570       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4571     } else if (isa<ClassTemplateDecl>(D)) {
4572       CheckAbstractClassUsage(Info,
4573                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4574     }
4575   }
4576 }
4577 
4578 /// \brief Check class-level dllimport/dllexport attribute.
4579 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4580   Attr *ClassAttr = getDLLAttr(Class);
4581 
4582   // MSVC inherits DLL attributes to partial class template specializations.
4583   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4584     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4585       if (Attr *TemplateAttr =
4586               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4587         auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4588         A->setInherited(true);
4589         ClassAttr = A;
4590       }
4591     }
4592   }
4593 
4594   if (!ClassAttr)
4595     return;
4596 
4597   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4598       !ClassAttr->isInherited()) {
4599     // Diagnose dll attributes on members of class with dll attribute.
4600     for (Decl *Member : Class->decls()) {
4601       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4602         continue;
4603       InheritableAttr *MemberAttr = getDLLAttr(Member);
4604       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4605         continue;
4606 
4607       S.Diag(MemberAttr->getLocation(),
4608              diag::err_attribute_dll_member_of_dll_class)
4609           << MemberAttr << ClassAttr;
4610       S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4611       Member->setInvalidDecl();
4612     }
4613   }
4614 
4615   if (Class->getDescribedClassTemplate())
4616     // Don't inherit dll attribute until the template is instantiated.
4617     return;
4618 
4619   bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4620 
4621   // Force declaration of implicit members so they can inherit the attribute.
4622   S.ForceDeclarationOfImplicitMembers(Class);
4623 
4624   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4625   // seem to be true in practice?
4626 
4627   TemplateSpecializationKind TSK =
4628     Class->getTemplateSpecializationKind();
4629 
4630   for (Decl *Member : Class->decls()) {
4631     VarDecl *VD = dyn_cast<VarDecl>(Member);
4632     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4633 
4634     // Only methods and static fields inherit the attributes.
4635     if (!VD && !MD)
4636       continue;
4637 
4638     // Don't process deleted methods.
4639     if (MD && MD->isDeleted())
4640       continue;
4641 
4642     if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4643         MD->isInlined()) {
4644       // Current MSVC versions don't export the move assignment operators, so
4645       // don't attempt to import them if we have a definition.
4646       continue;
4647     }
4648 
4649     if (!getDLLAttr(Member)) {
4650       auto *NewAttr =
4651           cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4652       NewAttr->setInherited(true);
4653       Member->addAttr(NewAttr);
4654     }
4655 
4656     if (MD && ClassExported) {
4657       if (MD->isUserProvided()) {
4658         // Instantiate non-default methods..
4659 
4660         // .. except for certain kinds of template specializations.
4661         if (TSK == TSK_ExplicitInstantiationDeclaration)
4662           continue;
4663         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4664           continue;
4665 
4666         S.MarkFunctionReferenced(Class->getLocation(), MD);
4667       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4668                  MD->isCopyAssignmentOperator() ||
4669                  MD->isMoveAssignmentOperator()) {
4670         // Instantiate non-trivial or explicitly defaulted methods, and the
4671         // copy assignment / move assignment operators.
4672         S.MarkFunctionReferenced(Class->getLocation(), MD);
4673         // Resolve its exception specification; CodeGen needs it.
4674         auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4675         S.ResolveExceptionSpec(Class->getLocation(), FPT);
4676         S.ActOnFinishInlineMethodDef(MD);
4677       }
4678     }
4679   }
4680 }
4681 
4682 /// \brief Perform semantic checks on a class definition that has been
4683 /// completing, introducing implicitly-declared members, checking for
4684 /// abstract types, etc.
4685 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4686   if (!Record)
4687     return;
4688 
4689   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4690     AbstractUsageInfo Info(*this, Record);
4691     CheckAbstractClassUsage(Info, Record);
4692   }
4693 
4694   // If this is not an aggregate type and has no user-declared constructor,
4695   // complain about any non-static data members of reference or const scalar
4696   // type, since they will never get initializers.
4697   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4698       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4699       !Record->isLambda()) {
4700     bool Complained = false;
4701     for (const auto *F : Record->fields()) {
4702       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4703         continue;
4704 
4705       if (F->getType()->isReferenceType() ||
4706           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4707         if (!Complained) {
4708           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4709             << Record->getTagKind() << Record;
4710           Complained = true;
4711         }
4712 
4713         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4714           << F->getType()->isReferenceType()
4715           << F->getDeclName();
4716       }
4717     }
4718   }
4719 
4720   if (Record->isDynamicClass() && !Record->isDependentType())
4721     DynamicClasses.push_back(Record);
4722 
4723   if (Record->getIdentifier()) {
4724     // C++ [class.mem]p13:
4725     //   If T is the name of a class, then each of the following shall have a
4726     //   name different from T:
4727     //     - every member of every anonymous union that is a member of class T.
4728     //
4729     // C++ [class.mem]p14:
4730     //   In addition, if class T has a user-declared constructor (12.1), every
4731     //   non-static data member of class T shall have a name different from T.
4732     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4733     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4734          ++I) {
4735       NamedDecl *D = *I;
4736       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4737           isa<IndirectFieldDecl>(D)) {
4738         Diag(D->getLocation(), diag::err_member_name_of_class)
4739           << D->getDeclName();
4740         break;
4741       }
4742     }
4743   }
4744 
4745   // Warn if the class has virtual methods but non-virtual public destructor.
4746   if (Record->isPolymorphic() && !Record->isDependentType()) {
4747     CXXDestructorDecl *dtor = Record->getDestructor();
4748     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4749         !Record->hasAttr<FinalAttr>())
4750       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4751            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4752   }
4753 
4754   if (Record->isAbstract()) {
4755     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4756       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4757         << FA->isSpelledAsSealed();
4758       DiagnoseAbstractType(Record);
4759     }
4760   }
4761 
4762   if (!Record->isDependentType()) {
4763     for (auto *M : Record->methods()) {
4764       // See if a method overloads virtual methods in a base
4765       // class without overriding any.
4766       if (!M->isStatic())
4767         DiagnoseHiddenVirtualMethods(M);
4768 
4769       // Check whether the explicitly-defaulted special members are valid.
4770       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4771         CheckExplicitlyDefaultedSpecialMember(M);
4772 
4773       // For an explicitly defaulted or deleted special member, we defer
4774       // determining triviality until the class is complete. That time is now!
4775       if (!M->isImplicit() && !M->isUserProvided()) {
4776         CXXSpecialMember CSM = getSpecialMember(M);
4777         if (CSM != CXXInvalid) {
4778           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4779 
4780           // Inform the class that we've finished declaring this member.
4781           Record->finishedDefaultedOrDeletedMember(M);
4782         }
4783       }
4784     }
4785   }
4786 
4787   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4788   // function that is not a constructor declares that member function to be
4789   // const. [...] The class of which that function is a member shall be
4790   // a literal type.
4791   //
4792   // If the class has virtual bases, any constexpr members will already have
4793   // been diagnosed by the checks performed on the member declaration, so
4794   // suppress this (less useful) diagnostic.
4795   //
4796   // We delay this until we know whether an explicitly-defaulted (or deleted)
4797   // destructor for the class is trivial.
4798   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4799       !Record->isLiteral() && !Record->getNumVBases()) {
4800     for (const auto *M : Record->methods()) {
4801       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
4802         switch (Record->getTemplateSpecializationKind()) {
4803         case TSK_ImplicitInstantiation:
4804         case TSK_ExplicitInstantiationDeclaration:
4805         case TSK_ExplicitInstantiationDefinition:
4806           // If a template instantiates to a non-literal type, but its members
4807           // instantiate to constexpr functions, the template is technically
4808           // ill-formed, but we allow it for sanity.
4809           continue;
4810 
4811         case TSK_Undeclared:
4812         case TSK_ExplicitSpecialization:
4813           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4814                              diag::err_constexpr_method_non_literal);
4815           break;
4816         }
4817 
4818         // Only produce one error per class.
4819         break;
4820       }
4821     }
4822   }
4823 
4824   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4825   // whether this class uses any C++ features that are implemented
4826   // completely differently in MSVC, and if so, emit a diagnostic.
4827   // That diagnostic defaults to an error, but we allow projects to
4828   // map it down to a warning (or ignore it).  It's a fairly common
4829   // practice among users of the ms_struct pragma to mass-annotate
4830   // headers, sweeping up a bunch of types that the project doesn't
4831   // really rely on MSVC-compatible layout for.  We must therefore
4832   // support "ms_struct except for C++ stuff" as a secondary ABI.
4833   if (Record->isMsStruct(Context) &&
4834       (Record->isPolymorphic() || Record->getNumBases())) {
4835     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4836   }
4837 
4838   // Declare inheriting constructors. We do this eagerly here because:
4839   // - The standard requires an eager diagnostic for conflicting inheriting
4840   //   constructors from different classes.
4841   // - The lazy declaration of the other implicit constructors is so as to not
4842   //   waste space and performance on classes that are not meant to be
4843   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4844   //   have inheriting constructors.
4845   DeclareInheritingConstructors(Record);
4846 
4847   checkDLLAttribute(*this, Record);
4848 }
4849 
4850 /// Look up the special member function that would be called by a special
4851 /// member function for a subobject of class type.
4852 ///
4853 /// \param Class The class type of the subobject.
4854 /// \param CSM The kind of special member function.
4855 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4856 /// \param ConstRHS True if this is a copy operation with a const object
4857 ///        on its RHS, that is, if the argument to the outer special member
4858 ///        function is 'const' and this is not a field marked 'mutable'.
4859 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4860     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4861     unsigned FieldQuals, bool ConstRHS) {
4862   unsigned LHSQuals = 0;
4863   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4864     LHSQuals = FieldQuals;
4865 
4866   unsigned RHSQuals = FieldQuals;
4867   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4868     RHSQuals = 0;
4869   else if (ConstRHS)
4870     RHSQuals |= Qualifiers::Const;
4871 
4872   return S.LookupSpecialMember(Class, CSM,
4873                                RHSQuals & Qualifiers::Const,
4874                                RHSQuals & Qualifiers::Volatile,
4875                                false,
4876                                LHSQuals & Qualifiers::Const,
4877                                LHSQuals & Qualifiers::Volatile);
4878 }
4879 
4880 /// Is the special member function which would be selected to perform the
4881 /// specified operation on the specified class type a constexpr constructor?
4882 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4883                                      Sema::CXXSpecialMember CSM,
4884                                      unsigned Quals, bool ConstRHS) {
4885   Sema::SpecialMemberOverloadResult *SMOR =
4886       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
4887   if (!SMOR || !SMOR->getMethod())
4888     // A constructor we wouldn't select can't be "involved in initializing"
4889     // anything.
4890     return true;
4891   return SMOR->getMethod()->isConstexpr();
4892 }
4893 
4894 /// Determine whether the specified special member function would be constexpr
4895 /// if it were implicitly defined.
4896 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4897                                               Sema::CXXSpecialMember CSM,
4898                                               bool ConstArg) {
4899   if (!S.getLangOpts().CPlusPlus11)
4900     return false;
4901 
4902   // C++11 [dcl.constexpr]p4:
4903   // In the definition of a constexpr constructor [...]
4904   bool Ctor = true;
4905   switch (CSM) {
4906   case Sema::CXXDefaultConstructor:
4907     // Since default constructor lookup is essentially trivial (and cannot
4908     // involve, for instance, template instantiation), we compute whether a
4909     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4910     //
4911     // This is important for performance; we need to know whether the default
4912     // constructor is constexpr to determine whether the type is a literal type.
4913     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4914 
4915   case Sema::CXXCopyConstructor:
4916   case Sema::CXXMoveConstructor:
4917     // For copy or move constructors, we need to perform overload resolution.
4918     break;
4919 
4920   case Sema::CXXCopyAssignment:
4921   case Sema::CXXMoveAssignment:
4922     if (!S.getLangOpts().CPlusPlus14)
4923       return false;
4924     // In C++1y, we need to perform overload resolution.
4925     Ctor = false;
4926     break;
4927 
4928   case Sema::CXXDestructor:
4929   case Sema::CXXInvalid:
4930     return false;
4931   }
4932 
4933   //   -- if the class is a non-empty union, or for each non-empty anonymous
4934   //      union member of a non-union class, exactly one non-static data member
4935   //      shall be initialized; [DR1359]
4936   //
4937   // If we squint, this is guaranteed, since exactly one non-static data member
4938   // will be initialized (if the constructor isn't deleted), we just don't know
4939   // which one.
4940   if (Ctor && ClassDecl->isUnion())
4941     return true;
4942 
4943   //   -- the class shall not have any virtual base classes;
4944   if (Ctor && ClassDecl->getNumVBases())
4945     return false;
4946 
4947   // C++1y [class.copy]p26:
4948   //   -- [the class] is a literal type, and
4949   if (!Ctor && !ClassDecl->isLiteral())
4950     return false;
4951 
4952   //   -- every constructor involved in initializing [...] base class
4953   //      sub-objects shall be a constexpr constructor;
4954   //   -- the assignment operator selected to copy/move each direct base
4955   //      class is a constexpr function, and
4956   for (const auto &B : ClassDecl->bases()) {
4957     const RecordType *BaseType = B.getType()->getAs<RecordType>();
4958     if (!BaseType) continue;
4959 
4960     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4961     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
4962       return false;
4963   }
4964 
4965   //   -- every constructor involved in initializing non-static data members
4966   //      [...] shall be a constexpr constructor;
4967   //   -- every non-static data member and base class sub-object shall be
4968   //      initialized
4969   //   -- for each non-static data member of X that is of class type (or array
4970   //      thereof), the assignment operator selected to copy/move that member is
4971   //      a constexpr function
4972   for (const auto *F : ClassDecl->fields()) {
4973     if (F->isInvalidDecl())
4974       continue;
4975     QualType BaseType = S.Context.getBaseElementType(F->getType());
4976     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
4977       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4978       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4979                                     BaseType.getCVRQualifiers(),
4980                                     ConstArg && !F->isMutable()))
4981         return false;
4982     }
4983   }
4984 
4985   // All OK, it's constexpr!
4986   return true;
4987 }
4988 
4989 static Sema::ImplicitExceptionSpecification
4990 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4991   switch (S.getSpecialMember(MD)) {
4992   case Sema::CXXDefaultConstructor:
4993     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4994   case Sema::CXXCopyConstructor:
4995     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4996   case Sema::CXXCopyAssignment:
4997     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4998   case Sema::CXXMoveConstructor:
4999     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5000   case Sema::CXXMoveAssignment:
5001     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5002   case Sema::CXXDestructor:
5003     return S.ComputeDefaultedDtorExceptionSpec(MD);
5004   case Sema::CXXInvalid:
5005     break;
5006   }
5007   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5008          "only special members have implicit exception specs");
5009   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5010 }
5011 
5012 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5013                                                             CXXMethodDecl *MD) {
5014   FunctionProtoType::ExtProtoInfo EPI;
5015 
5016   // Build an exception specification pointing back at this member.
5017   EPI.ExceptionSpec.Type = EST_Unevaluated;
5018   EPI.ExceptionSpec.SourceDecl = MD;
5019 
5020   // Set the calling convention to the default for C++ instance methods.
5021   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5022       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5023                                             /*IsCXXMethod=*/true));
5024   return EPI;
5025 }
5026 
5027 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5028   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5029   if (FPT->getExceptionSpecType() != EST_Unevaluated)
5030     return;
5031 
5032   // Evaluate the exception specification.
5033   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5034 
5035   // Update the type of the special member to use it.
5036   UpdateExceptionSpec(MD, ESI);
5037 
5038   // A user-provided destructor can be defined outside the class. When that
5039   // happens, be sure to update the exception specification on both
5040   // declarations.
5041   const FunctionProtoType *CanonicalFPT =
5042     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5043   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5044     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5045 }
5046 
5047 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5048   CXXRecordDecl *RD = MD->getParent();
5049   CXXSpecialMember CSM = getSpecialMember(MD);
5050 
5051   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5052          "not an explicitly-defaulted special member");
5053 
5054   // Whether this was the first-declared instance of the constructor.
5055   // This affects whether we implicitly add an exception spec and constexpr.
5056   bool First = MD == MD->getCanonicalDecl();
5057 
5058   bool HadError = false;
5059 
5060   // C++11 [dcl.fct.def.default]p1:
5061   //   A function that is explicitly defaulted shall
5062   //     -- be a special member function (checked elsewhere),
5063   //     -- have the same type (except for ref-qualifiers, and except that a
5064   //        copy operation can take a non-const reference) as an implicit
5065   //        declaration, and
5066   //     -- not have default arguments.
5067   unsigned ExpectedParams = 1;
5068   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5069     ExpectedParams = 0;
5070   if (MD->getNumParams() != ExpectedParams) {
5071     // This also checks for default arguments: a copy or move constructor with a
5072     // default argument is classified as a default constructor, and assignment
5073     // operations and destructors can't have default arguments.
5074     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5075       << CSM << MD->getSourceRange();
5076     HadError = true;
5077   } else if (MD->isVariadic()) {
5078     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5079       << CSM << MD->getSourceRange();
5080     HadError = true;
5081   }
5082 
5083   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5084 
5085   bool CanHaveConstParam = false;
5086   if (CSM == CXXCopyConstructor)
5087     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5088   else if (CSM == CXXCopyAssignment)
5089     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5090 
5091   QualType ReturnType = Context.VoidTy;
5092   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5093     // Check for return type matching.
5094     ReturnType = Type->getReturnType();
5095     QualType ExpectedReturnType =
5096         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5097     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5098       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5099         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5100       HadError = true;
5101     }
5102 
5103     // A defaulted special member cannot have cv-qualifiers.
5104     if (Type->getTypeQuals()) {
5105       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5106         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5107       HadError = true;
5108     }
5109   }
5110 
5111   // Check for parameter type matching.
5112   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5113   bool HasConstParam = false;
5114   if (ExpectedParams && ArgType->isReferenceType()) {
5115     // Argument must be reference to possibly-const T.
5116     QualType ReferentType = ArgType->getPointeeType();
5117     HasConstParam = ReferentType.isConstQualified();
5118 
5119     if (ReferentType.isVolatileQualified()) {
5120       Diag(MD->getLocation(),
5121            diag::err_defaulted_special_member_volatile_param) << CSM;
5122       HadError = true;
5123     }
5124 
5125     if (HasConstParam && !CanHaveConstParam) {
5126       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5127         Diag(MD->getLocation(),
5128              diag::err_defaulted_special_member_copy_const_param)
5129           << (CSM == CXXCopyAssignment);
5130         // FIXME: Explain why this special member can't be const.
5131       } else {
5132         Diag(MD->getLocation(),
5133              diag::err_defaulted_special_member_move_const_param)
5134           << (CSM == CXXMoveAssignment);
5135       }
5136       HadError = true;
5137     }
5138   } else if (ExpectedParams) {
5139     // A copy assignment operator can take its argument by value, but a
5140     // defaulted one cannot.
5141     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5142     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5143     HadError = true;
5144   }
5145 
5146   // C++11 [dcl.fct.def.default]p2:
5147   //   An explicitly-defaulted function may be declared constexpr only if it
5148   //   would have been implicitly declared as constexpr,
5149   // Do not apply this rule to members of class templates, since core issue 1358
5150   // makes such functions always instantiate to constexpr functions. For
5151   // functions which cannot be constexpr (for non-constructors in C++11 and for
5152   // destructors in C++1y), this is checked elsewhere.
5153   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5154                                                      HasConstParam);
5155   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5156                                  : isa<CXXConstructorDecl>(MD)) &&
5157       MD->isConstexpr() && !Constexpr &&
5158       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5159     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5160     // FIXME: Explain why the special member can't be constexpr.
5161     HadError = true;
5162   }
5163 
5164   //   and may have an explicit exception-specification only if it is compatible
5165   //   with the exception-specification on the implicit declaration.
5166   if (Type->hasExceptionSpec()) {
5167     // Delay the check if this is the first declaration of the special member,
5168     // since we may not have parsed some necessary in-class initializers yet.
5169     if (First) {
5170       // If the exception specification needs to be instantiated, do so now,
5171       // before we clobber it with an EST_Unevaluated specification below.
5172       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5173         InstantiateExceptionSpec(MD->getLocStart(), MD);
5174         Type = MD->getType()->getAs<FunctionProtoType>();
5175       }
5176       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5177     } else
5178       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5179   }
5180 
5181   //   If a function is explicitly defaulted on its first declaration,
5182   if (First) {
5183     //  -- it is implicitly considered to be constexpr if the implicit
5184     //     definition would be,
5185     MD->setConstexpr(Constexpr);
5186 
5187     //  -- it is implicitly considered to have the same exception-specification
5188     //     as if it had been implicitly declared,
5189     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5190     EPI.ExceptionSpec.Type = EST_Unevaluated;
5191     EPI.ExceptionSpec.SourceDecl = MD;
5192     MD->setType(Context.getFunctionType(ReturnType,
5193                                         llvm::makeArrayRef(&ArgType,
5194                                                            ExpectedParams),
5195                                         EPI));
5196   }
5197 
5198   if (ShouldDeleteSpecialMember(MD, CSM)) {
5199     if (First) {
5200       SetDeclDeleted(MD, MD->getLocation());
5201     } else {
5202       // C++11 [dcl.fct.def.default]p4:
5203       //   [For a] user-provided explicitly-defaulted function [...] if such a
5204       //   function is implicitly defined as deleted, the program is ill-formed.
5205       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5206       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5207       HadError = true;
5208     }
5209   }
5210 
5211   if (HadError)
5212     MD->setInvalidDecl();
5213 }
5214 
5215 /// Check whether the exception specification provided for an
5216 /// explicitly-defaulted special member matches the exception specification
5217 /// that would have been generated for an implicit special member, per
5218 /// C++11 [dcl.fct.def.default]p2.
5219 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5220     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5221   // Compute the implicit exception specification.
5222   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5223                                                        /*IsCXXMethod=*/true);
5224   FunctionProtoType::ExtProtoInfo EPI(CC);
5225   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5226                           .getExceptionSpec();
5227   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5228     Context.getFunctionType(Context.VoidTy, None, EPI));
5229 
5230   // Ensure that it matches.
5231   CheckEquivalentExceptionSpec(
5232     PDiag(diag::err_incorrect_defaulted_exception_spec)
5233       << getSpecialMember(MD), PDiag(),
5234     ImplicitType, SourceLocation(),
5235     SpecifiedType, MD->getLocation());
5236 }
5237 
5238 void Sema::CheckDelayedMemberExceptionSpecs() {
5239   SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5240               2> Checks;
5241   SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
5242 
5243   std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5244   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5245 
5246   // Perform any deferred checking of exception specifications for virtual
5247   // destructors.
5248   for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5249     const CXXDestructorDecl *Dtor = Checks[i].first;
5250     assert(!Dtor->getParent()->isDependentType() &&
5251            "Should not ever add destructors of templates into the list.");
5252     CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5253   }
5254 
5255   // Check that any explicitly-defaulted methods have exception specifications
5256   // compatible with their implicit exception specifications.
5257   for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5258     CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5259                                                 Specs[I].second);
5260 }
5261 
5262 namespace {
5263 struct SpecialMemberDeletionInfo {
5264   Sema &S;
5265   CXXMethodDecl *MD;
5266   Sema::CXXSpecialMember CSM;
5267   bool Diagnose;
5268 
5269   // Properties of the special member, computed for convenience.
5270   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5271   SourceLocation Loc;
5272 
5273   bool AllFieldsAreConst;
5274 
5275   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5276                             Sema::CXXSpecialMember CSM, bool Diagnose)
5277     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5278       IsConstructor(false), IsAssignment(false), IsMove(false),
5279       ConstArg(false), Loc(MD->getLocation()),
5280       AllFieldsAreConst(true) {
5281     switch (CSM) {
5282       case Sema::CXXDefaultConstructor:
5283       case Sema::CXXCopyConstructor:
5284         IsConstructor = true;
5285         break;
5286       case Sema::CXXMoveConstructor:
5287         IsConstructor = true;
5288         IsMove = true;
5289         break;
5290       case Sema::CXXCopyAssignment:
5291         IsAssignment = true;
5292         break;
5293       case Sema::CXXMoveAssignment:
5294         IsAssignment = true;
5295         IsMove = true;
5296         break;
5297       case Sema::CXXDestructor:
5298         break;
5299       case Sema::CXXInvalid:
5300         llvm_unreachable("invalid special member kind");
5301     }
5302 
5303     if (MD->getNumParams()) {
5304       if (const ReferenceType *RT =
5305               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5306         ConstArg = RT->getPointeeType().isConstQualified();
5307     }
5308   }
5309 
5310   bool inUnion() const { return MD->getParent()->isUnion(); }
5311 
5312   /// Look up the corresponding special member in the given class.
5313   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5314                                               unsigned Quals, bool IsMutable) {
5315     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5316                                        ConstArg && !IsMutable);
5317   }
5318 
5319   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5320 
5321   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5322   bool shouldDeleteForField(FieldDecl *FD);
5323   bool shouldDeleteForAllConstMembers();
5324 
5325   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5326                                      unsigned Quals);
5327   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5328                                     Sema::SpecialMemberOverloadResult *SMOR,
5329                                     bool IsDtorCallInCtor);
5330 
5331   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5332 };
5333 }
5334 
5335 /// Is the given special member inaccessible when used on the given
5336 /// sub-object.
5337 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5338                                              CXXMethodDecl *target) {
5339   /// If we're operating on a base class, the object type is the
5340   /// type of this special member.
5341   QualType objectTy;
5342   AccessSpecifier access = target->getAccess();
5343   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5344     objectTy = S.Context.getTypeDeclType(MD->getParent());
5345     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5346 
5347   // If we're operating on a field, the object type is the type of the field.
5348   } else {
5349     objectTy = S.Context.getTypeDeclType(target->getParent());
5350   }
5351 
5352   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5353 }
5354 
5355 /// Check whether we should delete a special member due to the implicit
5356 /// definition containing a call to a special member of a subobject.
5357 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5358     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5359     bool IsDtorCallInCtor) {
5360   CXXMethodDecl *Decl = SMOR->getMethod();
5361   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5362 
5363   int DiagKind = -1;
5364 
5365   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5366     DiagKind = !Decl ? 0 : 1;
5367   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5368     DiagKind = 2;
5369   else if (!isAccessible(Subobj, Decl))
5370     DiagKind = 3;
5371   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5372            !Decl->isTrivial()) {
5373     // A member of a union must have a trivial corresponding special member.
5374     // As a weird special case, a destructor call from a union's constructor
5375     // must be accessible and non-deleted, but need not be trivial. Such a
5376     // destructor is never actually called, but is semantically checked as
5377     // if it were.
5378     DiagKind = 4;
5379   }
5380 
5381   if (DiagKind == -1)
5382     return false;
5383 
5384   if (Diagnose) {
5385     if (Field) {
5386       S.Diag(Field->getLocation(),
5387              diag::note_deleted_special_member_class_subobject)
5388         << CSM << MD->getParent() << /*IsField*/true
5389         << Field << DiagKind << IsDtorCallInCtor;
5390     } else {
5391       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5392       S.Diag(Base->getLocStart(),
5393              diag::note_deleted_special_member_class_subobject)
5394         << CSM << MD->getParent() << /*IsField*/false
5395         << Base->getType() << DiagKind << IsDtorCallInCtor;
5396     }
5397 
5398     if (DiagKind == 1)
5399       S.NoteDeletedFunction(Decl);
5400     // FIXME: Explain inaccessibility if DiagKind == 3.
5401   }
5402 
5403   return true;
5404 }
5405 
5406 /// Check whether we should delete a special member function due to having a
5407 /// direct or virtual base class or non-static data member of class type M.
5408 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5409     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5410   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5411   bool IsMutable = Field && Field->isMutable();
5412 
5413   // C++11 [class.ctor]p5:
5414   // -- any direct or virtual base class, or non-static data member with no
5415   //    brace-or-equal-initializer, has class type M (or array thereof) and
5416   //    either M has no default constructor or overload resolution as applied
5417   //    to M's default constructor results in an ambiguity or in a function
5418   //    that is deleted or inaccessible
5419   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5420   // -- a direct or virtual base class B that cannot be copied/moved because
5421   //    overload resolution, as applied to B's corresponding special member,
5422   //    results in an ambiguity or a function that is deleted or inaccessible
5423   //    from the defaulted special member
5424   // C++11 [class.dtor]p5:
5425   // -- any direct or virtual base class [...] has a type with a destructor
5426   //    that is deleted or inaccessible
5427   if (!(CSM == Sema::CXXDefaultConstructor &&
5428         Field && Field->hasInClassInitializer()) &&
5429       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5430                                    false))
5431     return true;
5432 
5433   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5434   // -- any direct or virtual base class or non-static data member has a
5435   //    type with a destructor that is deleted or inaccessible
5436   if (IsConstructor) {
5437     Sema::SpecialMemberOverloadResult *SMOR =
5438         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5439                               false, false, false, false, false);
5440     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5441       return true;
5442   }
5443 
5444   return false;
5445 }
5446 
5447 /// Check whether we should delete a special member function due to the class
5448 /// having a particular direct or virtual base class.
5449 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5450   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5451   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5452 }
5453 
5454 /// Check whether we should delete a special member function due to the class
5455 /// having a particular non-static data member.
5456 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5457   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5458   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5459 
5460   if (CSM == Sema::CXXDefaultConstructor) {
5461     // For a default constructor, all references must be initialized in-class
5462     // and, if a union, it must have a non-const member.
5463     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5464       if (Diagnose)
5465         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5466           << MD->getParent() << FD << FieldType << /*Reference*/0;
5467       return true;
5468     }
5469     // C++11 [class.ctor]p5: any non-variant non-static data member of
5470     // const-qualified type (or array thereof) with no
5471     // brace-or-equal-initializer does not have a user-provided default
5472     // constructor.
5473     if (!inUnion() && FieldType.isConstQualified() &&
5474         !FD->hasInClassInitializer() &&
5475         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5476       if (Diagnose)
5477         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5478           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5479       return true;
5480     }
5481 
5482     if (inUnion() && !FieldType.isConstQualified())
5483       AllFieldsAreConst = false;
5484   } else if (CSM == Sema::CXXCopyConstructor) {
5485     // For a copy constructor, data members must not be of rvalue reference
5486     // type.
5487     if (FieldType->isRValueReferenceType()) {
5488       if (Diagnose)
5489         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5490           << MD->getParent() << FD << FieldType;
5491       return true;
5492     }
5493   } else if (IsAssignment) {
5494     // For an assignment operator, data members must not be of reference type.
5495     if (FieldType->isReferenceType()) {
5496       if (Diagnose)
5497         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5498           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5499       return true;
5500     }
5501     if (!FieldRecord && FieldType.isConstQualified()) {
5502       // C++11 [class.copy]p23:
5503       // -- a non-static data member of const non-class type (or array thereof)
5504       if (Diagnose)
5505         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5506           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5507       return true;
5508     }
5509   }
5510 
5511   if (FieldRecord) {
5512     // Some additional restrictions exist on the variant members.
5513     if (!inUnion() && FieldRecord->isUnion() &&
5514         FieldRecord->isAnonymousStructOrUnion()) {
5515       bool AllVariantFieldsAreConst = true;
5516 
5517       // FIXME: Handle anonymous unions declared within anonymous unions.
5518       for (auto *UI : FieldRecord->fields()) {
5519         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5520 
5521         if (!UnionFieldType.isConstQualified())
5522           AllVariantFieldsAreConst = false;
5523 
5524         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5525         if (UnionFieldRecord &&
5526             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5527                                           UnionFieldType.getCVRQualifiers()))
5528           return true;
5529       }
5530 
5531       // At least one member in each anonymous union must be non-const
5532       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5533           !FieldRecord->field_empty()) {
5534         if (Diagnose)
5535           S.Diag(FieldRecord->getLocation(),
5536                  diag::note_deleted_default_ctor_all_const)
5537             << MD->getParent() << /*anonymous union*/1;
5538         return true;
5539       }
5540 
5541       // Don't check the implicit member of the anonymous union type.
5542       // This is technically non-conformant, but sanity demands it.
5543       return false;
5544     }
5545 
5546     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5547                                       FieldType.getCVRQualifiers()))
5548       return true;
5549   }
5550 
5551   return false;
5552 }
5553 
5554 /// C++11 [class.ctor] p5:
5555 ///   A defaulted default constructor for a class X is defined as deleted if
5556 /// X is a union and all of its variant members are of const-qualified type.
5557 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5558   // This is a silly definition, because it gives an empty union a deleted
5559   // default constructor. Don't do that.
5560   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5561       !MD->getParent()->field_empty()) {
5562     if (Diagnose)
5563       S.Diag(MD->getParent()->getLocation(),
5564              diag::note_deleted_default_ctor_all_const)
5565         << MD->getParent() << /*not anonymous union*/0;
5566     return true;
5567   }
5568   return false;
5569 }
5570 
5571 /// Determine whether a defaulted special member function should be defined as
5572 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5573 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5574 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5575                                      bool Diagnose) {
5576   if (MD->isInvalidDecl())
5577     return false;
5578   CXXRecordDecl *RD = MD->getParent();
5579   assert(!RD->isDependentType() && "do deletion after instantiation");
5580   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5581     return false;
5582 
5583   // C++11 [expr.lambda.prim]p19:
5584   //   The closure type associated with a lambda-expression has a
5585   //   deleted (8.4.3) default constructor and a deleted copy
5586   //   assignment operator.
5587   if (RD->isLambda() &&
5588       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5589     if (Diagnose)
5590       Diag(RD->getLocation(), diag::note_lambda_decl);
5591     return true;
5592   }
5593 
5594   // For an anonymous struct or union, the copy and assignment special members
5595   // will never be used, so skip the check. For an anonymous union declared at
5596   // namespace scope, the constructor and destructor are used.
5597   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5598       RD->isAnonymousStructOrUnion())
5599     return false;
5600 
5601   // C++11 [class.copy]p7, p18:
5602   //   If the class definition declares a move constructor or move assignment
5603   //   operator, an implicitly declared copy constructor or copy assignment
5604   //   operator is defined as deleted.
5605   if (MD->isImplicit() &&
5606       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5607     CXXMethodDecl *UserDeclaredMove = nullptr;
5608 
5609     // In Microsoft mode, a user-declared move only causes the deletion of the
5610     // corresponding copy operation, not both copy operations.
5611     if (RD->hasUserDeclaredMoveConstructor() &&
5612         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5613       if (!Diagnose) return true;
5614 
5615       // Find any user-declared move constructor.
5616       for (auto *I : RD->ctors()) {
5617         if (I->isMoveConstructor()) {
5618           UserDeclaredMove = I;
5619           break;
5620         }
5621       }
5622       assert(UserDeclaredMove);
5623     } else if (RD->hasUserDeclaredMoveAssignment() &&
5624                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5625       if (!Diagnose) return true;
5626 
5627       // Find any user-declared move assignment operator.
5628       for (auto *I : RD->methods()) {
5629         if (I->isMoveAssignmentOperator()) {
5630           UserDeclaredMove = I;
5631           break;
5632         }
5633       }
5634       assert(UserDeclaredMove);
5635     }
5636 
5637     if (UserDeclaredMove) {
5638       Diag(UserDeclaredMove->getLocation(),
5639            diag::note_deleted_copy_user_declared_move)
5640         << (CSM == CXXCopyAssignment) << RD
5641         << UserDeclaredMove->isMoveAssignmentOperator();
5642       return true;
5643     }
5644   }
5645 
5646   // Do access control from the special member function
5647   ContextRAII MethodContext(*this, MD);
5648 
5649   // C++11 [class.dtor]p5:
5650   // -- for a virtual destructor, lookup of the non-array deallocation function
5651   //    results in an ambiguity or in a function that is deleted or inaccessible
5652   if (CSM == CXXDestructor && MD->isVirtual()) {
5653     FunctionDecl *OperatorDelete = nullptr;
5654     DeclarationName Name =
5655       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5656     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5657                                  OperatorDelete, false)) {
5658       if (Diagnose)
5659         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5660       return true;
5661     }
5662   }
5663 
5664   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5665 
5666   for (auto &BI : RD->bases())
5667     if (!BI.isVirtual() &&
5668         SMI.shouldDeleteForBase(&BI))
5669       return true;
5670 
5671   // Per DR1611, do not consider virtual bases of constructors of abstract
5672   // classes, since we are not going to construct them.
5673   if (!RD->isAbstract() || !SMI.IsConstructor) {
5674     for (auto &BI : RD->vbases())
5675       if (SMI.shouldDeleteForBase(&BI))
5676         return true;
5677   }
5678 
5679   for (auto *FI : RD->fields())
5680     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5681         SMI.shouldDeleteForField(FI))
5682       return true;
5683 
5684   if (SMI.shouldDeleteForAllConstMembers())
5685     return true;
5686 
5687   if (getLangOpts().CUDA) {
5688     // We should delete the special member in CUDA mode if target inference
5689     // failed.
5690     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5691                                                    Diagnose);
5692   }
5693 
5694   return false;
5695 }
5696 
5697 /// Perform lookup for a special member of the specified kind, and determine
5698 /// whether it is trivial. If the triviality can be determined without the
5699 /// lookup, skip it. This is intended for use when determining whether a
5700 /// special member of a containing object is trivial, and thus does not ever
5701 /// perform overload resolution for default constructors.
5702 ///
5703 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5704 /// member that was most likely to be intended to be trivial, if any.
5705 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5706                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5707                                      bool ConstRHS, CXXMethodDecl **Selected) {
5708   if (Selected)
5709     *Selected = nullptr;
5710 
5711   switch (CSM) {
5712   case Sema::CXXInvalid:
5713     llvm_unreachable("not a special member");
5714 
5715   case Sema::CXXDefaultConstructor:
5716     // C++11 [class.ctor]p5:
5717     //   A default constructor is trivial if:
5718     //    - all the [direct subobjects] have trivial default constructors
5719     //
5720     // Note, no overload resolution is performed in this case.
5721     if (RD->hasTrivialDefaultConstructor())
5722       return true;
5723 
5724     if (Selected) {
5725       // If there's a default constructor which could have been trivial, dig it
5726       // out. Otherwise, if there's any user-provided default constructor, point
5727       // to that as an example of why there's not a trivial one.
5728       CXXConstructorDecl *DefCtor = nullptr;
5729       if (RD->needsImplicitDefaultConstructor())
5730         S.DeclareImplicitDefaultConstructor(RD);
5731       for (auto *CI : RD->ctors()) {
5732         if (!CI->isDefaultConstructor())
5733           continue;
5734         DefCtor = CI;
5735         if (!DefCtor->isUserProvided())
5736           break;
5737       }
5738 
5739       *Selected = DefCtor;
5740     }
5741 
5742     return false;
5743 
5744   case Sema::CXXDestructor:
5745     // C++11 [class.dtor]p5:
5746     //   A destructor is trivial if:
5747     //    - all the direct [subobjects] have trivial destructors
5748     if (RD->hasTrivialDestructor())
5749       return true;
5750 
5751     if (Selected) {
5752       if (RD->needsImplicitDestructor())
5753         S.DeclareImplicitDestructor(RD);
5754       *Selected = RD->getDestructor();
5755     }
5756 
5757     return false;
5758 
5759   case Sema::CXXCopyConstructor:
5760     // C++11 [class.copy]p12:
5761     //   A copy constructor is trivial if:
5762     //    - the constructor selected to copy each direct [subobject] is trivial
5763     if (RD->hasTrivialCopyConstructor()) {
5764       if (Quals == Qualifiers::Const)
5765         // We must either select the trivial copy constructor or reach an
5766         // ambiguity; no need to actually perform overload resolution.
5767         return true;
5768     } else if (!Selected) {
5769       return false;
5770     }
5771     // In C++98, we are not supposed to perform overload resolution here, but we
5772     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5773     // cases like B as having a non-trivial copy constructor:
5774     //   struct A { template<typename T> A(T&); };
5775     //   struct B { mutable A a; };
5776     goto NeedOverloadResolution;
5777 
5778   case Sema::CXXCopyAssignment:
5779     // C++11 [class.copy]p25:
5780     //   A copy assignment operator is trivial if:
5781     //    - the assignment operator selected to copy each direct [subobject] is
5782     //      trivial
5783     if (RD->hasTrivialCopyAssignment()) {
5784       if (Quals == Qualifiers::Const)
5785         return true;
5786     } else if (!Selected) {
5787       return false;
5788     }
5789     // In C++98, we are not supposed to perform overload resolution here, but we
5790     // treat that as a language defect.
5791     goto NeedOverloadResolution;
5792 
5793   case Sema::CXXMoveConstructor:
5794   case Sema::CXXMoveAssignment:
5795   NeedOverloadResolution:
5796     Sema::SpecialMemberOverloadResult *SMOR =
5797         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5798 
5799     // The standard doesn't describe how to behave if the lookup is ambiguous.
5800     // We treat it as not making the member non-trivial, just like the standard
5801     // mandates for the default constructor. This should rarely matter, because
5802     // the member will also be deleted.
5803     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5804       return true;
5805 
5806     if (!SMOR->getMethod()) {
5807       assert(SMOR->getKind() ==
5808              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5809       return false;
5810     }
5811 
5812     // We deliberately don't check if we found a deleted special member. We're
5813     // not supposed to!
5814     if (Selected)
5815       *Selected = SMOR->getMethod();
5816     return SMOR->getMethod()->isTrivial();
5817   }
5818 
5819   llvm_unreachable("unknown special method kind");
5820 }
5821 
5822 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5823   for (auto *CI : RD->ctors())
5824     if (!CI->isImplicit())
5825       return CI;
5826 
5827   // Look for constructor templates.
5828   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5829   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5830     if (CXXConstructorDecl *CD =
5831           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5832       return CD;
5833   }
5834 
5835   return nullptr;
5836 }
5837 
5838 /// The kind of subobject we are checking for triviality. The values of this
5839 /// enumeration are used in diagnostics.
5840 enum TrivialSubobjectKind {
5841   /// The subobject is a base class.
5842   TSK_BaseClass,
5843   /// The subobject is a non-static data member.
5844   TSK_Field,
5845   /// The object is actually the complete object.
5846   TSK_CompleteObject
5847 };
5848 
5849 /// Check whether the special member selected for a given type would be trivial.
5850 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5851                                       QualType SubType, bool ConstRHS,
5852                                       Sema::CXXSpecialMember CSM,
5853                                       TrivialSubobjectKind Kind,
5854                                       bool Diagnose) {
5855   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5856   if (!SubRD)
5857     return true;
5858 
5859   CXXMethodDecl *Selected;
5860   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5861                                ConstRHS, Diagnose ? &Selected : nullptr))
5862     return true;
5863 
5864   if (Diagnose) {
5865     if (ConstRHS)
5866       SubType.addConst();
5867 
5868     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5869       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5870         << Kind << SubType.getUnqualifiedType();
5871       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5872         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5873     } else if (!Selected)
5874       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5875         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5876     else if (Selected->isUserProvided()) {
5877       if (Kind == TSK_CompleteObject)
5878         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5879           << Kind << SubType.getUnqualifiedType() << CSM;
5880       else {
5881         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5882           << Kind << SubType.getUnqualifiedType() << CSM;
5883         S.Diag(Selected->getLocation(), diag::note_declared_at);
5884       }
5885     } else {
5886       if (Kind != TSK_CompleteObject)
5887         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5888           << Kind << SubType.getUnqualifiedType() << CSM;
5889 
5890       // Explain why the defaulted or deleted special member isn't trivial.
5891       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5892     }
5893   }
5894 
5895   return false;
5896 }
5897 
5898 /// Check whether the members of a class type allow a special member to be
5899 /// trivial.
5900 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5901                                      Sema::CXXSpecialMember CSM,
5902                                      bool ConstArg, bool Diagnose) {
5903   for (const auto *FI : RD->fields()) {
5904     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5905       continue;
5906 
5907     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5908 
5909     // Pretend anonymous struct or union members are members of this class.
5910     if (FI->isAnonymousStructOrUnion()) {
5911       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5912                                     CSM, ConstArg, Diagnose))
5913         return false;
5914       continue;
5915     }
5916 
5917     // C++11 [class.ctor]p5:
5918     //   A default constructor is trivial if [...]
5919     //    -- no non-static data member of its class has a
5920     //       brace-or-equal-initializer
5921     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5922       if (Diagnose)
5923         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
5924       return false;
5925     }
5926 
5927     // Objective C ARC 4.3.5:
5928     //   [...] nontrivally ownership-qualified types are [...] not trivially
5929     //   default constructible, copy constructible, move constructible, copy
5930     //   assignable, move assignable, or destructible [...]
5931     if (S.getLangOpts().ObjCAutoRefCount &&
5932         FieldType.hasNonTrivialObjCLifetime()) {
5933       if (Diagnose)
5934         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5935           << RD << FieldType.getObjCLifetime();
5936       return false;
5937     }
5938 
5939     bool ConstRHS = ConstArg && !FI->isMutable();
5940     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5941                                    CSM, TSK_Field, Diagnose))
5942       return false;
5943   }
5944 
5945   return true;
5946 }
5947 
5948 /// Diagnose why the specified class does not have a trivial special member of
5949 /// the given kind.
5950 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5951   QualType Ty = Context.getRecordType(RD);
5952 
5953   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5954   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
5955                             TSK_CompleteObject, /*Diagnose*/true);
5956 }
5957 
5958 /// Determine whether a defaulted or deleted special member function is trivial,
5959 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5960 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5961 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5962                                   bool Diagnose) {
5963   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5964 
5965   CXXRecordDecl *RD = MD->getParent();
5966 
5967   bool ConstArg = false;
5968 
5969   // C++11 [class.copy]p12, p25: [DR1593]
5970   //   A [special member] is trivial if [...] its parameter-type-list is
5971   //   equivalent to the parameter-type-list of an implicit declaration [...]
5972   switch (CSM) {
5973   case CXXDefaultConstructor:
5974   case CXXDestructor:
5975     // Trivial default constructors and destructors cannot have parameters.
5976     break;
5977 
5978   case CXXCopyConstructor:
5979   case CXXCopyAssignment: {
5980     // Trivial copy operations always have const, non-volatile parameter types.
5981     ConstArg = true;
5982     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5983     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5984     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5985       if (Diagnose)
5986         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5987           << Param0->getSourceRange() << Param0->getType()
5988           << Context.getLValueReferenceType(
5989                Context.getRecordType(RD).withConst());
5990       return false;
5991     }
5992     break;
5993   }
5994 
5995   case CXXMoveConstructor:
5996   case CXXMoveAssignment: {
5997     // Trivial move operations always have non-cv-qualified parameters.
5998     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5999     const RValueReferenceType *RT =
6000       Param0->getType()->getAs<RValueReferenceType>();
6001     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6002       if (Diagnose)
6003         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6004           << Param0->getSourceRange() << Param0->getType()
6005           << Context.getRValueReferenceType(Context.getRecordType(RD));
6006       return false;
6007     }
6008     break;
6009   }
6010 
6011   case CXXInvalid:
6012     llvm_unreachable("not a special member");
6013   }
6014 
6015   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6016     if (Diagnose)
6017       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6018            diag::note_nontrivial_default_arg)
6019         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6020     return false;
6021   }
6022   if (MD->isVariadic()) {
6023     if (Diagnose)
6024       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6025     return false;
6026   }
6027 
6028   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6029   //   A copy/move [constructor or assignment operator] is trivial if
6030   //    -- the [member] selected to copy/move each direct base class subobject
6031   //       is trivial
6032   //
6033   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6034   //   A [default constructor or destructor] is trivial if
6035   //    -- all the direct base classes have trivial [default constructors or
6036   //       destructors]
6037   for (const auto &BI : RD->bases())
6038     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6039                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
6040       return false;
6041 
6042   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6043   //   A copy/move [constructor or assignment operator] for a class X is
6044   //   trivial if
6045   //    -- for each non-static data member of X that is of class type (or array
6046   //       thereof), the constructor selected to copy/move that member is
6047   //       trivial
6048   //
6049   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6050   //   A [default constructor or destructor] is trivial if
6051   //    -- for all of the non-static data members of its class that are of class
6052   //       type (or array thereof), each such class has a trivial [default
6053   //       constructor or destructor]
6054   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6055     return false;
6056 
6057   // C++11 [class.dtor]p5:
6058   //   A destructor is trivial if [...]
6059   //    -- the destructor is not virtual
6060   if (CSM == CXXDestructor && MD->isVirtual()) {
6061     if (Diagnose)
6062       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6063     return false;
6064   }
6065 
6066   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6067   //   A [special member] for class X is trivial if [...]
6068   //    -- class X has no virtual functions and no virtual base classes
6069   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6070     if (!Diagnose)
6071       return false;
6072 
6073     if (RD->getNumVBases()) {
6074       // Check for virtual bases. We already know that the corresponding
6075       // member in all bases is trivial, so vbases must all be direct.
6076       CXXBaseSpecifier &BS = *RD->vbases_begin();
6077       assert(BS.isVirtual());
6078       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6079       return false;
6080     }
6081 
6082     // Must have a virtual method.
6083     for (const auto *MI : RD->methods()) {
6084       if (MI->isVirtual()) {
6085         SourceLocation MLoc = MI->getLocStart();
6086         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6087         return false;
6088       }
6089     }
6090 
6091     llvm_unreachable("dynamic class with no vbases and no virtual functions");
6092   }
6093 
6094   // Looks like it's trivial!
6095   return true;
6096 }
6097 
6098 /// \brief Data used with FindHiddenVirtualMethod
6099 namespace {
6100   struct FindHiddenVirtualMethodData {
6101     Sema *S;
6102     CXXMethodDecl *Method;
6103     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6104     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6105   };
6106 }
6107 
6108 /// \brief Check whether any most overriden method from MD in Methods
6109 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
6110                   const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6111   if (MD->size_overridden_methods() == 0)
6112     return Methods.count(MD->getCanonicalDecl());
6113   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6114                                       E = MD->end_overridden_methods();
6115        I != E; ++I)
6116     if (CheckMostOverridenMethods(*I, Methods))
6117       return true;
6118   return false;
6119 }
6120 
6121 /// \brief Member lookup function that determines whether a given C++
6122 /// method overloads virtual methods in a base class without overriding any,
6123 /// to be used with CXXRecordDecl::lookupInBases().
6124 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6125                                     CXXBasePath &Path,
6126                                     void *UserData) {
6127   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6128 
6129   FindHiddenVirtualMethodData &Data
6130     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6131 
6132   DeclarationName Name = Data.Method->getDeclName();
6133   assert(Name.getNameKind() == DeclarationName::Identifier);
6134 
6135   bool foundSameNameMethod = false;
6136   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6137   for (Path.Decls = BaseRecord->lookup(Name);
6138        !Path.Decls.empty();
6139        Path.Decls = Path.Decls.slice(1)) {
6140     NamedDecl *D = Path.Decls.front();
6141     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6142       MD = MD->getCanonicalDecl();
6143       foundSameNameMethod = true;
6144       // Interested only in hidden virtual methods.
6145       if (!MD->isVirtual())
6146         continue;
6147       // If the method we are checking overrides a method from its base
6148       // don't warn about the other overloaded methods. Clang deviates from GCC
6149       // by only diagnosing overloads of inherited virtual functions that do not
6150       // override any other virtual functions in the base. GCC's
6151       // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6152       // function from a base class. These cases may be better served by a
6153       // warning (not specific to virtual functions) on call sites when the call
6154       // would select a different function from the base class, were it visible.
6155       // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6156       if (!Data.S->IsOverload(Data.Method, MD, false))
6157         return true;
6158       // Collect the overload only if its hidden.
6159       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
6160         overloadedMethods.push_back(MD);
6161     }
6162   }
6163 
6164   if (foundSameNameMethod)
6165     Data.OverloadedMethods.append(overloadedMethods.begin(),
6166                                    overloadedMethods.end());
6167   return foundSameNameMethod;
6168 }
6169 
6170 /// \brief Add the most overriden methods from MD to Methods
6171 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6172                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6173   if (MD->size_overridden_methods() == 0)
6174     Methods.insert(MD->getCanonicalDecl());
6175   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6176                                       E = MD->end_overridden_methods();
6177        I != E; ++I)
6178     AddMostOverridenMethods(*I, Methods);
6179 }
6180 
6181 /// \brief Check if a method overloads virtual methods in a base class without
6182 /// overriding any.
6183 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6184                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6185   if (!MD->getDeclName().isIdentifier())
6186     return;
6187 
6188   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6189                      /*bool RecordPaths=*/false,
6190                      /*bool DetectVirtual=*/false);
6191   FindHiddenVirtualMethodData Data;
6192   Data.Method = MD;
6193   Data.S = this;
6194 
6195   // Keep the base methods that were overriden or introduced in the subclass
6196   // by 'using' in a set. A base method not in this set is hidden.
6197   CXXRecordDecl *DC = MD->getParent();
6198   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6199   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6200     NamedDecl *ND = *I;
6201     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6202       ND = shad->getTargetDecl();
6203     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6204       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
6205   }
6206 
6207   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6208     OverloadedMethods = Data.OverloadedMethods;
6209 }
6210 
6211 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6212                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6213   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6214     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6215     PartialDiagnostic PD = PDiag(
6216          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6217     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6218     Diag(overloadedMD->getLocation(), PD);
6219   }
6220 }
6221 
6222 /// \brief Diagnose methods which overload virtual methods in a base class
6223 /// without overriding any.
6224 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6225   if (MD->isInvalidDecl())
6226     return;
6227 
6228   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6229     return;
6230 
6231   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6232   FindHiddenVirtualMethods(MD, OverloadedMethods);
6233   if (!OverloadedMethods.empty()) {
6234     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6235       << MD << (OverloadedMethods.size() > 1);
6236 
6237     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6238   }
6239 }
6240 
6241 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6242                                              Decl *TagDecl,
6243                                              SourceLocation LBrac,
6244                                              SourceLocation RBrac,
6245                                              AttributeList *AttrList) {
6246   if (!TagDecl)
6247     return;
6248 
6249   AdjustDeclIfTemplate(TagDecl);
6250 
6251   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6252     if (l->getKind() != AttributeList::AT_Visibility)
6253       continue;
6254     l->setInvalid();
6255     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6256       l->getName();
6257   }
6258 
6259   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6260               // strict aliasing violation!
6261               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6262               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6263 
6264   CheckCompletedCXXClass(
6265                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6266 }
6267 
6268 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6269 /// special functions, such as the default constructor, copy
6270 /// constructor, or destructor, to the given C++ class (C++
6271 /// [special]p1).  This routine can only be executed just before the
6272 /// definition of the class is complete.
6273 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6274   if (!ClassDecl->hasUserDeclaredConstructor())
6275     ++ASTContext::NumImplicitDefaultConstructors;
6276 
6277   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6278     ++ASTContext::NumImplicitCopyConstructors;
6279 
6280     // If the properties or semantics of the copy constructor couldn't be
6281     // determined while the class was being declared, force a declaration
6282     // of it now.
6283     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6284       DeclareImplicitCopyConstructor(ClassDecl);
6285   }
6286 
6287   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6288     ++ASTContext::NumImplicitMoveConstructors;
6289 
6290     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6291       DeclareImplicitMoveConstructor(ClassDecl);
6292   }
6293 
6294   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6295     ++ASTContext::NumImplicitCopyAssignmentOperators;
6296 
6297     // If we have a dynamic class, then the copy assignment operator may be
6298     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6299     // it shows up in the right place in the vtable and that we diagnose
6300     // problems with the implicit exception specification.
6301     if (ClassDecl->isDynamicClass() ||
6302         ClassDecl->needsOverloadResolutionForCopyAssignment())
6303       DeclareImplicitCopyAssignment(ClassDecl);
6304   }
6305 
6306   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6307     ++ASTContext::NumImplicitMoveAssignmentOperators;
6308 
6309     // Likewise for the move assignment operator.
6310     if (ClassDecl->isDynamicClass() ||
6311         ClassDecl->needsOverloadResolutionForMoveAssignment())
6312       DeclareImplicitMoveAssignment(ClassDecl);
6313   }
6314 
6315   if (!ClassDecl->hasUserDeclaredDestructor()) {
6316     ++ASTContext::NumImplicitDestructors;
6317 
6318     // If we have a dynamic class, then the destructor may be virtual, so we
6319     // have to declare the destructor immediately. This ensures that, e.g., it
6320     // shows up in the right place in the vtable and that we diagnose problems
6321     // with the implicit exception specification.
6322     if (ClassDecl->isDynamicClass() ||
6323         ClassDecl->needsOverloadResolutionForDestructor())
6324       DeclareImplicitDestructor(ClassDecl);
6325   }
6326 }
6327 
6328 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6329   if (!D)
6330     return 0;
6331 
6332   // The order of template parameters is not important here. All names
6333   // get added to the same scope.
6334   SmallVector<TemplateParameterList *, 4> ParameterLists;
6335 
6336   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6337     D = TD->getTemplatedDecl();
6338 
6339   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6340     ParameterLists.push_back(PSD->getTemplateParameters());
6341 
6342   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6343     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6344       ParameterLists.push_back(DD->getTemplateParameterList(i));
6345 
6346     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6347       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6348         ParameterLists.push_back(FTD->getTemplateParameters());
6349     }
6350   }
6351 
6352   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6353     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6354       ParameterLists.push_back(TD->getTemplateParameterList(i));
6355 
6356     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6357       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6358         ParameterLists.push_back(CTD->getTemplateParameters());
6359     }
6360   }
6361 
6362   unsigned Count = 0;
6363   for (TemplateParameterList *Params : ParameterLists) {
6364     if (Params->size() > 0)
6365       // Ignore explicit specializations; they don't contribute to the template
6366       // depth.
6367       ++Count;
6368     for (NamedDecl *Param : *Params) {
6369       if (Param->getDeclName()) {
6370         S->AddDecl(Param);
6371         IdResolver.AddDecl(Param);
6372       }
6373     }
6374   }
6375 
6376   return Count;
6377 }
6378 
6379 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6380   if (!RecordD) return;
6381   AdjustDeclIfTemplate(RecordD);
6382   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6383   PushDeclContext(S, Record);
6384 }
6385 
6386 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6387   if (!RecordD) return;
6388   PopDeclContext();
6389 }
6390 
6391 /// This is used to implement the constant expression evaluation part of the
6392 /// attribute enable_if extension. There is nothing in standard C++ which would
6393 /// require reentering parameters.
6394 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6395   if (!Param)
6396     return;
6397 
6398   S->AddDecl(Param);
6399   if (Param->getDeclName())
6400     IdResolver.AddDecl(Param);
6401 }
6402 
6403 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6404 /// parsing a top-level (non-nested) C++ class, and we are now
6405 /// parsing those parts of the given Method declaration that could
6406 /// not be parsed earlier (C++ [class.mem]p2), such as default
6407 /// arguments. This action should enter the scope of the given
6408 /// Method declaration as if we had just parsed the qualified method
6409 /// name. However, it should not bring the parameters into scope;
6410 /// that will be performed by ActOnDelayedCXXMethodParameter.
6411 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6412 }
6413 
6414 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6415 /// C++ method declaration. We're (re-)introducing the given
6416 /// function parameter into scope for use in parsing later parts of
6417 /// the method declaration. For example, we could see an
6418 /// ActOnParamDefaultArgument event for this parameter.
6419 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6420   if (!ParamD)
6421     return;
6422 
6423   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6424 
6425   // If this parameter has an unparsed default argument, clear it out
6426   // to make way for the parsed default argument.
6427   if (Param->hasUnparsedDefaultArg())
6428     Param->setDefaultArg(nullptr);
6429 
6430   S->AddDecl(Param);
6431   if (Param->getDeclName())
6432     IdResolver.AddDecl(Param);
6433 }
6434 
6435 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6436 /// processing the delayed method declaration for Method. The method
6437 /// declaration is now considered finished. There may be a separate
6438 /// ActOnStartOfFunctionDef action later (not necessarily
6439 /// immediately!) for this method, if it was also defined inside the
6440 /// class body.
6441 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6442   if (!MethodD)
6443     return;
6444 
6445   AdjustDeclIfTemplate(MethodD);
6446 
6447   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6448 
6449   // Now that we have our default arguments, check the constructor
6450   // again. It could produce additional diagnostics or affect whether
6451   // the class has implicitly-declared destructors, among other
6452   // things.
6453   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6454     CheckConstructor(Constructor);
6455 
6456   // Check the default arguments, which we may have added.
6457   if (!Method->isInvalidDecl())
6458     CheckCXXDefaultArguments(Method);
6459 }
6460 
6461 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6462 /// the well-formedness of the constructor declarator @p D with type @p
6463 /// R. If there are any errors in the declarator, this routine will
6464 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6465 /// will be updated to reflect a well-formed type for the constructor and
6466 /// returned.
6467 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6468                                           StorageClass &SC) {
6469   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6470 
6471   // C++ [class.ctor]p3:
6472   //   A constructor shall not be virtual (10.3) or static (9.4). A
6473   //   constructor can be invoked for a const, volatile or const
6474   //   volatile object. A constructor shall not be declared const,
6475   //   volatile, or const volatile (9.3.2).
6476   if (isVirtual) {
6477     if (!D.isInvalidType())
6478       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6479         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6480         << SourceRange(D.getIdentifierLoc());
6481     D.setInvalidType();
6482   }
6483   if (SC == SC_Static) {
6484     if (!D.isInvalidType())
6485       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6486         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6487         << SourceRange(D.getIdentifierLoc());
6488     D.setInvalidType();
6489     SC = SC_None;
6490   }
6491 
6492   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6493     diagnoseIgnoredQualifiers(
6494         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6495         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6496         D.getDeclSpec().getRestrictSpecLoc(),
6497         D.getDeclSpec().getAtomicSpecLoc());
6498     D.setInvalidType();
6499   }
6500 
6501   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6502   if (FTI.TypeQuals != 0) {
6503     if (FTI.TypeQuals & Qualifiers::Const)
6504       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6505         << "const" << SourceRange(D.getIdentifierLoc());
6506     if (FTI.TypeQuals & Qualifiers::Volatile)
6507       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6508         << "volatile" << SourceRange(D.getIdentifierLoc());
6509     if (FTI.TypeQuals & Qualifiers::Restrict)
6510       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6511         << "restrict" << SourceRange(D.getIdentifierLoc());
6512     D.setInvalidType();
6513   }
6514 
6515   // C++0x [class.ctor]p4:
6516   //   A constructor shall not be declared with a ref-qualifier.
6517   if (FTI.hasRefQualifier()) {
6518     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6519       << FTI.RefQualifierIsLValueRef
6520       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6521     D.setInvalidType();
6522   }
6523 
6524   // Rebuild the function type "R" without any type qualifiers (in
6525   // case any of the errors above fired) and with "void" as the
6526   // return type, since constructors don't have return types.
6527   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6528   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6529     return R;
6530 
6531   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6532   EPI.TypeQuals = 0;
6533   EPI.RefQualifier = RQ_None;
6534 
6535   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6536 }
6537 
6538 /// CheckConstructor - Checks a fully-formed constructor for
6539 /// well-formedness, issuing any diagnostics required. Returns true if
6540 /// the constructor declarator is invalid.
6541 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6542   CXXRecordDecl *ClassDecl
6543     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6544   if (!ClassDecl)
6545     return Constructor->setInvalidDecl();
6546 
6547   // C++ [class.copy]p3:
6548   //   A declaration of a constructor for a class X is ill-formed if
6549   //   its first parameter is of type (optionally cv-qualified) X and
6550   //   either there are no other parameters or else all other
6551   //   parameters have default arguments.
6552   if (!Constructor->isInvalidDecl() &&
6553       ((Constructor->getNumParams() == 1) ||
6554        (Constructor->getNumParams() > 1 &&
6555         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6556       Constructor->getTemplateSpecializationKind()
6557                                               != TSK_ImplicitInstantiation) {
6558     QualType ParamType = Constructor->getParamDecl(0)->getType();
6559     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6560     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6561       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6562       const char *ConstRef
6563         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6564                                                         : " const &";
6565       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6566         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6567 
6568       // FIXME: Rather that making the constructor invalid, we should endeavor
6569       // to fix the type.
6570       Constructor->setInvalidDecl();
6571     }
6572   }
6573 }
6574 
6575 /// CheckDestructor - Checks a fully-formed destructor definition for
6576 /// well-formedness, issuing any diagnostics required.  Returns true
6577 /// on error.
6578 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6579   CXXRecordDecl *RD = Destructor->getParent();
6580 
6581   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6582     SourceLocation Loc;
6583 
6584     if (!Destructor->isImplicit())
6585       Loc = Destructor->getLocation();
6586     else
6587       Loc = RD->getLocation();
6588 
6589     // If we have a virtual destructor, look up the deallocation function
6590     FunctionDecl *OperatorDelete = nullptr;
6591     DeclarationName Name =
6592     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6593     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6594       return true;
6595     // If there's no class-specific operator delete, look up the global
6596     // non-array delete.
6597     if (!OperatorDelete)
6598       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6599 
6600     MarkFunctionReferenced(Loc, OperatorDelete);
6601 
6602     Destructor->setOperatorDelete(OperatorDelete);
6603   }
6604 
6605   return false;
6606 }
6607 
6608 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6609 /// the well-formednes of the destructor declarator @p D with type @p
6610 /// R. If there are any errors in the declarator, this routine will
6611 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6612 /// will be updated to reflect a well-formed type for the destructor and
6613 /// returned.
6614 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6615                                          StorageClass& SC) {
6616   // C++ [class.dtor]p1:
6617   //   [...] A typedef-name that names a class is a class-name
6618   //   (7.1.3); however, a typedef-name that names a class shall not
6619   //   be used as the identifier in the declarator for a destructor
6620   //   declaration.
6621   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6622   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6623     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6624       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6625   else if (const TemplateSpecializationType *TST =
6626              DeclaratorType->getAs<TemplateSpecializationType>())
6627     if (TST->isTypeAlias())
6628       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6629         << DeclaratorType << 1;
6630 
6631   // C++ [class.dtor]p2:
6632   //   A destructor is used to destroy objects of its class type. A
6633   //   destructor takes no parameters, and no return type can be
6634   //   specified for it (not even void). The address of a destructor
6635   //   shall not be taken. A destructor shall not be static. A
6636   //   destructor can be invoked for a const, volatile or const
6637   //   volatile object. A destructor shall not be declared const,
6638   //   volatile or const volatile (9.3.2).
6639   if (SC == SC_Static) {
6640     if (!D.isInvalidType())
6641       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6642         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6643         << SourceRange(D.getIdentifierLoc())
6644         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6645 
6646     SC = SC_None;
6647   }
6648   if (!D.isInvalidType()) {
6649     // Destructors don't have return types, but the parser will
6650     // happily parse something like:
6651     //
6652     //   class X {
6653     //     float ~X();
6654     //   };
6655     //
6656     // The return type will be eliminated later.
6657     if (D.getDeclSpec().hasTypeSpecifier())
6658       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6659         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6660         << SourceRange(D.getIdentifierLoc());
6661     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6662       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6663                                 SourceLocation(),
6664                                 D.getDeclSpec().getConstSpecLoc(),
6665                                 D.getDeclSpec().getVolatileSpecLoc(),
6666                                 D.getDeclSpec().getRestrictSpecLoc(),
6667                                 D.getDeclSpec().getAtomicSpecLoc());
6668       D.setInvalidType();
6669     }
6670   }
6671 
6672   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6673   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6674     if (FTI.TypeQuals & Qualifiers::Const)
6675       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6676         << "const" << SourceRange(D.getIdentifierLoc());
6677     if (FTI.TypeQuals & Qualifiers::Volatile)
6678       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6679         << "volatile" << SourceRange(D.getIdentifierLoc());
6680     if (FTI.TypeQuals & Qualifiers::Restrict)
6681       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6682         << "restrict" << SourceRange(D.getIdentifierLoc());
6683     D.setInvalidType();
6684   }
6685 
6686   // C++0x [class.dtor]p2:
6687   //   A destructor shall not be declared with a ref-qualifier.
6688   if (FTI.hasRefQualifier()) {
6689     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6690       << FTI.RefQualifierIsLValueRef
6691       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6692     D.setInvalidType();
6693   }
6694 
6695   // Make sure we don't have any parameters.
6696   if (FTIHasNonVoidParameters(FTI)) {
6697     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6698 
6699     // Delete the parameters.
6700     FTI.freeParams();
6701     D.setInvalidType();
6702   }
6703 
6704   // Make sure the destructor isn't variadic.
6705   if (FTI.isVariadic) {
6706     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6707     D.setInvalidType();
6708   }
6709 
6710   // Rebuild the function type "R" without any type qualifiers or
6711   // parameters (in case any of the errors above fired) and with
6712   // "void" as the return type, since destructors don't have return
6713   // types.
6714   if (!D.isInvalidType())
6715     return R;
6716 
6717   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6718   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6719   EPI.Variadic = false;
6720   EPI.TypeQuals = 0;
6721   EPI.RefQualifier = RQ_None;
6722   return Context.getFunctionType(Context.VoidTy, None, EPI);
6723 }
6724 
6725 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6726 /// well-formednes of the conversion function declarator @p D with
6727 /// type @p R. If there are any errors in the declarator, this routine
6728 /// will emit diagnostics and return true. Otherwise, it will return
6729 /// false. Either way, the type @p R will be updated to reflect a
6730 /// well-formed type for the conversion operator.
6731 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6732                                      StorageClass& SC) {
6733   // C++ [class.conv.fct]p1:
6734   //   Neither parameter types nor return type can be specified. The
6735   //   type of a conversion function (8.3.5) is "function taking no
6736   //   parameter returning conversion-type-id."
6737   if (SC == SC_Static) {
6738     if (!D.isInvalidType())
6739       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6740         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6741         << D.getName().getSourceRange();
6742     D.setInvalidType();
6743     SC = SC_None;
6744   }
6745 
6746   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6747 
6748   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6749     // Conversion functions don't have return types, but the parser will
6750     // happily parse something like:
6751     //
6752     //   class X {
6753     //     float operator bool();
6754     //   };
6755     //
6756     // The return type will be changed later anyway.
6757     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6758       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6759       << SourceRange(D.getIdentifierLoc());
6760     D.setInvalidType();
6761   }
6762 
6763   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6764 
6765   // Make sure we don't have any parameters.
6766   if (Proto->getNumParams() > 0) {
6767     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6768 
6769     // Delete the parameters.
6770     D.getFunctionTypeInfo().freeParams();
6771     D.setInvalidType();
6772   } else if (Proto->isVariadic()) {
6773     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6774     D.setInvalidType();
6775   }
6776 
6777   // Diagnose "&operator bool()" and other such nonsense.  This
6778   // is actually a gcc extension which we don't support.
6779   if (Proto->getReturnType() != ConvType) {
6780     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6781         << Proto->getReturnType();
6782     D.setInvalidType();
6783     ConvType = Proto->getReturnType();
6784   }
6785 
6786   // C++ [class.conv.fct]p4:
6787   //   The conversion-type-id shall not represent a function type nor
6788   //   an array type.
6789   if (ConvType->isArrayType()) {
6790     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6791     ConvType = Context.getPointerType(ConvType);
6792     D.setInvalidType();
6793   } else if (ConvType->isFunctionType()) {
6794     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6795     ConvType = Context.getPointerType(ConvType);
6796     D.setInvalidType();
6797   }
6798 
6799   // Rebuild the function type "R" without any parameters (in case any
6800   // of the errors above fired) and with the conversion type as the
6801   // return type.
6802   if (D.isInvalidType())
6803     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6804 
6805   // C++0x explicit conversion operators.
6806   if (D.getDeclSpec().isExplicitSpecified())
6807     Diag(D.getDeclSpec().getExplicitSpecLoc(),
6808          getLangOpts().CPlusPlus11 ?
6809            diag::warn_cxx98_compat_explicit_conversion_functions :
6810            diag::ext_explicit_conversion_functions)
6811       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6812 }
6813 
6814 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6815 /// the declaration of the given C++ conversion function. This routine
6816 /// is responsible for recording the conversion function in the C++
6817 /// class, if possible.
6818 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6819   assert(Conversion && "Expected to receive a conversion function declaration");
6820 
6821   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6822 
6823   // Make sure we aren't redeclaring the conversion function.
6824   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6825 
6826   // C++ [class.conv.fct]p1:
6827   //   [...] A conversion function is never used to convert a
6828   //   (possibly cv-qualified) object to the (possibly cv-qualified)
6829   //   same object type (or a reference to it), to a (possibly
6830   //   cv-qualified) base class of that type (or a reference to it),
6831   //   or to (possibly cv-qualified) void.
6832   // FIXME: Suppress this warning if the conversion function ends up being a
6833   // virtual function that overrides a virtual function in a base class.
6834   QualType ClassType
6835     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6836   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6837     ConvType = ConvTypeRef->getPointeeType();
6838   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6839       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6840     /* Suppress diagnostics for instantiations. */;
6841   else if (ConvType->isRecordType()) {
6842     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6843     if (ConvType == ClassType)
6844       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6845         << ClassType;
6846     else if (IsDerivedFrom(ClassType, ConvType))
6847       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6848         <<  ClassType << ConvType;
6849   } else if (ConvType->isVoidType()) {
6850     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6851       << ClassType << ConvType;
6852   }
6853 
6854   if (FunctionTemplateDecl *ConversionTemplate
6855                                 = Conversion->getDescribedFunctionTemplate())
6856     return ConversionTemplate;
6857 
6858   return Conversion;
6859 }
6860 
6861 //===----------------------------------------------------------------------===//
6862 // Namespace Handling
6863 //===----------------------------------------------------------------------===//
6864 
6865 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6866 /// reopened.
6867 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6868                                             SourceLocation Loc,
6869                                             IdentifierInfo *II, bool *IsInline,
6870                                             NamespaceDecl *PrevNS) {
6871   assert(*IsInline != PrevNS->isInline());
6872 
6873   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6874   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6875   // inline namespaces, with the intention of bringing names into namespace std.
6876   //
6877   // We support this just well enough to get that case working; this is not
6878   // sufficient to support reopening namespaces as inline in general.
6879   if (*IsInline && II && II->getName().startswith("__atomic") &&
6880       S.getSourceManager().isInSystemHeader(Loc)) {
6881     // Mark all prior declarations of the namespace as inline.
6882     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6883          NS = NS->getPreviousDecl())
6884       NS->setInline(*IsInline);
6885     // Patch up the lookup table for the containing namespace. This isn't really
6886     // correct, but it's good enough for this particular case.
6887     for (auto *I : PrevNS->decls())
6888       if (auto *ND = dyn_cast<NamedDecl>(I))
6889         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6890     return;
6891   }
6892 
6893   if (PrevNS->isInline())
6894     // The user probably just forgot the 'inline', so suggest that it
6895     // be added back.
6896     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6897       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6898   else
6899     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
6900 
6901   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6902   *IsInline = PrevNS->isInline();
6903 }
6904 
6905 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6906 /// definition.
6907 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6908                                    SourceLocation InlineLoc,
6909                                    SourceLocation NamespaceLoc,
6910                                    SourceLocation IdentLoc,
6911                                    IdentifierInfo *II,
6912                                    SourceLocation LBrace,
6913                                    AttributeList *AttrList) {
6914   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6915   // For anonymous namespace, take the location of the left brace.
6916   SourceLocation Loc = II ? IdentLoc : LBrace;
6917   bool IsInline = InlineLoc.isValid();
6918   bool IsInvalid = false;
6919   bool IsStd = false;
6920   bool AddToKnown = false;
6921   Scope *DeclRegionScope = NamespcScope->getParent();
6922 
6923   NamespaceDecl *PrevNS = nullptr;
6924   if (II) {
6925     // C++ [namespace.def]p2:
6926     //   The identifier in an original-namespace-definition shall not
6927     //   have been previously defined in the declarative region in
6928     //   which the original-namespace-definition appears. The
6929     //   identifier in an original-namespace-definition is the name of
6930     //   the namespace. Subsequently in that declarative region, it is
6931     //   treated as an original-namespace-name.
6932     //
6933     // Since namespace names are unique in their scope, and we don't
6934     // look through using directives, just look for any ordinary names.
6935 
6936     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6937     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6938     Decl::IDNS_Namespace;
6939     NamedDecl *PrevDecl = nullptr;
6940     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6941     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6942          ++I) {
6943       if ((*I)->getIdentifierNamespace() & IDNS) {
6944         PrevDecl = *I;
6945         break;
6946       }
6947     }
6948 
6949     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6950 
6951     if (PrevNS) {
6952       // This is an extended namespace definition.
6953       if (IsInline != PrevNS->isInline())
6954         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6955                                         &IsInline, PrevNS);
6956     } else if (PrevDecl) {
6957       // This is an invalid name redefinition.
6958       Diag(Loc, diag::err_redefinition_different_kind)
6959         << II;
6960       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6961       IsInvalid = true;
6962       // Continue on to push Namespc as current DeclContext and return it.
6963     } else if (II->isStr("std") &&
6964                CurContext->getRedeclContext()->isTranslationUnit()) {
6965       // This is the first "real" definition of the namespace "std", so update
6966       // our cache of the "std" namespace to point at this definition.
6967       PrevNS = getStdNamespace();
6968       IsStd = true;
6969       AddToKnown = !IsInline;
6970     } else {
6971       // We've seen this namespace for the first time.
6972       AddToKnown = !IsInline;
6973     }
6974   } else {
6975     // Anonymous namespaces.
6976 
6977     // Determine whether the parent already has an anonymous namespace.
6978     DeclContext *Parent = CurContext->getRedeclContext();
6979     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6980       PrevNS = TU->getAnonymousNamespace();
6981     } else {
6982       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6983       PrevNS = ND->getAnonymousNamespace();
6984     }
6985 
6986     if (PrevNS && IsInline != PrevNS->isInline())
6987       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6988                                       &IsInline, PrevNS);
6989   }
6990 
6991   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6992                                                  StartLoc, Loc, II, PrevNS);
6993   if (IsInvalid)
6994     Namespc->setInvalidDecl();
6995 
6996   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6997 
6998   // FIXME: Should we be merging attributes?
6999   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7000     PushNamespaceVisibilityAttr(Attr, Loc);
7001 
7002   if (IsStd)
7003     StdNamespace = Namespc;
7004   if (AddToKnown)
7005     KnownNamespaces[Namespc] = false;
7006 
7007   if (II) {
7008     PushOnScopeChains(Namespc, DeclRegionScope);
7009   } else {
7010     // Link the anonymous namespace into its parent.
7011     DeclContext *Parent = CurContext->getRedeclContext();
7012     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7013       TU->setAnonymousNamespace(Namespc);
7014     } else {
7015       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7016     }
7017 
7018     CurContext->addDecl(Namespc);
7019 
7020     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
7021     //   behaves as if it were replaced by
7022     //     namespace unique { /* empty body */ }
7023     //     using namespace unique;
7024     //     namespace unique { namespace-body }
7025     //   where all occurrences of 'unique' in a translation unit are
7026     //   replaced by the same identifier and this identifier differs
7027     //   from all other identifiers in the entire program.
7028 
7029     // We just create the namespace with an empty name and then add an
7030     // implicit using declaration, just like the standard suggests.
7031     //
7032     // CodeGen enforces the "universally unique" aspect by giving all
7033     // declarations semantically contained within an anonymous
7034     // namespace internal linkage.
7035 
7036     if (!PrevNS) {
7037       UsingDirectiveDecl* UD
7038         = UsingDirectiveDecl::Create(Context, Parent,
7039                                      /* 'using' */ LBrace,
7040                                      /* 'namespace' */ SourceLocation(),
7041                                      /* qualifier */ NestedNameSpecifierLoc(),
7042                                      /* identifier */ SourceLocation(),
7043                                      Namespc,
7044                                      /* Ancestor */ Parent);
7045       UD->setImplicit();
7046       Parent->addDecl(UD);
7047     }
7048   }
7049 
7050   ActOnDocumentableDecl(Namespc);
7051 
7052   // Although we could have an invalid decl (i.e. the namespace name is a
7053   // redefinition), push it as current DeclContext and try to continue parsing.
7054   // FIXME: We should be able to push Namespc here, so that the each DeclContext
7055   // for the namespace has the declarations that showed up in that particular
7056   // namespace definition.
7057   PushDeclContext(NamespcScope, Namespc);
7058   return Namespc;
7059 }
7060 
7061 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7062 /// is a namespace alias, returns the namespace it points to.
7063 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7064   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7065     return AD->getNamespace();
7066   return dyn_cast_or_null<NamespaceDecl>(D);
7067 }
7068 
7069 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7070 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7071 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7072   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7073   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7074   Namespc->setRBraceLoc(RBrace);
7075   PopDeclContext();
7076   if (Namespc->hasAttr<VisibilityAttr>())
7077     PopPragmaVisibility(true, RBrace);
7078 }
7079 
7080 CXXRecordDecl *Sema::getStdBadAlloc() const {
7081   return cast_or_null<CXXRecordDecl>(
7082                                   StdBadAlloc.get(Context.getExternalSource()));
7083 }
7084 
7085 NamespaceDecl *Sema::getStdNamespace() const {
7086   return cast_or_null<NamespaceDecl>(
7087                                  StdNamespace.get(Context.getExternalSource()));
7088 }
7089 
7090 /// \brief Retrieve the special "std" namespace, which may require us to
7091 /// implicitly define the namespace.
7092 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7093   if (!StdNamespace) {
7094     // The "std" namespace has not yet been defined, so build one implicitly.
7095     StdNamespace = NamespaceDecl::Create(Context,
7096                                          Context.getTranslationUnitDecl(),
7097                                          /*Inline=*/false,
7098                                          SourceLocation(), SourceLocation(),
7099                                          &PP.getIdentifierTable().get("std"),
7100                                          /*PrevDecl=*/nullptr);
7101     getStdNamespace()->setImplicit(true);
7102   }
7103 
7104   return getStdNamespace();
7105 }
7106 
7107 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7108   assert(getLangOpts().CPlusPlus &&
7109          "Looking for std::initializer_list outside of C++.");
7110 
7111   // We're looking for implicit instantiations of
7112   // template <typename E> class std::initializer_list.
7113 
7114   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7115     return false;
7116 
7117   ClassTemplateDecl *Template = nullptr;
7118   const TemplateArgument *Arguments = nullptr;
7119 
7120   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7121 
7122     ClassTemplateSpecializationDecl *Specialization =
7123         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7124     if (!Specialization)
7125       return false;
7126 
7127     Template = Specialization->getSpecializedTemplate();
7128     Arguments = Specialization->getTemplateArgs().data();
7129   } else if (const TemplateSpecializationType *TST =
7130                  Ty->getAs<TemplateSpecializationType>()) {
7131     Template = dyn_cast_or_null<ClassTemplateDecl>(
7132         TST->getTemplateName().getAsTemplateDecl());
7133     Arguments = TST->getArgs();
7134   }
7135   if (!Template)
7136     return false;
7137 
7138   if (!StdInitializerList) {
7139     // Haven't recognized std::initializer_list yet, maybe this is it.
7140     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7141     if (TemplateClass->getIdentifier() !=
7142             &PP.getIdentifierTable().get("initializer_list") ||
7143         !getStdNamespace()->InEnclosingNamespaceSetOf(
7144             TemplateClass->getDeclContext()))
7145       return false;
7146     // This is a template called std::initializer_list, but is it the right
7147     // template?
7148     TemplateParameterList *Params = Template->getTemplateParameters();
7149     if (Params->getMinRequiredArguments() != 1)
7150       return false;
7151     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7152       return false;
7153 
7154     // It's the right template.
7155     StdInitializerList = Template;
7156   }
7157 
7158   if (Template != StdInitializerList)
7159     return false;
7160 
7161   // This is an instance of std::initializer_list. Find the argument type.
7162   if (Element)
7163     *Element = Arguments[0].getAsType();
7164   return true;
7165 }
7166 
7167 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7168   NamespaceDecl *Std = S.getStdNamespace();
7169   if (!Std) {
7170     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7171     return nullptr;
7172   }
7173 
7174   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7175                       Loc, Sema::LookupOrdinaryName);
7176   if (!S.LookupQualifiedName(Result, Std)) {
7177     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7178     return nullptr;
7179   }
7180   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7181   if (!Template) {
7182     Result.suppressDiagnostics();
7183     // We found something weird. Complain about the first thing we found.
7184     NamedDecl *Found = *Result.begin();
7185     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7186     return nullptr;
7187   }
7188 
7189   // We found some template called std::initializer_list. Now verify that it's
7190   // correct.
7191   TemplateParameterList *Params = Template->getTemplateParameters();
7192   if (Params->getMinRequiredArguments() != 1 ||
7193       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7194     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7195     return nullptr;
7196   }
7197 
7198   return Template;
7199 }
7200 
7201 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7202   if (!StdInitializerList) {
7203     StdInitializerList = LookupStdInitializerList(*this, Loc);
7204     if (!StdInitializerList)
7205       return QualType();
7206   }
7207 
7208   TemplateArgumentListInfo Args(Loc, Loc);
7209   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7210                                        Context.getTrivialTypeSourceInfo(Element,
7211                                                                         Loc)));
7212   return Context.getCanonicalType(
7213       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7214 }
7215 
7216 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7217   // C++ [dcl.init.list]p2:
7218   //   A constructor is an initializer-list constructor if its first parameter
7219   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7220   //   std::initializer_list<E> for some type E, and either there are no other
7221   //   parameters or else all other parameters have default arguments.
7222   if (Ctor->getNumParams() < 1 ||
7223       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7224     return false;
7225 
7226   QualType ArgType = Ctor->getParamDecl(0)->getType();
7227   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7228     ArgType = RT->getPointeeType().getUnqualifiedType();
7229 
7230   return isStdInitializerList(ArgType, nullptr);
7231 }
7232 
7233 /// \brief Determine whether a using statement is in a context where it will be
7234 /// apply in all contexts.
7235 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7236   switch (CurContext->getDeclKind()) {
7237     case Decl::TranslationUnit:
7238       return true;
7239     case Decl::LinkageSpec:
7240       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7241     default:
7242       return false;
7243   }
7244 }
7245 
7246 namespace {
7247 
7248 // Callback to only accept typo corrections that are namespaces.
7249 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7250 public:
7251   bool ValidateCandidate(const TypoCorrection &candidate) override {
7252     if (NamedDecl *ND = candidate.getCorrectionDecl())
7253       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7254     return false;
7255   }
7256 };
7257 
7258 }
7259 
7260 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7261                                        CXXScopeSpec &SS,
7262                                        SourceLocation IdentLoc,
7263                                        IdentifierInfo *Ident) {
7264   NamespaceValidatorCCC Validator;
7265   R.clear();
7266   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
7267                                                R.getLookupKind(), Sc, &SS,
7268                                                Validator,
7269                                                Sema::CTK_ErrorRecovery)) {
7270     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7271       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7272       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7273                               Ident->getName().equals(CorrectedStr);
7274       S.diagnoseTypo(Corrected,
7275                      S.PDiag(diag::err_using_directive_member_suggest)
7276                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7277                      S.PDiag(diag::note_namespace_defined_here));
7278     } else {
7279       S.diagnoseTypo(Corrected,
7280                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7281                      S.PDiag(diag::note_namespace_defined_here));
7282     }
7283     R.addDecl(Corrected.getCorrectionDecl());
7284     return true;
7285   }
7286   return false;
7287 }
7288 
7289 Decl *Sema::ActOnUsingDirective(Scope *S,
7290                                           SourceLocation UsingLoc,
7291                                           SourceLocation NamespcLoc,
7292                                           CXXScopeSpec &SS,
7293                                           SourceLocation IdentLoc,
7294                                           IdentifierInfo *NamespcName,
7295                                           AttributeList *AttrList) {
7296   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7297   assert(NamespcName && "Invalid NamespcName.");
7298   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7299 
7300   // This can only happen along a recovery path.
7301   while (S->getFlags() & Scope::TemplateParamScope)
7302     S = S->getParent();
7303   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7304 
7305   UsingDirectiveDecl *UDir = nullptr;
7306   NestedNameSpecifier *Qualifier = nullptr;
7307   if (SS.isSet())
7308     Qualifier = SS.getScopeRep();
7309 
7310   // Lookup namespace name.
7311   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7312   LookupParsedName(R, S, &SS);
7313   if (R.isAmbiguous())
7314     return nullptr;
7315 
7316   if (R.empty()) {
7317     R.clear();
7318     // Allow "using namespace std;" or "using namespace ::std;" even if
7319     // "std" hasn't been defined yet, for GCC compatibility.
7320     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7321         NamespcName->isStr("std")) {
7322       Diag(IdentLoc, diag::ext_using_undefined_std);
7323       R.addDecl(getOrCreateStdNamespace());
7324       R.resolveKind();
7325     }
7326     // Otherwise, attempt typo correction.
7327     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7328   }
7329 
7330   if (!R.empty()) {
7331     NamedDecl *Named = R.getFoundDecl();
7332     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7333         && "expected namespace decl");
7334     // C++ [namespace.udir]p1:
7335     //   A using-directive specifies that the names in the nominated
7336     //   namespace can be used in the scope in which the
7337     //   using-directive appears after the using-directive. During
7338     //   unqualified name lookup (3.4.1), the names appear as if they
7339     //   were declared in the nearest enclosing namespace which
7340     //   contains both the using-directive and the nominated
7341     //   namespace. [Note: in this context, "contains" means "contains
7342     //   directly or indirectly". ]
7343 
7344     // Find enclosing context containing both using-directive and
7345     // nominated namespace.
7346     NamespaceDecl *NS = getNamespaceDecl(Named);
7347     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7348     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7349       CommonAncestor = CommonAncestor->getParent();
7350 
7351     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7352                                       SS.getWithLocInContext(Context),
7353                                       IdentLoc, Named, CommonAncestor);
7354 
7355     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7356         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7357       Diag(IdentLoc, diag::warn_using_directive_in_header);
7358     }
7359 
7360     PushUsingDirective(S, UDir);
7361   } else {
7362     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7363   }
7364 
7365   if (UDir)
7366     ProcessDeclAttributeList(S, UDir, AttrList);
7367 
7368   return UDir;
7369 }
7370 
7371 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7372   // If the scope has an associated entity and the using directive is at
7373   // namespace or translation unit scope, add the UsingDirectiveDecl into
7374   // its lookup structure so qualified name lookup can find it.
7375   DeclContext *Ctx = S->getEntity();
7376   if (Ctx && !Ctx->isFunctionOrMethod())
7377     Ctx->addDecl(UDir);
7378   else
7379     // Otherwise, it is at block scope. The using-directives will affect lookup
7380     // only to the end of the scope.
7381     S->PushUsingDirective(UDir);
7382 }
7383 
7384 
7385 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7386                                   AccessSpecifier AS,
7387                                   bool HasUsingKeyword,
7388                                   SourceLocation UsingLoc,
7389                                   CXXScopeSpec &SS,
7390                                   UnqualifiedId &Name,
7391                                   AttributeList *AttrList,
7392                                   bool HasTypenameKeyword,
7393                                   SourceLocation TypenameLoc) {
7394   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7395 
7396   switch (Name.getKind()) {
7397   case UnqualifiedId::IK_ImplicitSelfParam:
7398   case UnqualifiedId::IK_Identifier:
7399   case UnqualifiedId::IK_OperatorFunctionId:
7400   case UnqualifiedId::IK_LiteralOperatorId:
7401   case UnqualifiedId::IK_ConversionFunctionId:
7402     break;
7403 
7404   case UnqualifiedId::IK_ConstructorName:
7405   case UnqualifiedId::IK_ConstructorTemplateId:
7406     // C++11 inheriting constructors.
7407     Diag(Name.getLocStart(),
7408          getLangOpts().CPlusPlus11 ?
7409            diag::warn_cxx98_compat_using_decl_constructor :
7410            diag::err_using_decl_constructor)
7411       << SS.getRange();
7412 
7413     if (getLangOpts().CPlusPlus11) break;
7414 
7415     return nullptr;
7416 
7417   case UnqualifiedId::IK_DestructorName:
7418     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7419       << SS.getRange();
7420     return nullptr;
7421 
7422   case UnqualifiedId::IK_TemplateId:
7423     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7424       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7425     return nullptr;
7426   }
7427 
7428   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7429   DeclarationName TargetName = TargetNameInfo.getName();
7430   if (!TargetName)
7431     return nullptr;
7432 
7433   // Warn about access declarations.
7434   if (!HasUsingKeyword) {
7435     Diag(Name.getLocStart(),
7436          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7437                                    : diag::warn_access_decl_deprecated)
7438       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7439   }
7440 
7441   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7442       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7443     return nullptr;
7444 
7445   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7446                                         TargetNameInfo, AttrList,
7447                                         /* IsInstantiation */ false,
7448                                         HasTypenameKeyword, TypenameLoc);
7449   if (UD)
7450     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7451 
7452   return UD;
7453 }
7454 
7455 /// \brief Determine whether a using declaration considers the given
7456 /// declarations as "equivalent", e.g., if they are redeclarations of
7457 /// the same entity or are both typedefs of the same type.
7458 static bool
7459 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7460   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7461     return true;
7462 
7463   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7464     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7465       return Context.hasSameType(TD1->getUnderlyingType(),
7466                                  TD2->getUnderlyingType());
7467 
7468   return false;
7469 }
7470 
7471 
7472 /// Determines whether to create a using shadow decl for a particular
7473 /// decl, given the set of decls existing prior to this using lookup.
7474 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7475                                 const LookupResult &Previous,
7476                                 UsingShadowDecl *&PrevShadow) {
7477   // Diagnose finding a decl which is not from a base class of the
7478   // current class.  We do this now because there are cases where this
7479   // function will silently decide not to build a shadow decl, which
7480   // will pre-empt further diagnostics.
7481   //
7482   // We don't need to do this in C++0x because we do the check once on
7483   // the qualifier.
7484   //
7485   // FIXME: diagnose the following if we care enough:
7486   //   struct A { int foo; };
7487   //   struct B : A { using A::foo; };
7488   //   template <class T> struct C : A {};
7489   //   template <class T> struct D : C<T> { using B::foo; } // <---
7490   // This is invalid (during instantiation) in C++03 because B::foo
7491   // resolves to the using decl in B, which is not a base class of D<T>.
7492   // We can't diagnose it immediately because C<T> is an unknown
7493   // specialization.  The UsingShadowDecl in D<T> then points directly
7494   // to A::foo, which will look well-formed when we instantiate.
7495   // The right solution is to not collapse the shadow-decl chain.
7496   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7497     DeclContext *OrigDC = Orig->getDeclContext();
7498 
7499     // Handle enums and anonymous structs.
7500     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7501     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7502     while (OrigRec->isAnonymousStructOrUnion())
7503       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7504 
7505     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7506       if (OrigDC == CurContext) {
7507         Diag(Using->getLocation(),
7508              diag::err_using_decl_nested_name_specifier_is_current_class)
7509           << Using->getQualifierLoc().getSourceRange();
7510         Diag(Orig->getLocation(), diag::note_using_decl_target);
7511         return true;
7512       }
7513 
7514       Diag(Using->getQualifierLoc().getBeginLoc(),
7515            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7516         << Using->getQualifier()
7517         << cast<CXXRecordDecl>(CurContext)
7518         << Using->getQualifierLoc().getSourceRange();
7519       Diag(Orig->getLocation(), diag::note_using_decl_target);
7520       return true;
7521     }
7522   }
7523 
7524   if (Previous.empty()) return false;
7525 
7526   NamedDecl *Target = Orig;
7527   if (isa<UsingShadowDecl>(Target))
7528     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7529 
7530   // If the target happens to be one of the previous declarations, we
7531   // don't have a conflict.
7532   //
7533   // FIXME: but we might be increasing its access, in which case we
7534   // should redeclare it.
7535   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7536   bool FoundEquivalentDecl = false;
7537   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7538          I != E; ++I) {
7539     NamedDecl *D = (*I)->getUnderlyingDecl();
7540     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7541       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7542         PrevShadow = Shadow;
7543       FoundEquivalentDecl = true;
7544     }
7545 
7546     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7547   }
7548 
7549   if (FoundEquivalentDecl)
7550     return false;
7551 
7552   if (FunctionDecl *FD = Target->getAsFunction()) {
7553     NamedDecl *OldDecl = nullptr;
7554     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7555                           /*IsForUsingDecl*/ true)) {
7556     case Ovl_Overload:
7557       return false;
7558 
7559     case Ovl_NonFunction:
7560       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7561       break;
7562 
7563     // We found a decl with the exact signature.
7564     case Ovl_Match:
7565       // If we're in a record, we want to hide the target, so we
7566       // return true (without a diagnostic) to tell the caller not to
7567       // build a shadow decl.
7568       if (CurContext->isRecord())
7569         return true;
7570 
7571       // If we're not in a record, this is an error.
7572       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7573       break;
7574     }
7575 
7576     Diag(Target->getLocation(), diag::note_using_decl_target);
7577     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7578     return true;
7579   }
7580 
7581   // Target is not a function.
7582 
7583   if (isa<TagDecl>(Target)) {
7584     // No conflict between a tag and a non-tag.
7585     if (!Tag) return false;
7586 
7587     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7588     Diag(Target->getLocation(), diag::note_using_decl_target);
7589     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7590     return true;
7591   }
7592 
7593   // No conflict between a tag and a non-tag.
7594   if (!NonTag) return false;
7595 
7596   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7597   Diag(Target->getLocation(), diag::note_using_decl_target);
7598   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7599   return true;
7600 }
7601 
7602 /// Builds a shadow declaration corresponding to a 'using' declaration.
7603 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7604                                             UsingDecl *UD,
7605                                             NamedDecl *Orig,
7606                                             UsingShadowDecl *PrevDecl) {
7607 
7608   // If we resolved to another shadow declaration, just coalesce them.
7609   NamedDecl *Target = Orig;
7610   if (isa<UsingShadowDecl>(Target)) {
7611     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7612     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7613   }
7614 
7615   UsingShadowDecl *Shadow
7616     = UsingShadowDecl::Create(Context, CurContext,
7617                               UD->getLocation(), UD, Target);
7618   UD->addShadowDecl(Shadow);
7619 
7620   Shadow->setAccess(UD->getAccess());
7621   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7622     Shadow->setInvalidDecl();
7623 
7624   Shadow->setPreviousDecl(PrevDecl);
7625 
7626   if (S)
7627     PushOnScopeChains(Shadow, S);
7628   else
7629     CurContext->addDecl(Shadow);
7630 
7631 
7632   return Shadow;
7633 }
7634 
7635 /// Hides a using shadow declaration.  This is required by the current
7636 /// using-decl implementation when a resolvable using declaration in a
7637 /// class is followed by a declaration which would hide or override
7638 /// one or more of the using decl's targets; for example:
7639 ///
7640 ///   struct Base { void foo(int); };
7641 ///   struct Derived : Base {
7642 ///     using Base::foo;
7643 ///     void foo(int);
7644 ///   };
7645 ///
7646 /// The governing language is C++03 [namespace.udecl]p12:
7647 ///
7648 ///   When a using-declaration brings names from a base class into a
7649 ///   derived class scope, member functions in the derived class
7650 ///   override and/or hide member functions with the same name and
7651 ///   parameter types in a base class (rather than conflicting).
7652 ///
7653 /// There are two ways to implement this:
7654 ///   (1) optimistically create shadow decls when they're not hidden
7655 ///       by existing declarations, or
7656 ///   (2) don't create any shadow decls (or at least don't make them
7657 ///       visible) until we've fully parsed/instantiated the class.
7658 /// The problem with (1) is that we might have to retroactively remove
7659 /// a shadow decl, which requires several O(n) operations because the
7660 /// decl structures are (very reasonably) not designed for removal.
7661 /// (2) avoids this but is very fiddly and phase-dependent.
7662 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7663   if (Shadow->getDeclName().getNameKind() ==
7664         DeclarationName::CXXConversionFunctionName)
7665     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7666 
7667   // Remove it from the DeclContext...
7668   Shadow->getDeclContext()->removeDecl(Shadow);
7669 
7670   // ...and the scope, if applicable...
7671   if (S) {
7672     S->RemoveDecl(Shadow);
7673     IdResolver.RemoveDecl(Shadow);
7674   }
7675 
7676   // ...and the using decl.
7677   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7678 
7679   // TODO: complain somehow if Shadow was used.  It shouldn't
7680   // be possible for this to happen, because...?
7681 }
7682 
7683 /// Find the base specifier for a base class with the given type.
7684 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7685                                                 QualType DesiredBase,
7686                                                 bool &AnyDependentBases) {
7687   // Check whether the named type is a direct base class.
7688   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7689   for (auto &Base : Derived->bases()) {
7690     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7691     if (CanonicalDesiredBase == BaseType)
7692       return &Base;
7693     if (BaseType->isDependentType())
7694       AnyDependentBases = true;
7695   }
7696   return nullptr;
7697 }
7698 
7699 namespace {
7700 class UsingValidatorCCC : public CorrectionCandidateCallback {
7701 public:
7702   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7703                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7704       : HasTypenameKeyword(HasTypenameKeyword),
7705         IsInstantiation(IsInstantiation), OldNNS(NNS),
7706         RequireMemberOf(RequireMemberOf) {}
7707 
7708   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7709     NamedDecl *ND = Candidate.getCorrectionDecl();
7710 
7711     // Keywords are not valid here.
7712     if (!ND || isa<NamespaceDecl>(ND))
7713       return false;
7714 
7715     // Completely unqualified names are invalid for a 'using' declaration.
7716     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7717       return false;
7718 
7719     if (RequireMemberOf) {
7720       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7721       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7722         // No-one ever wants a using-declaration to name an injected-class-name
7723         // of a base class, unless they're declaring an inheriting constructor.
7724         ASTContext &Ctx = ND->getASTContext();
7725         if (!Ctx.getLangOpts().CPlusPlus11)
7726           return false;
7727         QualType FoundType = Ctx.getRecordType(FoundRecord);
7728 
7729         // Check that the injected-class-name is named as a member of its own
7730         // type; we don't want to suggest 'using Derived::Base;', since that
7731         // means something else.
7732         NestedNameSpecifier *Specifier =
7733             Candidate.WillReplaceSpecifier()
7734                 ? Candidate.getCorrectionSpecifier()
7735                 : OldNNS;
7736         if (!Specifier->getAsType() ||
7737             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7738           return false;
7739 
7740         // Check that this inheriting constructor declaration actually names a
7741         // direct base class of the current class.
7742         bool AnyDependentBases = false;
7743         if (!findDirectBaseWithType(RequireMemberOf,
7744                                     Ctx.getRecordType(FoundRecord),
7745                                     AnyDependentBases) &&
7746             !AnyDependentBases)
7747           return false;
7748       } else {
7749         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7750         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7751           return false;
7752 
7753         // FIXME: Check that the base class member is accessible?
7754       }
7755     }
7756 
7757     if (isa<TypeDecl>(ND))
7758       return HasTypenameKeyword || !IsInstantiation;
7759 
7760     return !HasTypenameKeyword;
7761   }
7762 
7763 private:
7764   bool HasTypenameKeyword;
7765   bool IsInstantiation;
7766   NestedNameSpecifier *OldNNS;
7767   CXXRecordDecl *RequireMemberOf;
7768 };
7769 } // end anonymous namespace
7770 
7771 /// Builds a using declaration.
7772 ///
7773 /// \param IsInstantiation - Whether this call arises from an
7774 ///   instantiation of an unresolved using declaration.  We treat
7775 ///   the lookup differently for these declarations.
7776 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7777                                        SourceLocation UsingLoc,
7778                                        CXXScopeSpec &SS,
7779                                        DeclarationNameInfo NameInfo,
7780                                        AttributeList *AttrList,
7781                                        bool IsInstantiation,
7782                                        bool HasTypenameKeyword,
7783                                        SourceLocation TypenameLoc) {
7784   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7785   SourceLocation IdentLoc = NameInfo.getLoc();
7786   assert(IdentLoc.isValid() && "Invalid TargetName location.");
7787 
7788   // FIXME: We ignore attributes for now.
7789 
7790   if (SS.isEmpty()) {
7791     Diag(IdentLoc, diag::err_using_requires_qualname);
7792     return nullptr;
7793   }
7794 
7795   // Do the redeclaration lookup in the current scope.
7796   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7797                         ForRedeclaration);
7798   Previous.setHideTags(false);
7799   if (S) {
7800     LookupName(Previous, S);
7801 
7802     // It is really dumb that we have to do this.
7803     LookupResult::Filter F = Previous.makeFilter();
7804     while (F.hasNext()) {
7805       NamedDecl *D = F.next();
7806       if (!isDeclInScope(D, CurContext, S))
7807         F.erase();
7808       // If we found a local extern declaration that's not ordinarily visible,
7809       // and this declaration is being added to a non-block scope, ignore it.
7810       // We're only checking for scope conflicts here, not also for violations
7811       // of the linkage rules.
7812       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7813                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7814         F.erase();
7815     }
7816     F.done();
7817   } else {
7818     assert(IsInstantiation && "no scope in non-instantiation");
7819     assert(CurContext->isRecord() && "scope not record in instantiation");
7820     LookupQualifiedName(Previous, CurContext);
7821   }
7822 
7823   // Check for invalid redeclarations.
7824   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7825                                   SS, IdentLoc, Previous))
7826     return nullptr;
7827 
7828   // Check for bad qualifiers.
7829   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
7830     return nullptr;
7831 
7832   DeclContext *LookupContext = computeDeclContext(SS);
7833   NamedDecl *D;
7834   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7835   if (!LookupContext) {
7836     if (HasTypenameKeyword) {
7837       // FIXME: not all declaration name kinds are legal here
7838       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7839                                               UsingLoc, TypenameLoc,
7840                                               QualifierLoc,
7841                                               IdentLoc, NameInfo.getName());
7842     } else {
7843       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7844                                            QualifierLoc, NameInfo);
7845     }
7846     D->setAccess(AS);
7847     CurContext->addDecl(D);
7848     return D;
7849   }
7850 
7851   auto Build = [&](bool Invalid) {
7852     UsingDecl *UD =
7853         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7854                           HasTypenameKeyword);
7855     UD->setAccess(AS);
7856     CurContext->addDecl(UD);
7857     UD->setInvalidDecl(Invalid);
7858     return UD;
7859   };
7860   auto BuildInvalid = [&]{ return Build(true); };
7861   auto BuildValid = [&]{ return Build(false); };
7862 
7863   if (RequireCompleteDeclContext(SS, LookupContext))
7864     return BuildInvalid();
7865 
7866   // The normal rules do not apply to inheriting constructor declarations.
7867   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7868     UsingDecl *UD = BuildValid();
7869     CheckInheritingConstructorUsingDecl(UD);
7870     return UD;
7871   }
7872 
7873   // Otherwise, look up the target name.
7874 
7875   LookupResult R(*this, NameInfo, LookupOrdinaryName);
7876 
7877   // Unlike most lookups, we don't always want to hide tag
7878   // declarations: tag names are visible through the using declaration
7879   // even if hidden by ordinary names, *except* in a dependent context
7880   // where it's important for the sanity of two-phase lookup.
7881   if (!IsInstantiation)
7882     R.setHideTags(false);
7883 
7884   // For the purposes of this lookup, we have a base object type
7885   // equal to that of the current context.
7886   if (CurContext->isRecord()) {
7887     R.setBaseObjectType(
7888                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7889   }
7890 
7891   LookupQualifiedName(R, LookupContext);
7892 
7893   // Try to correct typos if possible.
7894   if (R.empty()) {
7895     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
7896                           dyn_cast<CXXRecordDecl>(CurContext));
7897     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7898                                                R.getLookupKind(), S, &SS, CCC,
7899                                                CTK_ErrorRecovery)){
7900       // We reject any correction for which ND would be NULL.
7901       NamedDecl *ND = Corrected.getCorrectionDecl();
7902 
7903       // We reject candidates where DroppedSpecifier == true, hence the
7904       // literal '0' below.
7905       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7906                                 << NameInfo.getName() << LookupContext << 0
7907                                 << SS.getRange());
7908 
7909       // If we corrected to an inheriting constructor, handle it as one.
7910       auto *RD = dyn_cast<CXXRecordDecl>(ND);
7911       if (RD && RD->isInjectedClassName()) {
7912         // Fix up the information we'll use to build the using declaration.
7913         if (Corrected.WillReplaceSpecifier()) {
7914           NestedNameSpecifierLocBuilder Builder;
7915           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7916                               QualifierLoc.getSourceRange());
7917           QualifierLoc = Builder.getWithLocInContext(Context);
7918         }
7919 
7920         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7921             Context.getCanonicalType(Context.getRecordType(RD))));
7922         NameInfo.setNamedTypeInfo(nullptr);
7923 
7924         // Build it and process it as an inheriting constructor.
7925         UsingDecl *UD = BuildValid();
7926         CheckInheritingConstructorUsingDecl(UD);
7927         return UD;
7928       }
7929 
7930       // FIXME: Pick up all the declarations if we found an overloaded function.
7931       R.setLookupName(Corrected.getCorrection());
7932       R.addDecl(ND);
7933     } else {
7934       Diag(IdentLoc, diag::err_no_member)
7935         << NameInfo.getName() << LookupContext << SS.getRange();
7936       return BuildInvalid();
7937     }
7938   }
7939 
7940   if (R.isAmbiguous())
7941     return BuildInvalid();
7942 
7943   if (HasTypenameKeyword) {
7944     // If we asked for a typename and got a non-type decl, error out.
7945     if (!R.getAsSingle<TypeDecl>()) {
7946       Diag(IdentLoc, diag::err_using_typename_non_type);
7947       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7948         Diag((*I)->getUnderlyingDecl()->getLocation(),
7949              diag::note_using_decl_target);
7950       return BuildInvalid();
7951     }
7952   } else {
7953     // If we asked for a non-typename and we got a type, error out,
7954     // but only if this is an instantiation of an unresolved using
7955     // decl.  Otherwise just silently find the type name.
7956     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7957       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7958       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7959       return BuildInvalid();
7960     }
7961   }
7962 
7963   // C++0x N2914 [namespace.udecl]p6:
7964   // A using-declaration shall not name a namespace.
7965   if (R.getAsSingle<NamespaceDecl>()) {
7966     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7967       << SS.getRange();
7968     return BuildInvalid();
7969   }
7970 
7971   UsingDecl *UD = BuildValid();
7972   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7973     UsingShadowDecl *PrevDecl = nullptr;
7974     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7975       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7976   }
7977 
7978   return UD;
7979 }
7980 
7981 /// Additional checks for a using declaration referring to a constructor name.
7982 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7983   assert(!UD->hasTypename() && "expecting a constructor name");
7984 
7985   const Type *SourceType = UD->getQualifier()->getAsType();
7986   assert(SourceType &&
7987          "Using decl naming constructor doesn't have type in scope spec.");
7988   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7989 
7990   // Check whether the named type is a direct base class.
7991   bool AnyDependentBases = false;
7992   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7993                                       AnyDependentBases);
7994   if (!Base && !AnyDependentBases) {
7995     Diag(UD->getUsingLoc(),
7996          diag::err_using_decl_constructor_not_in_direct_base)
7997       << UD->getNameInfo().getSourceRange()
7998       << QualType(SourceType, 0) << TargetClass;
7999     UD->setInvalidDecl();
8000     return true;
8001   }
8002 
8003   if (Base)
8004     Base->setInheritConstructors();
8005 
8006   return false;
8007 }
8008 
8009 /// Checks that the given using declaration is not an invalid
8010 /// redeclaration.  Note that this is checking only for the using decl
8011 /// itself, not for any ill-formedness among the UsingShadowDecls.
8012 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8013                                        bool HasTypenameKeyword,
8014                                        const CXXScopeSpec &SS,
8015                                        SourceLocation NameLoc,
8016                                        const LookupResult &Prev) {
8017   // C++03 [namespace.udecl]p8:
8018   // C++0x [namespace.udecl]p10:
8019   //   A using-declaration is a declaration and can therefore be used
8020   //   repeatedly where (and only where) multiple declarations are
8021   //   allowed.
8022   //
8023   // That's in non-member contexts.
8024   if (!CurContext->getRedeclContext()->isRecord())
8025     return false;
8026 
8027   NestedNameSpecifier *Qual = SS.getScopeRep();
8028 
8029   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8030     NamedDecl *D = *I;
8031 
8032     bool DTypename;
8033     NestedNameSpecifier *DQual;
8034     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8035       DTypename = UD->hasTypename();
8036       DQual = UD->getQualifier();
8037     } else if (UnresolvedUsingValueDecl *UD
8038                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8039       DTypename = false;
8040       DQual = UD->getQualifier();
8041     } else if (UnresolvedUsingTypenameDecl *UD
8042                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8043       DTypename = true;
8044       DQual = UD->getQualifier();
8045     } else continue;
8046 
8047     // using decls differ if one says 'typename' and the other doesn't.
8048     // FIXME: non-dependent using decls?
8049     if (HasTypenameKeyword != DTypename) continue;
8050 
8051     // using decls differ if they name different scopes (but note that
8052     // template instantiation can cause this check to trigger when it
8053     // didn't before instantiation).
8054     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8055         Context.getCanonicalNestedNameSpecifier(DQual))
8056       continue;
8057 
8058     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8059     Diag(D->getLocation(), diag::note_using_decl) << 1;
8060     return true;
8061   }
8062 
8063   return false;
8064 }
8065 
8066 
8067 /// Checks that the given nested-name qualifier used in a using decl
8068 /// in the current context is appropriately related to the current
8069 /// scope.  If an error is found, diagnoses it and returns true.
8070 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8071                                    const CXXScopeSpec &SS,
8072                                    const DeclarationNameInfo &NameInfo,
8073                                    SourceLocation NameLoc) {
8074   DeclContext *NamedContext = computeDeclContext(SS);
8075 
8076   if (!CurContext->isRecord()) {
8077     // C++03 [namespace.udecl]p3:
8078     // C++0x [namespace.udecl]p8:
8079     //   A using-declaration for a class member shall be a member-declaration.
8080 
8081     // If we weren't able to compute a valid scope, it must be a
8082     // dependent class scope.
8083     if (!NamedContext || NamedContext->isRecord()) {
8084       auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
8085       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8086         RD = nullptr;
8087 
8088       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8089         << SS.getRange();
8090 
8091       // If we have a complete, non-dependent source type, try to suggest a
8092       // way to get the same effect.
8093       if (!RD)
8094         return true;
8095 
8096       // Find what this using-declaration was referring to.
8097       LookupResult R(*this, NameInfo, LookupOrdinaryName);
8098       R.setHideTags(false);
8099       R.suppressDiagnostics();
8100       LookupQualifiedName(R, RD);
8101 
8102       if (R.getAsSingle<TypeDecl>()) {
8103         if (getLangOpts().CPlusPlus11) {
8104           // Convert 'using X::Y;' to 'using Y = X::Y;'.
8105           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8106             << 0 // alias declaration
8107             << FixItHint::CreateInsertion(SS.getBeginLoc(),
8108                                           NameInfo.getName().getAsString() +
8109                                               " = ");
8110         } else {
8111           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8112           SourceLocation InsertLoc =
8113               PP.getLocForEndOfToken(NameInfo.getLocEnd());
8114           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8115             << 1 // typedef declaration
8116             << FixItHint::CreateReplacement(UsingLoc, "typedef")
8117             << FixItHint::CreateInsertion(
8118                    InsertLoc, " " + NameInfo.getName().getAsString());
8119         }
8120       } else if (R.getAsSingle<VarDecl>()) {
8121         // Don't provide a fixit outside C++11 mode; we don't want to suggest
8122         // repeating the type of the static data member here.
8123         FixItHint FixIt;
8124         if (getLangOpts().CPlusPlus11) {
8125           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8126           FixIt = FixItHint::CreateReplacement(
8127               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8128         }
8129 
8130         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8131           << 2 // reference declaration
8132           << FixIt;
8133       }
8134       return true;
8135     }
8136 
8137     // Otherwise, everything is known to be fine.
8138     return false;
8139   }
8140 
8141   // The current scope is a record.
8142 
8143   // If the named context is dependent, we can't decide much.
8144   if (!NamedContext) {
8145     // FIXME: in C++0x, we can diagnose if we can prove that the
8146     // nested-name-specifier does not refer to a base class, which is
8147     // still possible in some cases.
8148 
8149     // Otherwise we have to conservatively report that things might be
8150     // okay.
8151     return false;
8152   }
8153 
8154   if (!NamedContext->isRecord()) {
8155     // Ideally this would point at the last name in the specifier,
8156     // but we don't have that level of source info.
8157     Diag(SS.getRange().getBegin(),
8158          diag::err_using_decl_nested_name_specifier_is_not_class)
8159       << SS.getScopeRep() << SS.getRange();
8160     return true;
8161   }
8162 
8163   if (!NamedContext->isDependentContext() &&
8164       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8165     return true;
8166 
8167   if (getLangOpts().CPlusPlus11) {
8168     // C++0x [namespace.udecl]p3:
8169     //   In a using-declaration used as a member-declaration, the
8170     //   nested-name-specifier shall name a base class of the class
8171     //   being defined.
8172 
8173     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8174                                  cast<CXXRecordDecl>(NamedContext))) {
8175       if (CurContext == NamedContext) {
8176         Diag(NameLoc,
8177              diag::err_using_decl_nested_name_specifier_is_current_class)
8178           << SS.getRange();
8179         return true;
8180       }
8181 
8182       Diag(SS.getRange().getBegin(),
8183            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8184         << SS.getScopeRep()
8185         << cast<CXXRecordDecl>(CurContext)
8186         << SS.getRange();
8187       return true;
8188     }
8189 
8190     return false;
8191   }
8192 
8193   // C++03 [namespace.udecl]p4:
8194   //   A using-declaration used as a member-declaration shall refer
8195   //   to a member of a base class of the class being defined [etc.].
8196 
8197   // Salient point: SS doesn't have to name a base class as long as
8198   // lookup only finds members from base classes.  Therefore we can
8199   // diagnose here only if we can prove that that can't happen,
8200   // i.e. if the class hierarchies provably don't intersect.
8201 
8202   // TODO: it would be nice if "definitely valid" results were cached
8203   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8204   // need to be repeated.
8205 
8206   struct UserData {
8207     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8208 
8209     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8210       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8211       Data->Bases.insert(Base);
8212       return true;
8213     }
8214 
8215     bool hasDependentBases(const CXXRecordDecl *Class) {
8216       return !Class->forallBases(collect, this);
8217     }
8218 
8219     /// Returns true if the base is dependent or is one of the
8220     /// accumulated base classes.
8221     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8222       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8223       return !Data->Bases.count(Base);
8224     }
8225 
8226     bool mightShareBases(const CXXRecordDecl *Class) {
8227       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8228     }
8229   };
8230 
8231   UserData Data;
8232 
8233   // Returns false if we find a dependent base.
8234   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8235     return false;
8236 
8237   // Returns false if the class has a dependent base or if it or one
8238   // of its bases is present in the base set of the current context.
8239   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8240     return false;
8241 
8242   Diag(SS.getRange().getBegin(),
8243        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8244     << SS.getScopeRep()
8245     << cast<CXXRecordDecl>(CurContext)
8246     << SS.getRange();
8247 
8248   return true;
8249 }
8250 
8251 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8252                                   AccessSpecifier AS,
8253                                   MultiTemplateParamsArg TemplateParamLists,
8254                                   SourceLocation UsingLoc,
8255                                   UnqualifiedId &Name,
8256                                   AttributeList *AttrList,
8257                                   TypeResult Type) {
8258   // Skip up to the relevant declaration scope.
8259   while (S->getFlags() & Scope::TemplateParamScope)
8260     S = S->getParent();
8261   assert((S->getFlags() & Scope::DeclScope) &&
8262          "got alias-declaration outside of declaration scope");
8263 
8264   if (Type.isInvalid())
8265     return nullptr;
8266 
8267   bool Invalid = false;
8268   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8269   TypeSourceInfo *TInfo = nullptr;
8270   GetTypeFromParser(Type.get(), &TInfo);
8271 
8272   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8273     return nullptr;
8274 
8275   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8276                                       UPPC_DeclarationType)) {
8277     Invalid = true;
8278     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8279                                              TInfo->getTypeLoc().getBeginLoc());
8280   }
8281 
8282   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8283   LookupName(Previous, S);
8284 
8285   // Warn about shadowing the name of a template parameter.
8286   if (Previous.isSingleResult() &&
8287       Previous.getFoundDecl()->isTemplateParameter()) {
8288     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8289     Previous.clear();
8290   }
8291 
8292   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8293          "name in alias declaration must be an identifier");
8294   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8295                                                Name.StartLocation,
8296                                                Name.Identifier, TInfo);
8297 
8298   NewTD->setAccess(AS);
8299 
8300   if (Invalid)
8301     NewTD->setInvalidDecl();
8302 
8303   ProcessDeclAttributeList(S, NewTD, AttrList);
8304 
8305   CheckTypedefForVariablyModifiedType(S, NewTD);
8306   Invalid |= NewTD->isInvalidDecl();
8307 
8308   bool Redeclaration = false;
8309 
8310   NamedDecl *NewND;
8311   if (TemplateParamLists.size()) {
8312     TypeAliasTemplateDecl *OldDecl = nullptr;
8313     TemplateParameterList *OldTemplateParams = nullptr;
8314 
8315     if (TemplateParamLists.size() != 1) {
8316       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8317         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8318          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8319     }
8320     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8321 
8322     // Only consider previous declarations in the same scope.
8323     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8324                          /*ExplicitInstantiationOrSpecialization*/false);
8325     if (!Previous.empty()) {
8326       Redeclaration = true;
8327 
8328       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8329       if (!OldDecl && !Invalid) {
8330         Diag(UsingLoc, diag::err_redefinition_different_kind)
8331           << Name.Identifier;
8332 
8333         NamedDecl *OldD = Previous.getRepresentativeDecl();
8334         if (OldD->getLocation().isValid())
8335           Diag(OldD->getLocation(), diag::note_previous_definition);
8336 
8337         Invalid = true;
8338       }
8339 
8340       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8341         if (TemplateParameterListsAreEqual(TemplateParams,
8342                                            OldDecl->getTemplateParameters(),
8343                                            /*Complain=*/true,
8344                                            TPL_TemplateMatch))
8345           OldTemplateParams = OldDecl->getTemplateParameters();
8346         else
8347           Invalid = true;
8348 
8349         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8350         if (!Invalid &&
8351             !Context.hasSameType(OldTD->getUnderlyingType(),
8352                                  NewTD->getUnderlyingType())) {
8353           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8354           // but we can't reasonably accept it.
8355           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8356             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8357           if (OldTD->getLocation().isValid())
8358             Diag(OldTD->getLocation(), diag::note_previous_definition);
8359           Invalid = true;
8360         }
8361       }
8362     }
8363 
8364     // Merge any previous default template arguments into our parameters,
8365     // and check the parameter list.
8366     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8367                                    TPC_TypeAliasTemplate))
8368       return nullptr;
8369 
8370     TypeAliasTemplateDecl *NewDecl =
8371       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8372                                     Name.Identifier, TemplateParams,
8373                                     NewTD);
8374     NewTD->setDescribedAliasTemplate(NewDecl);
8375 
8376     NewDecl->setAccess(AS);
8377 
8378     if (Invalid)
8379       NewDecl->setInvalidDecl();
8380     else if (OldDecl)
8381       NewDecl->setPreviousDecl(OldDecl);
8382 
8383     NewND = NewDecl;
8384   } else {
8385     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8386     NewND = NewTD;
8387   }
8388 
8389   if (!Redeclaration)
8390     PushOnScopeChains(NewND, S);
8391 
8392   ActOnDocumentableDecl(NewND);
8393   return NewND;
8394 }
8395 
8396 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8397                                    SourceLocation AliasLoc,
8398                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
8399                                    SourceLocation IdentLoc,
8400                                    IdentifierInfo *Ident) {
8401 
8402   // Lookup the namespace name.
8403   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8404   LookupParsedName(R, S, &SS);
8405 
8406   if (R.isAmbiguous())
8407     return nullptr;
8408 
8409   if (R.empty()) {
8410     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8411       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8412       return nullptr;
8413     }
8414   }
8415   assert(!R.isAmbiguous() && !R.empty());
8416 
8417   // Check if we have a previous declaration with the same name.
8418   NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8419                                          ForRedeclaration);
8420   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8421     PrevDecl = nullptr;
8422 
8423   if (PrevDecl) {
8424     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8425       // We already have an alias with the same name that points to the same
8426       // namespace; check that it matches.
8427       if (!AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) {
8428         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8429           << Alias;
8430         Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8431           << AD->getNamespace();
8432         return nullptr;
8433       }
8434     } else {
8435       unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8436                             ? diag::err_redefinition
8437                             : diag::err_redefinition_different_kind;
8438       Diag(AliasLoc, DiagID) << Alias;
8439       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8440       return nullptr;
8441     }
8442   }
8443 
8444   NamespaceAliasDecl *AliasDecl =
8445     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8446                                Alias, SS.getWithLocInContext(Context),
8447                                IdentLoc, R.getFoundDecl());
8448   if (PrevDecl)
8449     AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
8450 
8451   PushOnScopeChains(AliasDecl, S);
8452   return AliasDecl;
8453 }
8454 
8455 Sema::ImplicitExceptionSpecification
8456 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8457                                                CXXMethodDecl *MD) {
8458   CXXRecordDecl *ClassDecl = MD->getParent();
8459 
8460   // C++ [except.spec]p14:
8461   //   An implicitly declared special member function (Clause 12) shall have an
8462   //   exception-specification. [...]
8463   ImplicitExceptionSpecification ExceptSpec(*this);
8464   if (ClassDecl->isInvalidDecl())
8465     return ExceptSpec;
8466 
8467   // Direct base-class constructors.
8468   for (const auto &B : ClassDecl->bases()) {
8469     if (B.isVirtual()) // Handled below.
8470       continue;
8471 
8472     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8473       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8474       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8475       // If this is a deleted function, add it anyway. This might be conformant
8476       // with the standard. This might not. I'm not sure. It might not matter.
8477       if (Constructor)
8478         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8479     }
8480   }
8481 
8482   // Virtual base-class constructors.
8483   for (const auto &B : ClassDecl->vbases()) {
8484     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8485       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8486       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8487       // If this is a deleted function, add it anyway. This might be conformant
8488       // with the standard. This might not. I'm not sure. It might not matter.
8489       if (Constructor)
8490         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8491     }
8492   }
8493 
8494   // Field constructors.
8495   for (const auto *F : ClassDecl->fields()) {
8496     if (F->hasInClassInitializer()) {
8497       if (Expr *E = F->getInClassInitializer())
8498         ExceptSpec.CalledExpr(E);
8499       else if (!F->isInvalidDecl())
8500         // DR1351:
8501         //   If the brace-or-equal-initializer of a non-static data member
8502         //   invokes a defaulted default constructor of its class or of an
8503         //   enclosing class in a potentially evaluated subexpression, the
8504         //   program is ill-formed.
8505         //
8506         // This resolution is unworkable: the exception specification of the
8507         // default constructor can be needed in an unevaluated context, in
8508         // particular, in the operand of a noexcept-expression, and we can be
8509         // unable to compute an exception specification for an enclosed class.
8510         //
8511         // We do not allow an in-class initializer to require the evaluation
8512         // of the exception specification for any in-class initializer whose
8513         // definition is not lexically complete.
8514         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
8515     } else if (const RecordType *RecordTy
8516               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8517       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8518       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8519       // If this is a deleted function, add it anyway. This might be conformant
8520       // with the standard. This might not. I'm not sure. It might not matter.
8521       // In particular, the problem is that this function never gets called. It
8522       // might just be ill-formed because this function attempts to refer to
8523       // a deleted function here.
8524       if (Constructor)
8525         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8526     }
8527   }
8528 
8529   return ExceptSpec;
8530 }
8531 
8532 Sema::ImplicitExceptionSpecification
8533 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8534   CXXRecordDecl *ClassDecl = CD->getParent();
8535 
8536   // C++ [except.spec]p14:
8537   //   An inheriting constructor [...] shall have an exception-specification. [...]
8538   ImplicitExceptionSpecification ExceptSpec(*this);
8539   if (ClassDecl->isInvalidDecl())
8540     return ExceptSpec;
8541 
8542   // Inherited constructor.
8543   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8544   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8545   // FIXME: Copying or moving the parameters could add extra exceptions to the
8546   // set, as could the default arguments for the inherited constructor. This
8547   // will be addressed when we implement the resolution of core issue 1351.
8548   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8549 
8550   // Direct base-class constructors.
8551   for (const auto &B : ClassDecl->bases()) {
8552     if (B.isVirtual()) // Handled below.
8553       continue;
8554 
8555     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8556       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8557       if (BaseClassDecl == InheritedDecl)
8558         continue;
8559       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8560       if (Constructor)
8561         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8562     }
8563   }
8564 
8565   // Virtual base-class constructors.
8566   for (const auto &B : ClassDecl->vbases()) {
8567     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8568       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8569       if (BaseClassDecl == InheritedDecl)
8570         continue;
8571       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8572       if (Constructor)
8573         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8574     }
8575   }
8576 
8577   // Field constructors.
8578   for (const auto *F : ClassDecl->fields()) {
8579     if (F->hasInClassInitializer()) {
8580       if (Expr *E = F->getInClassInitializer())
8581         ExceptSpec.CalledExpr(E);
8582       else if (!F->isInvalidDecl())
8583         Diag(CD->getLocation(),
8584              diag::err_in_class_initializer_references_def_ctor) << CD;
8585     } else if (const RecordType *RecordTy
8586               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8587       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8588       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8589       if (Constructor)
8590         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8591     }
8592   }
8593 
8594   return ExceptSpec;
8595 }
8596 
8597 namespace {
8598 /// RAII object to register a special member as being currently declared.
8599 struct DeclaringSpecialMember {
8600   Sema &S;
8601   Sema::SpecialMemberDecl D;
8602   bool WasAlreadyBeingDeclared;
8603 
8604   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8605     : S(S), D(RD, CSM) {
8606     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8607     if (WasAlreadyBeingDeclared)
8608       // This almost never happens, but if it does, ensure that our cache
8609       // doesn't contain a stale result.
8610       S.SpecialMemberCache.clear();
8611 
8612     // FIXME: Register a note to be produced if we encounter an error while
8613     // declaring the special member.
8614   }
8615   ~DeclaringSpecialMember() {
8616     if (!WasAlreadyBeingDeclared)
8617       S.SpecialMembersBeingDeclared.erase(D);
8618   }
8619 
8620   /// \brief Are we already trying to declare this special member?
8621   bool isAlreadyBeingDeclared() const {
8622     return WasAlreadyBeingDeclared;
8623   }
8624 };
8625 }
8626 
8627 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8628                                                      CXXRecordDecl *ClassDecl) {
8629   // C++ [class.ctor]p5:
8630   //   A default constructor for a class X is a constructor of class X
8631   //   that can be called without an argument. If there is no
8632   //   user-declared constructor for class X, a default constructor is
8633   //   implicitly declared. An implicitly-declared default constructor
8634   //   is an inline public member of its class.
8635   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8636          "Should not build implicit default constructor!");
8637 
8638   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8639   if (DSM.isAlreadyBeingDeclared())
8640     return nullptr;
8641 
8642   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8643                                                      CXXDefaultConstructor,
8644                                                      false);
8645 
8646   // Create the actual constructor declaration.
8647   CanQualType ClassType
8648     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8649   SourceLocation ClassLoc = ClassDecl->getLocation();
8650   DeclarationName Name
8651     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8652   DeclarationNameInfo NameInfo(Name, ClassLoc);
8653   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8654       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8655       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8656       /*isImplicitlyDeclared=*/true, Constexpr);
8657   DefaultCon->setAccess(AS_public);
8658   DefaultCon->setDefaulted();
8659 
8660   if (getLangOpts().CUDA) {
8661     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8662                                             DefaultCon,
8663                                             /* ConstRHS */ false,
8664                                             /* Diagnose */ false);
8665   }
8666 
8667   // Build an exception specification pointing back at this constructor.
8668   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8669   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8670 
8671   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8672   // constructors is easy to compute.
8673   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8674 
8675   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8676     SetDeclDeleted(DefaultCon, ClassLoc);
8677 
8678   // Note that we have declared this constructor.
8679   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8680 
8681   if (Scope *S = getScopeForContext(ClassDecl))
8682     PushOnScopeChains(DefaultCon, S, false);
8683   ClassDecl->addDecl(DefaultCon);
8684 
8685   return DefaultCon;
8686 }
8687 
8688 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8689                                             CXXConstructorDecl *Constructor) {
8690   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8691           !Constructor->doesThisDeclarationHaveABody() &&
8692           !Constructor->isDeleted()) &&
8693     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8694 
8695   CXXRecordDecl *ClassDecl = Constructor->getParent();
8696   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8697 
8698   SynthesizedFunctionScope Scope(*this, Constructor);
8699   DiagnosticErrorTrap Trap(Diags);
8700   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8701       Trap.hasErrorOccurred()) {
8702     Diag(CurrentLocation, diag::note_member_synthesized_at)
8703       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8704     Constructor->setInvalidDecl();
8705     return;
8706   }
8707 
8708   // The exception specification is needed because we are defining the
8709   // function.
8710   ResolveExceptionSpec(CurrentLocation,
8711                        Constructor->getType()->castAs<FunctionProtoType>());
8712 
8713   SourceLocation Loc = Constructor->getLocEnd().isValid()
8714                            ? Constructor->getLocEnd()
8715                            : Constructor->getLocation();
8716   Constructor->setBody(new (Context) CompoundStmt(Loc));
8717 
8718   Constructor->markUsed(Context);
8719   MarkVTableUsed(CurrentLocation, ClassDecl);
8720 
8721   if (ASTMutationListener *L = getASTMutationListener()) {
8722     L->CompletedImplicitDefinition(Constructor);
8723   }
8724 
8725   DiagnoseUninitializedFields(*this, Constructor);
8726 }
8727 
8728 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8729   // Perform any delayed checks on exception specifications.
8730   CheckDelayedMemberExceptionSpecs();
8731 }
8732 
8733 namespace {
8734 /// Information on inheriting constructors to declare.
8735 class InheritingConstructorInfo {
8736 public:
8737   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8738       : SemaRef(SemaRef), Derived(Derived) {
8739     // Mark the constructors that we already have in the derived class.
8740     //
8741     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8742     //   unless there is a user-declared constructor with the same signature in
8743     //   the class where the using-declaration appears.
8744     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8745   }
8746 
8747   void inheritAll(CXXRecordDecl *RD) {
8748     visitAll(RD, &InheritingConstructorInfo::inherit);
8749   }
8750 
8751 private:
8752   /// Information about an inheriting constructor.
8753   struct InheritingConstructor {
8754     InheritingConstructor()
8755       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
8756 
8757     /// If \c true, a constructor with this signature is already declared
8758     /// in the derived class.
8759     bool DeclaredInDerived;
8760 
8761     /// The constructor which is inherited.
8762     const CXXConstructorDecl *BaseCtor;
8763 
8764     /// The derived constructor we declared.
8765     CXXConstructorDecl *DerivedCtor;
8766   };
8767 
8768   /// Inheriting constructors with a given canonical type. There can be at
8769   /// most one such non-template constructor, and any number of templated
8770   /// constructors.
8771   struct InheritingConstructorsForType {
8772     InheritingConstructor NonTemplate;
8773     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8774         Templates;
8775 
8776     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8777       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8778         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8779         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8780           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8781                                                false, S.TPL_TemplateMatch))
8782             return Templates[I].second;
8783         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8784         return Templates.back().second;
8785       }
8786 
8787       return NonTemplate;
8788     }
8789   };
8790 
8791   /// Get or create the inheriting constructor record for a constructor.
8792   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8793                                   QualType CtorType) {
8794     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8795         .getEntry(SemaRef, Ctor);
8796   }
8797 
8798   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8799 
8800   /// Process all constructors for a class.
8801   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8802     for (const auto *Ctor : RD->ctors())
8803       (this->*Callback)(Ctor);
8804     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8805              I(RD->decls_begin()), E(RD->decls_end());
8806          I != E; ++I) {
8807       const FunctionDecl *FD = (*I)->getTemplatedDecl();
8808       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8809         (this->*Callback)(CD);
8810     }
8811   }
8812 
8813   /// Note that a constructor (or constructor template) was declared in Derived.
8814   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8815     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8816   }
8817 
8818   /// Inherit a single constructor.
8819   void inherit(const CXXConstructorDecl *Ctor) {
8820     const FunctionProtoType *CtorType =
8821         Ctor->getType()->castAs<FunctionProtoType>();
8822     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
8823     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8824 
8825     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8826 
8827     // Core issue (no number yet): the ellipsis is always discarded.
8828     if (EPI.Variadic) {
8829       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8830       SemaRef.Diag(Ctor->getLocation(),
8831                    diag::note_using_decl_constructor_ellipsis);
8832       EPI.Variadic = false;
8833     }
8834 
8835     // Declare a constructor for each number of parameters.
8836     //
8837     // C++11 [class.inhctor]p1:
8838     //   The candidate set of inherited constructors from the class X named in
8839     //   the using-declaration consists of [... modulo defects ...] for each
8840     //   constructor or constructor template of X, the set of constructors or
8841     //   constructor templates that results from omitting any ellipsis parameter
8842     //   specification and successively omitting parameters with a default
8843     //   argument from the end of the parameter-type-list
8844     unsigned MinParams = minParamsToInherit(Ctor);
8845     unsigned Params = Ctor->getNumParams();
8846     if (Params >= MinParams) {
8847       do
8848         declareCtor(UsingLoc, Ctor,
8849                     SemaRef.Context.getFunctionType(
8850                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
8851       while (Params > MinParams &&
8852              Ctor->getParamDecl(--Params)->hasDefaultArg());
8853     }
8854   }
8855 
8856   /// Find the using-declaration which specified that we should inherit the
8857   /// constructors of \p Base.
8858   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8859     // No fancy lookup required; just look for the base constructor name
8860     // directly within the derived class.
8861     ASTContext &Context = SemaRef.Context;
8862     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8863         Context.getCanonicalType(Context.getRecordType(Base)));
8864     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8865     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8866   }
8867 
8868   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8869     // C++11 [class.inhctor]p3:
8870     //   [F]or each constructor template in the candidate set of inherited
8871     //   constructors, a constructor template is implicitly declared
8872     if (Ctor->getDescribedFunctionTemplate())
8873       return 0;
8874 
8875     //   For each non-template constructor in the candidate set of inherited
8876     //   constructors other than a constructor having no parameters or a
8877     //   copy/move constructor having a single parameter, a constructor is
8878     //   implicitly declared [...]
8879     if (Ctor->getNumParams() == 0)
8880       return 1;
8881     if (Ctor->isCopyOrMoveConstructor())
8882       return 2;
8883 
8884     // Per discussion on core reflector, never inherit a constructor which
8885     // would become a default, copy, or move constructor of Derived either.
8886     const ParmVarDecl *PD = Ctor->getParamDecl(0);
8887     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8888     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8889   }
8890 
8891   /// Declare a single inheriting constructor, inheriting the specified
8892   /// constructor, with the given type.
8893   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8894                    QualType DerivedType) {
8895     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8896 
8897     // C++11 [class.inhctor]p3:
8898     //   ... a constructor is implicitly declared with the same constructor
8899     //   characteristics unless there is a user-declared constructor with
8900     //   the same signature in the class where the using-declaration appears
8901     if (Entry.DeclaredInDerived)
8902       return;
8903 
8904     // C++11 [class.inhctor]p7:
8905     //   If two using-declarations declare inheriting constructors with the
8906     //   same signature, the program is ill-formed
8907     if (Entry.DerivedCtor) {
8908       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8909         // Only diagnose this once per constructor.
8910         if (Entry.DerivedCtor->isInvalidDecl())
8911           return;
8912         Entry.DerivedCtor->setInvalidDecl();
8913 
8914         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8915         SemaRef.Diag(BaseCtor->getLocation(),
8916                      diag::note_using_decl_constructor_conflict_current_ctor);
8917         SemaRef.Diag(Entry.BaseCtor->getLocation(),
8918                      diag::note_using_decl_constructor_conflict_previous_ctor);
8919         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8920                      diag::note_using_decl_constructor_conflict_previous_using);
8921       } else {
8922         // Core issue (no number): if the same inheriting constructor is
8923         // produced by multiple base class constructors from the same base
8924         // class, the inheriting constructor is defined as deleted.
8925         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8926       }
8927 
8928       return;
8929     }
8930 
8931     ASTContext &Context = SemaRef.Context;
8932     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8933         Context.getCanonicalType(Context.getRecordType(Derived)));
8934     DeclarationNameInfo NameInfo(Name, UsingLoc);
8935 
8936     TemplateParameterList *TemplateParams = nullptr;
8937     if (const FunctionTemplateDecl *FTD =
8938             BaseCtor->getDescribedFunctionTemplate()) {
8939       TemplateParams = FTD->getTemplateParameters();
8940       // We're reusing template parameters from a different DeclContext. This
8941       // is questionable at best, but works out because the template depth in
8942       // both places is guaranteed to be 0.
8943       // FIXME: Rebuild the template parameters in the new context, and
8944       // transform the function type to refer to them.
8945     }
8946 
8947     // Build type source info pointing at the using-declaration. This is
8948     // required by template instantiation.
8949     TypeSourceInfo *TInfo =
8950         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8951     FunctionProtoTypeLoc ProtoLoc =
8952         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8953 
8954     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8955         Context, Derived, UsingLoc, NameInfo, DerivedType,
8956         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8957         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8958 
8959     // Build an unevaluated exception specification for this constructor.
8960     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8961     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8962     EPI.ExceptionSpec.Type = EST_Unevaluated;
8963     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
8964     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
8965                                                  FPT->getParamTypes(), EPI));
8966 
8967     // Build the parameter declarations.
8968     SmallVector<ParmVarDecl *, 16> ParamDecls;
8969     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
8970       TypeSourceInfo *TInfo =
8971           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
8972       ParmVarDecl *PD = ParmVarDecl::Create(
8973           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8974           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
8975       PD->setScopeInfo(0, I);
8976       PD->setImplicit();
8977       ParamDecls.push_back(PD);
8978       ProtoLoc.setParam(I, PD);
8979     }
8980 
8981     // Set up the new constructor.
8982     DerivedCtor->setAccess(BaseCtor->getAccess());
8983     DerivedCtor->setParams(ParamDecls);
8984     DerivedCtor->setInheritedConstructor(BaseCtor);
8985     if (BaseCtor->isDeleted())
8986       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8987 
8988     // If this is a constructor template, build the template declaration.
8989     if (TemplateParams) {
8990       FunctionTemplateDecl *DerivedTemplate =
8991           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8992                                        TemplateParams, DerivedCtor);
8993       DerivedTemplate->setAccess(BaseCtor->getAccess());
8994       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8995       Derived->addDecl(DerivedTemplate);
8996     } else {
8997       Derived->addDecl(DerivedCtor);
8998     }
8999 
9000     Entry.BaseCtor = BaseCtor;
9001     Entry.DerivedCtor = DerivedCtor;
9002   }
9003 
9004   Sema &SemaRef;
9005   CXXRecordDecl *Derived;
9006   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9007   MapType Map;
9008 };
9009 }
9010 
9011 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9012   // Defer declaring the inheriting constructors until the class is
9013   // instantiated.
9014   if (ClassDecl->isDependentContext())
9015     return;
9016 
9017   // Find base classes from which we might inherit constructors.
9018   SmallVector<CXXRecordDecl*, 4> InheritedBases;
9019   for (const auto &BaseIt : ClassDecl->bases())
9020     if (BaseIt.getInheritConstructors())
9021       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9022 
9023   // Go no further if we're not inheriting any constructors.
9024   if (InheritedBases.empty())
9025     return;
9026 
9027   // Declare the inherited constructors.
9028   InheritingConstructorInfo ICI(*this, ClassDecl);
9029   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9030     ICI.inheritAll(InheritedBases[I]);
9031 }
9032 
9033 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9034                                        CXXConstructorDecl *Constructor) {
9035   CXXRecordDecl *ClassDecl = Constructor->getParent();
9036   assert(Constructor->getInheritedConstructor() &&
9037          !Constructor->doesThisDeclarationHaveABody() &&
9038          !Constructor->isDeleted());
9039 
9040   SynthesizedFunctionScope Scope(*this, Constructor);
9041   DiagnosticErrorTrap Trap(Diags);
9042   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9043       Trap.hasErrorOccurred()) {
9044     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9045       << Context.getTagDeclType(ClassDecl);
9046     Constructor->setInvalidDecl();
9047     return;
9048   }
9049 
9050   SourceLocation Loc = Constructor->getLocation();
9051   Constructor->setBody(new (Context) CompoundStmt(Loc));
9052 
9053   Constructor->markUsed(Context);
9054   MarkVTableUsed(CurrentLocation, ClassDecl);
9055 
9056   if (ASTMutationListener *L = getASTMutationListener()) {
9057     L->CompletedImplicitDefinition(Constructor);
9058   }
9059 }
9060 
9061 
9062 Sema::ImplicitExceptionSpecification
9063 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9064   CXXRecordDecl *ClassDecl = MD->getParent();
9065 
9066   // C++ [except.spec]p14:
9067   //   An implicitly declared special member function (Clause 12) shall have
9068   //   an exception-specification.
9069   ImplicitExceptionSpecification ExceptSpec(*this);
9070   if (ClassDecl->isInvalidDecl())
9071     return ExceptSpec;
9072 
9073   // Direct base-class destructors.
9074   for (const auto &B : ClassDecl->bases()) {
9075     if (B.isVirtual()) // Handled below.
9076       continue;
9077 
9078     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9079       ExceptSpec.CalledDecl(B.getLocStart(),
9080                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9081   }
9082 
9083   // Virtual base-class destructors.
9084   for (const auto &B : ClassDecl->vbases()) {
9085     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9086       ExceptSpec.CalledDecl(B.getLocStart(),
9087                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9088   }
9089 
9090   // Field destructors.
9091   for (const auto *F : ClassDecl->fields()) {
9092     if (const RecordType *RecordTy
9093         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9094       ExceptSpec.CalledDecl(F->getLocation(),
9095                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9096   }
9097 
9098   return ExceptSpec;
9099 }
9100 
9101 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9102   // C++ [class.dtor]p2:
9103   //   If a class has no user-declared destructor, a destructor is
9104   //   declared implicitly. An implicitly-declared destructor is an
9105   //   inline public member of its class.
9106   assert(ClassDecl->needsImplicitDestructor());
9107 
9108   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9109   if (DSM.isAlreadyBeingDeclared())
9110     return nullptr;
9111 
9112   // Create the actual destructor declaration.
9113   CanQualType ClassType
9114     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9115   SourceLocation ClassLoc = ClassDecl->getLocation();
9116   DeclarationName Name
9117     = Context.DeclarationNames.getCXXDestructorName(ClassType);
9118   DeclarationNameInfo NameInfo(Name, ClassLoc);
9119   CXXDestructorDecl *Destructor
9120       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9121                                   QualType(), nullptr, /*isInline=*/true,
9122                                   /*isImplicitlyDeclared=*/true);
9123   Destructor->setAccess(AS_public);
9124   Destructor->setDefaulted();
9125 
9126   if (getLangOpts().CUDA) {
9127     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9128                                             Destructor,
9129                                             /* ConstRHS */ false,
9130                                             /* Diagnose */ false);
9131   }
9132 
9133   // Build an exception specification pointing back at this destructor.
9134   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9135   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9136 
9137   AddOverriddenMethods(ClassDecl, Destructor);
9138 
9139   // We don't need to use SpecialMemberIsTrivial here; triviality for
9140   // destructors is easy to compute.
9141   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9142 
9143   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9144     SetDeclDeleted(Destructor, ClassLoc);
9145 
9146   // Note that we have declared this destructor.
9147   ++ASTContext::NumImplicitDestructorsDeclared;
9148 
9149   // Introduce this destructor into its scope.
9150   if (Scope *S = getScopeForContext(ClassDecl))
9151     PushOnScopeChains(Destructor, S, false);
9152   ClassDecl->addDecl(Destructor);
9153 
9154   return Destructor;
9155 }
9156 
9157 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9158                                     CXXDestructorDecl *Destructor) {
9159   assert((Destructor->isDefaulted() &&
9160           !Destructor->doesThisDeclarationHaveABody() &&
9161           !Destructor->isDeleted()) &&
9162          "DefineImplicitDestructor - call it for implicit default dtor");
9163   CXXRecordDecl *ClassDecl = Destructor->getParent();
9164   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9165 
9166   if (Destructor->isInvalidDecl())
9167     return;
9168 
9169   SynthesizedFunctionScope Scope(*this, Destructor);
9170 
9171   DiagnosticErrorTrap Trap(Diags);
9172   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9173                                          Destructor->getParent());
9174 
9175   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9176     Diag(CurrentLocation, diag::note_member_synthesized_at)
9177       << CXXDestructor << Context.getTagDeclType(ClassDecl);
9178 
9179     Destructor->setInvalidDecl();
9180     return;
9181   }
9182 
9183   // The exception specification is needed because we are defining the
9184   // function.
9185   ResolveExceptionSpec(CurrentLocation,
9186                        Destructor->getType()->castAs<FunctionProtoType>());
9187 
9188   SourceLocation Loc = Destructor->getLocEnd().isValid()
9189                            ? Destructor->getLocEnd()
9190                            : Destructor->getLocation();
9191   Destructor->setBody(new (Context) CompoundStmt(Loc));
9192   Destructor->markUsed(Context);
9193   MarkVTableUsed(CurrentLocation, ClassDecl);
9194 
9195   if (ASTMutationListener *L = getASTMutationListener()) {
9196     L->CompletedImplicitDefinition(Destructor);
9197   }
9198 }
9199 
9200 /// \brief Perform any semantic analysis which needs to be delayed until all
9201 /// pending class member declarations have been parsed.
9202 void Sema::ActOnFinishCXXMemberDecls() {
9203   // If the context is an invalid C++ class, just suppress these checks.
9204   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9205     if (Record->isInvalidDecl()) {
9206       DelayedDefaultedMemberExceptionSpecs.clear();
9207       DelayedDestructorExceptionSpecChecks.clear();
9208       return;
9209     }
9210   }
9211 }
9212 
9213 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9214                                          CXXDestructorDecl *Destructor) {
9215   assert(getLangOpts().CPlusPlus11 &&
9216          "adjusting dtor exception specs was introduced in c++11");
9217 
9218   // C++11 [class.dtor]p3:
9219   //   A declaration of a destructor that does not have an exception-
9220   //   specification is implicitly considered to have the same exception-
9221   //   specification as an implicit declaration.
9222   const FunctionProtoType *DtorType = Destructor->getType()->
9223                                         getAs<FunctionProtoType>();
9224   if (DtorType->hasExceptionSpec())
9225     return;
9226 
9227   // Replace the destructor's type, building off the existing one. Fortunately,
9228   // the only thing of interest in the destructor type is its extended info.
9229   // The return and arguments are fixed.
9230   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9231   EPI.ExceptionSpec.Type = EST_Unevaluated;
9232   EPI.ExceptionSpec.SourceDecl = Destructor;
9233   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9234 
9235   // FIXME: If the destructor has a body that could throw, and the newly created
9236   // spec doesn't allow exceptions, we should emit a warning, because this
9237   // change in behavior can break conforming C++03 programs at runtime.
9238   // However, we don't have a body or an exception specification yet, so it
9239   // needs to be done somewhere else.
9240 }
9241 
9242 namespace {
9243 /// \brief An abstract base class for all helper classes used in building the
9244 //  copy/move operators. These classes serve as factory functions and help us
9245 //  avoid using the same Expr* in the AST twice.
9246 class ExprBuilder {
9247   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9248   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9249 
9250 protected:
9251   static Expr *assertNotNull(Expr *E) {
9252     assert(E && "Expression construction must not fail.");
9253     return E;
9254   }
9255 
9256 public:
9257   ExprBuilder() {}
9258   virtual ~ExprBuilder() {}
9259 
9260   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9261 };
9262 
9263 class RefBuilder: public ExprBuilder {
9264   VarDecl *Var;
9265   QualType VarType;
9266 
9267 public:
9268   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9269     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9270   }
9271 
9272   RefBuilder(VarDecl *Var, QualType VarType)
9273       : Var(Var), VarType(VarType) {}
9274 };
9275 
9276 class ThisBuilder: public ExprBuilder {
9277 public:
9278   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9279     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9280   }
9281 };
9282 
9283 class CastBuilder: public ExprBuilder {
9284   const ExprBuilder &Builder;
9285   QualType Type;
9286   ExprValueKind Kind;
9287   const CXXCastPath &Path;
9288 
9289 public:
9290   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9291     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9292                                              CK_UncheckedDerivedToBase, Kind,
9293                                              &Path).get());
9294   }
9295 
9296   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9297               const CXXCastPath &Path)
9298       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9299 };
9300 
9301 class DerefBuilder: public ExprBuilder {
9302   const ExprBuilder &Builder;
9303 
9304 public:
9305   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9306     return assertNotNull(
9307         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9308   }
9309 
9310   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9311 };
9312 
9313 class MemberBuilder: public ExprBuilder {
9314   const ExprBuilder &Builder;
9315   QualType Type;
9316   CXXScopeSpec SS;
9317   bool IsArrow;
9318   LookupResult &MemberLookup;
9319 
9320 public:
9321   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9322     return assertNotNull(S.BuildMemberReferenceExpr(
9323         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9324         nullptr, MemberLookup, nullptr).get());
9325   }
9326 
9327   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9328                 LookupResult &MemberLookup)
9329       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9330         MemberLookup(MemberLookup) {}
9331 };
9332 
9333 class MoveCastBuilder: public ExprBuilder {
9334   const ExprBuilder &Builder;
9335 
9336 public:
9337   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9338     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9339   }
9340 
9341   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9342 };
9343 
9344 class LvalueConvBuilder: public ExprBuilder {
9345   const ExprBuilder &Builder;
9346 
9347 public:
9348   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9349     return assertNotNull(
9350         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9351   }
9352 
9353   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9354 };
9355 
9356 class SubscriptBuilder: public ExprBuilder {
9357   const ExprBuilder &Base;
9358   const ExprBuilder &Index;
9359 
9360 public:
9361   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9362     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9363         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9364   }
9365 
9366   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9367       : Base(Base), Index(Index) {}
9368 };
9369 
9370 } // end anonymous namespace
9371 
9372 /// When generating a defaulted copy or move assignment operator, if a field
9373 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9374 /// do so. This optimization only applies for arrays of scalars, and for arrays
9375 /// of class type where the selected copy/move-assignment operator is trivial.
9376 static StmtResult
9377 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9378                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9379   // Compute the size of the memory buffer to be copied.
9380   QualType SizeType = S.Context.getSizeType();
9381   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9382                    S.Context.getTypeSizeInChars(T).getQuantity());
9383 
9384   // Take the address of the field references for "from" and "to". We
9385   // directly construct UnaryOperators here because semantic analysis
9386   // does not permit us to take the address of an xvalue.
9387   Expr *From = FromB.build(S, Loc);
9388   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9389                          S.Context.getPointerType(From->getType()),
9390                          VK_RValue, OK_Ordinary, Loc);
9391   Expr *To = ToB.build(S, Loc);
9392   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9393                        S.Context.getPointerType(To->getType()),
9394                        VK_RValue, OK_Ordinary, Loc);
9395 
9396   const Type *E = T->getBaseElementTypeUnsafe();
9397   bool NeedsCollectableMemCpy =
9398     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9399 
9400   // Create a reference to the __builtin_objc_memmove_collectable function
9401   StringRef MemCpyName = NeedsCollectableMemCpy ?
9402     "__builtin_objc_memmove_collectable" :
9403     "__builtin_memcpy";
9404   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9405                  Sema::LookupOrdinaryName);
9406   S.LookupName(R, S.TUScope, true);
9407 
9408   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9409   if (!MemCpy)
9410     // Something went horribly wrong earlier, and we will have complained
9411     // about it.
9412     return StmtError();
9413 
9414   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9415                                             VK_RValue, Loc, nullptr);
9416   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9417 
9418   Expr *CallArgs[] = {
9419     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9420   };
9421   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9422                                     Loc, CallArgs, Loc);
9423 
9424   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9425   return Call.getAs<Stmt>();
9426 }
9427 
9428 /// \brief Builds a statement that copies/moves the given entity from \p From to
9429 /// \c To.
9430 ///
9431 /// This routine is used to copy/move the members of a class with an
9432 /// implicitly-declared copy/move assignment operator. When the entities being
9433 /// copied are arrays, this routine builds for loops to copy them.
9434 ///
9435 /// \param S The Sema object used for type-checking.
9436 ///
9437 /// \param Loc The location where the implicit copy/move is being generated.
9438 ///
9439 /// \param T The type of the expressions being copied/moved. Both expressions
9440 /// must have this type.
9441 ///
9442 /// \param To The expression we are copying/moving to.
9443 ///
9444 /// \param From The expression we are copying/moving from.
9445 ///
9446 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9447 /// Otherwise, it's a non-static member subobject.
9448 ///
9449 /// \param Copying Whether we're copying or moving.
9450 ///
9451 /// \param Depth Internal parameter recording the depth of the recursion.
9452 ///
9453 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9454 /// if a memcpy should be used instead.
9455 static StmtResult
9456 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9457                                  const ExprBuilder &To, const ExprBuilder &From,
9458                                  bool CopyingBaseSubobject, bool Copying,
9459                                  unsigned Depth = 0) {
9460   // C++11 [class.copy]p28:
9461   //   Each subobject is assigned in the manner appropriate to its type:
9462   //
9463   //     - if the subobject is of class type, as if by a call to operator= with
9464   //       the subobject as the object expression and the corresponding
9465   //       subobject of x as a single function argument (as if by explicit
9466   //       qualification; that is, ignoring any possible virtual overriding
9467   //       functions in more derived classes);
9468   //
9469   // C++03 [class.copy]p13:
9470   //     - if the subobject is of class type, the copy assignment operator for
9471   //       the class is used (as if by explicit qualification; that is,
9472   //       ignoring any possible virtual overriding functions in more derived
9473   //       classes);
9474   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9475     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9476 
9477     // Look for operator=.
9478     DeclarationName Name
9479       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9480     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9481     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9482 
9483     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9484     // operator.
9485     if (!S.getLangOpts().CPlusPlus11) {
9486       LookupResult::Filter F = OpLookup.makeFilter();
9487       while (F.hasNext()) {
9488         NamedDecl *D = F.next();
9489         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9490           if (Method->isCopyAssignmentOperator() ||
9491               (!Copying && Method->isMoveAssignmentOperator()))
9492             continue;
9493 
9494         F.erase();
9495       }
9496       F.done();
9497     }
9498 
9499     // Suppress the protected check (C++ [class.protected]) for each of the
9500     // assignment operators we found. This strange dance is required when
9501     // we're assigning via a base classes's copy-assignment operator. To
9502     // ensure that we're getting the right base class subobject (without
9503     // ambiguities), we need to cast "this" to that subobject type; to
9504     // ensure that we don't go through the virtual call mechanism, we need
9505     // to qualify the operator= name with the base class (see below). However,
9506     // this means that if the base class has a protected copy assignment
9507     // operator, the protected member access check will fail. So, we
9508     // rewrite "protected" access to "public" access in this case, since we
9509     // know by construction that we're calling from a derived class.
9510     if (CopyingBaseSubobject) {
9511       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9512            L != LEnd; ++L) {
9513         if (L.getAccess() == AS_protected)
9514           L.setAccess(AS_public);
9515       }
9516     }
9517 
9518     // Create the nested-name-specifier that will be used to qualify the
9519     // reference to operator=; this is required to suppress the virtual
9520     // call mechanism.
9521     CXXScopeSpec SS;
9522     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9523     SS.MakeTrivial(S.Context,
9524                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9525                                                CanonicalT),
9526                    Loc);
9527 
9528     // Create the reference to operator=.
9529     ExprResult OpEqualRef
9530       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9531                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9532                                    /*FirstQualifierInScope=*/nullptr,
9533                                    OpLookup,
9534                                    /*TemplateArgs=*/nullptr,
9535                                    /*SuppressQualifierCheck=*/true);
9536     if (OpEqualRef.isInvalid())
9537       return StmtError();
9538 
9539     // Build the call to the assignment operator.
9540 
9541     Expr *FromInst = From.build(S, Loc);
9542     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9543                                                   OpEqualRef.getAs<Expr>(),
9544                                                   Loc, FromInst, Loc);
9545     if (Call.isInvalid())
9546       return StmtError();
9547 
9548     // If we built a call to a trivial 'operator=' while copying an array,
9549     // bail out. We'll replace the whole shebang with a memcpy.
9550     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9551     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9552       return StmtResult((Stmt*)nullptr);
9553 
9554     // Convert to an expression-statement, and clean up any produced
9555     // temporaries.
9556     return S.ActOnExprStmt(Call);
9557   }
9558 
9559   //     - if the subobject is of scalar type, the built-in assignment
9560   //       operator is used.
9561   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9562   if (!ArrayTy) {
9563     ExprResult Assignment = S.CreateBuiltinBinOp(
9564         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9565     if (Assignment.isInvalid())
9566       return StmtError();
9567     return S.ActOnExprStmt(Assignment);
9568   }
9569 
9570   //     - if the subobject is an array, each element is assigned, in the
9571   //       manner appropriate to the element type;
9572 
9573   // Construct a loop over the array bounds, e.g.,
9574   //
9575   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9576   //
9577   // that will copy each of the array elements.
9578   QualType SizeType = S.Context.getSizeType();
9579 
9580   // Create the iteration variable.
9581   IdentifierInfo *IterationVarName = nullptr;
9582   {
9583     SmallString<8> Str;
9584     llvm::raw_svector_ostream OS(Str);
9585     OS << "__i" << Depth;
9586     IterationVarName = &S.Context.Idents.get(OS.str());
9587   }
9588   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9589                                           IterationVarName, SizeType,
9590                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9591                                           SC_None);
9592 
9593   // Initialize the iteration variable to zero.
9594   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9595   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9596 
9597   // Creates a reference to the iteration variable.
9598   RefBuilder IterationVarRef(IterationVar, SizeType);
9599   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9600 
9601   // Create the DeclStmt that holds the iteration variable.
9602   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9603 
9604   // Subscript the "from" and "to" expressions with the iteration variable.
9605   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9606   MoveCastBuilder FromIndexMove(FromIndexCopy);
9607   const ExprBuilder *FromIndex;
9608   if (Copying)
9609     FromIndex = &FromIndexCopy;
9610   else
9611     FromIndex = &FromIndexMove;
9612 
9613   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9614 
9615   // Build the copy/move for an individual element of the array.
9616   StmtResult Copy =
9617     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9618                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9619                                      Copying, Depth + 1);
9620   // Bail out if copying fails or if we determined that we should use memcpy.
9621   if (Copy.isInvalid() || !Copy.get())
9622     return Copy;
9623 
9624   // Create the comparison against the array bound.
9625   llvm::APInt Upper
9626     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9627   Expr *Comparison
9628     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9629                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9630                                      BO_NE, S.Context.BoolTy,
9631                                      VK_RValue, OK_Ordinary, Loc, false);
9632 
9633   // Create the pre-increment of the iteration variable.
9634   Expr *Increment
9635     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9636                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9637 
9638   // Construct the loop that copies all elements of this array.
9639   return S.ActOnForStmt(Loc, Loc, InitStmt,
9640                         S.MakeFullExpr(Comparison),
9641                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9642                         Loc, Copy.get());
9643 }
9644 
9645 static StmtResult
9646 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9647                       const ExprBuilder &To, const ExprBuilder &From,
9648                       bool CopyingBaseSubobject, bool Copying) {
9649   // Maybe we should use a memcpy?
9650   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9651       T.isTriviallyCopyableType(S.Context))
9652     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9653 
9654   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9655                                                      CopyingBaseSubobject,
9656                                                      Copying, 0));
9657 
9658   // If we ended up picking a trivial assignment operator for an array of a
9659   // non-trivially-copyable class type, just emit a memcpy.
9660   if (!Result.isInvalid() && !Result.get())
9661     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9662 
9663   return Result;
9664 }
9665 
9666 Sema::ImplicitExceptionSpecification
9667 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9668   CXXRecordDecl *ClassDecl = MD->getParent();
9669 
9670   ImplicitExceptionSpecification ExceptSpec(*this);
9671   if (ClassDecl->isInvalidDecl())
9672     return ExceptSpec;
9673 
9674   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9675   assert(T->getNumParams() == 1 && "not a copy assignment op");
9676   unsigned ArgQuals =
9677       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9678 
9679   // C++ [except.spec]p14:
9680   //   An implicitly declared special member function (Clause 12) shall have an
9681   //   exception-specification. [...]
9682 
9683   // It is unspecified whether or not an implicit copy assignment operator
9684   // attempts to deduplicate calls to assignment operators of virtual bases are
9685   // made. As such, this exception specification is effectively unspecified.
9686   // Based on a similar decision made for constness in C++0x, we're erring on
9687   // the side of assuming such calls to be made regardless of whether they
9688   // actually happen.
9689   for (const auto &Base : ClassDecl->bases()) {
9690     if (Base.isVirtual())
9691       continue;
9692 
9693     CXXRecordDecl *BaseClassDecl
9694       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9695     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9696                                                             ArgQuals, false, 0))
9697       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9698   }
9699 
9700   for (const auto &Base : ClassDecl->vbases()) {
9701     CXXRecordDecl *BaseClassDecl
9702       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9703     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9704                                                             ArgQuals, false, 0))
9705       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9706   }
9707 
9708   for (const auto *Field : ClassDecl->fields()) {
9709     QualType FieldType = Context.getBaseElementType(Field->getType());
9710     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9711       if (CXXMethodDecl *CopyAssign =
9712           LookupCopyingAssignment(FieldClassDecl,
9713                                   ArgQuals | FieldType.getCVRQualifiers(),
9714                                   false, 0))
9715         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9716     }
9717   }
9718 
9719   return ExceptSpec;
9720 }
9721 
9722 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9723   // Note: The following rules are largely analoguous to the copy
9724   // constructor rules. Note that virtual bases are not taken into account
9725   // for determining the argument type of the operator. Note also that
9726   // operators taking an object instead of a reference are allowed.
9727   assert(ClassDecl->needsImplicitCopyAssignment());
9728 
9729   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9730   if (DSM.isAlreadyBeingDeclared())
9731     return nullptr;
9732 
9733   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9734   QualType RetType = Context.getLValueReferenceType(ArgType);
9735   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9736   if (Const)
9737     ArgType = ArgType.withConst();
9738   ArgType = Context.getLValueReferenceType(ArgType);
9739 
9740   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9741                                                      CXXCopyAssignment,
9742                                                      Const);
9743 
9744   //   An implicitly-declared copy assignment operator is an inline public
9745   //   member of its class.
9746   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9747   SourceLocation ClassLoc = ClassDecl->getLocation();
9748   DeclarationNameInfo NameInfo(Name, ClassLoc);
9749   CXXMethodDecl *CopyAssignment =
9750       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9751                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9752                             /*isInline=*/true, Constexpr, SourceLocation());
9753   CopyAssignment->setAccess(AS_public);
9754   CopyAssignment->setDefaulted();
9755   CopyAssignment->setImplicit();
9756 
9757   if (getLangOpts().CUDA) {
9758     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
9759                                             CopyAssignment,
9760                                             /* ConstRHS */ Const,
9761                                             /* Diagnose */ false);
9762   }
9763 
9764   // Build an exception specification pointing back at this member.
9765   FunctionProtoType::ExtProtoInfo EPI =
9766       getImplicitMethodEPI(*this, CopyAssignment);
9767   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9768 
9769   // Add the parameter to the operator.
9770   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9771                                                ClassLoc, ClassLoc,
9772                                                /*Id=*/nullptr, ArgType,
9773                                                /*TInfo=*/nullptr, SC_None,
9774                                                nullptr);
9775   CopyAssignment->setParams(FromParam);
9776 
9777   AddOverriddenMethods(ClassDecl, CopyAssignment);
9778 
9779   CopyAssignment->setTrivial(
9780     ClassDecl->needsOverloadResolutionForCopyAssignment()
9781       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9782       : ClassDecl->hasTrivialCopyAssignment());
9783 
9784   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9785     SetDeclDeleted(CopyAssignment, ClassLoc);
9786 
9787   // Note that we have added this copy-assignment operator.
9788   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9789 
9790   if (Scope *S = getScopeForContext(ClassDecl))
9791     PushOnScopeChains(CopyAssignment, S, false);
9792   ClassDecl->addDecl(CopyAssignment);
9793 
9794   return CopyAssignment;
9795 }
9796 
9797 /// Diagnose an implicit copy operation for a class which is odr-used, but
9798 /// which is deprecated because the class has a user-declared copy constructor,
9799 /// copy assignment operator, or destructor.
9800 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9801                                             SourceLocation UseLoc) {
9802   assert(CopyOp->isImplicit());
9803 
9804   CXXRecordDecl *RD = CopyOp->getParent();
9805   CXXMethodDecl *UserDeclaredOperation = nullptr;
9806 
9807   // In Microsoft mode, assignment operations don't affect constructors and
9808   // vice versa.
9809   if (RD->hasUserDeclaredDestructor()) {
9810     UserDeclaredOperation = RD->getDestructor();
9811   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9812              RD->hasUserDeclaredCopyConstructor() &&
9813              !S.getLangOpts().MSVCCompat) {
9814     // Find any user-declared copy constructor.
9815     for (auto *I : RD->ctors()) {
9816       if (I->isCopyConstructor()) {
9817         UserDeclaredOperation = I;
9818         break;
9819       }
9820     }
9821     assert(UserDeclaredOperation);
9822   } else if (isa<CXXConstructorDecl>(CopyOp) &&
9823              RD->hasUserDeclaredCopyAssignment() &&
9824              !S.getLangOpts().MSVCCompat) {
9825     // Find any user-declared move assignment operator.
9826     for (auto *I : RD->methods()) {
9827       if (I->isCopyAssignmentOperator()) {
9828         UserDeclaredOperation = I;
9829         break;
9830       }
9831     }
9832     assert(UserDeclaredOperation);
9833   }
9834 
9835   if (UserDeclaredOperation) {
9836     S.Diag(UserDeclaredOperation->getLocation(),
9837          diag::warn_deprecated_copy_operation)
9838       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9839       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9840     S.Diag(UseLoc, diag::note_member_synthesized_at)
9841       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9842                                           : Sema::CXXCopyAssignment)
9843       << RD;
9844   }
9845 }
9846 
9847 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9848                                         CXXMethodDecl *CopyAssignOperator) {
9849   assert((CopyAssignOperator->isDefaulted() &&
9850           CopyAssignOperator->isOverloadedOperator() &&
9851           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9852           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9853           !CopyAssignOperator->isDeleted()) &&
9854          "DefineImplicitCopyAssignment called for wrong function");
9855 
9856   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9857 
9858   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9859     CopyAssignOperator->setInvalidDecl();
9860     return;
9861   }
9862 
9863   // C++11 [class.copy]p18:
9864   //   The [definition of an implicitly declared copy assignment operator] is
9865   //   deprecated if the class has a user-declared copy constructor or a
9866   //   user-declared destructor.
9867   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9868     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9869 
9870   CopyAssignOperator->markUsed(Context);
9871 
9872   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9873   DiagnosticErrorTrap Trap(Diags);
9874 
9875   // C++0x [class.copy]p30:
9876   //   The implicitly-defined or explicitly-defaulted copy assignment operator
9877   //   for a non-union class X performs memberwise copy assignment of its
9878   //   subobjects. The direct base classes of X are assigned first, in the
9879   //   order of their declaration in the base-specifier-list, and then the
9880   //   immediate non-static data members of X are assigned, in the order in
9881   //   which they were declared in the class definition.
9882 
9883   // The statements that form the synthesized function body.
9884   SmallVector<Stmt*, 8> Statements;
9885 
9886   // The parameter for the "other" object, which we are copying from.
9887   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9888   Qualifiers OtherQuals = Other->getType().getQualifiers();
9889   QualType OtherRefType = Other->getType();
9890   if (const LValueReferenceType *OtherRef
9891                                 = OtherRefType->getAs<LValueReferenceType>()) {
9892     OtherRefType = OtherRef->getPointeeType();
9893     OtherQuals = OtherRefType.getQualifiers();
9894   }
9895 
9896   // Our location for everything implicitly-generated.
9897   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9898                            ? CopyAssignOperator->getLocEnd()
9899                            : CopyAssignOperator->getLocation();
9900 
9901   // Builds a DeclRefExpr for the "other" object.
9902   RefBuilder OtherRef(Other, OtherRefType);
9903 
9904   // Builds the "this" pointer.
9905   ThisBuilder This;
9906 
9907   // Assign base classes.
9908   bool Invalid = false;
9909   for (auto &Base : ClassDecl->bases()) {
9910     // Form the assignment:
9911     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9912     QualType BaseType = Base.getType().getUnqualifiedType();
9913     if (!BaseType->isRecordType()) {
9914       Invalid = true;
9915       continue;
9916     }
9917 
9918     CXXCastPath BasePath;
9919     BasePath.push_back(&Base);
9920 
9921     // Construct the "from" expression, which is an implicit cast to the
9922     // appropriately-qualified base type.
9923     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9924                      VK_LValue, BasePath);
9925 
9926     // Dereference "this".
9927     DerefBuilder DerefThis(This);
9928     CastBuilder To(DerefThis,
9929                    Context.getCVRQualifiedType(
9930                        BaseType, CopyAssignOperator->getTypeQualifiers()),
9931                    VK_LValue, BasePath);
9932 
9933     // Build the copy.
9934     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9935                                             To, From,
9936                                             /*CopyingBaseSubobject=*/true,
9937                                             /*Copying=*/true);
9938     if (Copy.isInvalid()) {
9939       Diag(CurrentLocation, diag::note_member_synthesized_at)
9940         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9941       CopyAssignOperator->setInvalidDecl();
9942       return;
9943     }
9944 
9945     // Success! Record the copy.
9946     Statements.push_back(Copy.getAs<Expr>());
9947   }
9948 
9949   // Assign non-static members.
9950   for (auto *Field : ClassDecl->fields()) {
9951     if (Field->isUnnamedBitfield())
9952       continue;
9953 
9954     if (Field->isInvalidDecl()) {
9955       Invalid = true;
9956       continue;
9957     }
9958 
9959     // Check for members of reference type; we can't copy those.
9960     if (Field->getType()->isReferenceType()) {
9961       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9962         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9963       Diag(Field->getLocation(), diag::note_declared_at);
9964       Diag(CurrentLocation, diag::note_member_synthesized_at)
9965         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9966       Invalid = true;
9967       continue;
9968     }
9969 
9970     // Check for members of const-qualified, non-class type.
9971     QualType BaseType = Context.getBaseElementType(Field->getType());
9972     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9973       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9974         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9975       Diag(Field->getLocation(), diag::note_declared_at);
9976       Diag(CurrentLocation, diag::note_member_synthesized_at)
9977         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9978       Invalid = true;
9979       continue;
9980     }
9981 
9982     // Suppress assigning zero-width bitfields.
9983     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9984       continue;
9985 
9986     QualType FieldType = Field->getType().getNonReferenceType();
9987     if (FieldType->isIncompleteArrayType()) {
9988       assert(ClassDecl->hasFlexibleArrayMember() &&
9989              "Incomplete array type is not valid");
9990       continue;
9991     }
9992 
9993     // Build references to the field in the object we're copying from and to.
9994     CXXScopeSpec SS; // Intentionally empty
9995     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9996                               LookupMemberName);
9997     MemberLookup.addDecl(Field);
9998     MemberLookup.resolveKind();
9999 
10000     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10001 
10002     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10003 
10004     // Build the copy of this field.
10005     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10006                                             To, From,
10007                                             /*CopyingBaseSubobject=*/false,
10008                                             /*Copying=*/true);
10009     if (Copy.isInvalid()) {
10010       Diag(CurrentLocation, diag::note_member_synthesized_at)
10011         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10012       CopyAssignOperator->setInvalidDecl();
10013       return;
10014     }
10015 
10016     // Success! Record the copy.
10017     Statements.push_back(Copy.getAs<Stmt>());
10018   }
10019 
10020   if (!Invalid) {
10021     // Add a "return *this;"
10022     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10023 
10024     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10025     if (Return.isInvalid())
10026       Invalid = true;
10027     else {
10028       Statements.push_back(Return.getAs<Stmt>());
10029 
10030       if (Trap.hasErrorOccurred()) {
10031         Diag(CurrentLocation, diag::note_member_synthesized_at)
10032           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10033         Invalid = true;
10034       }
10035     }
10036   }
10037 
10038   // The exception specification is needed because we are defining the
10039   // function.
10040   ResolveExceptionSpec(CurrentLocation,
10041                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10042 
10043   if (Invalid) {
10044     CopyAssignOperator->setInvalidDecl();
10045     return;
10046   }
10047 
10048   StmtResult Body;
10049   {
10050     CompoundScopeRAII CompoundScope(*this);
10051     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10052                              /*isStmtExpr=*/false);
10053     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10054   }
10055   CopyAssignOperator->setBody(Body.getAs<Stmt>());
10056 
10057   if (ASTMutationListener *L = getASTMutationListener()) {
10058     L->CompletedImplicitDefinition(CopyAssignOperator);
10059   }
10060 }
10061 
10062 Sema::ImplicitExceptionSpecification
10063 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10064   CXXRecordDecl *ClassDecl = MD->getParent();
10065 
10066   ImplicitExceptionSpecification ExceptSpec(*this);
10067   if (ClassDecl->isInvalidDecl())
10068     return ExceptSpec;
10069 
10070   // C++0x [except.spec]p14:
10071   //   An implicitly declared special member function (Clause 12) shall have an
10072   //   exception-specification. [...]
10073 
10074   // It is unspecified whether or not an implicit move assignment operator
10075   // attempts to deduplicate calls to assignment operators of virtual bases are
10076   // made. As such, this exception specification is effectively unspecified.
10077   // Based on a similar decision made for constness in C++0x, we're erring on
10078   // the side of assuming such calls to be made regardless of whether they
10079   // actually happen.
10080   // Note that a move constructor is not implicitly declared when there are
10081   // virtual bases, but it can still be user-declared and explicitly defaulted.
10082   for (const auto &Base : ClassDecl->bases()) {
10083     if (Base.isVirtual())
10084       continue;
10085 
10086     CXXRecordDecl *BaseClassDecl
10087       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10088     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10089                                                            0, false, 0))
10090       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10091   }
10092 
10093   for (const auto &Base : ClassDecl->vbases()) {
10094     CXXRecordDecl *BaseClassDecl
10095       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10096     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10097                                                            0, false, 0))
10098       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10099   }
10100 
10101   for (const auto *Field : ClassDecl->fields()) {
10102     QualType FieldType = Context.getBaseElementType(Field->getType());
10103     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10104       if (CXXMethodDecl *MoveAssign =
10105               LookupMovingAssignment(FieldClassDecl,
10106                                      FieldType.getCVRQualifiers(),
10107                                      false, 0))
10108         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10109     }
10110   }
10111 
10112   return ExceptSpec;
10113 }
10114 
10115 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10116   assert(ClassDecl->needsImplicitMoveAssignment());
10117 
10118   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10119   if (DSM.isAlreadyBeingDeclared())
10120     return nullptr;
10121 
10122   // Note: The following rules are largely analoguous to the move
10123   // constructor rules.
10124 
10125   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10126   QualType RetType = Context.getLValueReferenceType(ArgType);
10127   ArgType = Context.getRValueReferenceType(ArgType);
10128 
10129   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10130                                                      CXXMoveAssignment,
10131                                                      false);
10132 
10133   //   An implicitly-declared move assignment operator is an inline public
10134   //   member of its class.
10135   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10136   SourceLocation ClassLoc = ClassDecl->getLocation();
10137   DeclarationNameInfo NameInfo(Name, ClassLoc);
10138   CXXMethodDecl *MoveAssignment =
10139       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10140                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10141                             /*isInline=*/true, Constexpr, SourceLocation());
10142   MoveAssignment->setAccess(AS_public);
10143   MoveAssignment->setDefaulted();
10144   MoveAssignment->setImplicit();
10145 
10146   if (getLangOpts().CUDA) {
10147     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10148                                             MoveAssignment,
10149                                             /* ConstRHS */ false,
10150                                             /* Diagnose */ false);
10151   }
10152 
10153   // Build an exception specification pointing back at this member.
10154   FunctionProtoType::ExtProtoInfo EPI =
10155       getImplicitMethodEPI(*this, MoveAssignment);
10156   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10157 
10158   // Add the parameter to the operator.
10159   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10160                                                ClassLoc, ClassLoc,
10161                                                /*Id=*/nullptr, ArgType,
10162                                                /*TInfo=*/nullptr, SC_None,
10163                                                nullptr);
10164   MoveAssignment->setParams(FromParam);
10165 
10166   AddOverriddenMethods(ClassDecl, MoveAssignment);
10167 
10168   MoveAssignment->setTrivial(
10169     ClassDecl->needsOverloadResolutionForMoveAssignment()
10170       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10171       : ClassDecl->hasTrivialMoveAssignment());
10172 
10173   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10174     ClassDecl->setImplicitMoveAssignmentIsDeleted();
10175     SetDeclDeleted(MoveAssignment, ClassLoc);
10176   }
10177 
10178   // Note that we have added this copy-assignment operator.
10179   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10180 
10181   if (Scope *S = getScopeForContext(ClassDecl))
10182     PushOnScopeChains(MoveAssignment, S, false);
10183   ClassDecl->addDecl(MoveAssignment);
10184 
10185   return MoveAssignment;
10186 }
10187 
10188 /// Check if we're implicitly defining a move assignment operator for a class
10189 /// with virtual bases. Such a move assignment might move-assign the virtual
10190 /// base multiple times.
10191 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10192                                                SourceLocation CurrentLocation) {
10193   assert(!Class->isDependentContext() && "should not define dependent move");
10194 
10195   // Only a virtual base could get implicitly move-assigned multiple times.
10196   // Only a non-trivial move assignment can observe this. We only want to
10197   // diagnose if we implicitly define an assignment operator that assigns
10198   // two base classes, both of which move-assign the same virtual base.
10199   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10200       Class->getNumBases() < 2)
10201     return;
10202 
10203   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10204   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10205   VBaseMap VBases;
10206 
10207   for (auto &BI : Class->bases()) {
10208     Worklist.push_back(&BI);
10209     while (!Worklist.empty()) {
10210       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10211       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10212 
10213       // If the base has no non-trivial move assignment operators,
10214       // we don't care about moves from it.
10215       if (!Base->hasNonTrivialMoveAssignment())
10216         continue;
10217 
10218       // If there's nothing virtual here, skip it.
10219       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10220         continue;
10221 
10222       // If we're not actually going to call a move assignment for this base,
10223       // or the selected move assignment is trivial, skip it.
10224       Sema::SpecialMemberOverloadResult *SMOR =
10225         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10226                               /*ConstArg*/false, /*VolatileArg*/false,
10227                               /*RValueThis*/true, /*ConstThis*/false,
10228                               /*VolatileThis*/false);
10229       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10230           !SMOR->getMethod()->isMoveAssignmentOperator())
10231         continue;
10232 
10233       if (BaseSpec->isVirtual()) {
10234         // We're going to move-assign this virtual base, and its move
10235         // assignment operator is not trivial. If this can happen for
10236         // multiple distinct direct bases of Class, diagnose it. (If it
10237         // only happens in one base, we'll diagnose it when synthesizing
10238         // that base class's move assignment operator.)
10239         CXXBaseSpecifier *&Existing =
10240             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10241                 .first->second;
10242         if (Existing && Existing != &BI) {
10243           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10244             << Class << Base;
10245           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10246             << (Base->getCanonicalDecl() ==
10247                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10248             << Base << Existing->getType() << Existing->getSourceRange();
10249           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10250             << (Base->getCanonicalDecl() ==
10251                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10252             << Base << BI.getType() << BaseSpec->getSourceRange();
10253 
10254           // Only diagnose each vbase once.
10255           Existing = nullptr;
10256         }
10257       } else {
10258         // Only walk over bases that have defaulted move assignment operators.
10259         // We assume that any user-provided move assignment operator handles
10260         // the multiple-moves-of-vbase case itself somehow.
10261         if (!SMOR->getMethod()->isDefaulted())
10262           continue;
10263 
10264         // We're going to move the base classes of Base. Add them to the list.
10265         for (auto &BI : Base->bases())
10266           Worklist.push_back(&BI);
10267       }
10268     }
10269   }
10270 }
10271 
10272 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10273                                         CXXMethodDecl *MoveAssignOperator) {
10274   assert((MoveAssignOperator->isDefaulted() &&
10275           MoveAssignOperator->isOverloadedOperator() &&
10276           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10277           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10278           !MoveAssignOperator->isDeleted()) &&
10279          "DefineImplicitMoveAssignment called for wrong function");
10280 
10281   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10282 
10283   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10284     MoveAssignOperator->setInvalidDecl();
10285     return;
10286   }
10287 
10288   MoveAssignOperator->markUsed(Context);
10289 
10290   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10291   DiagnosticErrorTrap Trap(Diags);
10292 
10293   // C++0x [class.copy]p28:
10294   //   The implicitly-defined or move assignment operator for a non-union class
10295   //   X performs memberwise move assignment of its subobjects. The direct base
10296   //   classes of X are assigned first, in the order of their declaration in the
10297   //   base-specifier-list, and then the immediate non-static data members of X
10298   //   are assigned, in the order in which they were declared in the class
10299   //   definition.
10300 
10301   // Issue a warning if our implicit move assignment operator will move
10302   // from a virtual base more than once.
10303   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10304 
10305   // The statements that form the synthesized function body.
10306   SmallVector<Stmt*, 8> Statements;
10307 
10308   // The parameter for the "other" object, which we are move from.
10309   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10310   QualType OtherRefType = Other->getType()->
10311       getAs<RValueReferenceType>()->getPointeeType();
10312   assert(!OtherRefType.getQualifiers() &&
10313          "Bad argument type of defaulted move assignment");
10314 
10315   // Our location for everything implicitly-generated.
10316   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10317                            ? MoveAssignOperator->getLocEnd()
10318                            : MoveAssignOperator->getLocation();
10319 
10320   // Builds a reference to the "other" object.
10321   RefBuilder OtherRef(Other, OtherRefType);
10322   // Cast to rvalue.
10323   MoveCastBuilder MoveOther(OtherRef);
10324 
10325   // Builds the "this" pointer.
10326   ThisBuilder This;
10327 
10328   // Assign base classes.
10329   bool Invalid = false;
10330   for (auto &Base : ClassDecl->bases()) {
10331     // C++11 [class.copy]p28:
10332     //   It is unspecified whether subobjects representing virtual base classes
10333     //   are assigned more than once by the implicitly-defined copy assignment
10334     //   operator.
10335     // FIXME: Do not assign to a vbase that will be assigned by some other base
10336     // class. For a move-assignment, this can result in the vbase being moved
10337     // multiple times.
10338 
10339     // Form the assignment:
10340     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10341     QualType BaseType = Base.getType().getUnqualifiedType();
10342     if (!BaseType->isRecordType()) {
10343       Invalid = true;
10344       continue;
10345     }
10346 
10347     CXXCastPath BasePath;
10348     BasePath.push_back(&Base);
10349 
10350     // Construct the "from" expression, which is an implicit cast to the
10351     // appropriately-qualified base type.
10352     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10353 
10354     // Dereference "this".
10355     DerefBuilder DerefThis(This);
10356 
10357     // Implicitly cast "this" to the appropriately-qualified base type.
10358     CastBuilder To(DerefThis,
10359                    Context.getCVRQualifiedType(
10360                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10361                    VK_LValue, BasePath);
10362 
10363     // Build the move.
10364     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10365                                             To, From,
10366                                             /*CopyingBaseSubobject=*/true,
10367                                             /*Copying=*/false);
10368     if (Move.isInvalid()) {
10369       Diag(CurrentLocation, diag::note_member_synthesized_at)
10370         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10371       MoveAssignOperator->setInvalidDecl();
10372       return;
10373     }
10374 
10375     // Success! Record the move.
10376     Statements.push_back(Move.getAs<Expr>());
10377   }
10378 
10379   // Assign non-static members.
10380   for (auto *Field : ClassDecl->fields()) {
10381     if (Field->isUnnamedBitfield())
10382       continue;
10383 
10384     if (Field->isInvalidDecl()) {
10385       Invalid = true;
10386       continue;
10387     }
10388 
10389     // Check for members of reference type; we can't move those.
10390     if (Field->getType()->isReferenceType()) {
10391       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10392         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10393       Diag(Field->getLocation(), diag::note_declared_at);
10394       Diag(CurrentLocation, diag::note_member_synthesized_at)
10395         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10396       Invalid = true;
10397       continue;
10398     }
10399 
10400     // Check for members of const-qualified, non-class type.
10401     QualType BaseType = Context.getBaseElementType(Field->getType());
10402     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10403       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10404         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10405       Diag(Field->getLocation(), diag::note_declared_at);
10406       Diag(CurrentLocation, diag::note_member_synthesized_at)
10407         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10408       Invalid = true;
10409       continue;
10410     }
10411 
10412     // Suppress assigning zero-width bitfields.
10413     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10414       continue;
10415 
10416     QualType FieldType = Field->getType().getNonReferenceType();
10417     if (FieldType->isIncompleteArrayType()) {
10418       assert(ClassDecl->hasFlexibleArrayMember() &&
10419              "Incomplete array type is not valid");
10420       continue;
10421     }
10422 
10423     // Build references to the field in the object we're copying from and to.
10424     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10425                               LookupMemberName);
10426     MemberLookup.addDecl(Field);
10427     MemberLookup.resolveKind();
10428     MemberBuilder From(MoveOther, OtherRefType,
10429                        /*IsArrow=*/false, MemberLookup);
10430     MemberBuilder To(This, getCurrentThisType(),
10431                      /*IsArrow=*/true, MemberLookup);
10432 
10433     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10434         "Member reference with rvalue base must be rvalue except for reference "
10435         "members, which aren't allowed for move assignment.");
10436 
10437     // Build the move of this field.
10438     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10439                                             To, From,
10440                                             /*CopyingBaseSubobject=*/false,
10441                                             /*Copying=*/false);
10442     if (Move.isInvalid()) {
10443       Diag(CurrentLocation, diag::note_member_synthesized_at)
10444         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10445       MoveAssignOperator->setInvalidDecl();
10446       return;
10447     }
10448 
10449     // Success! Record the copy.
10450     Statements.push_back(Move.getAs<Stmt>());
10451   }
10452 
10453   if (!Invalid) {
10454     // Add a "return *this;"
10455     ExprResult ThisObj =
10456         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10457 
10458     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10459     if (Return.isInvalid())
10460       Invalid = true;
10461     else {
10462       Statements.push_back(Return.getAs<Stmt>());
10463 
10464       if (Trap.hasErrorOccurred()) {
10465         Diag(CurrentLocation, diag::note_member_synthesized_at)
10466           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10467         Invalid = true;
10468       }
10469     }
10470   }
10471 
10472   // The exception specification is needed because we are defining the
10473   // function.
10474   ResolveExceptionSpec(CurrentLocation,
10475                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10476 
10477   if (Invalid) {
10478     MoveAssignOperator->setInvalidDecl();
10479     return;
10480   }
10481 
10482   StmtResult Body;
10483   {
10484     CompoundScopeRAII CompoundScope(*this);
10485     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10486                              /*isStmtExpr=*/false);
10487     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10488   }
10489   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10490 
10491   if (ASTMutationListener *L = getASTMutationListener()) {
10492     L->CompletedImplicitDefinition(MoveAssignOperator);
10493   }
10494 }
10495 
10496 Sema::ImplicitExceptionSpecification
10497 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10498   CXXRecordDecl *ClassDecl = MD->getParent();
10499 
10500   ImplicitExceptionSpecification ExceptSpec(*this);
10501   if (ClassDecl->isInvalidDecl())
10502     return ExceptSpec;
10503 
10504   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10505   assert(T->getNumParams() >= 1 && "not a copy ctor");
10506   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10507 
10508   // C++ [except.spec]p14:
10509   //   An implicitly declared special member function (Clause 12) shall have an
10510   //   exception-specification. [...]
10511   for (const auto &Base : ClassDecl->bases()) {
10512     // Virtual bases are handled below.
10513     if (Base.isVirtual())
10514       continue;
10515 
10516     CXXRecordDecl *BaseClassDecl
10517       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10518     if (CXXConstructorDecl *CopyConstructor =
10519           LookupCopyingConstructor(BaseClassDecl, Quals))
10520       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10521   }
10522   for (const auto &Base : ClassDecl->vbases()) {
10523     CXXRecordDecl *BaseClassDecl
10524       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10525     if (CXXConstructorDecl *CopyConstructor =
10526           LookupCopyingConstructor(BaseClassDecl, Quals))
10527       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10528   }
10529   for (const auto *Field : ClassDecl->fields()) {
10530     QualType FieldType = Context.getBaseElementType(Field->getType());
10531     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10532       if (CXXConstructorDecl *CopyConstructor =
10533               LookupCopyingConstructor(FieldClassDecl,
10534                                        Quals | FieldType.getCVRQualifiers()))
10535       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10536     }
10537   }
10538 
10539   return ExceptSpec;
10540 }
10541 
10542 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10543                                                     CXXRecordDecl *ClassDecl) {
10544   // C++ [class.copy]p4:
10545   //   If the class definition does not explicitly declare a copy
10546   //   constructor, one is declared implicitly.
10547   assert(ClassDecl->needsImplicitCopyConstructor());
10548 
10549   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10550   if (DSM.isAlreadyBeingDeclared())
10551     return nullptr;
10552 
10553   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10554   QualType ArgType = ClassType;
10555   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10556   if (Const)
10557     ArgType = ArgType.withConst();
10558   ArgType = Context.getLValueReferenceType(ArgType);
10559 
10560   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10561                                                      CXXCopyConstructor,
10562                                                      Const);
10563 
10564   DeclarationName Name
10565     = Context.DeclarationNames.getCXXConstructorName(
10566                                            Context.getCanonicalType(ClassType));
10567   SourceLocation ClassLoc = ClassDecl->getLocation();
10568   DeclarationNameInfo NameInfo(Name, ClassLoc);
10569 
10570   //   An implicitly-declared copy constructor is an inline public
10571   //   member of its class.
10572   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10573       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10574       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10575       Constexpr);
10576   CopyConstructor->setAccess(AS_public);
10577   CopyConstructor->setDefaulted();
10578 
10579   if (getLangOpts().CUDA) {
10580     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10581                                             CopyConstructor,
10582                                             /* ConstRHS */ Const,
10583                                             /* Diagnose */ false);
10584   }
10585 
10586   // Build an exception specification pointing back at this member.
10587   FunctionProtoType::ExtProtoInfo EPI =
10588       getImplicitMethodEPI(*this, CopyConstructor);
10589   CopyConstructor->setType(
10590       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10591 
10592   // Add the parameter to the constructor.
10593   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10594                                                ClassLoc, ClassLoc,
10595                                                /*IdentifierInfo=*/nullptr,
10596                                                ArgType, /*TInfo=*/nullptr,
10597                                                SC_None, nullptr);
10598   CopyConstructor->setParams(FromParam);
10599 
10600   CopyConstructor->setTrivial(
10601     ClassDecl->needsOverloadResolutionForCopyConstructor()
10602       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10603       : ClassDecl->hasTrivialCopyConstructor());
10604 
10605   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10606     SetDeclDeleted(CopyConstructor, ClassLoc);
10607 
10608   // Note that we have declared this constructor.
10609   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10610 
10611   if (Scope *S = getScopeForContext(ClassDecl))
10612     PushOnScopeChains(CopyConstructor, S, false);
10613   ClassDecl->addDecl(CopyConstructor);
10614 
10615   return CopyConstructor;
10616 }
10617 
10618 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10619                                    CXXConstructorDecl *CopyConstructor) {
10620   assert((CopyConstructor->isDefaulted() &&
10621           CopyConstructor->isCopyConstructor() &&
10622           !CopyConstructor->doesThisDeclarationHaveABody() &&
10623           !CopyConstructor->isDeleted()) &&
10624          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10625 
10626   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10627   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10628 
10629   // C++11 [class.copy]p7:
10630   //   The [definition of an implicitly declared copy constructor] is
10631   //   deprecated if the class has a user-declared copy assignment operator
10632   //   or a user-declared destructor.
10633   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10634     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10635 
10636   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10637   DiagnosticErrorTrap Trap(Diags);
10638 
10639   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10640       Trap.hasErrorOccurred()) {
10641     Diag(CurrentLocation, diag::note_member_synthesized_at)
10642       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10643     CopyConstructor->setInvalidDecl();
10644   }  else {
10645     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10646                              ? CopyConstructor->getLocEnd()
10647                              : CopyConstructor->getLocation();
10648     Sema::CompoundScopeRAII CompoundScope(*this);
10649     CopyConstructor->setBody(
10650         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10651   }
10652 
10653   // The exception specification is needed because we are defining the
10654   // function.
10655   ResolveExceptionSpec(CurrentLocation,
10656                        CopyConstructor->getType()->castAs<FunctionProtoType>());
10657 
10658   CopyConstructor->markUsed(Context);
10659   MarkVTableUsed(CurrentLocation, ClassDecl);
10660 
10661   if (ASTMutationListener *L = getASTMutationListener()) {
10662     L->CompletedImplicitDefinition(CopyConstructor);
10663   }
10664 }
10665 
10666 Sema::ImplicitExceptionSpecification
10667 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10668   CXXRecordDecl *ClassDecl = MD->getParent();
10669 
10670   // C++ [except.spec]p14:
10671   //   An implicitly declared special member function (Clause 12) shall have an
10672   //   exception-specification. [...]
10673   ImplicitExceptionSpecification ExceptSpec(*this);
10674   if (ClassDecl->isInvalidDecl())
10675     return ExceptSpec;
10676 
10677   // Direct base-class constructors.
10678   for (const auto &B : ClassDecl->bases()) {
10679     if (B.isVirtual()) // Handled below.
10680       continue;
10681 
10682     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10683       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10684       CXXConstructorDecl *Constructor =
10685           LookupMovingConstructor(BaseClassDecl, 0);
10686       // If this is a deleted function, add it anyway. This might be conformant
10687       // with the standard. This might not. I'm not sure. It might not matter.
10688       if (Constructor)
10689         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10690     }
10691   }
10692 
10693   // Virtual base-class constructors.
10694   for (const auto &B : ClassDecl->vbases()) {
10695     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10696       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10697       CXXConstructorDecl *Constructor =
10698           LookupMovingConstructor(BaseClassDecl, 0);
10699       // If this is a deleted function, add it anyway. This might be conformant
10700       // with the standard. This might not. I'm not sure. It might not matter.
10701       if (Constructor)
10702         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10703     }
10704   }
10705 
10706   // Field constructors.
10707   for (const auto *F : ClassDecl->fields()) {
10708     QualType FieldType = Context.getBaseElementType(F->getType());
10709     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10710       CXXConstructorDecl *Constructor =
10711           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10712       // If this is a deleted function, add it anyway. This might be conformant
10713       // with the standard. This might not. I'm not sure. It might not matter.
10714       // In particular, the problem is that this function never gets called. It
10715       // might just be ill-formed because this function attempts to refer to
10716       // a deleted function here.
10717       if (Constructor)
10718         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10719     }
10720   }
10721 
10722   return ExceptSpec;
10723 }
10724 
10725 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10726                                                     CXXRecordDecl *ClassDecl) {
10727   assert(ClassDecl->needsImplicitMoveConstructor());
10728 
10729   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10730   if (DSM.isAlreadyBeingDeclared())
10731     return nullptr;
10732 
10733   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10734   QualType ArgType = Context.getRValueReferenceType(ClassType);
10735 
10736   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10737                                                      CXXMoveConstructor,
10738                                                      false);
10739 
10740   DeclarationName Name
10741     = Context.DeclarationNames.getCXXConstructorName(
10742                                            Context.getCanonicalType(ClassType));
10743   SourceLocation ClassLoc = ClassDecl->getLocation();
10744   DeclarationNameInfo NameInfo(Name, ClassLoc);
10745 
10746   // C++11 [class.copy]p11:
10747   //   An implicitly-declared copy/move constructor is an inline public
10748   //   member of its class.
10749   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10750       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10751       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10752       Constexpr);
10753   MoveConstructor->setAccess(AS_public);
10754   MoveConstructor->setDefaulted();
10755 
10756   if (getLangOpts().CUDA) {
10757     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10758                                             MoveConstructor,
10759                                             /* ConstRHS */ false,
10760                                             /* Diagnose */ false);
10761   }
10762 
10763   // Build an exception specification pointing back at this member.
10764   FunctionProtoType::ExtProtoInfo EPI =
10765       getImplicitMethodEPI(*this, MoveConstructor);
10766   MoveConstructor->setType(
10767       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10768 
10769   // Add the parameter to the constructor.
10770   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10771                                                ClassLoc, ClassLoc,
10772                                                /*IdentifierInfo=*/nullptr,
10773                                                ArgType, /*TInfo=*/nullptr,
10774                                                SC_None, nullptr);
10775   MoveConstructor->setParams(FromParam);
10776 
10777   MoveConstructor->setTrivial(
10778     ClassDecl->needsOverloadResolutionForMoveConstructor()
10779       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10780       : ClassDecl->hasTrivialMoveConstructor());
10781 
10782   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10783     ClassDecl->setImplicitMoveConstructorIsDeleted();
10784     SetDeclDeleted(MoveConstructor, ClassLoc);
10785   }
10786 
10787   // Note that we have declared this constructor.
10788   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10789 
10790   if (Scope *S = getScopeForContext(ClassDecl))
10791     PushOnScopeChains(MoveConstructor, S, false);
10792   ClassDecl->addDecl(MoveConstructor);
10793 
10794   return MoveConstructor;
10795 }
10796 
10797 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10798                                    CXXConstructorDecl *MoveConstructor) {
10799   assert((MoveConstructor->isDefaulted() &&
10800           MoveConstructor->isMoveConstructor() &&
10801           !MoveConstructor->doesThisDeclarationHaveABody() &&
10802           !MoveConstructor->isDeleted()) &&
10803          "DefineImplicitMoveConstructor - call it for implicit move ctor");
10804 
10805   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10806   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10807 
10808   SynthesizedFunctionScope Scope(*this, MoveConstructor);
10809   DiagnosticErrorTrap Trap(Diags);
10810 
10811   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10812       Trap.hasErrorOccurred()) {
10813     Diag(CurrentLocation, diag::note_member_synthesized_at)
10814       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10815     MoveConstructor->setInvalidDecl();
10816   }  else {
10817     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10818                              ? MoveConstructor->getLocEnd()
10819                              : MoveConstructor->getLocation();
10820     Sema::CompoundScopeRAII CompoundScope(*this);
10821     MoveConstructor->setBody(ActOnCompoundStmt(
10822         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
10823   }
10824 
10825   // The exception specification is needed because we are defining the
10826   // function.
10827   ResolveExceptionSpec(CurrentLocation,
10828                        MoveConstructor->getType()->castAs<FunctionProtoType>());
10829 
10830   MoveConstructor->markUsed(Context);
10831   MarkVTableUsed(CurrentLocation, ClassDecl);
10832 
10833   if (ASTMutationListener *L = getASTMutationListener()) {
10834     L->CompletedImplicitDefinition(MoveConstructor);
10835   }
10836 }
10837 
10838 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10839   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10840 }
10841 
10842 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10843                             SourceLocation CurrentLocation,
10844                             CXXConversionDecl *Conv) {
10845   CXXRecordDecl *Lambda = Conv->getParent();
10846   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10847   // If we are defining a specialization of a conversion to function-ptr
10848   // cache the deduced template arguments for this specialization
10849   // so that we can use them to retrieve the corresponding call-operator
10850   // and static-invoker.
10851   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10852 
10853   // Retrieve the corresponding call-operator specialization.
10854   if (Lambda->isGenericLambda()) {
10855     assert(Conv->isFunctionTemplateSpecialization());
10856     FunctionTemplateDecl *CallOpTemplate =
10857         CallOp->getDescribedFunctionTemplate();
10858     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10859     void *InsertPos = nullptr;
10860     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10861                                                 DeducedTemplateArgs->asArray(),
10862                                                 InsertPos);
10863     assert(CallOpSpec &&
10864           "Conversion operator must have a corresponding call operator");
10865     CallOp = cast<CXXMethodDecl>(CallOpSpec);
10866   }
10867   // Mark the call operator referenced (and add to pending instantiations
10868   // if necessary).
10869   // For both the conversion and static-invoker template specializations
10870   // we construct their body's in this function, so no need to add them
10871   // to the PendingInstantiations.
10872   MarkFunctionReferenced(CurrentLocation, CallOp);
10873 
10874   SynthesizedFunctionScope Scope(*this, Conv);
10875   DiagnosticErrorTrap Trap(Diags);
10876 
10877   // Retrieve the static invoker...
10878   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10879   // ... and get the corresponding specialization for a generic lambda.
10880   if (Lambda->isGenericLambda()) {
10881     assert(DeducedTemplateArgs &&
10882       "Must have deduced template arguments from Conversion Operator");
10883     FunctionTemplateDecl *InvokeTemplate =
10884                           Invoker->getDescribedFunctionTemplate();
10885     void *InsertPos = nullptr;
10886     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10887                                                 DeducedTemplateArgs->asArray(),
10888                                                 InsertPos);
10889     assert(InvokeSpec &&
10890       "Must have a corresponding static invoker specialization");
10891     Invoker = cast<CXXMethodDecl>(InvokeSpec);
10892   }
10893   // Construct the body of the conversion function { return __invoke; }.
10894   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10895                                         VK_LValue, Conv->getLocation()).get();
10896    assert(FunctionRef && "Can't refer to __invoke function?");
10897    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
10898    Conv->setBody(new (Context) CompoundStmt(Context, Return,
10899                                             Conv->getLocation(),
10900                                             Conv->getLocation()));
10901 
10902   Conv->markUsed(Context);
10903   Conv->setReferenced();
10904 
10905   // Fill in the __invoke function with a dummy implementation. IR generation
10906   // will fill in the actual details.
10907   Invoker->markUsed(Context);
10908   Invoker->setReferenced();
10909   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10910 
10911   if (ASTMutationListener *L = getASTMutationListener()) {
10912     L->CompletedImplicitDefinition(Conv);
10913     L->CompletedImplicitDefinition(Invoker);
10914    }
10915 }
10916 
10917 
10918 
10919 void Sema::DefineImplicitLambdaToBlockPointerConversion(
10920        SourceLocation CurrentLocation,
10921        CXXConversionDecl *Conv)
10922 {
10923   assert(!Conv->getParent()->isGenericLambda());
10924 
10925   Conv->markUsed(Context);
10926 
10927   SynthesizedFunctionScope Scope(*this, Conv);
10928   DiagnosticErrorTrap Trap(Diags);
10929 
10930   // Copy-initialize the lambda object as needed to capture it.
10931   Expr *This = ActOnCXXThis(CurrentLocation).get();
10932   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
10933 
10934   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10935                                                         Conv->getLocation(),
10936                                                         Conv, DerefThis);
10937 
10938   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10939   // behavior.  Note that only the general conversion function does this
10940   // (since it's unusable otherwise); in the case where we inline the
10941   // block literal, it has block literal lifetime semantics.
10942   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10943     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10944                                           CK_CopyAndAutoreleaseBlockObject,
10945                                           BuildBlock.get(), nullptr, VK_RValue);
10946 
10947   if (BuildBlock.isInvalid()) {
10948     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10949     Conv->setInvalidDecl();
10950     return;
10951   }
10952 
10953   // Create the return statement that returns the block from the conversion
10954   // function.
10955   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
10956   if (Return.isInvalid()) {
10957     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10958     Conv->setInvalidDecl();
10959     return;
10960   }
10961 
10962   // Set the body of the conversion function.
10963   Stmt *ReturnS = Return.get();
10964   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10965                                            Conv->getLocation(),
10966                                            Conv->getLocation()));
10967 
10968   // We're done; notify the mutation listener, if any.
10969   if (ASTMutationListener *L = getASTMutationListener()) {
10970     L->CompletedImplicitDefinition(Conv);
10971   }
10972 }
10973 
10974 /// \brief Determine whether the given list arguments contains exactly one
10975 /// "real" (non-default) argument.
10976 static bool hasOneRealArgument(MultiExprArg Args) {
10977   switch (Args.size()) {
10978   case 0:
10979     return false;
10980 
10981   default:
10982     if (!Args[1]->isDefaultArgument())
10983       return false;
10984 
10985     // fall through
10986   case 1:
10987     return !Args[0]->isDefaultArgument();
10988   }
10989 
10990   return false;
10991 }
10992 
10993 ExprResult
10994 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10995                             CXXConstructorDecl *Constructor,
10996                             MultiExprArg ExprArgs,
10997                             bool HadMultipleCandidates,
10998                             bool IsListInitialization,
10999                             bool IsStdInitListInitialization,
11000                             bool RequiresZeroInit,
11001                             unsigned ConstructKind,
11002                             SourceRange ParenRange) {
11003   bool Elidable = false;
11004 
11005   // C++0x [class.copy]p34:
11006   //   When certain criteria are met, an implementation is allowed to
11007   //   omit the copy/move construction of a class object, even if the
11008   //   copy/move constructor and/or destructor for the object have
11009   //   side effects. [...]
11010   //     - when a temporary class object that has not been bound to a
11011   //       reference (12.2) would be copied/moved to a class object
11012   //       with the same cv-unqualified type, the copy/move operation
11013   //       can be omitted by constructing the temporary object
11014   //       directly into the target of the omitted copy/move
11015   if (ConstructKind == CXXConstructExpr::CK_Complete &&
11016       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11017     Expr *SubExpr = ExprArgs[0];
11018     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11019   }
11020 
11021   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11022                                Elidable, ExprArgs, HadMultipleCandidates,
11023                                IsListInitialization,
11024                                IsStdInitListInitialization, RequiresZeroInit,
11025                                ConstructKind, ParenRange);
11026 }
11027 
11028 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11029 /// including handling of its default argument expressions.
11030 ExprResult
11031 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11032                             CXXConstructorDecl *Constructor, bool Elidable,
11033                             MultiExprArg ExprArgs,
11034                             bool HadMultipleCandidates,
11035                             bool IsListInitialization,
11036                             bool IsStdInitListInitialization,
11037                             bool RequiresZeroInit,
11038                             unsigned ConstructKind,
11039                             SourceRange ParenRange) {
11040   MarkFunctionReferenced(ConstructLoc, Constructor);
11041   return CXXConstructExpr::Create(
11042       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11043       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11044       RequiresZeroInit,
11045       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11046       ParenRange);
11047 }
11048 
11049 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11050   if (VD->isInvalidDecl()) return;
11051 
11052   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11053   if (ClassDecl->isInvalidDecl()) return;
11054   if (ClassDecl->hasIrrelevantDestructor()) return;
11055   if (ClassDecl->isDependentContext()) return;
11056 
11057   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11058   MarkFunctionReferenced(VD->getLocation(), Destructor);
11059   CheckDestructorAccess(VD->getLocation(), Destructor,
11060                         PDiag(diag::err_access_dtor_var)
11061                         << VD->getDeclName()
11062                         << VD->getType());
11063   DiagnoseUseOfDecl(Destructor, VD->getLocation());
11064 
11065   if (Destructor->isTrivial()) return;
11066   if (!VD->hasGlobalStorage()) return;
11067 
11068   // Emit warning for non-trivial dtor in global scope (a real global,
11069   // class-static, function-static).
11070   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11071 
11072   // TODO: this should be re-enabled for static locals by !CXAAtExit
11073   if (!VD->isStaticLocal())
11074     Diag(VD->getLocation(), diag::warn_global_destructor);
11075 }
11076 
11077 /// \brief Given a constructor and the set of arguments provided for the
11078 /// constructor, convert the arguments and add any required default arguments
11079 /// to form a proper call to this constructor.
11080 ///
11081 /// \returns true if an error occurred, false otherwise.
11082 bool
11083 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11084                               MultiExprArg ArgsPtr,
11085                               SourceLocation Loc,
11086                               SmallVectorImpl<Expr*> &ConvertedArgs,
11087                               bool AllowExplicit,
11088                               bool IsListInitialization) {
11089   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11090   unsigned NumArgs = ArgsPtr.size();
11091   Expr **Args = ArgsPtr.data();
11092 
11093   const FunctionProtoType *Proto
11094     = Constructor->getType()->getAs<FunctionProtoType>();
11095   assert(Proto && "Constructor without a prototype?");
11096   unsigned NumParams = Proto->getNumParams();
11097 
11098   // If too few arguments are available, we'll fill in the rest with defaults.
11099   if (NumArgs < NumParams)
11100     ConvertedArgs.reserve(NumParams);
11101   else
11102     ConvertedArgs.reserve(NumArgs);
11103 
11104   VariadicCallType CallType =
11105     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11106   SmallVector<Expr *, 8> AllArgs;
11107   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11108                                         Proto, 0,
11109                                         llvm::makeArrayRef(Args, NumArgs),
11110                                         AllArgs,
11111                                         CallType, AllowExplicit,
11112                                         IsListInitialization);
11113   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11114 
11115   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11116 
11117   CheckConstructorCall(Constructor,
11118                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11119                        Proto, Loc);
11120 
11121   return Invalid;
11122 }
11123 
11124 static inline bool
11125 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11126                                        const FunctionDecl *FnDecl) {
11127   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11128   if (isa<NamespaceDecl>(DC)) {
11129     return SemaRef.Diag(FnDecl->getLocation(),
11130                         diag::err_operator_new_delete_declared_in_namespace)
11131       << FnDecl->getDeclName();
11132   }
11133 
11134   if (isa<TranslationUnitDecl>(DC) &&
11135       FnDecl->getStorageClass() == SC_Static) {
11136     return SemaRef.Diag(FnDecl->getLocation(),
11137                         diag::err_operator_new_delete_declared_static)
11138       << FnDecl->getDeclName();
11139   }
11140 
11141   return false;
11142 }
11143 
11144 static inline bool
11145 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11146                             CanQualType ExpectedResultType,
11147                             CanQualType ExpectedFirstParamType,
11148                             unsigned DependentParamTypeDiag,
11149                             unsigned InvalidParamTypeDiag) {
11150   QualType ResultType =
11151       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11152 
11153   // Check that the result type is not dependent.
11154   if (ResultType->isDependentType())
11155     return SemaRef.Diag(FnDecl->getLocation(),
11156                         diag::err_operator_new_delete_dependent_result_type)
11157     << FnDecl->getDeclName() << ExpectedResultType;
11158 
11159   // Check that the result type is what we expect.
11160   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11161     return SemaRef.Diag(FnDecl->getLocation(),
11162                         diag::err_operator_new_delete_invalid_result_type)
11163     << FnDecl->getDeclName() << ExpectedResultType;
11164 
11165   // A function template must have at least 2 parameters.
11166   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11167     return SemaRef.Diag(FnDecl->getLocation(),
11168                       diag::err_operator_new_delete_template_too_few_parameters)
11169         << FnDecl->getDeclName();
11170 
11171   // The function decl must have at least 1 parameter.
11172   if (FnDecl->getNumParams() == 0)
11173     return SemaRef.Diag(FnDecl->getLocation(),
11174                         diag::err_operator_new_delete_too_few_parameters)
11175       << FnDecl->getDeclName();
11176 
11177   // Check the first parameter type is not dependent.
11178   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11179   if (FirstParamType->isDependentType())
11180     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11181       << FnDecl->getDeclName() << ExpectedFirstParamType;
11182 
11183   // Check that the first parameter type is what we expect.
11184   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11185       ExpectedFirstParamType)
11186     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11187     << FnDecl->getDeclName() << ExpectedFirstParamType;
11188 
11189   return false;
11190 }
11191 
11192 static bool
11193 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11194   // C++ [basic.stc.dynamic.allocation]p1:
11195   //   A program is ill-formed if an allocation function is declared in a
11196   //   namespace scope other than global scope or declared static in global
11197   //   scope.
11198   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11199     return true;
11200 
11201   CanQualType SizeTy =
11202     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11203 
11204   // C++ [basic.stc.dynamic.allocation]p1:
11205   //  The return type shall be void*. The first parameter shall have type
11206   //  std::size_t.
11207   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11208                                   SizeTy,
11209                                   diag::err_operator_new_dependent_param_type,
11210                                   diag::err_operator_new_param_type))
11211     return true;
11212 
11213   // C++ [basic.stc.dynamic.allocation]p1:
11214   //  The first parameter shall not have an associated default argument.
11215   if (FnDecl->getParamDecl(0)->hasDefaultArg())
11216     return SemaRef.Diag(FnDecl->getLocation(),
11217                         diag::err_operator_new_default_arg)
11218       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11219 
11220   return false;
11221 }
11222 
11223 static bool
11224 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11225   // C++ [basic.stc.dynamic.deallocation]p1:
11226   //   A program is ill-formed if deallocation functions are declared in a
11227   //   namespace scope other than global scope or declared static in global
11228   //   scope.
11229   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11230     return true;
11231 
11232   // C++ [basic.stc.dynamic.deallocation]p2:
11233   //   Each deallocation function shall return void and its first parameter
11234   //   shall be void*.
11235   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11236                                   SemaRef.Context.VoidPtrTy,
11237                                  diag::err_operator_delete_dependent_param_type,
11238                                  diag::err_operator_delete_param_type))
11239     return true;
11240 
11241   return false;
11242 }
11243 
11244 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11245 /// of this overloaded operator is well-formed. If so, returns false;
11246 /// otherwise, emits appropriate diagnostics and returns true.
11247 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11248   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11249          "Expected an overloaded operator declaration");
11250 
11251   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11252 
11253   // C++ [over.oper]p5:
11254   //   The allocation and deallocation functions, operator new,
11255   //   operator new[], operator delete and operator delete[], are
11256   //   described completely in 3.7.3. The attributes and restrictions
11257   //   found in the rest of this subclause do not apply to them unless
11258   //   explicitly stated in 3.7.3.
11259   if (Op == OO_Delete || Op == OO_Array_Delete)
11260     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11261 
11262   if (Op == OO_New || Op == OO_Array_New)
11263     return CheckOperatorNewDeclaration(*this, FnDecl);
11264 
11265   // C++ [over.oper]p6:
11266   //   An operator function shall either be a non-static member
11267   //   function or be a non-member function and have at least one
11268   //   parameter whose type is a class, a reference to a class, an
11269   //   enumeration, or a reference to an enumeration.
11270   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11271     if (MethodDecl->isStatic())
11272       return Diag(FnDecl->getLocation(),
11273                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11274   } else {
11275     bool ClassOrEnumParam = false;
11276     for (auto Param : FnDecl->params()) {
11277       QualType ParamType = Param->getType().getNonReferenceType();
11278       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11279           ParamType->isEnumeralType()) {
11280         ClassOrEnumParam = true;
11281         break;
11282       }
11283     }
11284 
11285     if (!ClassOrEnumParam)
11286       return Diag(FnDecl->getLocation(),
11287                   diag::err_operator_overload_needs_class_or_enum)
11288         << FnDecl->getDeclName();
11289   }
11290 
11291   // C++ [over.oper]p8:
11292   //   An operator function cannot have default arguments (8.3.6),
11293   //   except where explicitly stated below.
11294   //
11295   // Only the function-call operator allows default arguments
11296   // (C++ [over.call]p1).
11297   if (Op != OO_Call) {
11298     for (auto Param : FnDecl->params()) {
11299       if (Param->hasDefaultArg())
11300         return Diag(Param->getLocation(),
11301                     diag::err_operator_overload_default_arg)
11302           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11303     }
11304   }
11305 
11306   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11307     { false, false, false }
11308 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11309     , { Unary, Binary, MemberOnly }
11310 #include "clang/Basic/OperatorKinds.def"
11311   };
11312 
11313   bool CanBeUnaryOperator = OperatorUses[Op][0];
11314   bool CanBeBinaryOperator = OperatorUses[Op][1];
11315   bool MustBeMemberOperator = OperatorUses[Op][2];
11316 
11317   // C++ [over.oper]p8:
11318   //   [...] Operator functions cannot have more or fewer parameters
11319   //   than the number required for the corresponding operator, as
11320   //   described in the rest of this subclause.
11321   unsigned NumParams = FnDecl->getNumParams()
11322                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11323   if (Op != OO_Call &&
11324       ((NumParams == 1 && !CanBeUnaryOperator) ||
11325        (NumParams == 2 && !CanBeBinaryOperator) ||
11326        (NumParams < 1) || (NumParams > 2))) {
11327     // We have the wrong number of parameters.
11328     unsigned ErrorKind;
11329     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11330       ErrorKind = 2;  // 2 -> unary or binary.
11331     } else if (CanBeUnaryOperator) {
11332       ErrorKind = 0;  // 0 -> unary
11333     } else {
11334       assert(CanBeBinaryOperator &&
11335              "All non-call overloaded operators are unary or binary!");
11336       ErrorKind = 1;  // 1 -> binary
11337     }
11338 
11339     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11340       << FnDecl->getDeclName() << NumParams << ErrorKind;
11341   }
11342 
11343   // Overloaded operators other than operator() cannot be variadic.
11344   if (Op != OO_Call &&
11345       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11346     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11347       << FnDecl->getDeclName();
11348   }
11349 
11350   // Some operators must be non-static member functions.
11351   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11352     return Diag(FnDecl->getLocation(),
11353                 diag::err_operator_overload_must_be_member)
11354       << FnDecl->getDeclName();
11355   }
11356 
11357   // C++ [over.inc]p1:
11358   //   The user-defined function called operator++ implements the
11359   //   prefix and postfix ++ operator. If this function is a member
11360   //   function with no parameters, or a non-member function with one
11361   //   parameter of class or enumeration type, it defines the prefix
11362   //   increment operator ++ for objects of that type. If the function
11363   //   is a member function with one parameter (which shall be of type
11364   //   int) or a non-member function with two parameters (the second
11365   //   of which shall be of type int), it defines the postfix
11366   //   increment operator ++ for objects of that type.
11367   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11368     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11369     QualType ParamType = LastParam->getType();
11370 
11371     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11372         !ParamType->isDependentType())
11373       return Diag(LastParam->getLocation(),
11374                   diag::err_operator_overload_post_incdec_must_be_int)
11375         << LastParam->getType() << (Op == OO_MinusMinus);
11376   }
11377 
11378   return false;
11379 }
11380 
11381 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11382 /// of this literal operator function is well-formed. If so, returns
11383 /// false; otherwise, emits appropriate diagnostics and returns true.
11384 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11385   if (isa<CXXMethodDecl>(FnDecl)) {
11386     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11387       << FnDecl->getDeclName();
11388     return true;
11389   }
11390 
11391   if (FnDecl->isExternC()) {
11392     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11393     return true;
11394   }
11395 
11396   bool Valid = false;
11397 
11398   // This might be the definition of a literal operator template.
11399   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11400   // This might be a specialization of a literal operator template.
11401   if (!TpDecl)
11402     TpDecl = FnDecl->getPrimaryTemplate();
11403 
11404   // template <char...> type operator "" name() and
11405   // template <class T, T...> type operator "" name() are the only valid
11406   // template signatures, and the only valid signatures with no parameters.
11407   if (TpDecl) {
11408     if (FnDecl->param_size() == 0) {
11409       // Must have one or two template parameters
11410       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11411       if (Params->size() == 1) {
11412         NonTypeTemplateParmDecl *PmDecl =
11413           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11414 
11415         // The template parameter must be a char parameter pack.
11416         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11417             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11418           Valid = true;
11419       } else if (Params->size() == 2) {
11420         TemplateTypeParmDecl *PmType =
11421           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11422         NonTypeTemplateParmDecl *PmArgs =
11423           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11424 
11425         // The second template parameter must be a parameter pack with the
11426         // first template parameter as its type.
11427         if (PmType && PmArgs &&
11428             !PmType->isTemplateParameterPack() &&
11429             PmArgs->isTemplateParameterPack()) {
11430           const TemplateTypeParmType *TArgs =
11431             PmArgs->getType()->getAs<TemplateTypeParmType>();
11432           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11433               TArgs->getIndex() == PmType->getIndex()) {
11434             Valid = true;
11435             if (ActiveTemplateInstantiations.empty())
11436               Diag(FnDecl->getLocation(),
11437                    diag::ext_string_literal_operator_template);
11438           }
11439         }
11440       }
11441     }
11442   } else if (FnDecl->param_size()) {
11443     // Check the first parameter
11444     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11445 
11446     QualType T = (*Param)->getType().getUnqualifiedType();
11447 
11448     // unsigned long long int, long double, and any character type are allowed
11449     // as the only parameters.
11450     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11451         Context.hasSameType(T, Context.LongDoubleTy) ||
11452         Context.hasSameType(T, Context.CharTy) ||
11453         Context.hasSameType(T, Context.WideCharTy) ||
11454         Context.hasSameType(T, Context.Char16Ty) ||
11455         Context.hasSameType(T, Context.Char32Ty)) {
11456       if (++Param == FnDecl->param_end())
11457         Valid = true;
11458       goto FinishedParams;
11459     }
11460 
11461     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11462     const PointerType *PT = T->getAs<PointerType>();
11463     if (!PT)
11464       goto FinishedParams;
11465     T = PT->getPointeeType();
11466     if (!T.isConstQualified() || T.isVolatileQualified())
11467       goto FinishedParams;
11468     T = T.getUnqualifiedType();
11469 
11470     // Move on to the second parameter;
11471     ++Param;
11472 
11473     // If there is no second parameter, the first must be a const char *
11474     if (Param == FnDecl->param_end()) {
11475       if (Context.hasSameType(T, Context.CharTy))
11476         Valid = true;
11477       goto FinishedParams;
11478     }
11479 
11480     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11481     // are allowed as the first parameter to a two-parameter function
11482     if (!(Context.hasSameType(T, Context.CharTy) ||
11483           Context.hasSameType(T, Context.WideCharTy) ||
11484           Context.hasSameType(T, Context.Char16Ty) ||
11485           Context.hasSameType(T, Context.Char32Ty)))
11486       goto FinishedParams;
11487 
11488     // The second and final parameter must be an std::size_t
11489     T = (*Param)->getType().getUnqualifiedType();
11490     if (Context.hasSameType(T, Context.getSizeType()) &&
11491         ++Param == FnDecl->param_end())
11492       Valid = true;
11493   }
11494 
11495   // FIXME: This diagnostic is absolutely terrible.
11496 FinishedParams:
11497   if (!Valid) {
11498     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11499       << FnDecl->getDeclName();
11500     return true;
11501   }
11502 
11503   // A parameter-declaration-clause containing a default argument is not
11504   // equivalent to any of the permitted forms.
11505   for (auto Param : FnDecl->params()) {
11506     if (Param->hasDefaultArg()) {
11507       Diag(Param->getDefaultArgRange().getBegin(),
11508            diag::err_literal_operator_default_argument)
11509         << Param->getDefaultArgRange();
11510       break;
11511     }
11512   }
11513 
11514   StringRef LiteralName
11515     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11516   if (LiteralName[0] != '_') {
11517     // C++11 [usrlit.suffix]p1:
11518     //   Literal suffix identifiers that do not start with an underscore
11519     //   are reserved for future standardization.
11520     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11521       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11522   }
11523 
11524   return false;
11525 }
11526 
11527 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11528 /// linkage specification, including the language and (if present)
11529 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11530 /// language string literal. LBraceLoc, if valid, provides the location of
11531 /// the '{' brace. Otherwise, this linkage specification does not
11532 /// have any braces.
11533 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11534                                            Expr *LangStr,
11535                                            SourceLocation LBraceLoc) {
11536   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11537   if (!Lit->isAscii()) {
11538     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11539       << LangStr->getSourceRange();
11540     return nullptr;
11541   }
11542 
11543   StringRef Lang = Lit->getString();
11544   LinkageSpecDecl::LanguageIDs Language;
11545   if (Lang == "C")
11546     Language = LinkageSpecDecl::lang_c;
11547   else if (Lang == "C++")
11548     Language = LinkageSpecDecl::lang_cxx;
11549   else {
11550     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11551       << LangStr->getSourceRange();
11552     return nullptr;
11553   }
11554 
11555   // FIXME: Add all the various semantics of linkage specifications
11556 
11557   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11558                                                LangStr->getExprLoc(), Language,
11559                                                LBraceLoc.isValid());
11560   CurContext->addDecl(D);
11561   PushDeclContext(S, D);
11562   return D;
11563 }
11564 
11565 /// ActOnFinishLinkageSpecification - Complete the definition of
11566 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11567 /// valid, it's the position of the closing '}' brace in a linkage
11568 /// specification that uses braces.
11569 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11570                                             Decl *LinkageSpec,
11571                                             SourceLocation RBraceLoc) {
11572   if (RBraceLoc.isValid()) {
11573     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11574     LSDecl->setRBraceLoc(RBraceLoc);
11575   }
11576   PopDeclContext();
11577   return LinkageSpec;
11578 }
11579 
11580 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11581                                   AttributeList *AttrList,
11582                                   SourceLocation SemiLoc) {
11583   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11584   // Attribute declarations appertain to empty declaration so we handle
11585   // them here.
11586   if (AttrList)
11587     ProcessDeclAttributeList(S, ED, AttrList);
11588 
11589   CurContext->addDecl(ED);
11590   return ED;
11591 }
11592 
11593 /// \brief Perform semantic analysis for the variable declaration that
11594 /// occurs within a C++ catch clause, returning the newly-created
11595 /// variable.
11596 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11597                                          TypeSourceInfo *TInfo,
11598                                          SourceLocation StartLoc,
11599                                          SourceLocation Loc,
11600                                          IdentifierInfo *Name) {
11601   bool Invalid = false;
11602   QualType ExDeclType = TInfo->getType();
11603 
11604   // Arrays and functions decay.
11605   if (ExDeclType->isArrayType())
11606     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11607   else if (ExDeclType->isFunctionType())
11608     ExDeclType = Context.getPointerType(ExDeclType);
11609 
11610   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11611   // The exception-declaration shall not denote a pointer or reference to an
11612   // incomplete type, other than [cv] void*.
11613   // N2844 forbids rvalue references.
11614   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11615     Diag(Loc, diag::err_catch_rvalue_ref);
11616     Invalid = true;
11617   }
11618 
11619   QualType BaseType = ExDeclType;
11620   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11621   unsigned DK = diag::err_catch_incomplete;
11622   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11623     BaseType = Ptr->getPointeeType();
11624     Mode = 1;
11625     DK = diag::err_catch_incomplete_ptr;
11626   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11627     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11628     BaseType = Ref->getPointeeType();
11629     Mode = 2;
11630     DK = diag::err_catch_incomplete_ref;
11631   }
11632   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11633       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11634     Invalid = true;
11635 
11636   if (!Invalid && !ExDeclType->isDependentType() &&
11637       RequireNonAbstractType(Loc, ExDeclType,
11638                              diag::err_abstract_type_in_decl,
11639                              AbstractVariableType))
11640     Invalid = true;
11641 
11642   // Only the non-fragile NeXT runtime currently supports C++ catches
11643   // of ObjC types, and no runtime supports catching ObjC types by value.
11644   if (!Invalid && getLangOpts().ObjC1) {
11645     QualType T = ExDeclType;
11646     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11647       T = RT->getPointeeType();
11648 
11649     if (T->isObjCObjectType()) {
11650       Diag(Loc, diag::err_objc_object_catch);
11651       Invalid = true;
11652     } else if (T->isObjCObjectPointerType()) {
11653       // FIXME: should this be a test for macosx-fragile specifically?
11654       if (getLangOpts().ObjCRuntime.isFragile())
11655         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11656     }
11657   }
11658 
11659   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11660                                     ExDeclType, TInfo, SC_None);
11661   ExDecl->setExceptionVariable(true);
11662 
11663   // In ARC, infer 'retaining' for variables of retainable type.
11664   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11665     Invalid = true;
11666 
11667   if (!Invalid && !ExDeclType->isDependentType()) {
11668     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11669       // Insulate this from anything else we might currently be parsing.
11670       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11671 
11672       // C++ [except.handle]p16:
11673       //   The object declared in an exception-declaration or, if the
11674       //   exception-declaration does not specify a name, a temporary (12.2) is
11675       //   copy-initialized (8.5) from the exception object. [...]
11676       //   The object is destroyed when the handler exits, after the destruction
11677       //   of any automatic objects initialized within the handler.
11678       //
11679       // We just pretend to initialize the object with itself, then make sure
11680       // it can be destroyed later.
11681       QualType initType = ExDeclType;
11682 
11683       InitializedEntity entity =
11684         InitializedEntity::InitializeVariable(ExDecl);
11685       InitializationKind initKind =
11686         InitializationKind::CreateCopy(Loc, SourceLocation());
11687 
11688       Expr *opaqueValue =
11689         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11690       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11691       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11692       if (result.isInvalid())
11693         Invalid = true;
11694       else {
11695         // If the constructor used was non-trivial, set this as the
11696         // "initializer".
11697         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
11698         if (!construct->getConstructor()->isTrivial()) {
11699           Expr *init = MaybeCreateExprWithCleanups(construct);
11700           ExDecl->setInit(init);
11701         }
11702 
11703         // And make sure it's destructable.
11704         FinalizeVarWithDestructor(ExDecl, recordType);
11705       }
11706     }
11707   }
11708 
11709   if (Invalid)
11710     ExDecl->setInvalidDecl();
11711 
11712   return ExDecl;
11713 }
11714 
11715 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11716 /// handler.
11717 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11718   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11719   bool Invalid = D.isInvalidType();
11720 
11721   // Check for unexpanded parameter packs.
11722   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11723                                       UPPC_ExceptionType)) {
11724     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11725                                              D.getIdentifierLoc());
11726     Invalid = true;
11727   }
11728 
11729   IdentifierInfo *II = D.getIdentifier();
11730   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11731                                              LookupOrdinaryName,
11732                                              ForRedeclaration)) {
11733     // The scope should be freshly made just for us. There is just no way
11734     // it contains any previous declaration, except for function parameters in
11735     // a function-try-block's catch statement.
11736     assert(!S->isDeclScope(PrevDecl));
11737     if (isDeclInScope(PrevDecl, CurContext, S)) {
11738       Diag(D.getIdentifierLoc(), diag::err_redefinition)
11739         << D.getIdentifier();
11740       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11741       Invalid = true;
11742     } else if (PrevDecl->isTemplateParameter())
11743       // Maybe we will complain about the shadowed template parameter.
11744       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11745   }
11746 
11747   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11748     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11749       << D.getCXXScopeSpec().getRange();
11750     Invalid = true;
11751   }
11752 
11753   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11754                                               D.getLocStart(),
11755                                               D.getIdentifierLoc(),
11756                                               D.getIdentifier());
11757   if (Invalid)
11758     ExDecl->setInvalidDecl();
11759 
11760   // Add the exception declaration into this scope.
11761   if (II)
11762     PushOnScopeChains(ExDecl, S);
11763   else
11764     CurContext->addDecl(ExDecl);
11765 
11766   ProcessDeclAttributes(S, ExDecl, D);
11767   return ExDecl;
11768 }
11769 
11770 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11771                                          Expr *AssertExpr,
11772                                          Expr *AssertMessageExpr,
11773                                          SourceLocation RParenLoc) {
11774   StringLiteral *AssertMessage =
11775       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
11776 
11777   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11778     return nullptr;
11779 
11780   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11781                                       AssertMessage, RParenLoc, false);
11782 }
11783 
11784 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11785                                          Expr *AssertExpr,
11786                                          StringLiteral *AssertMessage,
11787                                          SourceLocation RParenLoc,
11788                                          bool Failed) {
11789   assert(AssertExpr != nullptr && "Expected non-null condition");
11790   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11791       !Failed) {
11792     // In a static_assert-declaration, the constant-expression shall be a
11793     // constant expression that can be contextually converted to bool.
11794     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11795     if (Converted.isInvalid())
11796       Failed = true;
11797 
11798     llvm::APSInt Cond;
11799     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11800           diag::err_static_assert_expression_is_not_constant,
11801           /*AllowFold=*/false).isInvalid())
11802       Failed = true;
11803 
11804     if (!Failed && !Cond) {
11805       SmallString<256> MsgBuffer;
11806       llvm::raw_svector_ostream Msg(MsgBuffer);
11807       if (AssertMessage)
11808         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
11809       Diag(StaticAssertLoc, diag::err_static_assert_failed)
11810         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
11811       Failed = true;
11812     }
11813   }
11814 
11815   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11816                                         AssertExpr, AssertMessage, RParenLoc,
11817                                         Failed);
11818 
11819   CurContext->addDecl(Decl);
11820   return Decl;
11821 }
11822 
11823 /// \brief Perform semantic analysis of the given friend type declaration.
11824 ///
11825 /// \returns A friend declaration that.
11826 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11827                                       SourceLocation FriendLoc,
11828                                       TypeSourceInfo *TSInfo) {
11829   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11830 
11831   QualType T = TSInfo->getType();
11832   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11833 
11834   // C++03 [class.friend]p2:
11835   //   An elaborated-type-specifier shall be used in a friend declaration
11836   //   for a class.*
11837   //
11838   //   * The class-key of the elaborated-type-specifier is required.
11839   if (!ActiveTemplateInstantiations.empty()) {
11840     // Do not complain about the form of friend template types during
11841     // template instantiation; we will already have complained when the
11842     // template was declared.
11843   } else {
11844     if (!T->isElaboratedTypeSpecifier()) {
11845       // If we evaluated the type to a record type, suggest putting
11846       // a tag in front.
11847       if (const RecordType *RT = T->getAs<RecordType>()) {
11848         RecordDecl *RD = RT->getDecl();
11849 
11850         SmallString<16> InsertionText(" ");
11851         InsertionText += RD->getKindName();
11852 
11853         Diag(TypeRange.getBegin(),
11854              getLangOpts().CPlusPlus11 ?
11855                diag::warn_cxx98_compat_unelaborated_friend_type :
11856                diag::ext_unelaborated_friend_type)
11857           << (unsigned) RD->getTagKind()
11858           << T
11859           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11860                                         InsertionText);
11861       } else {
11862         Diag(FriendLoc,
11863              getLangOpts().CPlusPlus11 ?
11864                diag::warn_cxx98_compat_nonclass_type_friend :
11865                diag::ext_nonclass_type_friend)
11866           << T
11867           << TypeRange;
11868       }
11869     } else if (T->getAs<EnumType>()) {
11870       Diag(FriendLoc,
11871            getLangOpts().CPlusPlus11 ?
11872              diag::warn_cxx98_compat_enum_friend :
11873              diag::ext_enum_friend)
11874         << T
11875         << TypeRange;
11876     }
11877 
11878     // C++11 [class.friend]p3:
11879     //   A friend declaration that does not declare a function shall have one
11880     //   of the following forms:
11881     //     friend elaborated-type-specifier ;
11882     //     friend simple-type-specifier ;
11883     //     friend typename-specifier ;
11884     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11885       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11886   }
11887 
11888   //   If the type specifier in a friend declaration designates a (possibly
11889   //   cv-qualified) class type, that class is declared as a friend; otherwise,
11890   //   the friend declaration is ignored.
11891   return FriendDecl::Create(Context, CurContext,
11892                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
11893                             FriendLoc);
11894 }
11895 
11896 /// Handle a friend tag declaration where the scope specifier was
11897 /// templated.
11898 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11899                                     unsigned TagSpec, SourceLocation TagLoc,
11900                                     CXXScopeSpec &SS,
11901                                     IdentifierInfo *Name,
11902                                     SourceLocation NameLoc,
11903                                     AttributeList *Attr,
11904                                     MultiTemplateParamsArg TempParamLists) {
11905   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11906 
11907   bool isExplicitSpecialization = false;
11908   bool Invalid = false;
11909 
11910   if (TemplateParameterList *TemplateParams =
11911           MatchTemplateParametersToScopeSpecifier(
11912               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
11913               isExplicitSpecialization, Invalid)) {
11914     if (TemplateParams->size() > 0) {
11915       // This is a declaration of a class template.
11916       if (Invalid)
11917         return nullptr;
11918 
11919       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
11920                                 NameLoc, Attr, TemplateParams, AS_public,
11921                                 /*ModulePrivateLoc=*/SourceLocation(),
11922                                 FriendLoc, TempParamLists.size() - 1,
11923                                 TempParamLists.data()).get();
11924     } else {
11925       // The "template<>" header is extraneous.
11926       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11927         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11928       isExplicitSpecialization = true;
11929     }
11930   }
11931 
11932   if (Invalid) return nullptr;
11933 
11934   bool isAllExplicitSpecializations = true;
11935   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11936     if (TempParamLists[I]->size()) {
11937       isAllExplicitSpecializations = false;
11938       break;
11939     }
11940   }
11941 
11942   // FIXME: don't ignore attributes.
11943 
11944   // If it's explicit specializations all the way down, just forget
11945   // about the template header and build an appropriate non-templated
11946   // friend.  TODO: for source fidelity, remember the headers.
11947   if (isAllExplicitSpecializations) {
11948     if (SS.isEmpty()) {
11949       bool Owned = false;
11950       bool IsDependent = false;
11951       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11952                       Attr, AS_public,
11953                       /*ModulePrivateLoc=*/SourceLocation(),
11954                       MultiTemplateParamsArg(), Owned, IsDependent,
11955                       /*ScopedEnumKWLoc=*/SourceLocation(),
11956                       /*ScopedEnumUsesClassTag=*/false,
11957                       /*UnderlyingType=*/TypeResult(),
11958                       /*IsTypeSpecifier=*/false);
11959     }
11960 
11961     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11962     ElaboratedTypeKeyword Keyword
11963       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11964     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11965                                    *Name, NameLoc);
11966     if (T.isNull())
11967       return nullptr;
11968 
11969     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11970     if (isa<DependentNameType>(T)) {
11971       DependentNameTypeLoc TL =
11972           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11973       TL.setElaboratedKeywordLoc(TagLoc);
11974       TL.setQualifierLoc(QualifierLoc);
11975       TL.setNameLoc(NameLoc);
11976     } else {
11977       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11978       TL.setElaboratedKeywordLoc(TagLoc);
11979       TL.setQualifierLoc(QualifierLoc);
11980       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11981     }
11982 
11983     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11984                                             TSI, FriendLoc, TempParamLists);
11985     Friend->setAccess(AS_public);
11986     CurContext->addDecl(Friend);
11987     return Friend;
11988   }
11989 
11990   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11991 
11992 
11993 
11994   // Handle the case of a templated-scope friend class.  e.g.
11995   //   template <class T> class A<T>::B;
11996   // FIXME: we don't support these right now.
11997   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11998     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
11999   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12000   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12001   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12002   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12003   TL.setElaboratedKeywordLoc(TagLoc);
12004   TL.setQualifierLoc(SS.getWithLocInContext(Context));
12005   TL.setNameLoc(NameLoc);
12006 
12007   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12008                                           TSI, FriendLoc, TempParamLists);
12009   Friend->setAccess(AS_public);
12010   Friend->setUnsupportedFriend(true);
12011   CurContext->addDecl(Friend);
12012   return Friend;
12013 }
12014 
12015 
12016 /// Handle a friend type declaration.  This works in tandem with
12017 /// ActOnTag.
12018 ///
12019 /// Notes on friend class templates:
12020 ///
12021 /// We generally treat friend class declarations as if they were
12022 /// declaring a class.  So, for example, the elaborated type specifier
12023 /// in a friend declaration is required to obey the restrictions of a
12024 /// class-head (i.e. no typedefs in the scope chain), template
12025 /// parameters are required to match up with simple template-ids, &c.
12026 /// However, unlike when declaring a template specialization, it's
12027 /// okay to refer to a template specialization without an empty
12028 /// template parameter declaration, e.g.
12029 ///   friend class A<T>::B<unsigned>;
12030 /// We permit this as a special case; if there are any template
12031 /// parameters present at all, require proper matching, i.e.
12032 ///   template <> template \<class T> friend class A<int>::B;
12033 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12034                                 MultiTemplateParamsArg TempParams) {
12035   SourceLocation Loc = DS.getLocStart();
12036 
12037   assert(DS.isFriendSpecified());
12038   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12039 
12040   // Try to convert the decl specifier to a type.  This works for
12041   // friend templates because ActOnTag never produces a ClassTemplateDecl
12042   // for a TUK_Friend.
12043   Declarator TheDeclarator(DS, Declarator::MemberContext);
12044   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12045   QualType T = TSI->getType();
12046   if (TheDeclarator.isInvalidType())
12047     return nullptr;
12048 
12049   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12050     return nullptr;
12051 
12052   // This is definitely an error in C++98.  It's probably meant to
12053   // be forbidden in C++0x, too, but the specification is just
12054   // poorly written.
12055   //
12056   // The problem is with declarations like the following:
12057   //   template <T> friend A<T>::foo;
12058   // where deciding whether a class C is a friend or not now hinges
12059   // on whether there exists an instantiation of A that causes
12060   // 'foo' to equal C.  There are restrictions on class-heads
12061   // (which we declare (by fiat) elaborated friend declarations to
12062   // be) that makes this tractable.
12063   //
12064   // FIXME: handle "template <> friend class A<T>;", which
12065   // is possibly well-formed?  Who even knows?
12066   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12067     Diag(Loc, diag::err_tagless_friend_type_template)
12068       << DS.getSourceRange();
12069     return nullptr;
12070   }
12071 
12072   // C++98 [class.friend]p1: A friend of a class is a function
12073   //   or class that is not a member of the class . . .
12074   // This is fixed in DR77, which just barely didn't make the C++03
12075   // deadline.  It's also a very silly restriction that seriously
12076   // affects inner classes and which nobody else seems to implement;
12077   // thus we never diagnose it, not even in -pedantic.
12078   //
12079   // But note that we could warn about it: it's always useless to
12080   // friend one of your own members (it's not, however, worthless to
12081   // friend a member of an arbitrary specialization of your template).
12082 
12083   Decl *D;
12084   if (unsigned NumTempParamLists = TempParams.size())
12085     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12086                                    NumTempParamLists,
12087                                    TempParams.data(),
12088                                    TSI,
12089                                    DS.getFriendSpecLoc());
12090   else
12091     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12092 
12093   if (!D)
12094     return nullptr;
12095 
12096   D->setAccess(AS_public);
12097   CurContext->addDecl(D);
12098 
12099   return D;
12100 }
12101 
12102 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12103                                         MultiTemplateParamsArg TemplateParams) {
12104   const DeclSpec &DS = D.getDeclSpec();
12105 
12106   assert(DS.isFriendSpecified());
12107   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12108 
12109   SourceLocation Loc = D.getIdentifierLoc();
12110   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12111 
12112   // C++ [class.friend]p1
12113   //   A friend of a class is a function or class....
12114   // Note that this sees through typedefs, which is intended.
12115   // It *doesn't* see through dependent types, which is correct
12116   // according to [temp.arg.type]p3:
12117   //   If a declaration acquires a function type through a
12118   //   type dependent on a template-parameter and this causes
12119   //   a declaration that does not use the syntactic form of a
12120   //   function declarator to have a function type, the program
12121   //   is ill-formed.
12122   if (!TInfo->getType()->isFunctionType()) {
12123     Diag(Loc, diag::err_unexpected_friend);
12124 
12125     // It might be worthwhile to try to recover by creating an
12126     // appropriate declaration.
12127     return nullptr;
12128   }
12129 
12130   // C++ [namespace.memdef]p3
12131   //  - If a friend declaration in a non-local class first declares a
12132   //    class or function, the friend class or function is a member
12133   //    of the innermost enclosing namespace.
12134   //  - The name of the friend is not found by simple name lookup
12135   //    until a matching declaration is provided in that namespace
12136   //    scope (either before or after the class declaration granting
12137   //    friendship).
12138   //  - If a friend function is called, its name may be found by the
12139   //    name lookup that considers functions from namespaces and
12140   //    classes associated with the types of the function arguments.
12141   //  - When looking for a prior declaration of a class or a function
12142   //    declared as a friend, scopes outside the innermost enclosing
12143   //    namespace scope are not considered.
12144 
12145   CXXScopeSpec &SS = D.getCXXScopeSpec();
12146   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12147   DeclarationName Name = NameInfo.getName();
12148   assert(Name);
12149 
12150   // Check for unexpanded parameter packs.
12151   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12152       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12153       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12154     return nullptr;
12155 
12156   // The context we found the declaration in, or in which we should
12157   // create the declaration.
12158   DeclContext *DC;
12159   Scope *DCScope = S;
12160   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12161                         ForRedeclaration);
12162 
12163   // There are five cases here.
12164   //   - There's no scope specifier and we're in a local class. Only look
12165   //     for functions declared in the immediately-enclosing block scope.
12166   // We recover from invalid scope qualifiers as if they just weren't there.
12167   FunctionDecl *FunctionContainingLocalClass = nullptr;
12168   if ((SS.isInvalid() || !SS.isSet()) &&
12169       (FunctionContainingLocalClass =
12170            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12171     // C++11 [class.friend]p11:
12172     //   If a friend declaration appears in a local class and the name
12173     //   specified is an unqualified name, a prior declaration is
12174     //   looked up without considering scopes that are outside the
12175     //   innermost enclosing non-class scope. For a friend function
12176     //   declaration, if there is no prior declaration, the program is
12177     //   ill-formed.
12178 
12179     // Find the innermost enclosing non-class scope. This is the block
12180     // scope containing the local class definition (or for a nested class,
12181     // the outer local class).
12182     DCScope = S->getFnParent();
12183 
12184     // Look up the function name in the scope.
12185     Previous.clear(LookupLocalFriendName);
12186     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12187 
12188     if (!Previous.empty()) {
12189       // All possible previous declarations must have the same context:
12190       // either they were declared at block scope or they are members of
12191       // one of the enclosing local classes.
12192       DC = Previous.getRepresentativeDecl()->getDeclContext();
12193     } else {
12194       // This is ill-formed, but provide the context that we would have
12195       // declared the function in, if we were permitted to, for error recovery.
12196       DC = FunctionContainingLocalClass;
12197     }
12198     adjustContextForLocalExternDecl(DC);
12199 
12200     // C++ [class.friend]p6:
12201     //   A function can be defined in a friend declaration of a class if and
12202     //   only if the class is a non-local class (9.8), the function name is
12203     //   unqualified, and the function has namespace scope.
12204     if (D.isFunctionDefinition()) {
12205       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12206     }
12207 
12208   //   - There's no scope specifier, in which case we just go to the
12209   //     appropriate scope and look for a function or function template
12210   //     there as appropriate.
12211   } else if (SS.isInvalid() || !SS.isSet()) {
12212     // C++11 [namespace.memdef]p3:
12213     //   If the name in a friend declaration is neither qualified nor
12214     //   a template-id and the declaration is a function or an
12215     //   elaborated-type-specifier, the lookup to determine whether
12216     //   the entity has been previously declared shall not consider
12217     //   any scopes outside the innermost enclosing namespace.
12218     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12219 
12220     // Find the appropriate context according to the above.
12221     DC = CurContext;
12222 
12223     // Skip class contexts.  If someone can cite chapter and verse
12224     // for this behavior, that would be nice --- it's what GCC and
12225     // EDG do, and it seems like a reasonable intent, but the spec
12226     // really only says that checks for unqualified existing
12227     // declarations should stop at the nearest enclosing namespace,
12228     // not that they should only consider the nearest enclosing
12229     // namespace.
12230     while (DC->isRecord())
12231       DC = DC->getParent();
12232 
12233     DeclContext *LookupDC = DC;
12234     while (LookupDC->isTransparentContext())
12235       LookupDC = LookupDC->getParent();
12236 
12237     while (true) {
12238       LookupQualifiedName(Previous, LookupDC);
12239 
12240       if (!Previous.empty()) {
12241         DC = LookupDC;
12242         break;
12243       }
12244 
12245       if (isTemplateId) {
12246         if (isa<TranslationUnitDecl>(LookupDC)) break;
12247       } else {
12248         if (LookupDC->isFileContext()) break;
12249       }
12250       LookupDC = LookupDC->getParent();
12251     }
12252 
12253     DCScope = getScopeForDeclContext(S, DC);
12254 
12255   //   - There's a non-dependent scope specifier, in which case we
12256   //     compute it and do a previous lookup there for a function
12257   //     or function template.
12258   } else if (!SS.getScopeRep()->isDependent()) {
12259     DC = computeDeclContext(SS);
12260     if (!DC) return nullptr;
12261 
12262     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12263 
12264     LookupQualifiedName(Previous, DC);
12265 
12266     // Ignore things found implicitly in the wrong scope.
12267     // TODO: better diagnostics for this case.  Suggesting the right
12268     // qualified scope would be nice...
12269     LookupResult::Filter F = Previous.makeFilter();
12270     while (F.hasNext()) {
12271       NamedDecl *D = F.next();
12272       if (!DC->InEnclosingNamespaceSetOf(
12273               D->getDeclContext()->getRedeclContext()))
12274         F.erase();
12275     }
12276     F.done();
12277 
12278     if (Previous.empty()) {
12279       D.setInvalidType();
12280       Diag(Loc, diag::err_qualified_friend_not_found)
12281           << Name << TInfo->getType();
12282       return nullptr;
12283     }
12284 
12285     // C++ [class.friend]p1: A friend of a class is a function or
12286     //   class that is not a member of the class . . .
12287     if (DC->Equals(CurContext))
12288       Diag(DS.getFriendSpecLoc(),
12289            getLangOpts().CPlusPlus11 ?
12290              diag::warn_cxx98_compat_friend_is_member :
12291              diag::err_friend_is_member);
12292 
12293     if (D.isFunctionDefinition()) {
12294       // C++ [class.friend]p6:
12295       //   A function can be defined in a friend declaration of a class if and
12296       //   only if the class is a non-local class (9.8), the function name is
12297       //   unqualified, and the function has namespace scope.
12298       SemaDiagnosticBuilder DB
12299         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12300 
12301       DB << SS.getScopeRep();
12302       if (DC->isFileContext())
12303         DB << FixItHint::CreateRemoval(SS.getRange());
12304       SS.clear();
12305     }
12306 
12307   //   - There's a scope specifier that does not match any template
12308   //     parameter lists, in which case we use some arbitrary context,
12309   //     create a method or method template, and wait for instantiation.
12310   //   - There's a scope specifier that does match some template
12311   //     parameter lists, which we don't handle right now.
12312   } else {
12313     if (D.isFunctionDefinition()) {
12314       // C++ [class.friend]p6:
12315       //   A function can be defined in a friend declaration of a class if and
12316       //   only if the class is a non-local class (9.8), the function name is
12317       //   unqualified, and the function has namespace scope.
12318       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12319         << SS.getScopeRep();
12320     }
12321 
12322     DC = CurContext;
12323     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12324   }
12325 
12326   if (!DC->isRecord()) {
12327     // This implies that it has to be an operator or function.
12328     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12329         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12330         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12331       Diag(Loc, diag::err_introducing_special_friend) <<
12332         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12333          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12334       return nullptr;
12335     }
12336   }
12337 
12338   // FIXME: This is an egregious hack to cope with cases where the scope stack
12339   // does not contain the declaration context, i.e., in an out-of-line
12340   // definition of a class.
12341   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12342   if (!DCScope) {
12343     FakeDCScope.setEntity(DC);
12344     DCScope = &FakeDCScope;
12345   }
12346 
12347   bool AddToScope = true;
12348   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12349                                           TemplateParams, AddToScope);
12350   if (!ND) return nullptr;
12351 
12352   assert(ND->getLexicalDeclContext() == CurContext);
12353 
12354   // If we performed typo correction, we might have added a scope specifier
12355   // and changed the decl context.
12356   DC = ND->getDeclContext();
12357 
12358   // Add the function declaration to the appropriate lookup tables,
12359   // adjusting the redeclarations list as necessary.  We don't
12360   // want to do this yet if the friending class is dependent.
12361   //
12362   // Also update the scope-based lookup if the target context's
12363   // lookup context is in lexical scope.
12364   if (!CurContext->isDependentContext()) {
12365     DC = DC->getRedeclContext();
12366     DC->makeDeclVisibleInContext(ND);
12367     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12368       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12369   }
12370 
12371   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12372                                        D.getIdentifierLoc(), ND,
12373                                        DS.getFriendSpecLoc());
12374   FrD->setAccess(AS_public);
12375   CurContext->addDecl(FrD);
12376 
12377   if (ND->isInvalidDecl()) {
12378     FrD->setInvalidDecl();
12379   } else {
12380     if (DC->isRecord()) CheckFriendAccess(ND);
12381 
12382     FunctionDecl *FD;
12383     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12384       FD = FTD->getTemplatedDecl();
12385     else
12386       FD = cast<FunctionDecl>(ND);
12387 
12388     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12389     // default argument expression, that declaration shall be a definition
12390     // and shall be the only declaration of the function or function
12391     // template in the translation unit.
12392     if (functionDeclHasDefaultArgument(FD)) {
12393       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12394         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12395         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12396       } else if (!D.isFunctionDefinition())
12397         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12398     }
12399 
12400     // Mark templated-scope function declarations as unsupported.
12401     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12402       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12403         << SS.getScopeRep() << SS.getRange()
12404         << cast<CXXRecordDecl>(CurContext);
12405       FrD->setUnsupportedFriend(true);
12406     }
12407   }
12408 
12409   return ND;
12410 }
12411 
12412 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12413   AdjustDeclIfTemplate(Dcl);
12414 
12415   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12416   if (!Fn) {
12417     Diag(DelLoc, diag::err_deleted_non_function);
12418     return;
12419   }
12420 
12421   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12422     // Don't consider the implicit declaration we generate for explicit
12423     // specializations. FIXME: Do not generate these implicit declarations.
12424     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12425          Prev->getPreviousDecl()) &&
12426         !Prev->isDefined()) {
12427       Diag(DelLoc, diag::err_deleted_decl_not_first);
12428       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12429            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12430                               : diag::note_previous_declaration);
12431     }
12432     // If the declaration wasn't the first, we delete the function anyway for
12433     // recovery.
12434     Fn = Fn->getCanonicalDecl();
12435   }
12436 
12437   // dllimport/dllexport cannot be deleted.
12438   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12439     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12440     Fn->setInvalidDecl();
12441   }
12442 
12443   if (Fn->isDeleted())
12444     return;
12445 
12446   // See if we're deleting a function which is already known to override a
12447   // non-deleted virtual function.
12448   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12449     bool IssuedDiagnostic = false;
12450     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12451                                         E = MD->end_overridden_methods();
12452          I != E; ++I) {
12453       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12454         if (!IssuedDiagnostic) {
12455           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12456           IssuedDiagnostic = true;
12457         }
12458         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12459       }
12460     }
12461   }
12462 
12463   // C++11 [basic.start.main]p3:
12464   //   A program that defines main as deleted [...] is ill-formed.
12465   if (Fn->isMain())
12466     Diag(DelLoc, diag::err_deleted_main);
12467 
12468   Fn->setDeletedAsWritten();
12469 }
12470 
12471 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12472   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12473 
12474   if (MD) {
12475     if (MD->getParent()->isDependentType()) {
12476       MD->setDefaulted();
12477       MD->setExplicitlyDefaulted();
12478       return;
12479     }
12480 
12481     CXXSpecialMember Member = getSpecialMember(MD);
12482     if (Member == CXXInvalid) {
12483       if (!MD->isInvalidDecl())
12484         Diag(DefaultLoc, diag::err_default_special_members);
12485       return;
12486     }
12487 
12488     MD->setDefaulted();
12489     MD->setExplicitlyDefaulted();
12490 
12491     // If this definition appears within the record, do the checking when
12492     // the record is complete.
12493     const FunctionDecl *Primary = MD;
12494     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12495       // Find the uninstantiated declaration that actually had the '= default'
12496       // on it.
12497       Pattern->isDefined(Primary);
12498 
12499     // If the method was defaulted on its first declaration, we will have
12500     // already performed the checking in CheckCompletedCXXClass. Such a
12501     // declaration doesn't trigger an implicit definition.
12502     if (Primary == Primary->getCanonicalDecl())
12503       return;
12504 
12505     CheckExplicitlyDefaultedSpecialMember(MD);
12506 
12507     if (MD->isInvalidDecl())
12508       return;
12509 
12510     switch (Member) {
12511     case CXXDefaultConstructor:
12512       DefineImplicitDefaultConstructor(DefaultLoc,
12513                                        cast<CXXConstructorDecl>(MD));
12514       break;
12515     case CXXCopyConstructor:
12516       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12517       break;
12518     case CXXCopyAssignment:
12519       DefineImplicitCopyAssignment(DefaultLoc, MD);
12520       break;
12521     case CXXDestructor:
12522       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12523       break;
12524     case CXXMoveConstructor:
12525       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12526       break;
12527     case CXXMoveAssignment:
12528       DefineImplicitMoveAssignment(DefaultLoc, MD);
12529       break;
12530     case CXXInvalid:
12531       llvm_unreachable("Invalid special member.");
12532     }
12533   } else {
12534     Diag(DefaultLoc, diag::err_default_special_members);
12535   }
12536 }
12537 
12538 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12539   for (Stmt::child_range CI = S->children(); CI; ++CI) {
12540     Stmt *SubStmt = *CI;
12541     if (!SubStmt)
12542       continue;
12543     if (isa<ReturnStmt>(SubStmt))
12544       Self.Diag(SubStmt->getLocStart(),
12545            diag::err_return_in_constructor_handler);
12546     if (!isa<Expr>(SubStmt))
12547       SearchForReturnInStmt(Self, SubStmt);
12548   }
12549 }
12550 
12551 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12552   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12553     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12554     SearchForReturnInStmt(*this, Handler);
12555   }
12556 }
12557 
12558 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12559                                              const CXXMethodDecl *Old) {
12560   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12561   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12562 
12563   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12564 
12565   // If the calling conventions match, everything is fine
12566   if (NewCC == OldCC)
12567     return false;
12568 
12569   // If the calling conventions mismatch because the new function is static,
12570   // suppress the calling convention mismatch error; the error about static
12571   // function override (err_static_overrides_virtual from
12572   // Sema::CheckFunctionDeclaration) is more clear.
12573   if (New->getStorageClass() == SC_Static)
12574     return false;
12575 
12576   Diag(New->getLocation(),
12577        diag::err_conflicting_overriding_cc_attributes)
12578     << New->getDeclName() << New->getType() << Old->getType();
12579   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12580   return true;
12581 }
12582 
12583 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12584                                              const CXXMethodDecl *Old) {
12585   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12586   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12587 
12588   if (Context.hasSameType(NewTy, OldTy) ||
12589       NewTy->isDependentType() || OldTy->isDependentType())
12590     return false;
12591 
12592   // Check if the return types are covariant
12593   QualType NewClassTy, OldClassTy;
12594 
12595   /// Both types must be pointers or references to classes.
12596   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12597     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12598       NewClassTy = NewPT->getPointeeType();
12599       OldClassTy = OldPT->getPointeeType();
12600     }
12601   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12602     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12603       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12604         NewClassTy = NewRT->getPointeeType();
12605         OldClassTy = OldRT->getPointeeType();
12606       }
12607     }
12608   }
12609 
12610   // The return types aren't either both pointers or references to a class type.
12611   if (NewClassTy.isNull()) {
12612     Diag(New->getLocation(),
12613          diag::err_different_return_type_for_overriding_virtual_function)
12614         << New->getDeclName() << NewTy << OldTy
12615         << New->getReturnTypeSourceRange();
12616     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12617         << Old->getReturnTypeSourceRange();
12618 
12619     return true;
12620   }
12621 
12622   // C++ [class.virtual]p6:
12623   //   If the return type of D::f differs from the return type of B::f, the
12624   //   class type in the return type of D::f shall be complete at the point of
12625   //   declaration of D::f or shall be the class type D.
12626   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12627     if (!RT->isBeingDefined() &&
12628         RequireCompleteType(New->getLocation(), NewClassTy,
12629                             diag::err_covariant_return_incomplete,
12630                             New->getDeclName()))
12631     return true;
12632   }
12633 
12634   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12635     // Check if the new class derives from the old class.
12636     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12637       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12638           << New->getDeclName() << NewTy << OldTy
12639           << New->getReturnTypeSourceRange();
12640       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12641           << Old->getReturnTypeSourceRange();
12642       return true;
12643     }
12644 
12645     // Check if we the conversion from derived to base is valid.
12646     if (CheckDerivedToBaseConversion(
12647             NewClassTy, OldClassTy,
12648             diag::err_covariant_return_inaccessible_base,
12649             diag::err_covariant_return_ambiguous_derived_to_base_conv,
12650             New->getLocation(), New->getReturnTypeSourceRange(),
12651             New->getDeclName(), nullptr)) {
12652       // FIXME: this note won't trigger for delayed access control
12653       // diagnostics, and it's impossible to get an undelayed error
12654       // here from access control during the original parse because
12655       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12656       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12657           << Old->getReturnTypeSourceRange();
12658       return true;
12659     }
12660   }
12661 
12662   // The qualifiers of the return types must be the same.
12663   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12664     Diag(New->getLocation(),
12665          diag::err_covariant_return_type_different_qualifications)
12666         << New->getDeclName() << NewTy << OldTy
12667         << New->getReturnTypeSourceRange();
12668     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12669         << Old->getReturnTypeSourceRange();
12670     return true;
12671   };
12672 
12673 
12674   // The new class type must have the same or less qualifiers as the old type.
12675   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12676     Diag(New->getLocation(),
12677          diag::err_covariant_return_type_class_type_more_qualified)
12678         << New->getDeclName() << NewTy << OldTy
12679         << New->getReturnTypeSourceRange();
12680     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12681         << Old->getReturnTypeSourceRange();
12682     return true;
12683   };
12684 
12685   return false;
12686 }
12687 
12688 /// \brief Mark the given method pure.
12689 ///
12690 /// \param Method the method to be marked pure.
12691 ///
12692 /// \param InitRange the source range that covers the "0" initializer.
12693 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12694   SourceLocation EndLoc = InitRange.getEnd();
12695   if (EndLoc.isValid())
12696     Method->setRangeEnd(EndLoc);
12697 
12698   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12699     Method->setPure();
12700     return false;
12701   }
12702 
12703   if (!Method->isInvalidDecl())
12704     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12705       << Method->getDeclName() << InitRange;
12706   return true;
12707 }
12708 
12709 /// \brief Determine whether the given declaration is a static data member.
12710 static bool isStaticDataMember(const Decl *D) {
12711   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12712     return Var->isStaticDataMember();
12713 
12714   return false;
12715 }
12716 
12717 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12718 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12719 /// is a fresh scope pushed for just this purpose.
12720 ///
12721 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12722 /// static data member of class X, names should be looked up in the scope of
12723 /// class X.
12724 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12725   // If there is no declaration, there was an error parsing it.
12726   if (!D || D->isInvalidDecl())
12727     return;
12728 
12729   // We will always have a nested name specifier here, but this declaration
12730   // might not be out of line if the specifier names the current namespace:
12731   //   extern int n;
12732   //   int ::n = 0;
12733   if (D->isOutOfLine())
12734     EnterDeclaratorContext(S, D->getDeclContext());
12735 
12736   // If we are parsing the initializer for a static data member, push a
12737   // new expression evaluation context that is associated with this static
12738   // data member.
12739   if (isStaticDataMember(D))
12740     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12741 }
12742 
12743 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12744 /// initializer for the out-of-line declaration 'D'.
12745 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12746   // If there is no declaration, there was an error parsing it.
12747   if (!D || D->isInvalidDecl())
12748     return;
12749 
12750   if (isStaticDataMember(D))
12751     PopExpressionEvaluationContext();
12752 
12753   if (D->isOutOfLine())
12754     ExitDeclaratorContext(S);
12755 }
12756 
12757 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12758 /// C++ if/switch/while/for statement.
12759 /// e.g: "if (int x = f()) {...}"
12760 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12761   // C++ 6.4p2:
12762   // The declarator shall not specify a function or an array.
12763   // The type-specifier-seq shall not contain typedef and shall not declare a
12764   // new class or enumeration.
12765   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12766          "Parser allowed 'typedef' as storage class of condition decl.");
12767 
12768   Decl *Dcl = ActOnDeclarator(S, D);
12769   if (!Dcl)
12770     return true;
12771 
12772   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12773     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12774       << D.getSourceRange();
12775     return true;
12776   }
12777 
12778   return Dcl;
12779 }
12780 
12781 void Sema::LoadExternalVTableUses() {
12782   if (!ExternalSource)
12783     return;
12784 
12785   SmallVector<ExternalVTableUse, 4> VTables;
12786   ExternalSource->ReadUsedVTables(VTables);
12787   SmallVector<VTableUse, 4> NewUses;
12788   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12789     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12790       = VTablesUsed.find(VTables[I].Record);
12791     // Even if a definition wasn't required before, it may be required now.
12792     if (Pos != VTablesUsed.end()) {
12793       if (!Pos->second && VTables[I].DefinitionRequired)
12794         Pos->second = true;
12795       continue;
12796     }
12797 
12798     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12799     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12800   }
12801 
12802   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12803 }
12804 
12805 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12806                           bool DefinitionRequired) {
12807   // Ignore any vtable uses in unevaluated operands or for classes that do
12808   // not have a vtable.
12809   if (!Class->isDynamicClass() || Class->isDependentContext() ||
12810       CurContext->isDependentContext() || isUnevaluatedContext())
12811     return;
12812 
12813   // Try to insert this class into the map.
12814   LoadExternalVTableUses();
12815   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12816   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12817     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12818   if (!Pos.second) {
12819     // If we already had an entry, check to see if we are promoting this vtable
12820     // to required a definition. If so, we need to reappend to the VTableUses
12821     // list, since we may have already processed the first entry.
12822     if (DefinitionRequired && !Pos.first->second) {
12823       Pos.first->second = true;
12824     } else {
12825       // Otherwise, we can early exit.
12826       return;
12827     }
12828   } else {
12829     // The Microsoft ABI requires that we perform the destructor body
12830     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12831     // the deleting destructor is emitted with the vtable, not with the
12832     // destructor definition as in the Itanium ABI.
12833     // If it has a definition, we do the check at that point instead.
12834     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12835         Class->hasUserDeclaredDestructor() &&
12836         !Class->getDestructor()->isDefined() &&
12837         !Class->getDestructor()->isDeleted()) {
12838       CXXDestructorDecl *DD = Class->getDestructor();
12839       ContextRAII SavedContext(*this, DD);
12840       CheckDestructor(DD);
12841     }
12842   }
12843 
12844   // Local classes need to have their virtual members marked
12845   // immediately. For all other classes, we mark their virtual members
12846   // at the end of the translation unit.
12847   if (Class->isLocalClass())
12848     MarkVirtualMembersReferenced(Loc, Class);
12849   else
12850     VTableUses.push_back(std::make_pair(Class, Loc));
12851 }
12852 
12853 bool Sema::DefineUsedVTables() {
12854   LoadExternalVTableUses();
12855   if (VTableUses.empty())
12856     return false;
12857 
12858   // Note: The VTableUses vector could grow as a result of marking
12859   // the members of a class as "used", so we check the size each
12860   // time through the loop and prefer indices (which are stable) to
12861   // iterators (which are not).
12862   bool DefinedAnything = false;
12863   for (unsigned I = 0; I != VTableUses.size(); ++I) {
12864     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12865     if (!Class)
12866       continue;
12867 
12868     SourceLocation Loc = VTableUses[I].second;
12869 
12870     bool DefineVTable = true;
12871 
12872     // If this class has a key function, but that key function is
12873     // defined in another translation unit, we don't need to emit the
12874     // vtable even though we're using it.
12875     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12876     if (KeyFunction && !KeyFunction->hasBody()) {
12877       // The key function is in another translation unit.
12878       DefineVTable = false;
12879       TemplateSpecializationKind TSK =
12880           KeyFunction->getTemplateSpecializationKind();
12881       assert(TSK != TSK_ExplicitInstantiationDefinition &&
12882              TSK != TSK_ImplicitInstantiation &&
12883              "Instantiations don't have key functions");
12884       (void)TSK;
12885     } else if (!KeyFunction) {
12886       // If we have a class with no key function that is the subject
12887       // of an explicit instantiation declaration, suppress the
12888       // vtable; it will live with the explicit instantiation
12889       // definition.
12890       bool IsExplicitInstantiationDeclaration
12891         = Class->getTemplateSpecializationKind()
12892                                       == TSK_ExplicitInstantiationDeclaration;
12893       for (auto R : Class->redecls()) {
12894         TemplateSpecializationKind TSK
12895           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
12896         if (TSK == TSK_ExplicitInstantiationDeclaration)
12897           IsExplicitInstantiationDeclaration = true;
12898         else if (TSK == TSK_ExplicitInstantiationDefinition) {
12899           IsExplicitInstantiationDeclaration = false;
12900           break;
12901         }
12902       }
12903 
12904       if (IsExplicitInstantiationDeclaration)
12905         DefineVTable = false;
12906     }
12907 
12908     // The exception specifications for all virtual members may be needed even
12909     // if we are not providing an authoritative form of the vtable in this TU.
12910     // We may choose to emit it available_externally anyway.
12911     if (!DefineVTable) {
12912       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12913       continue;
12914     }
12915 
12916     // Mark all of the virtual members of this class as referenced, so
12917     // that we can build a vtable. Then, tell the AST consumer that a
12918     // vtable for this class is required.
12919     DefinedAnything = true;
12920     MarkVirtualMembersReferenced(Loc, Class);
12921     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12922     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12923 
12924     // Optionally warn if we're emitting a weak vtable.
12925     if (Class->isExternallyVisible() &&
12926         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12927       const FunctionDecl *KeyFunctionDef = nullptr;
12928       if (!KeyFunction ||
12929           (KeyFunction->hasBody(KeyFunctionDef) &&
12930            KeyFunctionDef->isInlined()))
12931         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12932              TSK_ExplicitInstantiationDefinition
12933              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12934           << Class;
12935     }
12936   }
12937   VTableUses.clear();
12938 
12939   return DefinedAnything;
12940 }
12941 
12942 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12943                                                  const CXXRecordDecl *RD) {
12944   for (const auto *I : RD->methods())
12945     if (I->isVirtual() && !I->isPure())
12946       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
12947 }
12948 
12949 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12950                                         const CXXRecordDecl *RD) {
12951   // Mark all functions which will appear in RD's vtable as used.
12952   CXXFinalOverriderMap FinalOverriders;
12953   RD->getFinalOverriders(FinalOverriders);
12954   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12955                                             E = FinalOverriders.end();
12956        I != E; ++I) {
12957     for (OverridingMethods::const_iterator OI = I->second.begin(),
12958                                            OE = I->second.end();
12959          OI != OE; ++OI) {
12960       assert(OI->second.size() > 0 && "no final overrider");
12961       CXXMethodDecl *Overrider = OI->second.front().Method;
12962 
12963       // C++ [basic.def.odr]p2:
12964       //   [...] A virtual member function is used if it is not pure. [...]
12965       if (!Overrider->isPure())
12966         MarkFunctionReferenced(Loc, Overrider);
12967     }
12968   }
12969 
12970   // Only classes that have virtual bases need a VTT.
12971   if (RD->getNumVBases() == 0)
12972     return;
12973 
12974   for (const auto &I : RD->bases()) {
12975     const CXXRecordDecl *Base =
12976         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
12977     if (Base->getNumVBases() == 0)
12978       continue;
12979     MarkVirtualMembersReferenced(Loc, Base);
12980   }
12981 }
12982 
12983 /// SetIvarInitializers - This routine builds initialization ASTs for the
12984 /// Objective-C implementation whose ivars need be initialized.
12985 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12986   if (!getLangOpts().CPlusPlus)
12987     return;
12988   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12989     SmallVector<ObjCIvarDecl*, 8> ivars;
12990     CollectIvarsToConstructOrDestruct(OID, ivars);
12991     if (ivars.empty())
12992       return;
12993     SmallVector<CXXCtorInitializer*, 32> AllToInit;
12994     for (unsigned i = 0; i < ivars.size(); i++) {
12995       FieldDecl *Field = ivars[i];
12996       if (Field->isInvalidDecl())
12997         continue;
12998 
12999       CXXCtorInitializer *Member;
13000       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13001       InitializationKind InitKind =
13002         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13003 
13004       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13005       ExprResult MemberInit =
13006         InitSeq.Perform(*this, InitEntity, InitKind, None);
13007       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13008       // Note, MemberInit could actually come back empty if no initialization
13009       // is required (e.g., because it would call a trivial default constructor)
13010       if (!MemberInit.get() || MemberInit.isInvalid())
13011         continue;
13012 
13013       Member =
13014         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13015                                          SourceLocation(),
13016                                          MemberInit.getAs<Expr>(),
13017                                          SourceLocation());
13018       AllToInit.push_back(Member);
13019 
13020       // Be sure that the destructor is accessible and is marked as referenced.
13021       if (const RecordType *RecordTy
13022                   = Context.getBaseElementType(Field->getType())
13023                                                         ->getAs<RecordType>()) {
13024                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13025         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13026           MarkFunctionReferenced(Field->getLocation(), Destructor);
13027           CheckDestructorAccess(Field->getLocation(), Destructor,
13028                             PDiag(diag::err_access_dtor_ivar)
13029                               << Context.getBaseElementType(Field->getType()));
13030         }
13031       }
13032     }
13033     ObjCImplementation->setIvarInitializers(Context,
13034                                             AllToInit.data(), AllToInit.size());
13035   }
13036 }
13037 
13038 static
13039 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13040                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13041                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13042                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13043                            Sema &S) {
13044   if (Ctor->isInvalidDecl())
13045     return;
13046 
13047   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13048 
13049   // Target may not be determinable yet, for instance if this is a dependent
13050   // call in an uninstantiated template.
13051   if (Target) {
13052     const FunctionDecl *FNTarget = nullptr;
13053     (void)Target->hasBody(FNTarget);
13054     Target = const_cast<CXXConstructorDecl*>(
13055       cast_or_null<CXXConstructorDecl>(FNTarget));
13056   }
13057 
13058   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13059                      // Avoid dereferencing a null pointer here.
13060                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13061 
13062   if (!Current.insert(Canonical))
13063     return;
13064 
13065   // We know that beyond here, we aren't chaining into a cycle.
13066   if (!Target || !Target->isDelegatingConstructor() ||
13067       Target->isInvalidDecl() || Valid.count(TCanonical)) {
13068     Valid.insert(Current.begin(), Current.end());
13069     Current.clear();
13070   // We've hit a cycle.
13071   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13072              Current.count(TCanonical)) {
13073     // If we haven't diagnosed this cycle yet, do so now.
13074     if (!Invalid.count(TCanonical)) {
13075       S.Diag((*Ctor->init_begin())->getSourceLocation(),
13076              diag::warn_delegating_ctor_cycle)
13077         << Ctor;
13078 
13079       // Don't add a note for a function delegating directly to itself.
13080       if (TCanonical != Canonical)
13081         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13082 
13083       CXXConstructorDecl *C = Target;
13084       while (C->getCanonicalDecl() != Canonical) {
13085         const FunctionDecl *FNTarget = nullptr;
13086         (void)C->getTargetConstructor()->hasBody(FNTarget);
13087         assert(FNTarget && "Ctor cycle through bodiless function");
13088 
13089         C = const_cast<CXXConstructorDecl*>(
13090           cast<CXXConstructorDecl>(FNTarget));
13091         S.Diag(C->getLocation(), diag::note_which_delegates_to);
13092       }
13093     }
13094 
13095     Invalid.insert(Current.begin(), Current.end());
13096     Current.clear();
13097   } else {
13098     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13099   }
13100 }
13101 
13102 
13103 void Sema::CheckDelegatingCtorCycles() {
13104   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13105 
13106   for (DelegatingCtorDeclsType::iterator
13107          I = DelegatingCtorDecls.begin(ExternalSource),
13108          E = DelegatingCtorDecls.end();
13109        I != E; ++I)
13110     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13111 
13112   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13113                                                          CE = Invalid.end();
13114        CI != CE; ++CI)
13115     (*CI)->setInvalidDecl();
13116 }
13117 
13118 namespace {
13119   /// \brief AST visitor that finds references to the 'this' expression.
13120   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13121     Sema &S;
13122 
13123   public:
13124     explicit FindCXXThisExpr(Sema &S) : S(S) { }
13125 
13126     bool VisitCXXThisExpr(CXXThisExpr *E) {
13127       S.Diag(E->getLocation(), diag::err_this_static_member_func)
13128         << E->isImplicit();
13129       return false;
13130     }
13131   };
13132 }
13133 
13134 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13135   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13136   if (!TSInfo)
13137     return false;
13138 
13139   TypeLoc TL = TSInfo->getTypeLoc();
13140   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13141   if (!ProtoTL)
13142     return false;
13143 
13144   // C++11 [expr.prim.general]p3:
13145   //   [The expression this] shall not appear before the optional
13146   //   cv-qualifier-seq and it shall not appear within the declaration of a
13147   //   static member function (although its type and value category are defined
13148   //   within a static member function as they are within a non-static member
13149   //   function). [ Note: this is because declaration matching does not occur
13150   //  until the complete declarator is known. - end note ]
13151   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13152   FindCXXThisExpr Finder(*this);
13153 
13154   // If the return type came after the cv-qualifier-seq, check it now.
13155   if (Proto->hasTrailingReturn() &&
13156       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13157     return true;
13158 
13159   // Check the exception specification.
13160   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13161     return true;
13162 
13163   return checkThisInStaticMemberFunctionAttributes(Method);
13164 }
13165 
13166 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13167   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13168   if (!TSInfo)
13169     return false;
13170 
13171   TypeLoc TL = TSInfo->getTypeLoc();
13172   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13173   if (!ProtoTL)
13174     return false;
13175 
13176   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13177   FindCXXThisExpr Finder(*this);
13178 
13179   switch (Proto->getExceptionSpecType()) {
13180   case EST_Uninstantiated:
13181   case EST_Unevaluated:
13182   case EST_BasicNoexcept:
13183   case EST_DynamicNone:
13184   case EST_MSAny:
13185   case EST_None:
13186     break;
13187 
13188   case EST_ComputedNoexcept:
13189     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13190       return true;
13191 
13192   case EST_Dynamic:
13193     for (const auto &E : Proto->exceptions()) {
13194       if (!Finder.TraverseType(E))
13195         return true;
13196     }
13197     break;
13198   }
13199 
13200   return false;
13201 }
13202 
13203 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13204   FindCXXThisExpr Finder(*this);
13205 
13206   // Check attributes.
13207   for (const auto *A : Method->attrs()) {
13208     // FIXME: This should be emitted by tblgen.
13209     Expr *Arg = nullptr;
13210     ArrayRef<Expr *> Args;
13211     if (const auto *G = dyn_cast<GuardedByAttr>(A))
13212       Arg = G->getArg();
13213     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13214       Arg = G->getArg();
13215     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13216       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13217     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13218       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13219     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13220       Arg = ETLF->getSuccessValue();
13221       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13222     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13223       Arg = STLF->getSuccessValue();
13224       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13225     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13226       Arg = LR->getArg();
13227     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13228       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13229     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13230       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13231     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13232       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13233     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13234       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13235     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13236       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13237 
13238     if (Arg && !Finder.TraverseStmt(Arg))
13239       return true;
13240 
13241     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13242       if (!Finder.TraverseStmt(Args[I]))
13243         return true;
13244     }
13245   }
13246 
13247   return false;
13248 }
13249 
13250 void
13251 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
13252                                   ArrayRef<ParsedType> DynamicExceptions,
13253                                   ArrayRef<SourceRange> DynamicExceptionRanges,
13254                                   Expr *NoexceptExpr,
13255                                   SmallVectorImpl<QualType> &Exceptions,
13256                                   FunctionProtoType::ExceptionSpecInfo &ESI) {
13257   Exceptions.clear();
13258   ESI.Type = EST;
13259   if (EST == EST_Dynamic) {
13260     Exceptions.reserve(DynamicExceptions.size());
13261     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13262       // FIXME: Preserve type source info.
13263       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13264 
13265       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13266       collectUnexpandedParameterPacks(ET, Unexpanded);
13267       if (!Unexpanded.empty()) {
13268         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
13269                                          UPPC_ExceptionType,
13270                                          Unexpanded);
13271         continue;
13272       }
13273 
13274       // Check that the type is valid for an exception spec, and
13275       // drop it if not.
13276       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13277         Exceptions.push_back(ET);
13278     }
13279     ESI.Exceptions = Exceptions;
13280     return;
13281   }
13282 
13283   if (EST == EST_ComputedNoexcept) {
13284     // If an error occurred, there's no expression here.
13285     if (NoexceptExpr) {
13286       assert((NoexceptExpr->isTypeDependent() ||
13287               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13288               Context.BoolTy) &&
13289              "Parser should have made sure that the expression is boolean");
13290       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13291         ESI.Type = EST_BasicNoexcept;
13292         return;
13293       }
13294 
13295       if (!NoexceptExpr->isValueDependent())
13296         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13297                          diag::err_noexcept_needs_constant_expression,
13298                          /*AllowFold*/ false).get();
13299       ESI.NoexceptExpr = NoexceptExpr;
13300     }
13301     return;
13302   }
13303 }
13304 
13305 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13306 ///
13307 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13308                                        SourceLocation DeclStart,
13309                                        Declarator &D, Expr *BitWidth,
13310                                        InClassInitStyle InitStyle,
13311                                        AccessSpecifier AS,
13312                                        AttributeList *MSPropertyAttr) {
13313   IdentifierInfo *II = D.getIdentifier();
13314   if (!II) {
13315     Diag(DeclStart, diag::err_anonymous_property);
13316     return nullptr;
13317   }
13318   SourceLocation Loc = D.getIdentifierLoc();
13319 
13320   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13321   QualType T = TInfo->getType();
13322   if (getLangOpts().CPlusPlus) {
13323     CheckExtraCXXDefaultArguments(D);
13324 
13325     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13326                                         UPPC_DataMemberType)) {
13327       D.setInvalidType();
13328       T = Context.IntTy;
13329       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13330     }
13331   }
13332 
13333   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13334 
13335   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13336     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13337          diag::err_invalid_thread)
13338       << DeclSpec::getSpecifierName(TSCS);
13339 
13340   // Check to see if this name was declared as a member previously
13341   NamedDecl *PrevDecl = nullptr;
13342   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13343   LookupName(Previous, S);
13344   switch (Previous.getResultKind()) {
13345   case LookupResult::Found:
13346   case LookupResult::FoundUnresolvedValue:
13347     PrevDecl = Previous.getAsSingle<NamedDecl>();
13348     break;
13349 
13350   case LookupResult::FoundOverloaded:
13351     PrevDecl = Previous.getRepresentativeDecl();
13352     break;
13353 
13354   case LookupResult::NotFound:
13355   case LookupResult::NotFoundInCurrentInstantiation:
13356   case LookupResult::Ambiguous:
13357     break;
13358   }
13359 
13360   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13361     // Maybe we will complain about the shadowed template parameter.
13362     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13363     // Just pretend that we didn't see the previous declaration.
13364     PrevDecl = nullptr;
13365   }
13366 
13367   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13368     PrevDecl = nullptr;
13369 
13370   SourceLocation TSSL = D.getLocStart();
13371   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13372   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13373       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13374   ProcessDeclAttributes(TUScope, NewPD, D);
13375   NewPD->setAccess(AS);
13376 
13377   if (NewPD->isInvalidDecl())
13378     Record->setInvalidDecl();
13379 
13380   if (D.getDeclSpec().isModulePrivateSpecified())
13381     NewPD->setModulePrivate();
13382 
13383   if (NewPD->isInvalidDecl() && PrevDecl) {
13384     // Don't introduce NewFD into scope; there's already something
13385     // with the same name in the same scope.
13386   } else if (II) {
13387     PushOnScopeChains(NewPD, S);
13388   } else
13389     Record->addDecl(NewPD);
13390 
13391   return NewPD;
13392 }
13393