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, Param->getType(), VK_RValue));
357 }
358 
359 /// CheckExtraCXXDefaultArguments - Check for any extra default
360 /// arguments in the declarator, which is not a function declaration
361 /// or definition and therefore is not permitted to have default
362 /// arguments. This routine should be invoked for every declarator
363 /// that is not a function declaration or definition.
364 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365   // C++ [dcl.fct.default]p3
366   //   A default argument expression shall be specified only in the
367   //   parameter-declaration-clause of a function declaration or in a
368   //   template-parameter (14.1). It shall not be specified for a
369   //   parameter pack. If it is specified in a
370   //   parameter-declaration-clause, it shall not occur within a
371   //   declarator or abstract-declarator of a parameter-declaration.
372   bool MightBeFunction = D.isFunctionDeclarationContext();
373   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
374     DeclaratorChunk &chunk = D.getTypeObject(i);
375     if (chunk.Kind == DeclaratorChunk::Function) {
376       if (MightBeFunction) {
377         // This is a function declaration. It can have default arguments, but
378         // keep looking in case its return type is a function type with default
379         // arguments.
380         MightBeFunction = false;
381         continue;
382       }
383       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
384            ++argIdx) {
385         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
386         if (Param->hasUnparsedDefaultArg()) {
387           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
388           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
389             << SourceRange((*Toks)[1].getLocation(),
390                            Toks->back().getLocation());
391           delete Toks;
392           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
393         } else if (Param->getDefaultArg()) {
394           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395             << Param->getDefaultArg()->getSourceRange();
396           Param->setDefaultArg(nullptr);
397         }
398       }
399     } else if (chunk.Kind != DeclaratorChunk::Paren) {
400       MightBeFunction = false;
401     }
402   }
403 }
404 
405 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408     if (!PVD->hasDefaultArg())
409       return false;
410     if (!PVD->hasInheritedDefaultArg())
411       return true;
412   }
413   return false;
414 }
415 
416 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
417 /// function, once we already know that they have the same
418 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419 /// error, false otherwise.
420 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421                                 Scope *S) {
422   bool Invalid = false;
423 
424   // C++ [dcl.fct.default]p4:
425   //   For non-template functions, default arguments can be added in
426   //   later declarations of a function in the same
427   //   scope. Declarations in different scopes have completely
428   //   distinct sets of default arguments. That is, declarations in
429   //   inner scopes do not acquire default arguments from
430   //   declarations in outer scopes, and vice versa. In a given
431   //   function declaration, all parameters subsequent to a
432   //   parameter with a default argument shall have default
433   //   arguments supplied in this or previous declarations. A
434   //   default argument shall not be redefined by a later
435   //   declaration (not even to the same value).
436   //
437   // C++ [dcl.fct.default]p6:
438   //   Except for member functions of class templates, the default arguments
439   //   in a member function definition that appears outside of the class
440   //   definition are added to the set of default arguments provided by the
441   //   member function declaration in the class definition.
442   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443     ParmVarDecl *OldParam = Old->getParamDecl(p);
444     ParmVarDecl *NewParam = New->getParamDecl(p);
445 
446     bool OldParamHasDfl = OldParam->hasDefaultArg();
447     bool NewParamHasDfl = NewParam->hasDefaultArg();
448 
449     NamedDecl *ND = Old;
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->getLexicalDeclContext();
455     if (!ScopeDC->isFunctionOrMethod())
456       ScopeDC = New->getDeclContext();
457     if (S && !isDeclInScope(ND, 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 
464     if (OldParamHasDfl && NewParamHasDfl) {
465 
466       unsigned DiagDefaultParamID =
467         diag::err_param_default_argument_redefinition;
468 
469       // MSVC accepts that default parameters be redefined for member functions
470       // of template class. The new default parameter's value is ignored.
471       Invalid = true;
472       if (getLangOpts().MicrosoftExt) {
473         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474         if (MD && MD->getParent()->getDescribedClassTemplate()) {
475           // Merge the old default argument into the new parameter.
476           NewParam->setHasInheritedDefaultArg();
477           if (OldParam->hasUninstantiatedDefaultArg())
478             NewParam->setUninstantiatedDefaultArg(
479                                       OldParam->getUninstantiatedDefaultArg());
480           else
481             NewParam->setDefaultArg(OldParam->getInit());
482           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
483           Invalid = false;
484         }
485       }
486 
487       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488       // hint here. Alternatively, we could walk the type-source information
489       // for NewParam to find the last source location in the type... but it
490       // isn't worth the effort right now. This is the kind of test case that
491       // is hard to get right:
492       //   int f(int);
493       //   void g(int (*fp)(int) = f);
494       //   void g(int (*fp)(int) = &f);
495       Diag(NewParam->getLocation(), DiagDefaultParamID)
496         << NewParam->getDefaultArgRange();
497 
498       // Look for the function declaration where the default argument was
499       // actually written, which may be a declaration prior to Old.
500       for (FunctionDecl *Older = Old->getPreviousDecl();
501            Older; Older = Older->getPreviousDecl()) {
502         if (!Older->getParamDecl(p)->hasDefaultArg())
503           break;
504 
505         OldParam = Older->getParamDecl(p);
506       }
507 
508       Diag(OldParam->getLocation(), diag::note_previous_definition)
509         << OldParam->getDefaultArgRange();
510     } else if (OldParamHasDfl) {
511       // Merge the old default argument into the new parameter.
512       // It's important to use getInit() here;  getDefaultArg()
513       // strips off any top-level ExprWithCleanups.
514       NewParam->setHasInheritedDefaultArg();
515       if (OldParam->hasUninstantiatedDefaultArg())
516         NewParam->setUninstantiatedDefaultArg(
517                                       OldParam->getUninstantiatedDefaultArg());
518       else
519         NewParam->setDefaultArg(OldParam->getInit());
520     } else if (NewParamHasDfl) {
521       if (New->getDescribedFunctionTemplate()) {
522         // Paragraph 4, quoted above, only applies to non-template functions.
523         Diag(NewParam->getLocation(),
524              diag::err_param_default_argument_template_redecl)
525           << NewParam->getDefaultArgRange();
526         Diag(Old->getLocation(), diag::note_template_prev_declaration)
527           << false;
528       } else if (New->getTemplateSpecializationKind()
529                    != TSK_ImplicitInstantiation &&
530                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
531         // C++ [temp.expr.spec]p21:
532         //   Default function arguments shall not be specified in a declaration
533         //   or a definition for one of the following explicit specializations:
534         //     - the explicit specialization of a function template;
535         //     - the explicit specialization of a member function template;
536         //     - the explicit specialization of a member function of a class
537         //       template where the class template specialization to which the
538         //       member function specialization belongs is implicitly
539         //       instantiated.
540         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542           << New->getDeclName()
543           << NewParam->getDefaultArgRange();
544       } else if (New->getDeclContext()->isDependentContext()) {
545         // C++ [dcl.fct.default]p6 (DR217):
546         //   Default arguments for a member function of a class template shall
547         //   be specified on the initial declaration of the member function
548         //   within the class template.
549         //
550         // Reading the tea leaves a bit in DR217 and its reference to DR205
551         // leads me to the conclusion that one cannot add default function
552         // arguments for an out-of-line definition of a member function of a
553         // dependent type.
554         int WhichKind = 2;
555         if (CXXRecordDecl *Record
556               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557           if (Record->getDescribedClassTemplate())
558             WhichKind = 0;
559           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560             WhichKind = 1;
561           else
562             WhichKind = 2;
563         }
564 
565         Diag(NewParam->getLocation(),
566              diag::err_param_default_argument_member_template_redecl)
567           << WhichKind
568           << NewParam->getDefaultArgRange();
569       }
570     }
571   }
572 
573   // DR1344: If a default argument is added outside a class definition and that
574   // default argument makes the function a special member function, the program
575   // is ill-formed. This can only happen for constructors.
576   if (isa<CXXConstructorDecl>(New) &&
577       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580     if (NewSM != OldSM) {
581       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582       assert(NewParam->hasDefaultArg());
583       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584         << NewParam->getDefaultArgRange() << NewSM;
585       Diag(Old->getLocation(), diag::note_previous_declaration);
586     }
587   }
588 
589   const FunctionDecl *Def;
590   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
591   // template has a constexpr specifier then all its declarations shall
592   // contain the constexpr specifier.
593   if (New->isConstexpr() != Old->isConstexpr()) {
594     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
595       << New << New->isConstexpr();
596     Diag(Old->getLocation(), diag::note_previous_declaration);
597     Invalid = true;
598   } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
599     // C++11 [dcl.fcn.spec]p4:
600     //   If the definition of a function appears in a translation unit before its
601     //   first declaration as inline, the program is ill-formed.
602     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
603     Diag(Def->getLocation(), diag::note_previous_definition);
604     Invalid = true;
605   }
606 
607   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
608   // argument expression, that declaration shall be a definition and shall be
609   // the only declaration of the function or function template in the
610   // translation unit.
611   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
612       functionDeclHasDefaultArgument(Old)) {
613     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
614     Diag(Old->getLocation(), diag::note_previous_declaration);
615     Invalid = true;
616   }
617 
618   if (CheckEquivalentExceptionSpec(Old, New))
619     Invalid = true;
620 
621   return Invalid;
622 }
623 
624 /// \brief Merge the exception specifications of two variable declarations.
625 ///
626 /// This is called when there's a redeclaration of a VarDecl. The function
627 /// checks if the redeclaration might have an exception specification and
628 /// validates compatibility and merges the specs if necessary.
629 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
630   // Shortcut if exceptions are disabled.
631   if (!getLangOpts().CXXExceptions)
632     return;
633 
634   assert(Context.hasSameType(New->getType(), Old->getType()) &&
635          "Should only be called if types are otherwise the same.");
636 
637   QualType NewType = New->getType();
638   QualType OldType = Old->getType();
639 
640   // We're only interested in pointers and references to functions, as well
641   // as pointers to member functions.
642   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
643     NewType = R->getPointeeType();
644     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
645   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
646     NewType = P->getPointeeType();
647     OldType = OldType->getAs<PointerType>()->getPointeeType();
648   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
649     NewType = M->getPointeeType();
650     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
651   }
652 
653   if (!NewType->isFunctionProtoType())
654     return;
655 
656   // There's lots of special cases for functions. For function pointers, system
657   // libraries are hopefully not as broken so that we don't need these
658   // workarounds.
659   if (CheckEquivalentExceptionSpec(
660         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
661         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
662     New->setInvalidDecl();
663   }
664 }
665 
666 /// CheckCXXDefaultArguments - Verify that the default arguments for a
667 /// function declaration are well-formed according to C++
668 /// [dcl.fct.default].
669 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
670   unsigned NumParams = FD->getNumParams();
671   unsigned p;
672 
673   // Find first parameter with a default argument
674   for (p = 0; p < NumParams; ++p) {
675     ParmVarDecl *Param = FD->getParamDecl(p);
676     if (Param->hasDefaultArg())
677       break;
678   }
679 
680   // C++ [dcl.fct.default]p4:
681   //   In a given function declaration, all parameters
682   //   subsequent to a parameter with a default argument shall
683   //   have default arguments supplied in this or previous
684   //   declarations. A default argument shall not be redefined
685   //   by a later declaration (not even to the same value).
686   unsigned LastMissingDefaultArg = 0;
687   for (; p < NumParams; ++p) {
688     ParmVarDecl *Param = FD->getParamDecl(p);
689     if (!Param->hasDefaultArg()) {
690       if (Param->isInvalidDecl())
691         /* We already complained about this parameter. */;
692       else if (Param->getIdentifier())
693         Diag(Param->getLocation(),
694              diag::err_param_default_argument_missing_name)
695           << Param->getIdentifier();
696       else
697         Diag(Param->getLocation(),
698              diag::err_param_default_argument_missing);
699 
700       LastMissingDefaultArg = p;
701     }
702   }
703 
704   if (LastMissingDefaultArg > 0) {
705     // Some default arguments were missing. Clear out all of the
706     // default arguments up to (and including) the last missing
707     // default argument, so that we leave the function parameters
708     // in a semantically valid state.
709     for (p = 0; p <= LastMissingDefaultArg; ++p) {
710       ParmVarDecl *Param = FD->getParamDecl(p);
711       if (Param->hasDefaultArg()) {
712         Param->setDefaultArg(nullptr);
713       }
714     }
715   }
716 }
717 
718 // CheckConstexprParameterTypes - Check whether a function's parameter types
719 // are all literal types. If so, return true. If not, produce a suitable
720 // diagnostic and return false.
721 static bool CheckConstexprParameterTypes(Sema &SemaRef,
722                                          const FunctionDecl *FD) {
723   unsigned ArgIndex = 0;
724   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
725   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
726                                               e = FT->param_type_end();
727        i != e; ++i, ++ArgIndex) {
728     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
729     SourceLocation ParamLoc = PD->getLocation();
730     if (!(*i)->isDependentType() &&
731         SemaRef.RequireLiteralType(ParamLoc, *i,
732                                    diag::err_constexpr_non_literal_param,
733                                    ArgIndex+1, PD->getSourceRange(),
734                                    isa<CXXConstructorDecl>(FD)))
735       return false;
736   }
737   return true;
738 }
739 
740 /// \brief Get diagnostic %select index for tag kind for
741 /// record diagnostic message.
742 /// WARNING: Indexes apply to particular diagnostics only!
743 ///
744 /// \returns diagnostic %select index.
745 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
746   switch (Tag) {
747   case TTK_Struct: return 0;
748   case TTK_Interface: return 1;
749   case TTK_Class:  return 2;
750   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
751   }
752 }
753 
754 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
755 // the requirements of a constexpr function definition or a constexpr
756 // constructor definition. If so, return true. If not, produce appropriate
757 // diagnostics and return false.
758 //
759 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
760 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
761   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
762   if (MD && MD->isInstance()) {
763     // C++11 [dcl.constexpr]p4:
764     //  The definition of a constexpr constructor shall satisfy the following
765     //  constraints:
766     //  - the class shall not have any virtual base classes;
767     const CXXRecordDecl *RD = MD->getParent();
768     if (RD->getNumVBases()) {
769       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
770         << isa<CXXConstructorDecl>(NewFD)
771         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
772       for (const auto &I : RD->vbases())
773         Diag(I.getLocStart(),
774              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
775       return false;
776     }
777   }
778 
779   if (!isa<CXXConstructorDecl>(NewFD)) {
780     // C++11 [dcl.constexpr]p3:
781     //  The definition of a constexpr function shall satisfy the following
782     //  constraints:
783     // - it shall not be virtual;
784     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
785     if (Method && Method->isVirtual()) {
786       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
787 
788       // If it's not obvious why this function is virtual, find an overridden
789       // function which uses the 'virtual' keyword.
790       const CXXMethodDecl *WrittenVirtual = Method;
791       while (!WrittenVirtual->isVirtualAsWritten())
792         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
793       if (WrittenVirtual != Method)
794         Diag(WrittenVirtual->getLocation(),
795              diag::note_overridden_virtual_function);
796       return false;
797     }
798 
799     // - its return type shall be a literal type;
800     QualType RT = NewFD->getReturnType();
801     if (!RT->isDependentType() &&
802         RequireLiteralType(NewFD->getLocation(), RT,
803                            diag::err_constexpr_non_literal_return))
804       return false;
805   }
806 
807   // - each of its parameter types shall be a literal type;
808   if (!CheckConstexprParameterTypes(*this, NewFD))
809     return false;
810 
811   return true;
812 }
813 
814 /// Check the given declaration statement is legal within a constexpr function
815 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
816 ///
817 /// \return true if the body is OK (maybe only as an extension), false if we
818 ///         have diagnosed a problem.
819 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
820                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
821   // C++11 [dcl.constexpr]p3 and p4:
822   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
823   //  contain only
824   for (const auto *DclIt : DS->decls()) {
825     switch (DclIt->getKind()) {
826     case Decl::StaticAssert:
827     case Decl::Using:
828     case Decl::UsingShadow:
829     case Decl::UsingDirective:
830     case Decl::UnresolvedUsingTypename:
831     case Decl::UnresolvedUsingValue:
832       //   - static_assert-declarations
833       //   - using-declarations,
834       //   - using-directives,
835       continue;
836 
837     case Decl::Typedef:
838     case Decl::TypeAlias: {
839       //   - typedef declarations and alias-declarations that do not define
840       //     classes or enumerations,
841       const auto *TN = cast<TypedefNameDecl>(DclIt);
842       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
843         // Don't allow variably-modified types in constexpr functions.
844         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
845         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
846           << TL.getSourceRange() << TL.getType()
847           << isa<CXXConstructorDecl>(Dcl);
848         return false;
849       }
850       continue;
851     }
852 
853     case Decl::Enum:
854     case Decl::CXXRecord:
855       // C++1y allows types to be defined, not just declared.
856       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
857         SemaRef.Diag(DS->getLocStart(),
858                      SemaRef.getLangOpts().CPlusPlus14
859                        ? diag::warn_cxx11_compat_constexpr_type_definition
860                        : diag::ext_constexpr_type_definition)
861           << isa<CXXConstructorDecl>(Dcl);
862       continue;
863 
864     case Decl::EnumConstant:
865     case Decl::IndirectField:
866     case Decl::ParmVar:
867       // These can only appear with other declarations which are banned in
868       // C++11 and permitted in C++1y, so ignore them.
869       continue;
870 
871     case Decl::Var: {
872       // C++1y [dcl.constexpr]p3 allows anything except:
873       //   a definition of a variable of non-literal type or of static or
874       //   thread storage duration or for which no initialization is performed.
875       const auto *VD = cast<VarDecl>(DclIt);
876       if (VD->isThisDeclarationADefinition()) {
877         if (VD->isStaticLocal()) {
878           SemaRef.Diag(VD->getLocation(),
879                        diag::err_constexpr_local_var_static)
880             << isa<CXXConstructorDecl>(Dcl)
881             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
882           return false;
883         }
884         if (!VD->getType()->isDependentType() &&
885             SemaRef.RequireLiteralType(
886               VD->getLocation(), VD->getType(),
887               diag::err_constexpr_local_var_non_literal_type,
888               isa<CXXConstructorDecl>(Dcl)))
889           return false;
890         if (!VD->getType()->isDependentType() &&
891             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
892           SemaRef.Diag(VD->getLocation(),
893                        diag::err_constexpr_local_var_no_init)
894             << isa<CXXConstructorDecl>(Dcl);
895           return false;
896         }
897       }
898       SemaRef.Diag(VD->getLocation(),
899                    SemaRef.getLangOpts().CPlusPlus14
900                     ? diag::warn_cxx11_compat_constexpr_local_var
901                     : diag::ext_constexpr_local_var)
902         << isa<CXXConstructorDecl>(Dcl);
903       continue;
904     }
905 
906     case Decl::NamespaceAlias:
907     case Decl::Function:
908       // These are disallowed in C++11 and permitted in C++1y. Allow them
909       // everywhere as an extension.
910       if (!Cxx1yLoc.isValid())
911         Cxx1yLoc = DS->getLocStart();
912       continue;
913 
914     default:
915       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
916         << isa<CXXConstructorDecl>(Dcl);
917       return false;
918     }
919   }
920 
921   return true;
922 }
923 
924 /// Check that the given field is initialized within a constexpr constructor.
925 ///
926 /// \param Dcl The constexpr constructor being checked.
927 /// \param Field The field being checked. This may be a member of an anonymous
928 ///        struct or union nested within the class being checked.
929 /// \param Inits All declarations, including anonymous struct/union members and
930 ///        indirect members, for which any initialization was provided.
931 /// \param Diagnosed Set to true if an error is produced.
932 static void CheckConstexprCtorInitializer(Sema &SemaRef,
933                                           const FunctionDecl *Dcl,
934                                           FieldDecl *Field,
935                                           llvm::SmallSet<Decl*, 16> &Inits,
936                                           bool &Diagnosed) {
937   if (Field->isInvalidDecl())
938     return;
939 
940   if (Field->isUnnamedBitfield())
941     return;
942 
943   // Anonymous unions with no variant members and empty anonymous structs do not
944   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
945   // indirect fields don't need initializing.
946   if (Field->isAnonymousStructOrUnion() &&
947       (Field->getType()->isUnionType()
948            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
949            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
950     return;
951 
952   if (!Inits.count(Field)) {
953     if (!Diagnosed) {
954       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
955       Diagnosed = true;
956     }
957     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
958   } else if (Field->isAnonymousStructOrUnion()) {
959     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
960     for (auto *I : RD->fields())
961       // If an anonymous union contains an anonymous struct of which any member
962       // is initialized, all members must be initialized.
963       if (!RD->isUnion() || Inits.count(I))
964         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
965   }
966 }
967 
968 /// Check the provided statement is allowed in a constexpr function
969 /// definition.
970 static bool
971 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
972                            SmallVectorImpl<SourceLocation> &ReturnStmts,
973                            SourceLocation &Cxx1yLoc) {
974   // - its function-body shall be [...] a compound-statement that contains only
975   switch (S->getStmtClass()) {
976   case Stmt::NullStmtClass:
977     //   - null statements,
978     return true;
979 
980   case Stmt::DeclStmtClass:
981     //   - static_assert-declarations
982     //   - using-declarations,
983     //   - using-directives,
984     //   - typedef declarations and alias-declarations that do not define
985     //     classes or enumerations,
986     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
987       return false;
988     return true;
989 
990   case Stmt::ReturnStmtClass:
991     //   - and exactly one return statement;
992     if (isa<CXXConstructorDecl>(Dcl)) {
993       // C++1y allows return statements in constexpr constructors.
994       if (!Cxx1yLoc.isValid())
995         Cxx1yLoc = S->getLocStart();
996       return true;
997     }
998 
999     ReturnStmts.push_back(S->getLocStart());
1000     return true;
1001 
1002   case Stmt::CompoundStmtClass: {
1003     // C++1y allows compound-statements.
1004     if (!Cxx1yLoc.isValid())
1005       Cxx1yLoc = S->getLocStart();
1006 
1007     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1008     for (auto *BodyIt : CompStmt->body()) {
1009       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1010                                       Cxx1yLoc))
1011         return false;
1012     }
1013     return true;
1014   }
1015 
1016   case Stmt::AttributedStmtClass:
1017     if (!Cxx1yLoc.isValid())
1018       Cxx1yLoc = S->getLocStart();
1019     return true;
1020 
1021   case Stmt::IfStmtClass: {
1022     // C++1y allows if-statements.
1023     if (!Cxx1yLoc.isValid())
1024       Cxx1yLoc = S->getLocStart();
1025 
1026     IfStmt *If = cast<IfStmt>(S);
1027     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1028                                     Cxx1yLoc))
1029       return false;
1030     if (If->getElse() &&
1031         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1032                                     Cxx1yLoc))
1033       return false;
1034     return true;
1035   }
1036 
1037   case Stmt::WhileStmtClass:
1038   case Stmt::DoStmtClass:
1039   case Stmt::ForStmtClass:
1040   case Stmt::CXXForRangeStmtClass:
1041   case Stmt::ContinueStmtClass:
1042     // C++1y allows all of these. We don't allow them as extensions in C++11,
1043     // because they don't make sense without variable mutation.
1044     if (!SemaRef.getLangOpts().CPlusPlus14)
1045       break;
1046     if (!Cxx1yLoc.isValid())
1047       Cxx1yLoc = S->getLocStart();
1048     for (Stmt::child_range Children = S->children(); Children; ++Children)
1049       if (*Children &&
1050           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1051                                       Cxx1yLoc))
1052         return false;
1053     return true;
1054 
1055   case Stmt::SwitchStmtClass:
1056   case Stmt::CaseStmtClass:
1057   case Stmt::DefaultStmtClass:
1058   case Stmt::BreakStmtClass:
1059     // C++1y allows switch-statements, and since they don't need variable
1060     // mutation, we can reasonably allow them in C++11 as an extension.
1061     if (!Cxx1yLoc.isValid())
1062       Cxx1yLoc = S->getLocStart();
1063     for (Stmt::child_range Children = S->children(); Children; ++Children)
1064       if (*Children &&
1065           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1066                                       Cxx1yLoc))
1067         return false;
1068     return true;
1069 
1070   default:
1071     if (!isa<Expr>(S))
1072       break;
1073 
1074     // C++1y allows expression-statements.
1075     if (!Cxx1yLoc.isValid())
1076       Cxx1yLoc = S->getLocStart();
1077     return true;
1078   }
1079 
1080   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1081     << isa<CXXConstructorDecl>(Dcl);
1082   return false;
1083 }
1084 
1085 /// Check the body for the given constexpr function declaration only contains
1086 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1087 ///
1088 /// \return true if the body is OK, false if we have diagnosed a problem.
1089 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1090   if (isa<CXXTryStmt>(Body)) {
1091     // C++11 [dcl.constexpr]p3:
1092     //  The definition of a constexpr function shall satisfy the following
1093     //  constraints: [...]
1094     // - its function-body shall be = delete, = default, or a
1095     //   compound-statement
1096     //
1097     // C++11 [dcl.constexpr]p4:
1098     //  In the definition of a constexpr constructor, [...]
1099     // - its function-body shall not be a function-try-block;
1100     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1101       << isa<CXXConstructorDecl>(Dcl);
1102     return false;
1103   }
1104 
1105   SmallVector<SourceLocation, 4> ReturnStmts;
1106 
1107   // - its function-body shall be [...] a compound-statement that contains only
1108   //   [... list of cases ...]
1109   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1110   SourceLocation Cxx1yLoc;
1111   for (auto *BodyIt : CompBody->body()) {
1112     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1113       return false;
1114   }
1115 
1116   if (Cxx1yLoc.isValid())
1117     Diag(Cxx1yLoc,
1118          getLangOpts().CPlusPlus14
1119            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1120            : diag::ext_constexpr_body_invalid_stmt)
1121       << isa<CXXConstructorDecl>(Dcl);
1122 
1123   if (const CXXConstructorDecl *Constructor
1124         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1125     const CXXRecordDecl *RD = Constructor->getParent();
1126     // DR1359:
1127     // - every non-variant non-static data member and base class sub-object
1128     //   shall be initialized;
1129     // DR1460:
1130     // - if the class is a union having variant members, exactly one of them
1131     //   shall be initialized;
1132     if (RD->isUnion()) {
1133       if (Constructor->getNumCtorInitializers() == 0 &&
1134           RD->hasVariantMembers()) {
1135         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1136         return false;
1137       }
1138     } else if (!Constructor->isDependentContext() &&
1139                !Constructor->isDelegatingConstructor()) {
1140       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1141 
1142       // Skip detailed checking if we have enough initializers, and we would
1143       // allow at most one initializer per member.
1144       bool AnyAnonStructUnionMembers = false;
1145       unsigned Fields = 0;
1146       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1147            E = RD->field_end(); I != E; ++I, ++Fields) {
1148         if (I->isAnonymousStructOrUnion()) {
1149           AnyAnonStructUnionMembers = true;
1150           break;
1151         }
1152       }
1153       // DR1460:
1154       // - if the class is a union-like class, but is not a union, for each of
1155       //   its anonymous union members having variant members, exactly one of
1156       //   them shall be initialized;
1157       if (AnyAnonStructUnionMembers ||
1158           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1159         // Check initialization of non-static data members. Base classes are
1160         // always initialized so do not need to be checked. Dependent bases
1161         // might not have initializers in the member initializer list.
1162         llvm::SmallSet<Decl*, 16> Inits;
1163         for (const auto *I: Constructor->inits()) {
1164           if (FieldDecl *FD = I->getMember())
1165             Inits.insert(FD);
1166           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1167             Inits.insert(ID->chain_begin(), ID->chain_end());
1168         }
1169 
1170         bool Diagnosed = false;
1171         for (auto *I : RD->fields())
1172           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1173         if (Diagnosed)
1174           return false;
1175       }
1176     }
1177   } else {
1178     if (ReturnStmts.empty()) {
1179       // C++1y doesn't require constexpr functions to contain a 'return'
1180       // statement. We still do, unless the return type might be void, because
1181       // otherwise if there's no return statement, the function cannot
1182       // be used in a core constant expression.
1183       bool OK = getLangOpts().CPlusPlus14 &&
1184                 (Dcl->getReturnType()->isVoidType() ||
1185                  Dcl->getReturnType()->isDependentType());
1186       Diag(Dcl->getLocation(),
1187            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1188               : diag::err_constexpr_body_no_return);
1189       return OK;
1190     }
1191     if (ReturnStmts.size() > 1) {
1192       Diag(ReturnStmts.back(),
1193            getLangOpts().CPlusPlus14
1194              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1195              : diag::ext_constexpr_body_multiple_return);
1196       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1197         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1198     }
1199   }
1200 
1201   // C++11 [dcl.constexpr]p5:
1202   //   if no function argument values exist such that the function invocation
1203   //   substitution would produce a constant expression, the program is
1204   //   ill-formed; no diagnostic required.
1205   // C++11 [dcl.constexpr]p3:
1206   //   - every constructor call and implicit conversion used in initializing the
1207   //     return value shall be one of those allowed in a constant expression.
1208   // C++11 [dcl.constexpr]p4:
1209   //   - every constructor involved in initializing non-static data members and
1210   //     base class sub-objects shall be a constexpr constructor.
1211   SmallVector<PartialDiagnosticAt, 8> Diags;
1212   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1213     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1214       << isa<CXXConstructorDecl>(Dcl);
1215     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1216       Diag(Diags[I].first, Diags[I].second);
1217     // Don't return false here: we allow this for compatibility in
1218     // system headers.
1219   }
1220 
1221   return true;
1222 }
1223 
1224 /// isCurrentClassName - Determine whether the identifier II is the
1225 /// name of the class type currently being defined. In the case of
1226 /// nested classes, this will only return true if II is the name of
1227 /// the innermost class.
1228 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1229                               const CXXScopeSpec *SS) {
1230   assert(getLangOpts().CPlusPlus && "No class names in C!");
1231 
1232   CXXRecordDecl *CurDecl;
1233   if (SS && SS->isSet() && !SS->isInvalid()) {
1234     DeclContext *DC = computeDeclContext(*SS, true);
1235     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1236   } else
1237     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1238 
1239   if (CurDecl && CurDecl->getIdentifier())
1240     return &II == CurDecl->getIdentifier();
1241   return false;
1242 }
1243 
1244 /// \brief Determine whether the identifier II is a typo for the name of
1245 /// the class type currently being defined. If so, update it to the identifier
1246 /// that should have been used.
1247 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1248   assert(getLangOpts().CPlusPlus && "No class names in C!");
1249 
1250   if (!getLangOpts().SpellChecking)
1251     return false;
1252 
1253   CXXRecordDecl *CurDecl;
1254   if (SS && SS->isSet() && !SS->isInvalid()) {
1255     DeclContext *DC = computeDeclContext(*SS, true);
1256     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1257   } else
1258     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1259 
1260   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1261       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1262           < II->getLength()) {
1263     II = CurDecl->getIdentifier();
1264     return true;
1265   }
1266 
1267   return false;
1268 }
1269 
1270 /// \brief Determine whether the given class is a base class of the given
1271 /// class, including looking at dependent bases.
1272 static bool findCircularInheritance(const CXXRecordDecl *Class,
1273                                     const CXXRecordDecl *Current) {
1274   SmallVector<const CXXRecordDecl*, 8> Queue;
1275 
1276   Class = Class->getCanonicalDecl();
1277   while (true) {
1278     for (const auto &I : Current->bases()) {
1279       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1280       if (!Base)
1281         continue;
1282 
1283       Base = Base->getDefinition();
1284       if (!Base)
1285         continue;
1286 
1287       if (Base->getCanonicalDecl() == Class)
1288         return true;
1289 
1290       Queue.push_back(Base);
1291     }
1292 
1293     if (Queue.empty())
1294       return false;
1295 
1296     Current = Queue.pop_back_val();
1297   }
1298 
1299   return false;
1300 }
1301 
1302 /// \brief Perform propagation of DLL attributes from a derived class to a
1303 /// templated base class for MS compatibility.
1304 static void propagateDLLAttrToBaseClassTemplate(
1305     Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1306     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1307   if (getDLLAttr(
1308           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1309     // If the base class template has a DLL attribute, don't try to change it.
1310     return;
1311   }
1312 
1313   if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1314     // If the base class is not already specialized, we can do the propagation.
1315     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1316     NewAttr->setInherited(true);
1317     BaseTemplateSpec->addAttr(NewAttr);
1318     return;
1319   }
1320 
1321   bool DifferentAttribute = false;
1322   if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1323     if (!SpecializationAttr->isInherited()) {
1324       // The template has previously been specialized or instantiated with an
1325       // explicit attribute. We should not try to change it.
1326       return;
1327     }
1328     if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1329       // The specialization already has the right attribute.
1330       return;
1331     }
1332     DifferentAttribute = true;
1333   }
1334 
1335   // The template was previously instantiated or explicitly specialized without
1336   // a dll attribute, or the template was previously instantiated with a
1337   // different inherited attribute. It's too late for us to change the
1338   // attribute, so warn that this is unsupported.
1339   S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1340       << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1341   S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1342   if (BaseTemplateSpec->isExplicitSpecialization()) {
1343     S.Diag(BaseTemplateSpec->getLocation(),
1344            diag::note_template_class_explicit_specialization_was_here)
1345         << BaseTemplateSpec;
1346   } else {
1347     S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1348            diag::note_template_class_instantiation_was_here)
1349         << BaseTemplateSpec;
1350   }
1351 }
1352 
1353 /// \brief Check the validity of a C++ base class specifier.
1354 ///
1355 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1356 /// and returns NULL otherwise.
1357 CXXBaseSpecifier *
1358 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1359                          SourceRange SpecifierRange,
1360                          bool Virtual, AccessSpecifier Access,
1361                          TypeSourceInfo *TInfo,
1362                          SourceLocation EllipsisLoc) {
1363   QualType BaseType = TInfo->getType();
1364 
1365   // C++ [class.union]p1:
1366   //   A union shall not have base classes.
1367   if (Class->isUnion()) {
1368     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1369       << SpecifierRange;
1370     return nullptr;
1371   }
1372 
1373   if (EllipsisLoc.isValid() &&
1374       !TInfo->getType()->containsUnexpandedParameterPack()) {
1375     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1376       << TInfo->getTypeLoc().getSourceRange();
1377     EllipsisLoc = SourceLocation();
1378   }
1379 
1380   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1381 
1382   if (BaseType->isDependentType()) {
1383     // Make sure that we don't have circular inheritance among our dependent
1384     // bases. For non-dependent bases, the check for completeness below handles
1385     // this.
1386     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1387       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1388           ((BaseDecl = BaseDecl->getDefinition()) &&
1389            findCircularInheritance(Class, BaseDecl))) {
1390         Diag(BaseLoc, diag::err_circular_inheritance)
1391           << BaseType << Context.getTypeDeclType(Class);
1392 
1393         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1394           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1395             << BaseType;
1396 
1397         return nullptr;
1398       }
1399     }
1400 
1401     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1402                                           Class->getTagKind() == TTK_Class,
1403                                           Access, TInfo, EllipsisLoc);
1404   }
1405 
1406   // Base specifiers must be record types.
1407   if (!BaseType->isRecordType()) {
1408     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1409     return nullptr;
1410   }
1411 
1412   // C++ [class.union]p1:
1413   //   A union shall not be used as a base class.
1414   if (BaseType->isUnionType()) {
1415     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1416     return nullptr;
1417   }
1418 
1419   // For the MS ABI, propagate DLL attributes to base class templates.
1420   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1421     if (Attr *ClassAttr = getDLLAttr(Class)) {
1422       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1423               BaseType->getAsCXXRecordDecl())) {
1424         propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1425                                             BaseTemplate, BaseLoc);
1426       }
1427     }
1428   }
1429 
1430   // C++ [class.derived]p2:
1431   //   The class-name in a base-specifier shall not be an incompletely
1432   //   defined class.
1433   if (RequireCompleteType(BaseLoc, BaseType,
1434                           diag::err_incomplete_base_class, SpecifierRange)) {
1435     Class->setInvalidDecl();
1436     return nullptr;
1437   }
1438 
1439   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1440   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1441   assert(BaseDecl && "Record type has no declaration");
1442   BaseDecl = BaseDecl->getDefinition();
1443   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1444   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1445   assert(CXXBaseDecl && "Base type is not a C++ type");
1446 
1447   // A class which contains a flexible array member is not suitable for use as a
1448   // base class:
1449   //   - If the layout determines that a base comes before another base,
1450   //     the flexible array member would index into the subsequent base.
1451   //   - If the layout determines that base comes before the derived class,
1452   //     the flexible array member would index into the derived class.
1453   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1454     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1455       << CXXBaseDecl->getDeclName();
1456     return nullptr;
1457   }
1458 
1459   // C++ [class]p3:
1460   //   If a class is marked final and it appears as a base-type-specifier in
1461   //   base-clause, the program is ill-formed.
1462   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1463     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1464       << CXXBaseDecl->getDeclName()
1465       << FA->isSpelledAsSealed();
1466     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1467         << CXXBaseDecl->getDeclName() << FA->getRange();
1468     return nullptr;
1469   }
1470 
1471   if (BaseDecl->isInvalidDecl())
1472     Class->setInvalidDecl();
1473 
1474   // Create the base specifier.
1475   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1476                                         Class->getTagKind() == TTK_Class,
1477                                         Access, TInfo, EllipsisLoc);
1478 }
1479 
1480 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1481 /// one entry in the base class list of a class specifier, for
1482 /// example:
1483 ///    class foo : public bar, virtual private baz {
1484 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1485 BaseResult
1486 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1487                          ParsedAttributes &Attributes,
1488                          bool Virtual, AccessSpecifier Access,
1489                          ParsedType basetype, SourceLocation BaseLoc,
1490                          SourceLocation EllipsisLoc) {
1491   if (!classdecl)
1492     return true;
1493 
1494   AdjustDeclIfTemplate(classdecl);
1495   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1496   if (!Class)
1497     return true;
1498 
1499   // We haven't yet attached the base specifiers.
1500   Class->setIsParsingBaseSpecifiers();
1501 
1502   // We do not support any C++11 attributes on base-specifiers yet.
1503   // Diagnose any attributes we see.
1504   if (!Attributes.empty()) {
1505     for (AttributeList *Attr = Attributes.getList(); Attr;
1506          Attr = Attr->getNext()) {
1507       if (Attr->isInvalid() ||
1508           Attr->getKind() == AttributeList::IgnoredAttribute)
1509         continue;
1510       Diag(Attr->getLoc(),
1511            Attr->getKind() == AttributeList::UnknownAttribute
1512              ? diag::warn_unknown_attribute_ignored
1513              : diag::err_base_specifier_attribute)
1514         << Attr->getName();
1515     }
1516   }
1517 
1518   TypeSourceInfo *TInfo = nullptr;
1519   GetTypeFromParser(basetype, &TInfo);
1520 
1521   if (EllipsisLoc.isInvalid() &&
1522       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1523                                       UPPC_BaseType))
1524     return true;
1525 
1526   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1527                                                       Virtual, Access, TInfo,
1528                                                       EllipsisLoc))
1529     return BaseSpec;
1530   else
1531     Class->setInvalidDecl();
1532 
1533   return true;
1534 }
1535 
1536 /// \brief Performs the actual work of attaching the given base class
1537 /// specifiers to a C++ class.
1538 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1539                                 unsigned NumBases) {
1540  if (NumBases == 0)
1541     return false;
1542 
1543   // Used to keep track of which base types we have already seen, so
1544   // that we can properly diagnose redundant direct base types. Note
1545   // that the key is always the unqualified canonical type of the base
1546   // class.
1547   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1548 
1549   // Copy non-redundant base specifiers into permanent storage.
1550   unsigned NumGoodBases = 0;
1551   bool Invalid = false;
1552   for (unsigned idx = 0; idx < NumBases; ++idx) {
1553     QualType NewBaseType
1554       = Context.getCanonicalType(Bases[idx]->getType());
1555     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1556 
1557     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1558     if (KnownBase) {
1559       // C++ [class.mi]p3:
1560       //   A class shall not be specified as a direct base class of a
1561       //   derived class more than once.
1562       Diag(Bases[idx]->getLocStart(),
1563            diag::err_duplicate_base_class)
1564         << KnownBase->getType()
1565         << Bases[idx]->getSourceRange();
1566 
1567       // Delete the duplicate base class specifier; we're going to
1568       // overwrite its pointer later.
1569       Context.Deallocate(Bases[idx]);
1570 
1571       Invalid = true;
1572     } else {
1573       // Okay, add this new base class.
1574       KnownBase = Bases[idx];
1575       Bases[NumGoodBases++] = Bases[idx];
1576       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1577         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1578         if (Class->isInterface() &&
1579               (!RD->isInterface() ||
1580                KnownBase->getAccessSpecifier() != AS_public)) {
1581           // The Microsoft extension __interface does not permit bases that
1582           // are not themselves public interfaces.
1583           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1584             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1585             << RD->getSourceRange();
1586           Invalid = true;
1587         }
1588         if (RD->hasAttr<WeakAttr>())
1589           Class->addAttr(WeakAttr::CreateImplicit(Context));
1590       }
1591     }
1592   }
1593 
1594   // Attach the remaining base class specifiers to the derived class.
1595   Class->setBases(Bases, NumGoodBases);
1596 
1597   // Delete the remaining (good) base class specifiers, since their
1598   // data has been copied into the CXXRecordDecl.
1599   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1600     Context.Deallocate(Bases[idx]);
1601 
1602   return Invalid;
1603 }
1604 
1605 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1606 /// class, after checking whether there are any duplicate base
1607 /// classes.
1608 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1609                                unsigned NumBases) {
1610   if (!ClassDecl || !Bases || !NumBases)
1611     return;
1612 
1613   AdjustDeclIfTemplate(ClassDecl);
1614   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1615 }
1616 
1617 /// \brief Determine whether the type \p Derived is a C++ class that is
1618 /// derived from the type \p Base.
1619 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1620   if (!getLangOpts().CPlusPlus)
1621     return false;
1622 
1623   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1624   if (!DerivedRD)
1625     return false;
1626 
1627   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1628   if (!BaseRD)
1629     return false;
1630 
1631   // If either the base or the derived type is invalid, don't try to
1632   // check whether one is derived from the other.
1633   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1634     return false;
1635 
1636   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1637   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1638 }
1639 
1640 /// \brief Determine whether the type \p Derived is a C++ class that is
1641 /// derived from the type \p Base.
1642 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1643   if (!getLangOpts().CPlusPlus)
1644     return false;
1645 
1646   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1647   if (!DerivedRD)
1648     return false;
1649 
1650   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1651   if (!BaseRD)
1652     return false;
1653 
1654   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1655 }
1656 
1657 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1658                               CXXCastPath &BasePathArray) {
1659   assert(BasePathArray.empty() && "Base path array must be empty!");
1660   assert(Paths.isRecordingPaths() && "Must record paths!");
1661 
1662   const CXXBasePath &Path = Paths.front();
1663 
1664   // We first go backward and check if we have a virtual base.
1665   // FIXME: It would be better if CXXBasePath had the base specifier for
1666   // the nearest virtual base.
1667   unsigned Start = 0;
1668   for (unsigned I = Path.size(); I != 0; --I) {
1669     if (Path[I - 1].Base->isVirtual()) {
1670       Start = I - 1;
1671       break;
1672     }
1673   }
1674 
1675   // Now add all bases.
1676   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1677     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1678 }
1679 
1680 /// \brief Determine whether the given base path includes a virtual
1681 /// base class.
1682 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1683   for (CXXCastPath::const_iterator B = BasePath.begin(),
1684                                 BEnd = BasePath.end();
1685        B != BEnd; ++B)
1686     if ((*B)->isVirtual())
1687       return true;
1688 
1689   return false;
1690 }
1691 
1692 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1693 /// conversion (where Derived and Base are class types) is
1694 /// well-formed, meaning that the conversion is unambiguous (and
1695 /// that all of the base classes are accessible). Returns true
1696 /// and emits a diagnostic if the code is ill-formed, returns false
1697 /// otherwise. Loc is the location where this routine should point to
1698 /// if there is an error, and Range is the source range to highlight
1699 /// if there is an error.
1700 bool
1701 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1702                                    unsigned InaccessibleBaseID,
1703                                    unsigned AmbigiousBaseConvID,
1704                                    SourceLocation Loc, SourceRange Range,
1705                                    DeclarationName Name,
1706                                    CXXCastPath *BasePath) {
1707   // First, determine whether the path from Derived to Base is
1708   // ambiguous. This is slightly more expensive than checking whether
1709   // the Derived to Base conversion exists, because here we need to
1710   // explore multiple paths to determine if there is an ambiguity.
1711   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1712                      /*DetectVirtual=*/false);
1713   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1714   assert(DerivationOkay &&
1715          "Can only be used with a derived-to-base conversion");
1716   (void)DerivationOkay;
1717 
1718   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1719     if (InaccessibleBaseID) {
1720       // Check that the base class can be accessed.
1721       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1722                                    InaccessibleBaseID)) {
1723         case AR_inaccessible:
1724           return true;
1725         case AR_accessible:
1726         case AR_dependent:
1727         case AR_delayed:
1728           break;
1729       }
1730     }
1731 
1732     // Build a base path if necessary.
1733     if (BasePath)
1734       BuildBasePathArray(Paths, *BasePath);
1735     return false;
1736   }
1737 
1738   if (AmbigiousBaseConvID) {
1739     // We know that the derived-to-base conversion is ambiguous, and
1740     // we're going to produce a diagnostic. Perform the derived-to-base
1741     // search just one more time to compute all of the possible paths so
1742     // that we can print them out. This is more expensive than any of
1743     // the previous derived-to-base checks we've done, but at this point
1744     // performance isn't as much of an issue.
1745     Paths.clear();
1746     Paths.setRecordingPaths(true);
1747     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1748     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1749     (void)StillOkay;
1750 
1751     // Build up a textual representation of the ambiguous paths, e.g.,
1752     // D -> B -> A, that will be used to illustrate the ambiguous
1753     // conversions in the diagnostic. We only print one of the paths
1754     // to each base class subobject.
1755     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1756 
1757     Diag(Loc, AmbigiousBaseConvID)
1758     << Derived << Base << PathDisplayStr << Range << Name;
1759   }
1760   return true;
1761 }
1762 
1763 bool
1764 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1765                                    SourceLocation Loc, SourceRange Range,
1766                                    CXXCastPath *BasePath,
1767                                    bool IgnoreAccess) {
1768   return CheckDerivedToBaseConversion(Derived, Base,
1769                                       IgnoreAccess ? 0
1770                                        : diag::err_upcast_to_inaccessible_base,
1771                                       diag::err_ambiguous_derived_to_base_conv,
1772                                       Loc, Range, DeclarationName(),
1773                                       BasePath);
1774 }
1775 
1776 
1777 /// @brief Builds a string representing ambiguous paths from a
1778 /// specific derived class to different subobjects of the same base
1779 /// class.
1780 ///
1781 /// This function builds a string that can be used in error messages
1782 /// to show the different paths that one can take through the
1783 /// inheritance hierarchy to go from the derived class to different
1784 /// subobjects of a base class. The result looks something like this:
1785 /// @code
1786 /// struct D -> struct B -> struct A
1787 /// struct D -> struct C -> struct A
1788 /// @endcode
1789 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1790   std::string PathDisplayStr;
1791   std::set<unsigned> DisplayedPaths;
1792   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1793        Path != Paths.end(); ++Path) {
1794     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1795       // We haven't displayed a path to this particular base
1796       // class subobject yet.
1797       PathDisplayStr += "\n    ";
1798       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1799       for (CXXBasePath::const_iterator Element = Path->begin();
1800            Element != Path->end(); ++Element)
1801         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1802     }
1803   }
1804 
1805   return PathDisplayStr;
1806 }
1807 
1808 //===----------------------------------------------------------------------===//
1809 // C++ class member Handling
1810 //===----------------------------------------------------------------------===//
1811 
1812 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1813 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1814                                 SourceLocation ASLoc,
1815                                 SourceLocation ColonLoc,
1816                                 AttributeList *Attrs) {
1817   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1818   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1819                                                   ASLoc, ColonLoc);
1820   CurContext->addHiddenDecl(ASDecl);
1821   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1822 }
1823 
1824 /// CheckOverrideControl - Check C++11 override control semantics.
1825 void Sema::CheckOverrideControl(NamedDecl *D) {
1826   if (D->isInvalidDecl())
1827     return;
1828 
1829   // We only care about "override" and "final" declarations.
1830   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1831     return;
1832 
1833   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1834 
1835   // We can't check dependent instance methods.
1836   if (MD && MD->isInstance() &&
1837       (MD->getParent()->hasAnyDependentBases() ||
1838        MD->getType()->isDependentType()))
1839     return;
1840 
1841   if (MD && !MD->isVirtual()) {
1842     // If we have a non-virtual method, check if if hides a virtual method.
1843     // (In that case, it's most likely the method has the wrong type.)
1844     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1845     FindHiddenVirtualMethods(MD, OverloadedMethods);
1846 
1847     if (!OverloadedMethods.empty()) {
1848       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1849         Diag(OA->getLocation(),
1850              diag::override_keyword_hides_virtual_member_function)
1851           << "override" << (OverloadedMethods.size() > 1);
1852       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1853         Diag(FA->getLocation(),
1854              diag::override_keyword_hides_virtual_member_function)
1855           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1856           << (OverloadedMethods.size() > 1);
1857       }
1858       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1859       MD->setInvalidDecl();
1860       return;
1861     }
1862     // Fall through into the general case diagnostic.
1863     // FIXME: We might want to attempt typo correction here.
1864   }
1865 
1866   if (!MD || !MD->isVirtual()) {
1867     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1868       Diag(OA->getLocation(),
1869            diag::override_keyword_only_allowed_on_virtual_member_functions)
1870         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1871       D->dropAttr<OverrideAttr>();
1872     }
1873     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1874       Diag(FA->getLocation(),
1875            diag::override_keyword_only_allowed_on_virtual_member_functions)
1876         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1877         << FixItHint::CreateRemoval(FA->getLocation());
1878       D->dropAttr<FinalAttr>();
1879     }
1880     return;
1881   }
1882 
1883   // C++11 [class.virtual]p5:
1884   //   If a virtual function is marked with the virt-specifier override and
1885   //   does not override a member function of a base class, the program is
1886   //   ill-formed.
1887   bool HasOverriddenMethods =
1888     MD->begin_overridden_methods() != MD->end_overridden_methods();
1889   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1890     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1891       << MD->getDeclName();
1892 }
1893 
1894 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1895 /// function overrides a virtual member function marked 'final', according to
1896 /// C++11 [class.virtual]p4.
1897 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1898                                                   const CXXMethodDecl *Old) {
1899   FinalAttr *FA = Old->getAttr<FinalAttr>();
1900   if (!FA)
1901     return false;
1902 
1903   Diag(New->getLocation(), diag::err_final_function_overridden)
1904     << New->getDeclName()
1905     << FA->isSpelledAsSealed();
1906   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1907   return true;
1908 }
1909 
1910 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1911   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1912   // FIXME: Destruction of ObjC lifetime types has side-effects.
1913   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1914     return !RD->isCompleteDefinition() ||
1915            !RD->hasTrivialDefaultConstructor() ||
1916            !RD->hasTrivialDestructor();
1917   return false;
1918 }
1919 
1920 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1921   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1922     if (it->isDeclspecPropertyAttribute())
1923       return it;
1924   return nullptr;
1925 }
1926 
1927 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1928 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1929 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1930 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1931 /// present (but parsing it has been deferred).
1932 NamedDecl *
1933 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1934                                MultiTemplateParamsArg TemplateParameterLists,
1935                                Expr *BW, const VirtSpecifiers &VS,
1936                                InClassInitStyle InitStyle) {
1937   const DeclSpec &DS = D.getDeclSpec();
1938   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1939   DeclarationName Name = NameInfo.getName();
1940   SourceLocation Loc = NameInfo.getLoc();
1941 
1942   // For anonymous bitfields, the location should point to the type.
1943   if (Loc.isInvalid())
1944     Loc = D.getLocStart();
1945 
1946   Expr *BitWidth = static_cast<Expr*>(BW);
1947 
1948   assert(isa<CXXRecordDecl>(CurContext));
1949   assert(!DS.isFriendSpecified());
1950 
1951   bool isFunc = D.isDeclarationOfFunction();
1952 
1953   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1954     // The Microsoft extension __interface only permits public member functions
1955     // and prohibits constructors, destructors, operators, non-public member
1956     // functions, static methods and data members.
1957     unsigned InvalidDecl;
1958     bool ShowDeclName = true;
1959     if (!isFunc)
1960       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1961     else if (AS != AS_public)
1962       InvalidDecl = 2;
1963     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1964       InvalidDecl = 3;
1965     else switch (Name.getNameKind()) {
1966       case DeclarationName::CXXConstructorName:
1967         InvalidDecl = 4;
1968         ShowDeclName = false;
1969         break;
1970 
1971       case DeclarationName::CXXDestructorName:
1972         InvalidDecl = 5;
1973         ShowDeclName = false;
1974         break;
1975 
1976       case DeclarationName::CXXOperatorName:
1977       case DeclarationName::CXXConversionFunctionName:
1978         InvalidDecl = 6;
1979         break;
1980 
1981       default:
1982         InvalidDecl = 0;
1983         break;
1984     }
1985 
1986     if (InvalidDecl) {
1987       if (ShowDeclName)
1988         Diag(Loc, diag::err_invalid_member_in_interface)
1989           << (InvalidDecl-1) << Name;
1990       else
1991         Diag(Loc, diag::err_invalid_member_in_interface)
1992           << (InvalidDecl-1) << "";
1993       return nullptr;
1994     }
1995   }
1996 
1997   // C++ 9.2p6: A member shall not be declared to have automatic storage
1998   // duration (auto, register) or with the extern storage-class-specifier.
1999   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2000   // data members and cannot be applied to names declared const or static,
2001   // and cannot be applied to reference members.
2002   switch (DS.getStorageClassSpec()) {
2003   case DeclSpec::SCS_unspecified:
2004   case DeclSpec::SCS_typedef:
2005   case DeclSpec::SCS_static:
2006     break;
2007   case DeclSpec::SCS_mutable:
2008     if (isFunc) {
2009       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2010 
2011       // FIXME: It would be nicer if the keyword was ignored only for this
2012       // declarator. Otherwise we could get follow-up errors.
2013       D.getMutableDeclSpec().ClearStorageClassSpecs();
2014     }
2015     break;
2016   default:
2017     Diag(DS.getStorageClassSpecLoc(),
2018          diag::err_storageclass_invalid_for_member);
2019     D.getMutableDeclSpec().ClearStorageClassSpecs();
2020     break;
2021   }
2022 
2023   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2024                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2025                       !isFunc);
2026 
2027   if (DS.isConstexprSpecified() && isInstField) {
2028     SemaDiagnosticBuilder B =
2029         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2030     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2031     if (InitStyle == ICIS_NoInit) {
2032       B << 0 << 0;
2033       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2034         B << FixItHint::CreateRemoval(ConstexprLoc);
2035       else {
2036         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2037         D.getMutableDeclSpec().ClearConstexprSpec();
2038         const char *PrevSpec;
2039         unsigned DiagID;
2040         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2041             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2042         (void)Failed;
2043         assert(!Failed && "Making a constexpr member const shouldn't fail");
2044       }
2045     } else {
2046       B << 1;
2047       const char *PrevSpec;
2048       unsigned DiagID;
2049       if (D.getMutableDeclSpec().SetStorageClassSpec(
2050           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2051           Context.getPrintingPolicy())) {
2052         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2053                "This is the only DeclSpec that should fail to be applied");
2054         B << 1;
2055       } else {
2056         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2057         isInstField = false;
2058       }
2059     }
2060   }
2061 
2062   NamedDecl *Member;
2063   if (isInstField) {
2064     CXXScopeSpec &SS = D.getCXXScopeSpec();
2065 
2066     // Data members must have identifiers for names.
2067     if (!Name.isIdentifier()) {
2068       Diag(Loc, diag::err_bad_variable_name)
2069         << Name;
2070       return nullptr;
2071     }
2072 
2073     IdentifierInfo *II = Name.getAsIdentifierInfo();
2074 
2075     // Member field could not be with "template" keyword.
2076     // So TemplateParameterLists should be empty in this case.
2077     if (TemplateParameterLists.size()) {
2078       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2079       if (TemplateParams->size()) {
2080         // There is no such thing as a member field template.
2081         Diag(D.getIdentifierLoc(), diag::err_template_member)
2082             << II
2083             << SourceRange(TemplateParams->getTemplateLoc(),
2084                 TemplateParams->getRAngleLoc());
2085       } else {
2086         // There is an extraneous 'template<>' for this member.
2087         Diag(TemplateParams->getTemplateLoc(),
2088             diag::err_template_member_noparams)
2089             << II
2090             << SourceRange(TemplateParams->getTemplateLoc(),
2091                 TemplateParams->getRAngleLoc());
2092       }
2093       return nullptr;
2094     }
2095 
2096     if (SS.isSet() && !SS.isInvalid()) {
2097       // The user provided a superfluous scope specifier inside a class
2098       // definition:
2099       //
2100       // class X {
2101       //   int X::member;
2102       // };
2103       if (DeclContext *DC = computeDeclContext(SS, false))
2104         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2105       else
2106         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2107           << Name << SS.getRange();
2108 
2109       SS.clear();
2110     }
2111 
2112     AttributeList *MSPropertyAttr =
2113       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2114     if (MSPropertyAttr) {
2115       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2116                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2117       if (!Member)
2118         return nullptr;
2119       isInstField = false;
2120     } else {
2121       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2122                                 BitWidth, InitStyle, AS);
2123       assert(Member && "HandleField never returns null");
2124     }
2125   } else {
2126     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2127 
2128     Member = HandleDeclarator(S, D, TemplateParameterLists);
2129     if (!Member)
2130       return nullptr;
2131 
2132     // Non-instance-fields can't have a bitfield.
2133     if (BitWidth) {
2134       if (Member->isInvalidDecl()) {
2135         // don't emit another diagnostic.
2136       } else if (isa<VarDecl>(Member)) {
2137         // C++ 9.6p3: A bit-field shall not be a static member.
2138         // "static member 'A' cannot be a bit-field"
2139         Diag(Loc, diag::err_static_not_bitfield)
2140           << Name << BitWidth->getSourceRange();
2141       } else if (isa<TypedefDecl>(Member)) {
2142         // "typedef member 'x' cannot be a bit-field"
2143         Diag(Loc, diag::err_typedef_not_bitfield)
2144           << Name << BitWidth->getSourceRange();
2145       } else {
2146         // A function typedef ("typedef int f(); f a;").
2147         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2148         Diag(Loc, diag::err_not_integral_type_bitfield)
2149           << Name << cast<ValueDecl>(Member)->getType()
2150           << BitWidth->getSourceRange();
2151       }
2152 
2153       BitWidth = nullptr;
2154       Member->setInvalidDecl();
2155     }
2156 
2157     Member->setAccess(AS);
2158 
2159     // If we have declared a member function template or static data member
2160     // template, set the access of the templated declaration as well.
2161     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2162       FunTmpl->getTemplatedDecl()->setAccess(AS);
2163     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2164       VarTmpl->getTemplatedDecl()->setAccess(AS);
2165   }
2166 
2167   if (VS.isOverrideSpecified())
2168     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2169   if (VS.isFinalSpecified())
2170     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2171                                             VS.isFinalSpelledSealed()));
2172 
2173   if (VS.getLastLocation().isValid()) {
2174     // Update the end location of a method that has a virt-specifiers.
2175     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2176       MD->setRangeEnd(VS.getLastLocation());
2177   }
2178 
2179   CheckOverrideControl(Member);
2180 
2181   assert((Name || isInstField) && "No identifier for non-field ?");
2182 
2183   if (isInstField) {
2184     FieldDecl *FD = cast<FieldDecl>(Member);
2185     FieldCollector->Add(FD);
2186 
2187     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2188       // Remember all explicit private FieldDecls that have a name, no side
2189       // effects and are not part of a dependent type declaration.
2190       if (!FD->isImplicit() && FD->getDeclName() &&
2191           FD->getAccess() == AS_private &&
2192           !FD->hasAttr<UnusedAttr>() &&
2193           !FD->getParent()->isDependentContext() &&
2194           !InitializationHasSideEffects(*FD))
2195         UnusedPrivateFields.insert(FD);
2196     }
2197   }
2198 
2199   return Member;
2200 }
2201 
2202 namespace {
2203   class UninitializedFieldVisitor
2204       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2205     Sema &S;
2206     // List of Decls to generate a warning on.  Also remove Decls that become
2207     // initialized.
2208     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2209     // If non-null, add a note to the warning pointing back to the constructor.
2210     const CXXConstructorDecl *Constructor;
2211   public:
2212     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2213     UninitializedFieldVisitor(Sema &S,
2214                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2215                               const CXXConstructorDecl *Constructor)
2216       : Inherited(S.Context), S(S), Decls(Decls),
2217         Constructor(Constructor) { }
2218 
2219     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
2220       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2221         return;
2222 
2223       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2224       // or union.
2225       MemberExpr *FieldME = ME;
2226 
2227       Expr *Base = ME;
2228       while (isa<MemberExpr>(Base)) {
2229         ME = cast<MemberExpr>(Base);
2230 
2231         if (isa<VarDecl>(ME->getMemberDecl()))
2232           return;
2233 
2234         if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2235           if (!FD->isAnonymousStructOrUnion())
2236             FieldME = ME;
2237 
2238         Base = ME->getBase();
2239       }
2240 
2241       if (!isa<CXXThisExpr>(Base))
2242         return;
2243 
2244       ValueDecl* FoundVD = FieldME->getMemberDecl();
2245 
2246       if (!Decls.count(FoundVD))
2247         return;
2248 
2249       const bool IsReference = FoundVD->getType()->isReferenceType();
2250 
2251       // Prevent double warnings on use of unbounded references.
2252       if (IsReference != CheckReferenceOnly)
2253         return;
2254 
2255       unsigned diag = IsReference
2256           ? diag::warn_reference_field_is_uninit
2257           : diag::warn_field_is_uninit;
2258       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2259       if (Constructor)
2260         S.Diag(Constructor->getLocation(),
2261                diag::note_uninit_in_this_constructor)
2262           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2263 
2264     }
2265 
2266     void HandleValue(Expr *E) {
2267       E = E->IgnoreParens();
2268 
2269       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2270         HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2271         return;
2272       }
2273 
2274       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2275         HandleValue(CO->getTrueExpr());
2276         HandleValue(CO->getFalseExpr());
2277         return;
2278       }
2279 
2280       if (BinaryConditionalOperator *BCO =
2281               dyn_cast<BinaryConditionalOperator>(E)) {
2282         HandleValue(BCO->getCommon());
2283         HandleValue(BCO->getFalseExpr());
2284         return;
2285       }
2286 
2287       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2288         switch (BO->getOpcode()) {
2289         default:
2290           return;
2291         case(BO_PtrMemD):
2292         case(BO_PtrMemI):
2293           HandleValue(BO->getLHS());
2294           return;
2295         case(BO_Comma):
2296           HandleValue(BO->getRHS());
2297           return;
2298         }
2299       }
2300     }
2301 
2302     void VisitMemberExpr(MemberExpr *ME) {
2303       // All uses of unbounded reference fields will warn.
2304       HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
2305 
2306       Inherited::VisitMemberExpr(ME);
2307     }
2308 
2309     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2310       if (E->getCastKind() == CK_LValueToRValue)
2311         HandleValue(E->getSubExpr());
2312 
2313       Inherited::VisitImplicitCastExpr(E);
2314     }
2315 
2316     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2317       if (E->getConstructor()->isCopyConstructor()) {
2318         Expr *ArgExpr = E->getArg(0);
2319         if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) {
2320           if (ICE->getCastKind() == CK_NoOp) {
2321             ArgExpr = ICE->getSubExpr();
2322           }
2323         }
2324 
2325         if (MemberExpr *ME = dyn_cast<MemberExpr>(ArgExpr)) {
2326           HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2327         }
2328       }
2329       Inherited::VisitCXXConstructExpr(E);
2330     }
2331 
2332     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2333       Expr *Callee = E->getCallee();
2334       if (isa<MemberExpr>(Callee))
2335         HandleValue(Callee);
2336 
2337       Inherited::VisitCXXMemberCallExpr(E);
2338     }
2339 
2340     void VisitCallExpr(CallExpr *E) {
2341       // Treat std::move as a use.
2342       if (E->getNumArgs() == 1) {
2343         if (FunctionDecl *FD = E->getDirectCallee()) {
2344           if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
2345             if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getArg(0))) {
2346               HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2347             }
2348           }
2349         }
2350       }
2351 
2352       Inherited::VisitCallExpr(E);
2353     }
2354 
2355     void VisitBinaryOperator(BinaryOperator *E) {
2356       // If a field assignment is detected, remove the field from the
2357       // uninitiailized field set.
2358       if (E->getOpcode() == BO_Assign)
2359         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2360           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2361             if (!FD->getType()->isReferenceType())
2362               Decls.erase(FD);
2363 
2364       Inherited::VisitBinaryOperator(E);
2365     }
2366   };
2367   static void CheckInitExprContainsUninitializedFields(
2368       Sema &S, Expr *E, llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2369       const CXXConstructorDecl *Constructor) {
2370     if (Decls.size() == 0)
2371       return;
2372 
2373     if (!E)
2374       return;
2375 
2376     if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2377       E = Default->getExpr();
2378       if (!E)
2379         return;
2380       // In class initializers will point to the constructor.
2381       UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2382     } else {
2383       UninitializedFieldVisitor(S, Decls, nullptr).Visit(E);
2384     }
2385   }
2386 
2387   // Diagnose value-uses of fields to initialize themselves, e.g.
2388   //   foo(foo)
2389   // where foo is not also a parameter to the constructor.
2390   // Also diagnose across field uninitialized use such as
2391   //   x(y), y(x)
2392   // TODO: implement -Wuninitialized and fold this into that framework.
2393   static void DiagnoseUninitializedFields(
2394       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2395 
2396     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2397                                            Constructor->getLocation())) {
2398       return;
2399     }
2400 
2401     if (Constructor->isInvalidDecl())
2402       return;
2403 
2404     const CXXRecordDecl *RD = Constructor->getParent();
2405 
2406     // Holds fields that are uninitialized.
2407     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2408 
2409     // At the beginning, all fields are uninitialized.
2410     for (auto *I : RD->decls()) {
2411       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2412         UninitializedFields.insert(FD);
2413       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2414         UninitializedFields.insert(IFD->getAnonField());
2415       }
2416     }
2417 
2418     for (const auto *FieldInit : Constructor->inits()) {
2419       Expr *InitExpr = FieldInit->getInit();
2420 
2421       CheckInitExprContainsUninitializedFields(
2422           SemaRef, InitExpr, UninitializedFields, Constructor);
2423 
2424       if (FieldDecl *Field = FieldInit->getAnyMember())
2425         UninitializedFields.erase(Field);
2426     }
2427   }
2428 } // namespace
2429 
2430 /// \brief Enter a new C++ default initializer scope. After calling this, the
2431 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2432 /// parsing or instantiating the initializer failed.
2433 void Sema::ActOnStartCXXInClassMemberInitializer() {
2434   // Create a synthetic function scope to represent the call to the constructor
2435   // that notionally surrounds a use of this initializer.
2436   PushFunctionScope();
2437 }
2438 
2439 /// \brief This is invoked after parsing an in-class initializer for a
2440 /// non-static C++ class member, and after instantiating an in-class initializer
2441 /// in a class template. Such actions are deferred until the class is complete.
2442 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2443                                                   SourceLocation InitLoc,
2444                                                   Expr *InitExpr) {
2445   // Pop the notional constructor scope we created earlier.
2446   PopFunctionScopeInfo(nullptr, D);
2447 
2448   FieldDecl *FD = cast<FieldDecl>(D);
2449   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2450          "must set init style when field is created");
2451 
2452   if (!InitExpr) {
2453     FD->setInvalidDecl();
2454     FD->removeInClassInitializer();
2455     return;
2456   }
2457 
2458   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2459     FD->setInvalidDecl();
2460     FD->removeInClassInitializer();
2461     return;
2462   }
2463 
2464   ExprResult Init = InitExpr;
2465   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2466     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2467     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2468         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2469         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2470     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2471     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2472     if (Init.isInvalid()) {
2473       FD->setInvalidDecl();
2474       return;
2475     }
2476   }
2477 
2478   // C++11 [class.base.init]p7:
2479   //   The initialization of each base and member constitutes a
2480   //   full-expression.
2481   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2482   if (Init.isInvalid()) {
2483     FD->setInvalidDecl();
2484     return;
2485   }
2486 
2487   InitExpr = Init.get();
2488 
2489   FD->setInClassInitializer(InitExpr);
2490 }
2491 
2492 /// \brief Find the direct and/or virtual base specifiers that
2493 /// correspond to the given base type, for use in base initialization
2494 /// within a constructor.
2495 static bool FindBaseInitializer(Sema &SemaRef,
2496                                 CXXRecordDecl *ClassDecl,
2497                                 QualType BaseType,
2498                                 const CXXBaseSpecifier *&DirectBaseSpec,
2499                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2500   // First, check for a direct base class.
2501   DirectBaseSpec = nullptr;
2502   for (const auto &Base : ClassDecl->bases()) {
2503     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2504       // We found a direct base of this type. That's what we're
2505       // initializing.
2506       DirectBaseSpec = &Base;
2507       break;
2508     }
2509   }
2510 
2511   // Check for a virtual base class.
2512   // FIXME: We might be able to short-circuit this if we know in advance that
2513   // there are no virtual bases.
2514   VirtualBaseSpec = nullptr;
2515   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2516     // We haven't found a base yet; search the class hierarchy for a
2517     // virtual base class.
2518     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2519                        /*DetectVirtual=*/false);
2520     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2521                               BaseType, Paths)) {
2522       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2523            Path != Paths.end(); ++Path) {
2524         if (Path->back().Base->isVirtual()) {
2525           VirtualBaseSpec = Path->back().Base;
2526           break;
2527         }
2528       }
2529     }
2530   }
2531 
2532   return DirectBaseSpec || VirtualBaseSpec;
2533 }
2534 
2535 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2536 MemInitResult
2537 Sema::ActOnMemInitializer(Decl *ConstructorD,
2538                           Scope *S,
2539                           CXXScopeSpec &SS,
2540                           IdentifierInfo *MemberOrBase,
2541                           ParsedType TemplateTypeTy,
2542                           const DeclSpec &DS,
2543                           SourceLocation IdLoc,
2544                           Expr *InitList,
2545                           SourceLocation EllipsisLoc) {
2546   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2547                              DS, IdLoc, InitList,
2548                              EllipsisLoc);
2549 }
2550 
2551 /// \brief Handle a C++ member initializer using parentheses syntax.
2552 MemInitResult
2553 Sema::ActOnMemInitializer(Decl *ConstructorD,
2554                           Scope *S,
2555                           CXXScopeSpec &SS,
2556                           IdentifierInfo *MemberOrBase,
2557                           ParsedType TemplateTypeTy,
2558                           const DeclSpec &DS,
2559                           SourceLocation IdLoc,
2560                           SourceLocation LParenLoc,
2561                           ArrayRef<Expr *> Args,
2562                           SourceLocation RParenLoc,
2563                           SourceLocation EllipsisLoc) {
2564   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2565                                            Args, RParenLoc);
2566   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2567                              DS, IdLoc, List, EllipsisLoc);
2568 }
2569 
2570 namespace {
2571 
2572 // Callback to only accept typo corrections that can be a valid C++ member
2573 // intializer: either a non-static field member or a base class.
2574 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2575 public:
2576   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2577       : ClassDecl(ClassDecl) {}
2578 
2579   bool ValidateCandidate(const TypoCorrection &candidate) override {
2580     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2581       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2582         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2583       return isa<TypeDecl>(ND);
2584     }
2585     return false;
2586   }
2587 
2588 private:
2589   CXXRecordDecl *ClassDecl;
2590 };
2591 
2592 }
2593 
2594 /// \brief Handle a C++ member initializer.
2595 MemInitResult
2596 Sema::BuildMemInitializer(Decl *ConstructorD,
2597                           Scope *S,
2598                           CXXScopeSpec &SS,
2599                           IdentifierInfo *MemberOrBase,
2600                           ParsedType TemplateTypeTy,
2601                           const DeclSpec &DS,
2602                           SourceLocation IdLoc,
2603                           Expr *Init,
2604                           SourceLocation EllipsisLoc) {
2605   if (!ConstructorD)
2606     return true;
2607 
2608   AdjustDeclIfTemplate(ConstructorD);
2609 
2610   CXXConstructorDecl *Constructor
2611     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2612   if (!Constructor) {
2613     // The user wrote a constructor initializer on a function that is
2614     // not a C++ constructor. Ignore the error for now, because we may
2615     // have more member initializers coming; we'll diagnose it just
2616     // once in ActOnMemInitializers.
2617     return true;
2618   }
2619 
2620   CXXRecordDecl *ClassDecl = Constructor->getParent();
2621 
2622   // C++ [class.base.init]p2:
2623   //   Names in a mem-initializer-id are looked up in the scope of the
2624   //   constructor's class and, if not found in that scope, are looked
2625   //   up in the scope containing the constructor's definition.
2626   //   [Note: if the constructor's class contains a member with the
2627   //   same name as a direct or virtual base class of the class, a
2628   //   mem-initializer-id naming the member or base class and composed
2629   //   of a single identifier refers to the class member. A
2630   //   mem-initializer-id for the hidden base class may be specified
2631   //   using a qualified name. ]
2632   if (!SS.getScopeRep() && !TemplateTypeTy) {
2633     // Look for a member, first.
2634     DeclContext::lookup_result Result
2635       = ClassDecl->lookup(MemberOrBase);
2636     if (!Result.empty()) {
2637       ValueDecl *Member;
2638       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2639           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2640         if (EllipsisLoc.isValid())
2641           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2642             << MemberOrBase
2643             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2644 
2645         return BuildMemberInitializer(Member, Init, IdLoc);
2646       }
2647     }
2648   }
2649   // It didn't name a member, so see if it names a class.
2650   QualType BaseType;
2651   TypeSourceInfo *TInfo = nullptr;
2652 
2653   if (TemplateTypeTy) {
2654     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2655   } else if (DS.getTypeSpecType() == TST_decltype) {
2656     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2657   } else {
2658     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2659     LookupParsedName(R, S, &SS);
2660 
2661     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2662     if (!TyD) {
2663       if (R.isAmbiguous()) return true;
2664 
2665       // We don't want access-control diagnostics here.
2666       R.suppressDiagnostics();
2667 
2668       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2669         bool NotUnknownSpecialization = false;
2670         DeclContext *DC = computeDeclContext(SS, false);
2671         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2672           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2673 
2674         if (!NotUnknownSpecialization) {
2675           // When the scope specifier can refer to a member of an unknown
2676           // specialization, we take it as a type name.
2677           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2678                                        SS.getWithLocInContext(Context),
2679                                        *MemberOrBase, IdLoc);
2680           if (BaseType.isNull())
2681             return true;
2682 
2683           R.clear();
2684           R.setLookupName(MemberOrBase);
2685         }
2686       }
2687 
2688       // If no results were found, try to correct typos.
2689       TypoCorrection Corr;
2690       MemInitializerValidatorCCC Validator(ClassDecl);
2691       if (R.empty() && BaseType.isNull() &&
2692           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2693                               Validator, CTK_ErrorRecovery, ClassDecl))) {
2694         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2695           // We have found a non-static data member with a similar
2696           // name to what was typed; complain and initialize that
2697           // member.
2698           diagnoseTypo(Corr,
2699                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2700                          << MemberOrBase << true);
2701           return BuildMemberInitializer(Member, Init, IdLoc);
2702         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2703           const CXXBaseSpecifier *DirectBaseSpec;
2704           const CXXBaseSpecifier *VirtualBaseSpec;
2705           if (FindBaseInitializer(*this, ClassDecl,
2706                                   Context.getTypeDeclType(Type),
2707                                   DirectBaseSpec, VirtualBaseSpec)) {
2708             // We have found a direct or virtual base class with a
2709             // similar name to what was typed; complain and initialize
2710             // that base class.
2711             diagnoseTypo(Corr,
2712                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2713                            << MemberOrBase << false,
2714                          PDiag() /*Suppress note, we provide our own.*/);
2715 
2716             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2717                                                               : VirtualBaseSpec;
2718             Diag(BaseSpec->getLocStart(),
2719                  diag::note_base_class_specified_here)
2720               << BaseSpec->getType()
2721               << BaseSpec->getSourceRange();
2722 
2723             TyD = Type;
2724           }
2725         }
2726       }
2727 
2728       if (!TyD && BaseType.isNull()) {
2729         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2730           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2731         return true;
2732       }
2733     }
2734 
2735     if (BaseType.isNull()) {
2736       BaseType = Context.getTypeDeclType(TyD);
2737       if (SS.isSet())
2738         // FIXME: preserve source range information
2739         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2740                                              BaseType);
2741     }
2742   }
2743 
2744   if (!TInfo)
2745     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2746 
2747   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2748 }
2749 
2750 /// Checks a member initializer expression for cases where reference (or
2751 /// pointer) members are bound to by-value parameters (or their addresses).
2752 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2753                                                Expr *Init,
2754                                                SourceLocation IdLoc) {
2755   QualType MemberTy = Member->getType();
2756 
2757   // We only handle pointers and references currently.
2758   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2759   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2760     return;
2761 
2762   const bool IsPointer = MemberTy->isPointerType();
2763   if (IsPointer) {
2764     if (const UnaryOperator *Op
2765           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2766       // The only case we're worried about with pointers requires taking the
2767       // address.
2768       if (Op->getOpcode() != UO_AddrOf)
2769         return;
2770 
2771       Init = Op->getSubExpr();
2772     } else {
2773       // We only handle address-of expression initializers for pointers.
2774       return;
2775     }
2776   }
2777 
2778   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2779     // We only warn when referring to a non-reference parameter declaration.
2780     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2781     if (!Parameter || Parameter->getType()->isReferenceType())
2782       return;
2783 
2784     S.Diag(Init->getExprLoc(),
2785            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2786                      : diag::warn_bind_ref_member_to_parameter)
2787       << Member << Parameter << Init->getSourceRange();
2788   } else {
2789     // Other initializers are fine.
2790     return;
2791   }
2792 
2793   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2794     << (unsigned)IsPointer;
2795 }
2796 
2797 MemInitResult
2798 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2799                              SourceLocation IdLoc) {
2800   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2801   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2802   assert((DirectMember || IndirectMember) &&
2803          "Member must be a FieldDecl or IndirectFieldDecl");
2804 
2805   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2806     return true;
2807 
2808   if (Member->isInvalidDecl())
2809     return true;
2810 
2811   MultiExprArg Args;
2812   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2813     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2814   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2815     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2816   } else {
2817     // Template instantiation doesn't reconstruct ParenListExprs for us.
2818     Args = Init;
2819   }
2820 
2821   SourceRange InitRange = Init->getSourceRange();
2822 
2823   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2824     // Can't check initialization for a member of dependent type or when
2825     // any of the arguments are type-dependent expressions.
2826     DiscardCleanupsInEvaluationContext();
2827   } else {
2828     bool InitList = false;
2829     if (isa<InitListExpr>(Init)) {
2830       InitList = true;
2831       Args = Init;
2832     }
2833 
2834     // Initialize the member.
2835     InitializedEntity MemberEntity =
2836       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2837                    : InitializedEntity::InitializeMember(IndirectMember,
2838                                                          nullptr);
2839     InitializationKind Kind =
2840       InitList ? InitializationKind::CreateDirectList(IdLoc)
2841                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2842                                                   InitRange.getEnd());
2843 
2844     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2845     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2846                                             nullptr);
2847     if (MemberInit.isInvalid())
2848       return true;
2849 
2850     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2851 
2852     // C++11 [class.base.init]p7:
2853     //   The initialization of each base and member constitutes a
2854     //   full-expression.
2855     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2856     if (MemberInit.isInvalid())
2857       return true;
2858 
2859     Init = MemberInit.get();
2860   }
2861 
2862   if (DirectMember) {
2863     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2864                                             InitRange.getBegin(), Init,
2865                                             InitRange.getEnd());
2866   } else {
2867     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2868                                             InitRange.getBegin(), Init,
2869                                             InitRange.getEnd());
2870   }
2871 }
2872 
2873 MemInitResult
2874 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2875                                  CXXRecordDecl *ClassDecl) {
2876   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2877   if (!LangOpts.CPlusPlus11)
2878     return Diag(NameLoc, diag::err_delegating_ctor)
2879       << TInfo->getTypeLoc().getLocalSourceRange();
2880   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2881 
2882   bool InitList = true;
2883   MultiExprArg Args = Init;
2884   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2885     InitList = false;
2886     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2887   }
2888 
2889   SourceRange InitRange = Init->getSourceRange();
2890   // Initialize the object.
2891   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2892                                      QualType(ClassDecl->getTypeForDecl(), 0));
2893   InitializationKind Kind =
2894     InitList ? InitializationKind::CreateDirectList(NameLoc)
2895              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2896                                                 InitRange.getEnd());
2897   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2898   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2899                                               Args, nullptr);
2900   if (DelegationInit.isInvalid())
2901     return true;
2902 
2903   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2904          "Delegating constructor with no target?");
2905 
2906   // C++11 [class.base.init]p7:
2907   //   The initialization of each base and member constitutes a
2908   //   full-expression.
2909   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2910                                        InitRange.getBegin());
2911   if (DelegationInit.isInvalid())
2912     return true;
2913 
2914   // If we are in a dependent context, template instantiation will
2915   // perform this type-checking again. Just save the arguments that we
2916   // received in a ParenListExpr.
2917   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2918   // of the information that we have about the base
2919   // initializer. However, deconstructing the ASTs is a dicey process,
2920   // and this approach is far more likely to get the corner cases right.
2921   if (CurContext->isDependentContext())
2922     DelegationInit = Init;
2923 
2924   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2925                                           DelegationInit.getAs<Expr>(),
2926                                           InitRange.getEnd());
2927 }
2928 
2929 MemInitResult
2930 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2931                            Expr *Init, CXXRecordDecl *ClassDecl,
2932                            SourceLocation EllipsisLoc) {
2933   SourceLocation BaseLoc
2934     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2935 
2936   if (!BaseType->isDependentType() && !BaseType->isRecordType())
2937     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2938              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2939 
2940   // C++ [class.base.init]p2:
2941   //   [...] Unless the mem-initializer-id names a nonstatic data
2942   //   member of the constructor's class or a direct or virtual base
2943   //   of that class, the mem-initializer is ill-formed. A
2944   //   mem-initializer-list can initialize a base class using any
2945   //   name that denotes that base class type.
2946   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2947 
2948   SourceRange InitRange = Init->getSourceRange();
2949   if (EllipsisLoc.isValid()) {
2950     // This is a pack expansion.
2951     if (!BaseType->containsUnexpandedParameterPack())  {
2952       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2953         << SourceRange(BaseLoc, InitRange.getEnd());
2954 
2955       EllipsisLoc = SourceLocation();
2956     }
2957   } else {
2958     // Check for any unexpanded parameter packs.
2959     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2960       return true;
2961 
2962     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2963       return true;
2964   }
2965 
2966   // Check for direct and virtual base classes.
2967   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2968   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
2969   if (!Dependent) {
2970     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2971                                        BaseType))
2972       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2973 
2974     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2975                         VirtualBaseSpec);
2976 
2977     // C++ [base.class.init]p2:
2978     // Unless the mem-initializer-id names a nonstatic data member of the
2979     // constructor's class or a direct or virtual base of that class, the
2980     // mem-initializer is ill-formed.
2981     if (!DirectBaseSpec && !VirtualBaseSpec) {
2982       // If the class has any dependent bases, then it's possible that
2983       // one of those types will resolve to the same type as
2984       // BaseType. Therefore, just treat this as a dependent base
2985       // class initialization.  FIXME: Should we try to check the
2986       // initialization anyway? It seems odd.
2987       if (ClassDecl->hasAnyDependentBases())
2988         Dependent = true;
2989       else
2990         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2991           << BaseType << Context.getTypeDeclType(ClassDecl)
2992           << BaseTInfo->getTypeLoc().getLocalSourceRange();
2993     }
2994   }
2995 
2996   if (Dependent) {
2997     DiscardCleanupsInEvaluationContext();
2998 
2999     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3000                                             /*IsVirtual=*/false,
3001                                             InitRange.getBegin(), Init,
3002                                             InitRange.getEnd(), EllipsisLoc);
3003   }
3004 
3005   // C++ [base.class.init]p2:
3006   //   If a mem-initializer-id is ambiguous because it designates both
3007   //   a direct non-virtual base class and an inherited virtual base
3008   //   class, the mem-initializer is ill-formed.
3009   if (DirectBaseSpec && VirtualBaseSpec)
3010     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3011       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3012 
3013   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3014   if (!BaseSpec)
3015     BaseSpec = VirtualBaseSpec;
3016 
3017   // Initialize the base.
3018   bool InitList = true;
3019   MultiExprArg Args = Init;
3020   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3021     InitList = false;
3022     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3023   }
3024 
3025   InitializedEntity BaseEntity =
3026     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3027   InitializationKind Kind =
3028     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3029              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3030                                                 InitRange.getEnd());
3031   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3032   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3033   if (BaseInit.isInvalid())
3034     return true;
3035 
3036   // C++11 [class.base.init]p7:
3037   //   The initialization of each base and member constitutes a
3038   //   full-expression.
3039   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3040   if (BaseInit.isInvalid())
3041     return true;
3042 
3043   // If we are in a dependent context, template instantiation will
3044   // perform this type-checking again. Just save the arguments that we
3045   // received in a ParenListExpr.
3046   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3047   // of the information that we have about the base
3048   // initializer. However, deconstructing the ASTs is a dicey process,
3049   // and this approach is far more likely to get the corner cases right.
3050   if (CurContext->isDependentContext())
3051     BaseInit = Init;
3052 
3053   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3054                                           BaseSpec->isVirtual(),
3055                                           InitRange.getBegin(),
3056                                           BaseInit.getAs<Expr>(),
3057                                           InitRange.getEnd(), EllipsisLoc);
3058 }
3059 
3060 // Create a static_cast\<T&&>(expr).
3061 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3062   if (T.isNull()) T = E->getType();
3063   QualType TargetType = SemaRef.BuildReferenceType(
3064       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3065   SourceLocation ExprLoc = E->getLocStart();
3066   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3067       TargetType, ExprLoc);
3068 
3069   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3070                                    SourceRange(ExprLoc, ExprLoc),
3071                                    E->getSourceRange()).get();
3072 }
3073 
3074 /// ImplicitInitializerKind - How an implicit base or member initializer should
3075 /// initialize its base or member.
3076 enum ImplicitInitializerKind {
3077   IIK_Default,
3078   IIK_Copy,
3079   IIK_Move,
3080   IIK_Inherit
3081 };
3082 
3083 static bool
3084 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3085                              ImplicitInitializerKind ImplicitInitKind,
3086                              CXXBaseSpecifier *BaseSpec,
3087                              bool IsInheritedVirtualBase,
3088                              CXXCtorInitializer *&CXXBaseInit) {
3089   InitializedEntity InitEntity
3090     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3091                                         IsInheritedVirtualBase);
3092 
3093   ExprResult BaseInit;
3094 
3095   switch (ImplicitInitKind) {
3096   case IIK_Inherit: {
3097     const CXXRecordDecl *Inherited =
3098         Constructor->getInheritedConstructor()->getParent();
3099     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3100     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3101       // C++11 [class.inhctor]p8:
3102       //   Each expression in the expression-list is of the form
3103       //   static_cast<T&&>(p), where p is the name of the corresponding
3104       //   constructor parameter and T is the declared type of p.
3105       SmallVector<Expr*, 16> Args;
3106       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3107         ParmVarDecl *PD = Constructor->getParamDecl(I);
3108         ExprResult ArgExpr =
3109             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3110                                      VK_LValue, SourceLocation());
3111         if (ArgExpr.isInvalid())
3112           return true;
3113         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3114       }
3115 
3116       InitializationKind InitKind = InitializationKind::CreateDirect(
3117           Constructor->getLocation(), SourceLocation(), SourceLocation());
3118       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3119       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3120       break;
3121     }
3122   }
3123   // Fall through.
3124   case IIK_Default: {
3125     InitializationKind InitKind
3126       = InitializationKind::CreateDefault(Constructor->getLocation());
3127     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3128     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3129     break;
3130   }
3131 
3132   case IIK_Move:
3133   case IIK_Copy: {
3134     bool Moving = ImplicitInitKind == IIK_Move;
3135     ParmVarDecl *Param = Constructor->getParamDecl(0);
3136     QualType ParamType = Param->getType().getNonReferenceType();
3137 
3138     Expr *CopyCtorArg =
3139       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3140                           SourceLocation(), Param, false,
3141                           Constructor->getLocation(), ParamType,
3142                           VK_LValue, nullptr);
3143 
3144     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3145 
3146     // Cast to the base class to avoid ambiguities.
3147     QualType ArgTy =
3148       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3149                                        ParamType.getQualifiers());
3150 
3151     if (Moving) {
3152       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3153     }
3154 
3155     CXXCastPath BasePath;
3156     BasePath.push_back(BaseSpec);
3157     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3158                                             CK_UncheckedDerivedToBase,
3159                                             Moving ? VK_XValue : VK_LValue,
3160                                             &BasePath).get();
3161 
3162     InitializationKind InitKind
3163       = InitializationKind::CreateDirect(Constructor->getLocation(),
3164                                          SourceLocation(), SourceLocation());
3165     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3166     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3167     break;
3168   }
3169   }
3170 
3171   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3172   if (BaseInit.isInvalid())
3173     return true;
3174 
3175   CXXBaseInit =
3176     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3177                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3178                                                         SourceLocation()),
3179                                              BaseSpec->isVirtual(),
3180                                              SourceLocation(),
3181                                              BaseInit.getAs<Expr>(),
3182                                              SourceLocation(),
3183                                              SourceLocation());
3184 
3185   return false;
3186 }
3187 
3188 static bool RefersToRValueRef(Expr *MemRef) {
3189   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3190   return Referenced->getType()->isRValueReferenceType();
3191 }
3192 
3193 static bool
3194 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3195                                ImplicitInitializerKind ImplicitInitKind,
3196                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3197                                CXXCtorInitializer *&CXXMemberInit) {
3198   if (Field->isInvalidDecl())
3199     return true;
3200 
3201   SourceLocation Loc = Constructor->getLocation();
3202 
3203   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3204     bool Moving = ImplicitInitKind == IIK_Move;
3205     ParmVarDecl *Param = Constructor->getParamDecl(0);
3206     QualType ParamType = Param->getType().getNonReferenceType();
3207 
3208     // Suppress copying zero-width bitfields.
3209     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3210       return false;
3211 
3212     Expr *MemberExprBase =
3213       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3214                           SourceLocation(), Param, false,
3215                           Loc, ParamType, VK_LValue, nullptr);
3216 
3217     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3218 
3219     if (Moving) {
3220       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3221     }
3222 
3223     // Build a reference to this field within the parameter.
3224     CXXScopeSpec SS;
3225     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3226                               Sema::LookupMemberName);
3227     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3228                                   : cast<ValueDecl>(Field), AS_public);
3229     MemberLookup.resolveKind();
3230     ExprResult CtorArg
3231       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3232                                          ParamType, Loc,
3233                                          /*IsArrow=*/false,
3234                                          SS,
3235                                          /*TemplateKWLoc=*/SourceLocation(),
3236                                          /*FirstQualifierInScope=*/nullptr,
3237                                          MemberLookup,
3238                                          /*TemplateArgs=*/nullptr);
3239     if (CtorArg.isInvalid())
3240       return true;
3241 
3242     // C++11 [class.copy]p15:
3243     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3244     //     with static_cast<T&&>(x.m);
3245     if (RefersToRValueRef(CtorArg.get())) {
3246       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3247     }
3248 
3249     // When the field we are copying is an array, create index variables for
3250     // each dimension of the array. We use these index variables to subscript
3251     // the source array, and other clients (e.g., CodeGen) will perform the
3252     // necessary iteration with these index variables.
3253     SmallVector<VarDecl *, 4> IndexVariables;
3254     QualType BaseType = Field->getType();
3255     QualType SizeType = SemaRef.Context.getSizeType();
3256     bool InitializingArray = false;
3257     while (const ConstantArrayType *Array
3258                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3259       InitializingArray = true;
3260       // Create the iteration variable for this array index.
3261       IdentifierInfo *IterationVarName = nullptr;
3262       {
3263         SmallString<8> Str;
3264         llvm::raw_svector_ostream OS(Str);
3265         OS << "__i" << IndexVariables.size();
3266         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3267       }
3268       VarDecl *IterationVar
3269         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3270                           IterationVarName, SizeType,
3271                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3272                           SC_None);
3273       IndexVariables.push_back(IterationVar);
3274 
3275       // Create a reference to the iteration variable.
3276       ExprResult IterationVarRef
3277         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3278       assert(!IterationVarRef.isInvalid() &&
3279              "Reference to invented variable cannot fail!");
3280       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3281       assert(!IterationVarRef.isInvalid() &&
3282              "Conversion of invented variable cannot fail!");
3283 
3284       // Subscript the array with this iteration variable.
3285       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3286                                                         IterationVarRef.get(),
3287                                                         Loc);
3288       if (CtorArg.isInvalid())
3289         return true;
3290 
3291       BaseType = Array->getElementType();
3292     }
3293 
3294     // The array subscript expression is an lvalue, which is wrong for moving.
3295     if (Moving && InitializingArray)
3296       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3297 
3298     // Construct the entity that we will be initializing. For an array, this
3299     // will be first element in the array, which may require several levels
3300     // of array-subscript entities.
3301     SmallVector<InitializedEntity, 4> Entities;
3302     Entities.reserve(1 + IndexVariables.size());
3303     if (Indirect)
3304       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3305     else
3306       Entities.push_back(InitializedEntity::InitializeMember(Field));
3307     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3308       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3309                                                               0,
3310                                                               Entities.back()));
3311 
3312     // Direct-initialize to use the copy constructor.
3313     InitializationKind InitKind =
3314       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3315 
3316     Expr *CtorArgE = CtorArg.getAs<Expr>();
3317     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3318 
3319     ExprResult MemberInit
3320       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3321                         MultiExprArg(&CtorArgE, 1));
3322     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3323     if (MemberInit.isInvalid())
3324       return true;
3325 
3326     if (Indirect) {
3327       assert(IndexVariables.size() == 0 &&
3328              "Indirect field improperly initialized");
3329       CXXMemberInit
3330         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3331                                                    Loc, Loc,
3332                                                    MemberInit.getAs<Expr>(),
3333                                                    Loc);
3334     } else
3335       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3336                                                  Loc, MemberInit.getAs<Expr>(),
3337                                                  Loc,
3338                                                  IndexVariables.data(),
3339                                                  IndexVariables.size());
3340     return false;
3341   }
3342 
3343   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3344          "Unhandled implicit init kind!");
3345 
3346   QualType FieldBaseElementType =
3347     SemaRef.Context.getBaseElementType(Field->getType());
3348 
3349   if (FieldBaseElementType->isRecordType()) {
3350     InitializedEntity InitEntity
3351       = Indirect? InitializedEntity::InitializeMember(Indirect)
3352                 : InitializedEntity::InitializeMember(Field);
3353     InitializationKind InitKind =
3354       InitializationKind::CreateDefault(Loc);
3355 
3356     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3357     ExprResult MemberInit =
3358       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3359 
3360     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3361     if (MemberInit.isInvalid())
3362       return true;
3363 
3364     if (Indirect)
3365       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3366                                                                Indirect, Loc,
3367                                                                Loc,
3368                                                                MemberInit.get(),
3369                                                                Loc);
3370     else
3371       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3372                                                                Field, Loc, Loc,
3373                                                                MemberInit.get(),
3374                                                                Loc);
3375     return false;
3376   }
3377 
3378   if (!Field->getParent()->isUnion()) {
3379     if (FieldBaseElementType->isReferenceType()) {
3380       SemaRef.Diag(Constructor->getLocation(),
3381                    diag::err_uninitialized_member_in_ctor)
3382       << (int)Constructor->isImplicit()
3383       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3384       << 0 << Field->getDeclName();
3385       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3386       return true;
3387     }
3388 
3389     if (FieldBaseElementType.isConstQualified()) {
3390       SemaRef.Diag(Constructor->getLocation(),
3391                    diag::err_uninitialized_member_in_ctor)
3392       << (int)Constructor->isImplicit()
3393       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3394       << 1 << Field->getDeclName();
3395       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3396       return true;
3397     }
3398   }
3399 
3400   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3401       FieldBaseElementType->isObjCRetainableType() &&
3402       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3403       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3404     // ARC:
3405     //   Default-initialize Objective-C pointers to NULL.
3406     CXXMemberInit
3407       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3408                                                  Loc, Loc,
3409                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3410                                                  Loc);
3411     return false;
3412   }
3413 
3414   // Nothing to initialize.
3415   CXXMemberInit = nullptr;
3416   return false;
3417 }
3418 
3419 namespace {
3420 struct BaseAndFieldInfo {
3421   Sema &S;
3422   CXXConstructorDecl *Ctor;
3423   bool AnyErrorsInInits;
3424   ImplicitInitializerKind IIK;
3425   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3426   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3427   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3428 
3429   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3430     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3431     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3432     if (Generated && Ctor->isCopyConstructor())
3433       IIK = IIK_Copy;
3434     else if (Generated && Ctor->isMoveConstructor())
3435       IIK = IIK_Move;
3436     else if (Ctor->getInheritedConstructor())
3437       IIK = IIK_Inherit;
3438     else
3439       IIK = IIK_Default;
3440   }
3441 
3442   bool isImplicitCopyOrMove() const {
3443     switch (IIK) {
3444     case IIK_Copy:
3445     case IIK_Move:
3446       return true;
3447 
3448     case IIK_Default:
3449     case IIK_Inherit:
3450       return false;
3451     }
3452 
3453     llvm_unreachable("Invalid ImplicitInitializerKind!");
3454   }
3455 
3456   bool addFieldInitializer(CXXCtorInitializer *Init) {
3457     AllToInit.push_back(Init);
3458 
3459     // Check whether this initializer makes the field "used".
3460     if (Init->getInit()->HasSideEffects(S.Context))
3461       S.UnusedPrivateFields.remove(Init->getAnyMember());
3462 
3463     return false;
3464   }
3465 
3466   bool isInactiveUnionMember(FieldDecl *Field) {
3467     RecordDecl *Record = Field->getParent();
3468     if (!Record->isUnion())
3469       return false;
3470 
3471     if (FieldDecl *Active =
3472             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3473       return Active != Field->getCanonicalDecl();
3474 
3475     // In an implicit copy or move constructor, ignore any in-class initializer.
3476     if (isImplicitCopyOrMove())
3477       return true;
3478 
3479     // If there's no explicit initialization, the field is active only if it
3480     // has an in-class initializer...
3481     if (Field->hasInClassInitializer())
3482       return false;
3483     // ... or it's an anonymous struct or union whose class has an in-class
3484     // initializer.
3485     if (!Field->isAnonymousStructOrUnion())
3486       return true;
3487     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3488     return !FieldRD->hasInClassInitializer();
3489   }
3490 
3491   /// \brief Determine whether the given field is, or is within, a union member
3492   /// that is inactive (because there was an initializer given for a different
3493   /// member of the union, or because the union was not initialized at all).
3494   bool isWithinInactiveUnionMember(FieldDecl *Field,
3495                                    IndirectFieldDecl *Indirect) {
3496     if (!Indirect)
3497       return isInactiveUnionMember(Field);
3498 
3499     for (auto *C : Indirect->chain()) {
3500       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3501       if (Field && isInactiveUnionMember(Field))
3502         return true;
3503     }
3504     return false;
3505   }
3506 };
3507 }
3508 
3509 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3510 /// array type.
3511 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3512   if (T->isIncompleteArrayType())
3513     return true;
3514 
3515   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3516     if (!ArrayT->getSize())
3517       return true;
3518 
3519     T = ArrayT->getElementType();
3520   }
3521 
3522   return false;
3523 }
3524 
3525 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3526                                     FieldDecl *Field,
3527                                     IndirectFieldDecl *Indirect = nullptr) {
3528   if (Field->isInvalidDecl())
3529     return false;
3530 
3531   // Overwhelmingly common case: we have a direct initializer for this field.
3532   if (CXXCtorInitializer *Init =
3533           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3534     return Info.addFieldInitializer(Init);
3535 
3536   // C++11 [class.base.init]p8:
3537   //   if the entity is a non-static data member that has a
3538   //   brace-or-equal-initializer and either
3539   //   -- the constructor's class is a union and no other variant member of that
3540   //      union is designated by a mem-initializer-id or
3541   //   -- the constructor's class is not a union, and, if the entity is a member
3542   //      of an anonymous union, no other member of that union is designated by
3543   //      a mem-initializer-id,
3544   //   the entity is initialized as specified in [dcl.init].
3545   //
3546   // We also apply the same rules to handle anonymous structs within anonymous
3547   // unions.
3548   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3549     return false;
3550 
3551   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3552     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3553                                            Info.Ctor->getLocation(), Field);
3554     CXXCtorInitializer *Init;
3555     if (Indirect)
3556       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3557                                                       SourceLocation(),
3558                                                       SourceLocation(), DIE,
3559                                                       SourceLocation());
3560     else
3561       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3562                                                       SourceLocation(),
3563                                                       SourceLocation(), DIE,
3564                                                       SourceLocation());
3565     return Info.addFieldInitializer(Init);
3566   }
3567 
3568   // Don't initialize incomplete or zero-length arrays.
3569   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3570     return false;
3571 
3572   // Don't try to build an implicit initializer if there were semantic
3573   // errors in any of the initializers (and therefore we might be
3574   // missing some that the user actually wrote).
3575   if (Info.AnyErrorsInInits)
3576     return false;
3577 
3578   CXXCtorInitializer *Init = nullptr;
3579   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3580                                      Indirect, Init))
3581     return true;
3582 
3583   if (!Init)
3584     return false;
3585 
3586   return Info.addFieldInitializer(Init);
3587 }
3588 
3589 bool
3590 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3591                                CXXCtorInitializer *Initializer) {
3592   assert(Initializer->isDelegatingInitializer());
3593   Constructor->setNumCtorInitializers(1);
3594   CXXCtorInitializer **initializer =
3595     new (Context) CXXCtorInitializer*[1];
3596   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3597   Constructor->setCtorInitializers(initializer);
3598 
3599   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3600     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3601     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3602   }
3603 
3604   DelegatingCtorDecls.push_back(Constructor);
3605 
3606   return false;
3607 }
3608 
3609 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3610                                ArrayRef<CXXCtorInitializer *> Initializers) {
3611   if (Constructor->isDependentContext()) {
3612     // Just store the initializers as written, they will be checked during
3613     // instantiation.
3614     if (!Initializers.empty()) {
3615       Constructor->setNumCtorInitializers(Initializers.size());
3616       CXXCtorInitializer **baseOrMemberInitializers =
3617         new (Context) CXXCtorInitializer*[Initializers.size()];
3618       memcpy(baseOrMemberInitializers, Initializers.data(),
3619              Initializers.size() * sizeof(CXXCtorInitializer*));
3620       Constructor->setCtorInitializers(baseOrMemberInitializers);
3621     }
3622 
3623     // Let template instantiation know whether we had errors.
3624     if (AnyErrors)
3625       Constructor->setInvalidDecl();
3626 
3627     return false;
3628   }
3629 
3630   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3631 
3632   // We need to build the initializer AST according to order of construction
3633   // and not what user specified in the Initializers list.
3634   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3635   if (!ClassDecl)
3636     return true;
3637 
3638   bool HadError = false;
3639 
3640   for (unsigned i = 0; i < Initializers.size(); i++) {
3641     CXXCtorInitializer *Member = Initializers[i];
3642 
3643     if (Member->isBaseInitializer())
3644       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3645     else {
3646       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3647 
3648       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3649         for (auto *C : F->chain()) {
3650           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3651           if (FD && FD->getParent()->isUnion())
3652             Info.ActiveUnionMember.insert(std::make_pair(
3653                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3654         }
3655       } else if (FieldDecl *FD = Member->getMember()) {
3656         if (FD->getParent()->isUnion())
3657           Info.ActiveUnionMember.insert(std::make_pair(
3658               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3659       }
3660     }
3661   }
3662 
3663   // Keep track of the direct virtual bases.
3664   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3665   for (auto &I : ClassDecl->bases()) {
3666     if (I.isVirtual())
3667       DirectVBases.insert(&I);
3668   }
3669 
3670   // Push virtual bases before others.
3671   for (auto &VBase : ClassDecl->vbases()) {
3672     if (CXXCtorInitializer *Value
3673         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3674       // [class.base.init]p7, per DR257:
3675       //   A mem-initializer where the mem-initializer-id names a virtual base
3676       //   class is ignored during execution of a constructor of any class that
3677       //   is not the most derived class.
3678       if (ClassDecl->isAbstract()) {
3679         // FIXME: Provide a fixit to remove the base specifier. This requires
3680         // tracking the location of the associated comma for a base specifier.
3681         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3682           << VBase.getType() << ClassDecl;
3683         DiagnoseAbstractType(ClassDecl);
3684       }
3685 
3686       Info.AllToInit.push_back(Value);
3687     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3688       // [class.base.init]p8, per DR257:
3689       //   If a given [...] base class is not named by a mem-initializer-id
3690       //   [...] and the entity is not a virtual base class of an abstract
3691       //   class, then [...] the entity is default-initialized.
3692       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3693       CXXCtorInitializer *CXXBaseInit;
3694       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3695                                        &VBase, IsInheritedVirtualBase,
3696                                        CXXBaseInit)) {
3697         HadError = true;
3698         continue;
3699       }
3700 
3701       Info.AllToInit.push_back(CXXBaseInit);
3702     }
3703   }
3704 
3705   // Non-virtual bases.
3706   for (auto &Base : ClassDecl->bases()) {
3707     // Virtuals are in the virtual base list and already constructed.
3708     if (Base.isVirtual())
3709       continue;
3710 
3711     if (CXXCtorInitializer *Value
3712           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3713       Info.AllToInit.push_back(Value);
3714     } else if (!AnyErrors) {
3715       CXXCtorInitializer *CXXBaseInit;
3716       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3717                                        &Base, /*IsInheritedVirtualBase=*/false,
3718                                        CXXBaseInit)) {
3719         HadError = true;
3720         continue;
3721       }
3722 
3723       Info.AllToInit.push_back(CXXBaseInit);
3724     }
3725   }
3726 
3727   // Fields.
3728   for (auto *Mem : ClassDecl->decls()) {
3729     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3730       // C++ [class.bit]p2:
3731       //   A declaration for a bit-field that omits the identifier declares an
3732       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3733       //   initialized.
3734       if (F->isUnnamedBitfield())
3735         continue;
3736 
3737       // If we're not generating the implicit copy/move constructor, then we'll
3738       // handle anonymous struct/union fields based on their individual
3739       // indirect fields.
3740       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3741         continue;
3742 
3743       if (CollectFieldInitializer(*this, Info, F))
3744         HadError = true;
3745       continue;
3746     }
3747 
3748     // Beyond this point, we only consider default initialization.
3749     if (Info.isImplicitCopyOrMove())
3750       continue;
3751 
3752     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
3753       if (F->getType()->isIncompleteArrayType()) {
3754         assert(ClassDecl->hasFlexibleArrayMember() &&
3755                "Incomplete array type is not valid");
3756         continue;
3757       }
3758 
3759       // Initialize each field of an anonymous struct individually.
3760       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3761         HadError = true;
3762 
3763       continue;
3764     }
3765   }
3766 
3767   unsigned NumInitializers = Info.AllToInit.size();
3768   if (NumInitializers > 0) {
3769     Constructor->setNumCtorInitializers(NumInitializers);
3770     CXXCtorInitializer **baseOrMemberInitializers =
3771       new (Context) CXXCtorInitializer*[NumInitializers];
3772     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3773            NumInitializers * sizeof(CXXCtorInitializer*));
3774     Constructor->setCtorInitializers(baseOrMemberInitializers);
3775 
3776     // Constructors implicitly reference the base and member
3777     // destructors.
3778     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3779                                            Constructor->getParent());
3780   }
3781 
3782   return HadError;
3783 }
3784 
3785 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3786   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3787     const RecordDecl *RD = RT->getDecl();
3788     if (RD->isAnonymousStructOrUnion()) {
3789       for (auto *Field : RD->fields())
3790         PopulateKeysForFields(Field, IdealInits);
3791       return;
3792     }
3793   }
3794   IdealInits.push_back(Field->getCanonicalDecl());
3795 }
3796 
3797 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3798   return Context.getCanonicalType(BaseType).getTypePtr();
3799 }
3800 
3801 static const void *GetKeyForMember(ASTContext &Context,
3802                                    CXXCtorInitializer *Member) {
3803   if (!Member->isAnyMemberInitializer())
3804     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3805 
3806   return Member->getAnyMember()->getCanonicalDecl();
3807 }
3808 
3809 static void DiagnoseBaseOrMemInitializerOrder(
3810     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3811     ArrayRef<CXXCtorInitializer *> Inits) {
3812   if (Constructor->getDeclContext()->isDependentContext())
3813     return;
3814 
3815   // Don't check initializers order unless the warning is enabled at the
3816   // location of at least one initializer.
3817   bool ShouldCheckOrder = false;
3818   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3819     CXXCtorInitializer *Init = Inits[InitIndex];
3820     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3821                                  Init->getSourceLocation())) {
3822       ShouldCheckOrder = true;
3823       break;
3824     }
3825   }
3826   if (!ShouldCheckOrder)
3827     return;
3828 
3829   // Build the list of bases and members in the order that they'll
3830   // actually be initialized.  The explicit initializers should be in
3831   // this same order but may be missing things.
3832   SmallVector<const void*, 32> IdealInitKeys;
3833 
3834   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3835 
3836   // 1. Virtual bases.
3837   for (const auto &VBase : ClassDecl->vbases())
3838     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
3839 
3840   // 2. Non-virtual bases.
3841   for (const auto &Base : ClassDecl->bases()) {
3842     if (Base.isVirtual())
3843       continue;
3844     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
3845   }
3846 
3847   // 3. Direct fields.
3848   for (auto *Field : ClassDecl->fields()) {
3849     if (Field->isUnnamedBitfield())
3850       continue;
3851 
3852     PopulateKeysForFields(Field, IdealInitKeys);
3853   }
3854 
3855   unsigned NumIdealInits = IdealInitKeys.size();
3856   unsigned IdealIndex = 0;
3857 
3858   CXXCtorInitializer *PrevInit = nullptr;
3859   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3860     CXXCtorInitializer *Init = Inits[InitIndex];
3861     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3862 
3863     // Scan forward to try to find this initializer in the idealized
3864     // initializers list.
3865     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3866       if (InitKey == IdealInitKeys[IdealIndex])
3867         break;
3868 
3869     // If we didn't find this initializer, it must be because we
3870     // scanned past it on a previous iteration.  That can only
3871     // happen if we're out of order;  emit a warning.
3872     if (IdealIndex == NumIdealInits && PrevInit) {
3873       Sema::SemaDiagnosticBuilder D =
3874         SemaRef.Diag(PrevInit->getSourceLocation(),
3875                      diag::warn_initializer_out_of_order);
3876 
3877       if (PrevInit->isAnyMemberInitializer())
3878         D << 0 << PrevInit->getAnyMember()->getDeclName();
3879       else
3880         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3881 
3882       if (Init->isAnyMemberInitializer())
3883         D << 0 << Init->getAnyMember()->getDeclName();
3884       else
3885         D << 1 << Init->getTypeSourceInfo()->getType();
3886 
3887       // Move back to the initializer's location in the ideal list.
3888       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3889         if (InitKey == IdealInitKeys[IdealIndex])
3890           break;
3891 
3892       assert(IdealIndex != NumIdealInits &&
3893              "initializer not found in initializer list");
3894     }
3895 
3896     PrevInit = Init;
3897   }
3898 }
3899 
3900 namespace {
3901 bool CheckRedundantInit(Sema &S,
3902                         CXXCtorInitializer *Init,
3903                         CXXCtorInitializer *&PrevInit) {
3904   if (!PrevInit) {
3905     PrevInit = Init;
3906     return false;
3907   }
3908 
3909   if (FieldDecl *Field = Init->getAnyMember())
3910     S.Diag(Init->getSourceLocation(),
3911            diag::err_multiple_mem_initialization)
3912       << Field->getDeclName()
3913       << Init->getSourceRange();
3914   else {
3915     const Type *BaseClass = Init->getBaseClass();
3916     assert(BaseClass && "neither field nor base");
3917     S.Diag(Init->getSourceLocation(),
3918            diag::err_multiple_base_initialization)
3919       << QualType(BaseClass, 0)
3920       << Init->getSourceRange();
3921   }
3922   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3923     << 0 << PrevInit->getSourceRange();
3924 
3925   return true;
3926 }
3927 
3928 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3929 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3930 
3931 bool CheckRedundantUnionInit(Sema &S,
3932                              CXXCtorInitializer *Init,
3933                              RedundantUnionMap &Unions) {
3934   FieldDecl *Field = Init->getAnyMember();
3935   RecordDecl *Parent = Field->getParent();
3936   NamedDecl *Child = Field;
3937 
3938   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3939     if (Parent->isUnion()) {
3940       UnionEntry &En = Unions[Parent];
3941       if (En.first && En.first != Child) {
3942         S.Diag(Init->getSourceLocation(),
3943                diag::err_multiple_mem_union_initialization)
3944           << Field->getDeclName()
3945           << Init->getSourceRange();
3946         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3947           << 0 << En.second->getSourceRange();
3948         return true;
3949       }
3950       if (!En.first) {
3951         En.first = Child;
3952         En.second = Init;
3953       }
3954       if (!Parent->isAnonymousStructOrUnion())
3955         return false;
3956     }
3957 
3958     Child = Parent;
3959     Parent = cast<RecordDecl>(Parent->getDeclContext());
3960   }
3961 
3962   return false;
3963 }
3964 }
3965 
3966 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3967 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3968                                 SourceLocation ColonLoc,
3969                                 ArrayRef<CXXCtorInitializer*> MemInits,
3970                                 bool AnyErrors) {
3971   if (!ConstructorDecl)
3972     return;
3973 
3974   AdjustDeclIfTemplate(ConstructorDecl);
3975 
3976   CXXConstructorDecl *Constructor
3977     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3978 
3979   if (!Constructor) {
3980     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3981     return;
3982   }
3983 
3984   // Mapping for the duplicate initializers check.
3985   // For member initializers, this is keyed with a FieldDecl*.
3986   // For base initializers, this is keyed with a Type*.
3987   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
3988 
3989   // Mapping for the inconsistent anonymous-union initializers check.
3990   RedundantUnionMap MemberUnions;
3991 
3992   bool HadError = false;
3993   for (unsigned i = 0; i < MemInits.size(); i++) {
3994     CXXCtorInitializer *Init = MemInits[i];
3995 
3996     // Set the source order index.
3997     Init->setSourceOrder(i);
3998 
3999     if (Init->isAnyMemberInitializer()) {
4000       const void *Key = GetKeyForMember(Context, Init);
4001       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4002           CheckRedundantUnionInit(*this, Init, MemberUnions))
4003         HadError = true;
4004     } else if (Init->isBaseInitializer()) {
4005       const void *Key = GetKeyForMember(Context, Init);
4006       if (CheckRedundantInit(*this, Init, Members[Key]))
4007         HadError = true;
4008     } else {
4009       assert(Init->isDelegatingInitializer());
4010       // This must be the only initializer
4011       if (MemInits.size() != 1) {
4012         Diag(Init->getSourceLocation(),
4013              diag::err_delegating_initializer_alone)
4014           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4015         // We will treat this as being the only initializer.
4016       }
4017       SetDelegatingInitializer(Constructor, MemInits[i]);
4018       // Return immediately as the initializer is set.
4019       return;
4020     }
4021   }
4022 
4023   if (HadError)
4024     return;
4025 
4026   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4027 
4028   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4029 
4030   DiagnoseUninitializedFields(*this, Constructor);
4031 }
4032 
4033 void
4034 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4035                                              CXXRecordDecl *ClassDecl) {
4036   // Ignore dependent contexts. Also ignore unions, since their members never
4037   // have destructors implicitly called.
4038   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4039     return;
4040 
4041   // FIXME: all the access-control diagnostics are positioned on the
4042   // field/base declaration.  That's probably good; that said, the
4043   // user might reasonably want to know why the destructor is being
4044   // emitted, and we currently don't say.
4045 
4046   // Non-static data members.
4047   for (auto *Field : ClassDecl->fields()) {
4048     if (Field->isInvalidDecl())
4049       continue;
4050 
4051     // Don't destroy incomplete or zero-length arrays.
4052     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4053       continue;
4054 
4055     QualType FieldType = Context.getBaseElementType(Field->getType());
4056 
4057     const RecordType* RT = FieldType->getAs<RecordType>();
4058     if (!RT)
4059       continue;
4060 
4061     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4062     if (FieldClassDecl->isInvalidDecl())
4063       continue;
4064     if (FieldClassDecl->hasIrrelevantDestructor())
4065       continue;
4066     // The destructor for an implicit anonymous union member is never invoked.
4067     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4068       continue;
4069 
4070     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4071     assert(Dtor && "No dtor found for FieldClassDecl!");
4072     CheckDestructorAccess(Field->getLocation(), Dtor,
4073                           PDiag(diag::err_access_dtor_field)
4074                             << Field->getDeclName()
4075                             << FieldType);
4076 
4077     MarkFunctionReferenced(Location, Dtor);
4078     DiagnoseUseOfDecl(Dtor, Location);
4079   }
4080 
4081   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4082 
4083   // Bases.
4084   for (const auto &Base : ClassDecl->bases()) {
4085     // Bases are always records in a well-formed non-dependent class.
4086     const RecordType *RT = Base.getType()->getAs<RecordType>();
4087 
4088     // Remember direct virtual bases.
4089     if (Base.isVirtual())
4090       DirectVirtualBases.insert(RT);
4091 
4092     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4093     // If our base class is invalid, we probably can't get its dtor anyway.
4094     if (BaseClassDecl->isInvalidDecl())
4095       continue;
4096     if (BaseClassDecl->hasIrrelevantDestructor())
4097       continue;
4098 
4099     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4100     assert(Dtor && "No dtor found for BaseClassDecl!");
4101 
4102     // FIXME: caret should be on the start of the class name
4103     CheckDestructorAccess(Base.getLocStart(), Dtor,
4104                           PDiag(diag::err_access_dtor_base)
4105                             << Base.getType()
4106                             << Base.getSourceRange(),
4107                           Context.getTypeDeclType(ClassDecl));
4108 
4109     MarkFunctionReferenced(Location, Dtor);
4110     DiagnoseUseOfDecl(Dtor, Location);
4111   }
4112 
4113   // Virtual bases.
4114   for (const auto &VBase : ClassDecl->vbases()) {
4115     // Bases are always records in a well-formed non-dependent class.
4116     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4117 
4118     // Ignore direct virtual bases.
4119     if (DirectVirtualBases.count(RT))
4120       continue;
4121 
4122     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4123     // If our base class is invalid, we probably can't get its dtor anyway.
4124     if (BaseClassDecl->isInvalidDecl())
4125       continue;
4126     if (BaseClassDecl->hasIrrelevantDestructor())
4127       continue;
4128 
4129     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4130     assert(Dtor && "No dtor found for BaseClassDecl!");
4131     if (CheckDestructorAccess(
4132             ClassDecl->getLocation(), Dtor,
4133             PDiag(diag::err_access_dtor_vbase)
4134                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4135             Context.getTypeDeclType(ClassDecl)) ==
4136         AR_accessible) {
4137       CheckDerivedToBaseConversion(
4138           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4139           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4140           SourceRange(), DeclarationName(), nullptr);
4141     }
4142 
4143     MarkFunctionReferenced(Location, Dtor);
4144     DiagnoseUseOfDecl(Dtor, Location);
4145   }
4146 }
4147 
4148 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4149   if (!CDtorDecl)
4150     return;
4151 
4152   if (CXXConstructorDecl *Constructor
4153       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4154     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4155     DiagnoseUninitializedFields(*this, Constructor);
4156   }
4157 }
4158 
4159 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4160                                   unsigned DiagID, AbstractDiagSelID SelID) {
4161   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4162     unsigned DiagID;
4163     AbstractDiagSelID SelID;
4164 
4165   public:
4166     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4167       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4168 
4169     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4170       if (Suppressed) return;
4171       if (SelID == -1)
4172         S.Diag(Loc, DiagID) << T;
4173       else
4174         S.Diag(Loc, DiagID) << SelID << T;
4175     }
4176   } Diagnoser(DiagID, SelID);
4177 
4178   return RequireNonAbstractType(Loc, T, Diagnoser);
4179 }
4180 
4181 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4182                                   TypeDiagnoser &Diagnoser) {
4183   if (!getLangOpts().CPlusPlus)
4184     return false;
4185 
4186   if (const ArrayType *AT = Context.getAsArrayType(T))
4187     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4188 
4189   if (const PointerType *PT = T->getAs<PointerType>()) {
4190     // Find the innermost pointer type.
4191     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4192       PT = T;
4193 
4194     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4195       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4196   }
4197 
4198   const RecordType *RT = T->getAs<RecordType>();
4199   if (!RT)
4200     return false;
4201 
4202   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4203 
4204   // We can't answer whether something is abstract until it has a
4205   // definition.  If it's currently being defined, we'll walk back
4206   // over all the declarations when we have a full definition.
4207   const CXXRecordDecl *Def = RD->getDefinition();
4208   if (!Def || Def->isBeingDefined())
4209     return false;
4210 
4211   if (!RD->isAbstract())
4212     return false;
4213 
4214   Diagnoser.diagnose(*this, Loc, T);
4215   DiagnoseAbstractType(RD);
4216 
4217   return true;
4218 }
4219 
4220 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4221   // Check if we've already emitted the list of pure virtual functions
4222   // for this class.
4223   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4224     return;
4225 
4226   // If the diagnostic is suppressed, don't emit the notes. We're only
4227   // going to emit them once, so try to attach them to a diagnostic we're
4228   // actually going to show.
4229   if (Diags.isLastDiagnosticIgnored())
4230     return;
4231 
4232   CXXFinalOverriderMap FinalOverriders;
4233   RD->getFinalOverriders(FinalOverriders);
4234 
4235   // Keep a set of seen pure methods so we won't diagnose the same method
4236   // more than once.
4237   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4238 
4239   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4240                                    MEnd = FinalOverriders.end();
4241        M != MEnd;
4242        ++M) {
4243     for (OverridingMethods::iterator SO = M->second.begin(),
4244                                   SOEnd = M->second.end();
4245          SO != SOEnd; ++SO) {
4246       // C++ [class.abstract]p4:
4247       //   A class is abstract if it contains or inherits at least one
4248       //   pure virtual function for which the final overrider is pure
4249       //   virtual.
4250 
4251       //
4252       if (SO->second.size() != 1)
4253         continue;
4254 
4255       if (!SO->second.front().Method->isPure())
4256         continue;
4257 
4258       if (!SeenPureMethods.insert(SO->second.front().Method))
4259         continue;
4260 
4261       Diag(SO->second.front().Method->getLocation(),
4262            diag::note_pure_virtual_function)
4263         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4264     }
4265   }
4266 
4267   if (!PureVirtualClassDiagSet)
4268     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4269   PureVirtualClassDiagSet->insert(RD);
4270 }
4271 
4272 namespace {
4273 struct AbstractUsageInfo {
4274   Sema &S;
4275   CXXRecordDecl *Record;
4276   CanQualType AbstractType;
4277   bool Invalid;
4278 
4279   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4280     : S(S), Record(Record),
4281       AbstractType(S.Context.getCanonicalType(
4282                    S.Context.getTypeDeclType(Record))),
4283       Invalid(false) {}
4284 
4285   void DiagnoseAbstractType() {
4286     if (Invalid) return;
4287     S.DiagnoseAbstractType(Record);
4288     Invalid = true;
4289   }
4290 
4291   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4292 };
4293 
4294 struct CheckAbstractUsage {
4295   AbstractUsageInfo &Info;
4296   const NamedDecl *Ctx;
4297 
4298   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4299     : Info(Info), Ctx(Ctx) {}
4300 
4301   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4302     switch (TL.getTypeLocClass()) {
4303 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4304 #define TYPELOC(CLASS, PARENT) \
4305     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4306 #include "clang/AST/TypeLocNodes.def"
4307     }
4308   }
4309 
4310   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4311     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4312     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4313       if (!TL.getParam(I))
4314         continue;
4315 
4316       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4317       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4318     }
4319   }
4320 
4321   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4322     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4323   }
4324 
4325   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4326     // Visit the type parameters from a permissive context.
4327     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4328       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4329       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4330         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4331           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4332       // TODO: other template argument types?
4333     }
4334   }
4335 
4336   // Visit pointee types from a permissive context.
4337 #define CheckPolymorphic(Type) \
4338   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4339     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4340   }
4341   CheckPolymorphic(PointerTypeLoc)
4342   CheckPolymorphic(ReferenceTypeLoc)
4343   CheckPolymorphic(MemberPointerTypeLoc)
4344   CheckPolymorphic(BlockPointerTypeLoc)
4345   CheckPolymorphic(AtomicTypeLoc)
4346 
4347   /// Handle all the types we haven't given a more specific
4348   /// implementation for above.
4349   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4350     // Every other kind of type that we haven't called out already
4351     // that has an inner type is either (1) sugar or (2) contains that
4352     // inner type in some way as a subobject.
4353     if (TypeLoc Next = TL.getNextTypeLoc())
4354       return Visit(Next, Sel);
4355 
4356     // If there's no inner type and we're in a permissive context,
4357     // don't diagnose.
4358     if (Sel == Sema::AbstractNone) return;
4359 
4360     // Check whether the type matches the abstract type.
4361     QualType T = TL.getType();
4362     if (T->isArrayType()) {
4363       Sel = Sema::AbstractArrayType;
4364       T = Info.S.Context.getBaseElementType(T);
4365     }
4366     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4367     if (CT != Info.AbstractType) return;
4368 
4369     // It matched; do some magic.
4370     if (Sel == Sema::AbstractArrayType) {
4371       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4372         << T << TL.getSourceRange();
4373     } else {
4374       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4375         << Sel << T << TL.getSourceRange();
4376     }
4377     Info.DiagnoseAbstractType();
4378   }
4379 };
4380 
4381 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4382                                   Sema::AbstractDiagSelID Sel) {
4383   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4384 }
4385 
4386 }
4387 
4388 /// Check for invalid uses of an abstract type in a method declaration.
4389 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4390                                     CXXMethodDecl *MD) {
4391   // No need to do the check on definitions, which require that
4392   // the return/param types be complete.
4393   if (MD->doesThisDeclarationHaveABody())
4394     return;
4395 
4396   // For safety's sake, just ignore it if we don't have type source
4397   // information.  This should never happen for non-implicit methods,
4398   // but...
4399   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4400     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4401 }
4402 
4403 /// Check for invalid uses of an abstract type within a class definition.
4404 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4405                                     CXXRecordDecl *RD) {
4406   for (auto *D : RD->decls()) {
4407     if (D->isImplicit()) continue;
4408 
4409     // Methods and method templates.
4410     if (isa<CXXMethodDecl>(D)) {
4411       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4412     } else if (isa<FunctionTemplateDecl>(D)) {
4413       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4414       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4415 
4416     // Fields and static variables.
4417     } else if (isa<FieldDecl>(D)) {
4418       FieldDecl *FD = cast<FieldDecl>(D);
4419       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4420         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4421     } else if (isa<VarDecl>(D)) {
4422       VarDecl *VD = cast<VarDecl>(D);
4423       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4424         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4425 
4426     // Nested classes and class templates.
4427     } else if (isa<CXXRecordDecl>(D)) {
4428       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4429     } else if (isa<ClassTemplateDecl>(D)) {
4430       CheckAbstractClassUsage(Info,
4431                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4432     }
4433   }
4434 }
4435 
4436 /// \brief Check class-level dllimport/dllexport attribute.
4437 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4438   Attr *ClassAttr = getDLLAttr(Class);
4439 
4440   // MSVC inherits DLL attributes to partial class template specializations.
4441   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4442     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4443       if (Attr *TemplateAttr =
4444               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4445         auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4446         A->setInherited(true);
4447         ClassAttr = A;
4448       }
4449     }
4450   }
4451 
4452   if (!ClassAttr)
4453     return;
4454 
4455   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4456       !ClassAttr->isInherited()) {
4457     // Diagnose dll attributes on members of class with dll attribute.
4458     for (Decl *Member : Class->decls()) {
4459       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4460         continue;
4461       InheritableAttr *MemberAttr = getDLLAttr(Member);
4462       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4463         continue;
4464 
4465       S.Diag(MemberAttr->getLocation(),
4466              diag::err_attribute_dll_member_of_dll_class)
4467           << MemberAttr << ClassAttr;
4468       S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4469       Member->setInvalidDecl();
4470     }
4471   }
4472 
4473   if (Class->getDescribedClassTemplate())
4474     // Don't inherit dll attribute until the template is instantiated.
4475     return;
4476 
4477   bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4478 
4479   // Force declaration of implicit members so they can inherit the attribute.
4480   S.ForceDeclarationOfImplicitMembers(Class);
4481 
4482   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4483   // seem to be true in practice?
4484 
4485   TemplateSpecializationKind TSK =
4486     Class->getTemplateSpecializationKind();
4487 
4488   for (Decl *Member : Class->decls()) {
4489     VarDecl *VD = dyn_cast<VarDecl>(Member);
4490     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4491 
4492     // Only methods and static fields inherit the attributes.
4493     if (!VD && !MD)
4494       continue;
4495 
4496     // Don't process deleted methods.
4497     if (MD && MD->isDeleted())
4498       continue;
4499 
4500     if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4501         MD->isInlined()) {
4502       // Current MSVC versions don't export the move assignment operators, so
4503       // don't attempt to import them if we have a definition.
4504       continue;
4505     }
4506 
4507     if (!getDLLAttr(Member)) {
4508       auto *NewAttr =
4509           cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4510       NewAttr->setInherited(true);
4511       Member->addAttr(NewAttr);
4512     }
4513 
4514     if (MD && ClassExported) {
4515       if (MD->isUserProvided()) {
4516         // Instantiate non-default methods..
4517 
4518         // .. except for certain kinds of template specializations.
4519         if (TSK == TSK_ExplicitInstantiationDeclaration)
4520           continue;
4521         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4522           continue;
4523 
4524         S.MarkFunctionReferenced(Class->getLocation(), MD);
4525       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4526                  MD->isCopyAssignmentOperator() ||
4527                  MD->isMoveAssignmentOperator()) {
4528         // Instantiate non-trivial or explicitly defaulted methods, and the
4529         // copy assignment / move assignment operators.
4530         S.MarkFunctionReferenced(Class->getLocation(), MD);
4531         // Resolve its exception specification; CodeGen needs it.
4532         auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4533         S.ResolveExceptionSpec(Class->getLocation(), FPT);
4534         S.ActOnFinishInlineMethodDef(MD);
4535       }
4536     }
4537   }
4538 }
4539 
4540 /// \brief Perform semantic checks on a class definition that has been
4541 /// completing, introducing implicitly-declared members, checking for
4542 /// abstract types, etc.
4543 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4544   if (!Record)
4545     return;
4546 
4547   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4548     AbstractUsageInfo Info(*this, Record);
4549     CheckAbstractClassUsage(Info, Record);
4550   }
4551 
4552   // If this is not an aggregate type and has no user-declared constructor,
4553   // complain about any non-static data members of reference or const scalar
4554   // type, since they will never get initializers.
4555   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4556       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4557       !Record->isLambda()) {
4558     bool Complained = false;
4559     for (const auto *F : Record->fields()) {
4560       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4561         continue;
4562 
4563       if (F->getType()->isReferenceType() ||
4564           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4565         if (!Complained) {
4566           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4567             << Record->getTagKind() << Record;
4568           Complained = true;
4569         }
4570 
4571         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4572           << F->getType()->isReferenceType()
4573           << F->getDeclName();
4574       }
4575     }
4576   }
4577 
4578   if (Record->isDynamicClass() && !Record->isDependentType())
4579     DynamicClasses.push_back(Record);
4580 
4581   if (Record->getIdentifier()) {
4582     // C++ [class.mem]p13:
4583     //   If T is the name of a class, then each of the following shall have a
4584     //   name different from T:
4585     //     - every member of every anonymous union that is a member of class T.
4586     //
4587     // C++ [class.mem]p14:
4588     //   In addition, if class T has a user-declared constructor (12.1), every
4589     //   non-static data member of class T shall have a name different from T.
4590     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4591     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4592          ++I) {
4593       NamedDecl *D = *I;
4594       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4595           isa<IndirectFieldDecl>(D)) {
4596         Diag(D->getLocation(), diag::err_member_name_of_class)
4597           << D->getDeclName();
4598         break;
4599       }
4600     }
4601   }
4602 
4603   // Warn if the class has virtual methods but non-virtual public destructor.
4604   if (Record->isPolymorphic() && !Record->isDependentType()) {
4605     CXXDestructorDecl *dtor = Record->getDestructor();
4606     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4607         !Record->hasAttr<FinalAttr>())
4608       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4609            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4610   }
4611 
4612   if (Record->isAbstract()) {
4613     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4614       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4615         << FA->isSpelledAsSealed();
4616       DiagnoseAbstractType(Record);
4617     }
4618   }
4619 
4620   if (!Record->isDependentType()) {
4621     for (auto *M : Record->methods()) {
4622       // See if a method overloads virtual methods in a base
4623       // class without overriding any.
4624       if (!M->isStatic())
4625         DiagnoseHiddenVirtualMethods(M);
4626 
4627       // Check whether the explicitly-defaulted special members are valid.
4628       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4629         CheckExplicitlyDefaultedSpecialMember(M);
4630 
4631       // For an explicitly defaulted or deleted special member, we defer
4632       // determining triviality until the class is complete. That time is now!
4633       if (!M->isImplicit() && !M->isUserProvided()) {
4634         CXXSpecialMember CSM = getSpecialMember(M);
4635         if (CSM != CXXInvalid) {
4636           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4637 
4638           // Inform the class that we've finished declaring this member.
4639           Record->finishedDefaultedOrDeletedMember(M);
4640         }
4641       }
4642     }
4643   }
4644 
4645   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4646   // function that is not a constructor declares that member function to be
4647   // const. [...] The class of which that function is a member shall be
4648   // a literal type.
4649   //
4650   // If the class has virtual bases, any constexpr members will already have
4651   // been diagnosed by the checks performed on the member declaration, so
4652   // suppress this (less useful) diagnostic.
4653   //
4654   // We delay this until we know whether an explicitly-defaulted (or deleted)
4655   // destructor for the class is trivial.
4656   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4657       !Record->isLiteral() && !Record->getNumVBases()) {
4658     for (const auto *M : Record->methods()) {
4659       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
4660         switch (Record->getTemplateSpecializationKind()) {
4661         case TSK_ImplicitInstantiation:
4662         case TSK_ExplicitInstantiationDeclaration:
4663         case TSK_ExplicitInstantiationDefinition:
4664           // If a template instantiates to a non-literal type, but its members
4665           // instantiate to constexpr functions, the template is technically
4666           // ill-formed, but we allow it for sanity.
4667           continue;
4668 
4669         case TSK_Undeclared:
4670         case TSK_ExplicitSpecialization:
4671           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4672                              diag::err_constexpr_method_non_literal);
4673           break;
4674         }
4675 
4676         // Only produce one error per class.
4677         break;
4678       }
4679     }
4680   }
4681 
4682   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4683   // whether this class uses any C++ features that are implemented
4684   // completely differently in MSVC, and if so, emit a diagnostic.
4685   // That diagnostic defaults to an error, but we allow projects to
4686   // map it down to a warning (or ignore it).  It's a fairly common
4687   // practice among users of the ms_struct pragma to mass-annotate
4688   // headers, sweeping up a bunch of types that the project doesn't
4689   // really rely on MSVC-compatible layout for.  We must therefore
4690   // support "ms_struct except for C++ stuff" as a secondary ABI.
4691   if (Record->isMsStruct(Context) &&
4692       (Record->isPolymorphic() || Record->getNumBases())) {
4693     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4694   }
4695 
4696   // Declare inheriting constructors. We do this eagerly here because:
4697   // - The standard requires an eager diagnostic for conflicting inheriting
4698   //   constructors from different classes.
4699   // - The lazy declaration of the other implicit constructors is so as to not
4700   //   waste space and performance on classes that are not meant to be
4701   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4702   //   have inheriting constructors.
4703   DeclareInheritingConstructors(Record);
4704 
4705   checkDLLAttribute(*this, Record);
4706 }
4707 
4708 /// Look up the special member function that would be called by a special
4709 /// member function for a subobject of class type.
4710 ///
4711 /// \param Class The class type of the subobject.
4712 /// \param CSM The kind of special member function.
4713 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4714 /// \param ConstRHS True if this is a copy operation with a const object
4715 ///        on its RHS, that is, if the argument to the outer special member
4716 ///        function is 'const' and this is not a field marked 'mutable'.
4717 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4718     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4719     unsigned FieldQuals, bool ConstRHS) {
4720   unsigned LHSQuals = 0;
4721   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4722     LHSQuals = FieldQuals;
4723 
4724   unsigned RHSQuals = FieldQuals;
4725   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4726     RHSQuals = 0;
4727   else if (ConstRHS)
4728     RHSQuals |= Qualifiers::Const;
4729 
4730   return S.LookupSpecialMember(Class, CSM,
4731                                RHSQuals & Qualifiers::Const,
4732                                RHSQuals & Qualifiers::Volatile,
4733                                false,
4734                                LHSQuals & Qualifiers::Const,
4735                                LHSQuals & Qualifiers::Volatile);
4736 }
4737 
4738 /// Is the special member function which would be selected to perform the
4739 /// specified operation on the specified class type a constexpr constructor?
4740 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4741                                      Sema::CXXSpecialMember CSM,
4742                                      unsigned Quals, bool ConstRHS) {
4743   Sema::SpecialMemberOverloadResult *SMOR =
4744       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
4745   if (!SMOR || !SMOR->getMethod())
4746     // A constructor we wouldn't select can't be "involved in initializing"
4747     // anything.
4748     return true;
4749   return SMOR->getMethod()->isConstexpr();
4750 }
4751 
4752 /// Determine whether the specified special member function would be constexpr
4753 /// if it were implicitly defined.
4754 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4755                                               Sema::CXXSpecialMember CSM,
4756                                               bool ConstArg) {
4757   if (!S.getLangOpts().CPlusPlus11)
4758     return false;
4759 
4760   // C++11 [dcl.constexpr]p4:
4761   // In the definition of a constexpr constructor [...]
4762   bool Ctor = true;
4763   switch (CSM) {
4764   case Sema::CXXDefaultConstructor:
4765     // Since default constructor lookup is essentially trivial (and cannot
4766     // involve, for instance, template instantiation), we compute whether a
4767     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4768     //
4769     // This is important for performance; we need to know whether the default
4770     // constructor is constexpr to determine whether the type is a literal type.
4771     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4772 
4773   case Sema::CXXCopyConstructor:
4774   case Sema::CXXMoveConstructor:
4775     // For copy or move constructors, we need to perform overload resolution.
4776     break;
4777 
4778   case Sema::CXXCopyAssignment:
4779   case Sema::CXXMoveAssignment:
4780     if (!S.getLangOpts().CPlusPlus14)
4781       return false;
4782     // In C++1y, we need to perform overload resolution.
4783     Ctor = false;
4784     break;
4785 
4786   case Sema::CXXDestructor:
4787   case Sema::CXXInvalid:
4788     return false;
4789   }
4790 
4791   //   -- if the class is a non-empty union, or for each non-empty anonymous
4792   //      union member of a non-union class, exactly one non-static data member
4793   //      shall be initialized; [DR1359]
4794   //
4795   // If we squint, this is guaranteed, since exactly one non-static data member
4796   // will be initialized (if the constructor isn't deleted), we just don't know
4797   // which one.
4798   if (Ctor && ClassDecl->isUnion())
4799     return true;
4800 
4801   //   -- the class shall not have any virtual base classes;
4802   if (Ctor && ClassDecl->getNumVBases())
4803     return false;
4804 
4805   // C++1y [class.copy]p26:
4806   //   -- [the class] is a literal type, and
4807   if (!Ctor && !ClassDecl->isLiteral())
4808     return false;
4809 
4810   //   -- every constructor involved in initializing [...] base class
4811   //      sub-objects shall be a constexpr constructor;
4812   //   -- the assignment operator selected to copy/move each direct base
4813   //      class is a constexpr function, and
4814   for (const auto &B : ClassDecl->bases()) {
4815     const RecordType *BaseType = B.getType()->getAs<RecordType>();
4816     if (!BaseType) continue;
4817 
4818     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4819     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
4820       return false;
4821   }
4822 
4823   //   -- every constructor involved in initializing non-static data members
4824   //      [...] shall be a constexpr constructor;
4825   //   -- every non-static data member and base class sub-object shall be
4826   //      initialized
4827   //   -- for each non-static data member of X that is of class type (or array
4828   //      thereof), the assignment operator selected to copy/move that member is
4829   //      a constexpr function
4830   for (const auto *F : ClassDecl->fields()) {
4831     if (F->isInvalidDecl())
4832       continue;
4833     QualType BaseType = S.Context.getBaseElementType(F->getType());
4834     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
4835       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4836       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4837                                     BaseType.getCVRQualifiers(),
4838                                     ConstArg && !F->isMutable()))
4839         return false;
4840     }
4841   }
4842 
4843   // All OK, it's constexpr!
4844   return true;
4845 }
4846 
4847 static Sema::ImplicitExceptionSpecification
4848 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4849   switch (S.getSpecialMember(MD)) {
4850   case Sema::CXXDefaultConstructor:
4851     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4852   case Sema::CXXCopyConstructor:
4853     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4854   case Sema::CXXCopyAssignment:
4855     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4856   case Sema::CXXMoveConstructor:
4857     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4858   case Sema::CXXMoveAssignment:
4859     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4860   case Sema::CXXDestructor:
4861     return S.ComputeDefaultedDtorExceptionSpec(MD);
4862   case Sema::CXXInvalid:
4863     break;
4864   }
4865   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4866          "only special members have implicit exception specs");
4867   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4868 }
4869 
4870 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4871                                                             CXXMethodDecl *MD) {
4872   FunctionProtoType::ExtProtoInfo EPI;
4873 
4874   // Build an exception specification pointing back at this member.
4875   EPI.ExceptionSpec.Type = EST_Unevaluated;
4876   EPI.ExceptionSpec.SourceDecl = MD;
4877 
4878   // Set the calling convention to the default for C++ instance methods.
4879   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4880       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4881                                             /*IsCXXMethod=*/true));
4882   return EPI;
4883 }
4884 
4885 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4886   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4887   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4888     return;
4889 
4890   // Evaluate the exception specification.
4891   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
4892 
4893   // Update the type of the special member to use it.
4894   UpdateExceptionSpec(MD, ESI);
4895 
4896   // A user-provided destructor can be defined outside the class. When that
4897   // happens, be sure to update the exception specification on both
4898   // declarations.
4899   const FunctionProtoType *CanonicalFPT =
4900     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4901   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4902     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
4903 }
4904 
4905 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4906   CXXRecordDecl *RD = MD->getParent();
4907   CXXSpecialMember CSM = getSpecialMember(MD);
4908 
4909   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4910          "not an explicitly-defaulted special member");
4911 
4912   // Whether this was the first-declared instance of the constructor.
4913   // This affects whether we implicitly add an exception spec and constexpr.
4914   bool First = MD == MD->getCanonicalDecl();
4915 
4916   bool HadError = false;
4917 
4918   // C++11 [dcl.fct.def.default]p1:
4919   //   A function that is explicitly defaulted shall
4920   //     -- be a special member function (checked elsewhere),
4921   //     -- have the same type (except for ref-qualifiers, and except that a
4922   //        copy operation can take a non-const reference) as an implicit
4923   //        declaration, and
4924   //     -- not have default arguments.
4925   unsigned ExpectedParams = 1;
4926   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4927     ExpectedParams = 0;
4928   if (MD->getNumParams() != ExpectedParams) {
4929     // This also checks for default arguments: a copy or move constructor with a
4930     // default argument is classified as a default constructor, and assignment
4931     // operations and destructors can't have default arguments.
4932     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4933       << CSM << MD->getSourceRange();
4934     HadError = true;
4935   } else if (MD->isVariadic()) {
4936     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4937       << CSM << MD->getSourceRange();
4938     HadError = true;
4939   }
4940 
4941   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4942 
4943   bool CanHaveConstParam = false;
4944   if (CSM == CXXCopyConstructor)
4945     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4946   else if (CSM == CXXCopyAssignment)
4947     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4948 
4949   QualType ReturnType = Context.VoidTy;
4950   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4951     // Check for return type matching.
4952     ReturnType = Type->getReturnType();
4953     QualType ExpectedReturnType =
4954         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4955     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4956       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4957         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4958       HadError = true;
4959     }
4960 
4961     // A defaulted special member cannot have cv-qualifiers.
4962     if (Type->getTypeQuals()) {
4963       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4964         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
4965       HadError = true;
4966     }
4967   }
4968 
4969   // Check for parameter type matching.
4970   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
4971   bool HasConstParam = false;
4972   if (ExpectedParams && ArgType->isReferenceType()) {
4973     // Argument must be reference to possibly-const T.
4974     QualType ReferentType = ArgType->getPointeeType();
4975     HasConstParam = ReferentType.isConstQualified();
4976 
4977     if (ReferentType.isVolatileQualified()) {
4978       Diag(MD->getLocation(),
4979            diag::err_defaulted_special_member_volatile_param) << CSM;
4980       HadError = true;
4981     }
4982 
4983     if (HasConstParam && !CanHaveConstParam) {
4984       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4985         Diag(MD->getLocation(),
4986              diag::err_defaulted_special_member_copy_const_param)
4987           << (CSM == CXXCopyAssignment);
4988         // FIXME: Explain why this special member can't be const.
4989       } else {
4990         Diag(MD->getLocation(),
4991              diag::err_defaulted_special_member_move_const_param)
4992           << (CSM == CXXMoveAssignment);
4993       }
4994       HadError = true;
4995     }
4996   } else if (ExpectedParams) {
4997     // A copy assignment operator can take its argument by value, but a
4998     // defaulted one cannot.
4999     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5000     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5001     HadError = true;
5002   }
5003 
5004   // C++11 [dcl.fct.def.default]p2:
5005   //   An explicitly-defaulted function may be declared constexpr only if it
5006   //   would have been implicitly declared as constexpr,
5007   // Do not apply this rule to members of class templates, since core issue 1358
5008   // makes such functions always instantiate to constexpr functions. For
5009   // functions which cannot be constexpr (for non-constructors in C++11 and for
5010   // destructors in C++1y), this is checked elsewhere.
5011   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5012                                                      HasConstParam);
5013   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5014                                  : isa<CXXConstructorDecl>(MD)) &&
5015       MD->isConstexpr() && !Constexpr &&
5016       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5017     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5018     // FIXME: Explain why the special member can't be constexpr.
5019     HadError = true;
5020   }
5021 
5022   //   and may have an explicit exception-specification only if it is compatible
5023   //   with the exception-specification on the implicit declaration.
5024   if (Type->hasExceptionSpec()) {
5025     // Delay the check if this is the first declaration of the special member,
5026     // since we may not have parsed some necessary in-class initializers yet.
5027     if (First) {
5028       // If the exception specification needs to be instantiated, do so now,
5029       // before we clobber it with an EST_Unevaluated specification below.
5030       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5031         InstantiateExceptionSpec(MD->getLocStart(), MD);
5032         Type = MD->getType()->getAs<FunctionProtoType>();
5033       }
5034       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5035     } else
5036       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5037   }
5038 
5039   //   If a function is explicitly defaulted on its first declaration,
5040   if (First) {
5041     //  -- it is implicitly considered to be constexpr if the implicit
5042     //     definition would be,
5043     MD->setConstexpr(Constexpr);
5044 
5045     //  -- it is implicitly considered to have the same exception-specification
5046     //     as if it had been implicitly declared,
5047     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5048     EPI.ExceptionSpec.Type = EST_Unevaluated;
5049     EPI.ExceptionSpec.SourceDecl = MD;
5050     MD->setType(Context.getFunctionType(ReturnType,
5051                                         llvm::makeArrayRef(&ArgType,
5052                                                            ExpectedParams),
5053                                         EPI));
5054   }
5055 
5056   if (ShouldDeleteSpecialMember(MD, CSM)) {
5057     if (First) {
5058       SetDeclDeleted(MD, MD->getLocation());
5059     } else {
5060       // C++11 [dcl.fct.def.default]p4:
5061       //   [For a] user-provided explicitly-defaulted function [...] if such a
5062       //   function is implicitly defined as deleted, the program is ill-formed.
5063       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5064       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5065       HadError = true;
5066     }
5067   }
5068 
5069   if (HadError)
5070     MD->setInvalidDecl();
5071 }
5072 
5073 /// Check whether the exception specification provided for an
5074 /// explicitly-defaulted special member matches the exception specification
5075 /// that would have been generated for an implicit special member, per
5076 /// C++11 [dcl.fct.def.default]p2.
5077 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5078     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5079   // Compute the implicit exception specification.
5080   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5081                                                        /*IsCXXMethod=*/true);
5082   FunctionProtoType::ExtProtoInfo EPI(CC);
5083   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5084                           .getExceptionSpec();
5085   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5086     Context.getFunctionType(Context.VoidTy, None, EPI));
5087 
5088   // Ensure that it matches.
5089   CheckEquivalentExceptionSpec(
5090     PDiag(diag::err_incorrect_defaulted_exception_spec)
5091       << getSpecialMember(MD), PDiag(),
5092     ImplicitType, SourceLocation(),
5093     SpecifiedType, MD->getLocation());
5094 }
5095 
5096 void Sema::CheckDelayedMemberExceptionSpecs() {
5097   SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5098               2> Checks;
5099   SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
5100 
5101   std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5102   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5103 
5104   // Perform any deferred checking of exception specifications for virtual
5105   // destructors.
5106   for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5107     const CXXDestructorDecl *Dtor = Checks[i].first;
5108     assert(!Dtor->getParent()->isDependentType() &&
5109            "Should not ever add destructors of templates into the list.");
5110     CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5111   }
5112 
5113   // Check that any explicitly-defaulted methods have exception specifications
5114   // compatible with their implicit exception specifications.
5115   for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5116     CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5117                                                 Specs[I].second);
5118 }
5119 
5120 namespace {
5121 struct SpecialMemberDeletionInfo {
5122   Sema &S;
5123   CXXMethodDecl *MD;
5124   Sema::CXXSpecialMember CSM;
5125   bool Diagnose;
5126 
5127   // Properties of the special member, computed for convenience.
5128   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5129   SourceLocation Loc;
5130 
5131   bool AllFieldsAreConst;
5132 
5133   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5134                             Sema::CXXSpecialMember CSM, bool Diagnose)
5135     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5136       IsConstructor(false), IsAssignment(false), IsMove(false),
5137       ConstArg(false), Loc(MD->getLocation()),
5138       AllFieldsAreConst(true) {
5139     switch (CSM) {
5140       case Sema::CXXDefaultConstructor:
5141       case Sema::CXXCopyConstructor:
5142         IsConstructor = true;
5143         break;
5144       case Sema::CXXMoveConstructor:
5145         IsConstructor = true;
5146         IsMove = true;
5147         break;
5148       case Sema::CXXCopyAssignment:
5149         IsAssignment = true;
5150         break;
5151       case Sema::CXXMoveAssignment:
5152         IsAssignment = true;
5153         IsMove = true;
5154         break;
5155       case Sema::CXXDestructor:
5156         break;
5157       case Sema::CXXInvalid:
5158         llvm_unreachable("invalid special member kind");
5159     }
5160 
5161     if (MD->getNumParams()) {
5162       if (const ReferenceType *RT =
5163               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5164         ConstArg = RT->getPointeeType().isConstQualified();
5165     }
5166   }
5167 
5168   bool inUnion() const { return MD->getParent()->isUnion(); }
5169 
5170   /// Look up the corresponding special member in the given class.
5171   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5172                                               unsigned Quals, bool IsMutable) {
5173     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5174                                        ConstArg && !IsMutable);
5175   }
5176 
5177   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5178 
5179   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5180   bool shouldDeleteForField(FieldDecl *FD);
5181   bool shouldDeleteForAllConstMembers();
5182 
5183   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5184                                      unsigned Quals);
5185   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5186                                     Sema::SpecialMemberOverloadResult *SMOR,
5187                                     bool IsDtorCallInCtor);
5188 
5189   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5190 };
5191 }
5192 
5193 /// Is the given special member inaccessible when used on the given
5194 /// sub-object.
5195 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5196                                              CXXMethodDecl *target) {
5197   /// If we're operating on a base class, the object type is the
5198   /// type of this special member.
5199   QualType objectTy;
5200   AccessSpecifier access = target->getAccess();
5201   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5202     objectTy = S.Context.getTypeDeclType(MD->getParent());
5203     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5204 
5205   // If we're operating on a field, the object type is the type of the field.
5206   } else {
5207     objectTy = S.Context.getTypeDeclType(target->getParent());
5208   }
5209 
5210   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5211 }
5212 
5213 /// Check whether we should delete a special member due to the implicit
5214 /// definition containing a call to a special member of a subobject.
5215 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5216     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5217     bool IsDtorCallInCtor) {
5218   CXXMethodDecl *Decl = SMOR->getMethod();
5219   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5220 
5221   int DiagKind = -1;
5222 
5223   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5224     DiagKind = !Decl ? 0 : 1;
5225   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5226     DiagKind = 2;
5227   else if (!isAccessible(Subobj, Decl))
5228     DiagKind = 3;
5229   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5230            !Decl->isTrivial()) {
5231     // A member of a union must have a trivial corresponding special member.
5232     // As a weird special case, a destructor call from a union's constructor
5233     // must be accessible and non-deleted, but need not be trivial. Such a
5234     // destructor is never actually called, but is semantically checked as
5235     // if it were.
5236     DiagKind = 4;
5237   }
5238 
5239   if (DiagKind == -1)
5240     return false;
5241 
5242   if (Diagnose) {
5243     if (Field) {
5244       S.Diag(Field->getLocation(),
5245              diag::note_deleted_special_member_class_subobject)
5246         << CSM << MD->getParent() << /*IsField*/true
5247         << Field << DiagKind << IsDtorCallInCtor;
5248     } else {
5249       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5250       S.Diag(Base->getLocStart(),
5251              diag::note_deleted_special_member_class_subobject)
5252         << CSM << MD->getParent() << /*IsField*/false
5253         << Base->getType() << DiagKind << IsDtorCallInCtor;
5254     }
5255 
5256     if (DiagKind == 1)
5257       S.NoteDeletedFunction(Decl);
5258     // FIXME: Explain inaccessibility if DiagKind == 3.
5259   }
5260 
5261   return true;
5262 }
5263 
5264 /// Check whether we should delete a special member function due to having a
5265 /// direct or virtual base class or non-static data member of class type M.
5266 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5267     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5268   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5269   bool IsMutable = Field && Field->isMutable();
5270 
5271   // C++11 [class.ctor]p5:
5272   // -- any direct or virtual base class, or non-static data member with no
5273   //    brace-or-equal-initializer, has class type M (or array thereof) and
5274   //    either M has no default constructor or overload resolution as applied
5275   //    to M's default constructor results in an ambiguity or in a function
5276   //    that is deleted or inaccessible
5277   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5278   // -- a direct or virtual base class B that cannot be copied/moved because
5279   //    overload resolution, as applied to B's corresponding special member,
5280   //    results in an ambiguity or a function that is deleted or inaccessible
5281   //    from the defaulted special member
5282   // C++11 [class.dtor]p5:
5283   // -- any direct or virtual base class [...] has a type with a destructor
5284   //    that is deleted or inaccessible
5285   if (!(CSM == Sema::CXXDefaultConstructor &&
5286         Field && Field->hasInClassInitializer()) &&
5287       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5288                                    false))
5289     return true;
5290 
5291   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5292   // -- any direct or virtual base class or non-static data member has a
5293   //    type with a destructor that is deleted or inaccessible
5294   if (IsConstructor) {
5295     Sema::SpecialMemberOverloadResult *SMOR =
5296         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5297                               false, false, false, false, false);
5298     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5299       return true;
5300   }
5301 
5302   return false;
5303 }
5304 
5305 /// Check whether we should delete a special member function due to the class
5306 /// having a particular direct or virtual base class.
5307 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5308   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5309   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5310 }
5311 
5312 /// Check whether we should delete a special member function due to the class
5313 /// having a particular non-static data member.
5314 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5315   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5316   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5317 
5318   if (CSM == Sema::CXXDefaultConstructor) {
5319     // For a default constructor, all references must be initialized in-class
5320     // and, if a union, it must have a non-const member.
5321     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5322       if (Diagnose)
5323         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5324           << MD->getParent() << FD << FieldType << /*Reference*/0;
5325       return true;
5326     }
5327     // C++11 [class.ctor]p5: any non-variant non-static data member of
5328     // const-qualified type (or array thereof) with no
5329     // brace-or-equal-initializer does not have a user-provided default
5330     // constructor.
5331     if (!inUnion() && FieldType.isConstQualified() &&
5332         !FD->hasInClassInitializer() &&
5333         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5334       if (Diagnose)
5335         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5336           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5337       return true;
5338     }
5339 
5340     if (inUnion() && !FieldType.isConstQualified())
5341       AllFieldsAreConst = false;
5342   } else if (CSM == Sema::CXXCopyConstructor) {
5343     // For a copy constructor, data members must not be of rvalue reference
5344     // type.
5345     if (FieldType->isRValueReferenceType()) {
5346       if (Diagnose)
5347         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5348           << MD->getParent() << FD << FieldType;
5349       return true;
5350     }
5351   } else if (IsAssignment) {
5352     // For an assignment operator, data members must not be of reference type.
5353     if (FieldType->isReferenceType()) {
5354       if (Diagnose)
5355         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5356           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5357       return true;
5358     }
5359     if (!FieldRecord && FieldType.isConstQualified()) {
5360       // C++11 [class.copy]p23:
5361       // -- a non-static data member of const non-class type (or array thereof)
5362       if (Diagnose)
5363         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5364           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5365       return true;
5366     }
5367   }
5368 
5369   if (FieldRecord) {
5370     // Some additional restrictions exist on the variant members.
5371     if (!inUnion() && FieldRecord->isUnion() &&
5372         FieldRecord->isAnonymousStructOrUnion()) {
5373       bool AllVariantFieldsAreConst = true;
5374 
5375       // FIXME: Handle anonymous unions declared within anonymous unions.
5376       for (auto *UI : FieldRecord->fields()) {
5377         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5378 
5379         if (!UnionFieldType.isConstQualified())
5380           AllVariantFieldsAreConst = false;
5381 
5382         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5383         if (UnionFieldRecord &&
5384             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5385                                           UnionFieldType.getCVRQualifiers()))
5386           return true;
5387       }
5388 
5389       // At least one member in each anonymous union must be non-const
5390       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5391           !FieldRecord->field_empty()) {
5392         if (Diagnose)
5393           S.Diag(FieldRecord->getLocation(),
5394                  diag::note_deleted_default_ctor_all_const)
5395             << MD->getParent() << /*anonymous union*/1;
5396         return true;
5397       }
5398 
5399       // Don't check the implicit member of the anonymous union type.
5400       // This is technically non-conformant, but sanity demands it.
5401       return false;
5402     }
5403 
5404     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5405                                       FieldType.getCVRQualifiers()))
5406       return true;
5407   }
5408 
5409   return false;
5410 }
5411 
5412 /// C++11 [class.ctor] p5:
5413 ///   A defaulted default constructor for a class X is defined as deleted if
5414 /// X is a union and all of its variant members are of const-qualified type.
5415 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5416   // This is a silly definition, because it gives an empty union a deleted
5417   // default constructor. Don't do that.
5418   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5419       !MD->getParent()->field_empty()) {
5420     if (Diagnose)
5421       S.Diag(MD->getParent()->getLocation(),
5422              diag::note_deleted_default_ctor_all_const)
5423         << MD->getParent() << /*not anonymous union*/0;
5424     return true;
5425   }
5426   return false;
5427 }
5428 
5429 /// Determine whether a defaulted special member function should be defined as
5430 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5431 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5432 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5433                                      bool Diagnose) {
5434   if (MD->isInvalidDecl())
5435     return false;
5436   CXXRecordDecl *RD = MD->getParent();
5437   assert(!RD->isDependentType() && "do deletion after instantiation");
5438   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5439     return false;
5440 
5441   // C++11 [expr.lambda.prim]p19:
5442   //   The closure type associated with a lambda-expression has a
5443   //   deleted (8.4.3) default constructor and a deleted copy
5444   //   assignment operator.
5445   if (RD->isLambda() &&
5446       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5447     if (Diagnose)
5448       Diag(RD->getLocation(), diag::note_lambda_decl);
5449     return true;
5450   }
5451 
5452   // For an anonymous struct or union, the copy and assignment special members
5453   // will never be used, so skip the check. For an anonymous union declared at
5454   // namespace scope, the constructor and destructor are used.
5455   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5456       RD->isAnonymousStructOrUnion())
5457     return false;
5458 
5459   // C++11 [class.copy]p7, p18:
5460   //   If the class definition declares a move constructor or move assignment
5461   //   operator, an implicitly declared copy constructor or copy assignment
5462   //   operator is defined as deleted.
5463   if (MD->isImplicit() &&
5464       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5465     CXXMethodDecl *UserDeclaredMove = nullptr;
5466 
5467     // In Microsoft mode, a user-declared move only causes the deletion of the
5468     // corresponding copy operation, not both copy operations.
5469     if (RD->hasUserDeclaredMoveConstructor() &&
5470         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5471       if (!Diagnose) return true;
5472 
5473       // Find any user-declared move constructor.
5474       for (auto *I : RD->ctors()) {
5475         if (I->isMoveConstructor()) {
5476           UserDeclaredMove = I;
5477           break;
5478         }
5479       }
5480       assert(UserDeclaredMove);
5481     } else if (RD->hasUserDeclaredMoveAssignment() &&
5482                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5483       if (!Diagnose) return true;
5484 
5485       // Find any user-declared move assignment operator.
5486       for (auto *I : RD->methods()) {
5487         if (I->isMoveAssignmentOperator()) {
5488           UserDeclaredMove = I;
5489           break;
5490         }
5491       }
5492       assert(UserDeclaredMove);
5493     }
5494 
5495     if (UserDeclaredMove) {
5496       Diag(UserDeclaredMove->getLocation(),
5497            diag::note_deleted_copy_user_declared_move)
5498         << (CSM == CXXCopyAssignment) << RD
5499         << UserDeclaredMove->isMoveAssignmentOperator();
5500       return true;
5501     }
5502   }
5503 
5504   // Do access control from the special member function
5505   ContextRAII MethodContext(*this, MD);
5506 
5507   // C++11 [class.dtor]p5:
5508   // -- for a virtual destructor, lookup of the non-array deallocation function
5509   //    results in an ambiguity or in a function that is deleted or inaccessible
5510   if (CSM == CXXDestructor && MD->isVirtual()) {
5511     FunctionDecl *OperatorDelete = nullptr;
5512     DeclarationName Name =
5513       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5514     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5515                                  OperatorDelete, false)) {
5516       if (Diagnose)
5517         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5518       return true;
5519     }
5520   }
5521 
5522   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5523 
5524   for (auto &BI : RD->bases())
5525     if (!BI.isVirtual() &&
5526         SMI.shouldDeleteForBase(&BI))
5527       return true;
5528 
5529   // Per DR1611, do not consider virtual bases of constructors of abstract
5530   // classes, since we are not going to construct them.
5531   if (!RD->isAbstract() || !SMI.IsConstructor) {
5532     for (auto &BI : RD->vbases())
5533       if (SMI.shouldDeleteForBase(&BI))
5534         return true;
5535   }
5536 
5537   for (auto *FI : RD->fields())
5538     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5539         SMI.shouldDeleteForField(FI))
5540       return true;
5541 
5542   if (SMI.shouldDeleteForAllConstMembers())
5543     return true;
5544 
5545   return false;
5546 }
5547 
5548 /// Perform lookup for a special member of the specified kind, and determine
5549 /// whether it is trivial. If the triviality can be determined without the
5550 /// lookup, skip it. This is intended for use when determining whether a
5551 /// special member of a containing object is trivial, and thus does not ever
5552 /// perform overload resolution for default constructors.
5553 ///
5554 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5555 /// member that was most likely to be intended to be trivial, if any.
5556 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5557                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5558                                      bool ConstRHS, CXXMethodDecl **Selected) {
5559   if (Selected)
5560     *Selected = nullptr;
5561 
5562   switch (CSM) {
5563   case Sema::CXXInvalid:
5564     llvm_unreachable("not a special member");
5565 
5566   case Sema::CXXDefaultConstructor:
5567     // C++11 [class.ctor]p5:
5568     //   A default constructor is trivial if:
5569     //    - all the [direct subobjects] have trivial default constructors
5570     //
5571     // Note, no overload resolution is performed in this case.
5572     if (RD->hasTrivialDefaultConstructor())
5573       return true;
5574 
5575     if (Selected) {
5576       // If there's a default constructor which could have been trivial, dig it
5577       // out. Otherwise, if there's any user-provided default constructor, point
5578       // to that as an example of why there's not a trivial one.
5579       CXXConstructorDecl *DefCtor = nullptr;
5580       if (RD->needsImplicitDefaultConstructor())
5581         S.DeclareImplicitDefaultConstructor(RD);
5582       for (auto *CI : RD->ctors()) {
5583         if (!CI->isDefaultConstructor())
5584           continue;
5585         DefCtor = CI;
5586         if (!DefCtor->isUserProvided())
5587           break;
5588       }
5589 
5590       *Selected = DefCtor;
5591     }
5592 
5593     return false;
5594 
5595   case Sema::CXXDestructor:
5596     // C++11 [class.dtor]p5:
5597     //   A destructor is trivial if:
5598     //    - all the direct [subobjects] have trivial destructors
5599     if (RD->hasTrivialDestructor())
5600       return true;
5601 
5602     if (Selected) {
5603       if (RD->needsImplicitDestructor())
5604         S.DeclareImplicitDestructor(RD);
5605       *Selected = RD->getDestructor();
5606     }
5607 
5608     return false;
5609 
5610   case Sema::CXXCopyConstructor:
5611     // C++11 [class.copy]p12:
5612     //   A copy constructor is trivial if:
5613     //    - the constructor selected to copy each direct [subobject] is trivial
5614     if (RD->hasTrivialCopyConstructor()) {
5615       if (Quals == Qualifiers::Const)
5616         // We must either select the trivial copy constructor or reach an
5617         // ambiguity; no need to actually perform overload resolution.
5618         return true;
5619     } else if (!Selected) {
5620       return false;
5621     }
5622     // In C++98, we are not supposed to perform overload resolution here, but we
5623     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5624     // cases like B as having a non-trivial copy constructor:
5625     //   struct A { template<typename T> A(T&); };
5626     //   struct B { mutable A a; };
5627     goto NeedOverloadResolution;
5628 
5629   case Sema::CXXCopyAssignment:
5630     // C++11 [class.copy]p25:
5631     //   A copy assignment operator is trivial if:
5632     //    - the assignment operator selected to copy each direct [subobject] is
5633     //      trivial
5634     if (RD->hasTrivialCopyAssignment()) {
5635       if (Quals == Qualifiers::Const)
5636         return true;
5637     } else if (!Selected) {
5638       return false;
5639     }
5640     // In C++98, we are not supposed to perform overload resolution here, but we
5641     // treat that as a language defect.
5642     goto NeedOverloadResolution;
5643 
5644   case Sema::CXXMoveConstructor:
5645   case Sema::CXXMoveAssignment:
5646   NeedOverloadResolution:
5647     Sema::SpecialMemberOverloadResult *SMOR =
5648         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5649 
5650     // The standard doesn't describe how to behave if the lookup is ambiguous.
5651     // We treat it as not making the member non-trivial, just like the standard
5652     // mandates for the default constructor. This should rarely matter, because
5653     // the member will also be deleted.
5654     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5655       return true;
5656 
5657     if (!SMOR->getMethod()) {
5658       assert(SMOR->getKind() ==
5659              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5660       return false;
5661     }
5662 
5663     // We deliberately don't check if we found a deleted special member. We're
5664     // not supposed to!
5665     if (Selected)
5666       *Selected = SMOR->getMethod();
5667     return SMOR->getMethod()->isTrivial();
5668   }
5669 
5670   llvm_unreachable("unknown special method kind");
5671 }
5672 
5673 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5674   for (auto *CI : RD->ctors())
5675     if (!CI->isImplicit())
5676       return CI;
5677 
5678   // Look for constructor templates.
5679   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5680   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5681     if (CXXConstructorDecl *CD =
5682           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5683       return CD;
5684   }
5685 
5686   return nullptr;
5687 }
5688 
5689 /// The kind of subobject we are checking for triviality. The values of this
5690 /// enumeration are used in diagnostics.
5691 enum TrivialSubobjectKind {
5692   /// The subobject is a base class.
5693   TSK_BaseClass,
5694   /// The subobject is a non-static data member.
5695   TSK_Field,
5696   /// The object is actually the complete object.
5697   TSK_CompleteObject
5698 };
5699 
5700 /// Check whether the special member selected for a given type would be trivial.
5701 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5702                                       QualType SubType, bool ConstRHS,
5703                                       Sema::CXXSpecialMember CSM,
5704                                       TrivialSubobjectKind Kind,
5705                                       bool Diagnose) {
5706   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5707   if (!SubRD)
5708     return true;
5709 
5710   CXXMethodDecl *Selected;
5711   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5712                                ConstRHS, Diagnose ? &Selected : nullptr))
5713     return true;
5714 
5715   if (Diagnose) {
5716     if (ConstRHS)
5717       SubType.addConst();
5718 
5719     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5720       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5721         << Kind << SubType.getUnqualifiedType();
5722       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5723         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5724     } else if (!Selected)
5725       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5726         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5727     else if (Selected->isUserProvided()) {
5728       if (Kind == TSK_CompleteObject)
5729         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5730           << Kind << SubType.getUnqualifiedType() << CSM;
5731       else {
5732         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5733           << Kind << SubType.getUnqualifiedType() << CSM;
5734         S.Diag(Selected->getLocation(), diag::note_declared_at);
5735       }
5736     } else {
5737       if (Kind != TSK_CompleteObject)
5738         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5739           << Kind << SubType.getUnqualifiedType() << CSM;
5740 
5741       // Explain why the defaulted or deleted special member isn't trivial.
5742       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5743     }
5744   }
5745 
5746   return false;
5747 }
5748 
5749 /// Check whether the members of a class type allow a special member to be
5750 /// trivial.
5751 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5752                                      Sema::CXXSpecialMember CSM,
5753                                      bool ConstArg, bool Diagnose) {
5754   for (const auto *FI : RD->fields()) {
5755     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5756       continue;
5757 
5758     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5759 
5760     // Pretend anonymous struct or union members are members of this class.
5761     if (FI->isAnonymousStructOrUnion()) {
5762       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5763                                     CSM, ConstArg, Diagnose))
5764         return false;
5765       continue;
5766     }
5767 
5768     // C++11 [class.ctor]p5:
5769     //   A default constructor is trivial if [...]
5770     //    -- no non-static data member of its class has a
5771     //       brace-or-equal-initializer
5772     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5773       if (Diagnose)
5774         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
5775       return false;
5776     }
5777 
5778     // Objective C ARC 4.3.5:
5779     //   [...] nontrivally ownership-qualified types are [...] not trivially
5780     //   default constructible, copy constructible, move constructible, copy
5781     //   assignable, move assignable, or destructible [...]
5782     if (S.getLangOpts().ObjCAutoRefCount &&
5783         FieldType.hasNonTrivialObjCLifetime()) {
5784       if (Diagnose)
5785         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5786           << RD << FieldType.getObjCLifetime();
5787       return false;
5788     }
5789 
5790     bool ConstRHS = ConstArg && !FI->isMutable();
5791     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5792                                    CSM, TSK_Field, Diagnose))
5793       return false;
5794   }
5795 
5796   return true;
5797 }
5798 
5799 /// Diagnose why the specified class does not have a trivial special member of
5800 /// the given kind.
5801 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5802   QualType Ty = Context.getRecordType(RD);
5803 
5804   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5805   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
5806                             TSK_CompleteObject, /*Diagnose*/true);
5807 }
5808 
5809 /// Determine whether a defaulted or deleted special member function is trivial,
5810 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5811 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5812 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5813                                   bool Diagnose) {
5814   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5815 
5816   CXXRecordDecl *RD = MD->getParent();
5817 
5818   bool ConstArg = false;
5819 
5820   // C++11 [class.copy]p12, p25: [DR1593]
5821   //   A [special member] is trivial if [...] its parameter-type-list is
5822   //   equivalent to the parameter-type-list of an implicit declaration [...]
5823   switch (CSM) {
5824   case CXXDefaultConstructor:
5825   case CXXDestructor:
5826     // Trivial default constructors and destructors cannot have parameters.
5827     break;
5828 
5829   case CXXCopyConstructor:
5830   case CXXCopyAssignment: {
5831     // Trivial copy operations always have const, non-volatile parameter types.
5832     ConstArg = true;
5833     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5834     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5835     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5836       if (Diagnose)
5837         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5838           << Param0->getSourceRange() << Param0->getType()
5839           << Context.getLValueReferenceType(
5840                Context.getRecordType(RD).withConst());
5841       return false;
5842     }
5843     break;
5844   }
5845 
5846   case CXXMoveConstructor:
5847   case CXXMoveAssignment: {
5848     // Trivial move operations always have non-cv-qualified parameters.
5849     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5850     const RValueReferenceType *RT =
5851       Param0->getType()->getAs<RValueReferenceType>();
5852     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5853       if (Diagnose)
5854         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5855           << Param0->getSourceRange() << Param0->getType()
5856           << Context.getRValueReferenceType(Context.getRecordType(RD));
5857       return false;
5858     }
5859     break;
5860   }
5861 
5862   case CXXInvalid:
5863     llvm_unreachable("not a special member");
5864   }
5865 
5866   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5867     if (Diagnose)
5868       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5869            diag::note_nontrivial_default_arg)
5870         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5871     return false;
5872   }
5873   if (MD->isVariadic()) {
5874     if (Diagnose)
5875       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5876     return false;
5877   }
5878 
5879   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5880   //   A copy/move [constructor or assignment operator] is trivial if
5881   //    -- the [member] selected to copy/move each direct base class subobject
5882   //       is trivial
5883   //
5884   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5885   //   A [default constructor or destructor] is trivial if
5886   //    -- all the direct base classes have trivial [default constructors or
5887   //       destructors]
5888   for (const auto &BI : RD->bases())
5889     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
5890                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
5891       return false;
5892 
5893   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5894   //   A copy/move [constructor or assignment operator] for a class X is
5895   //   trivial if
5896   //    -- for each non-static data member of X that is of class type (or array
5897   //       thereof), the constructor selected to copy/move that member is
5898   //       trivial
5899   //
5900   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5901   //   A [default constructor or destructor] is trivial if
5902   //    -- for all of the non-static data members of its class that are of class
5903   //       type (or array thereof), each such class has a trivial [default
5904   //       constructor or destructor]
5905   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5906     return false;
5907 
5908   // C++11 [class.dtor]p5:
5909   //   A destructor is trivial if [...]
5910   //    -- the destructor is not virtual
5911   if (CSM == CXXDestructor && MD->isVirtual()) {
5912     if (Diagnose)
5913       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5914     return false;
5915   }
5916 
5917   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5918   //   A [special member] for class X is trivial if [...]
5919   //    -- class X has no virtual functions and no virtual base classes
5920   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5921     if (!Diagnose)
5922       return false;
5923 
5924     if (RD->getNumVBases()) {
5925       // Check for virtual bases. We already know that the corresponding
5926       // member in all bases is trivial, so vbases must all be direct.
5927       CXXBaseSpecifier &BS = *RD->vbases_begin();
5928       assert(BS.isVirtual());
5929       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5930       return false;
5931     }
5932 
5933     // Must have a virtual method.
5934     for (const auto *MI : RD->methods()) {
5935       if (MI->isVirtual()) {
5936         SourceLocation MLoc = MI->getLocStart();
5937         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5938         return false;
5939       }
5940     }
5941 
5942     llvm_unreachable("dynamic class with no vbases and no virtual functions");
5943   }
5944 
5945   // Looks like it's trivial!
5946   return true;
5947 }
5948 
5949 /// \brief Data used with FindHiddenVirtualMethod
5950 namespace {
5951   struct FindHiddenVirtualMethodData {
5952     Sema *S;
5953     CXXMethodDecl *Method;
5954     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5955     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5956   };
5957 }
5958 
5959 /// \brief Check whether any most overriden method from MD in Methods
5960 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5961                   const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
5962   if (MD->size_overridden_methods() == 0)
5963     return Methods.count(MD->getCanonicalDecl());
5964   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5965                                       E = MD->end_overridden_methods();
5966        I != E; ++I)
5967     if (CheckMostOverridenMethods(*I, Methods))
5968       return true;
5969   return false;
5970 }
5971 
5972 /// \brief Member lookup function that determines whether a given C++
5973 /// method overloads virtual methods in a base class without overriding any,
5974 /// to be used with CXXRecordDecl::lookupInBases().
5975 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5976                                     CXXBasePath &Path,
5977                                     void *UserData) {
5978   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5979 
5980   FindHiddenVirtualMethodData &Data
5981     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5982 
5983   DeclarationName Name = Data.Method->getDeclName();
5984   assert(Name.getNameKind() == DeclarationName::Identifier);
5985 
5986   bool foundSameNameMethod = false;
5987   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5988   for (Path.Decls = BaseRecord->lookup(Name);
5989        !Path.Decls.empty();
5990        Path.Decls = Path.Decls.slice(1)) {
5991     NamedDecl *D = Path.Decls.front();
5992     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5993       MD = MD->getCanonicalDecl();
5994       foundSameNameMethod = true;
5995       // Interested only in hidden virtual methods.
5996       if (!MD->isVirtual())
5997         continue;
5998       // If the method we are checking overrides a method from its base
5999       // don't warn about the other overloaded methods. Clang deviates from GCC
6000       // by only diagnosing overloads of inherited virtual functions that do not
6001       // override any other virtual functions in the base. GCC's
6002       // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6003       // function from a base class. These cases may be better served by a
6004       // warning (not specific to virtual functions) on call sites when the call
6005       // would select a different function from the base class, were it visible.
6006       // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6007       if (!Data.S->IsOverload(Data.Method, MD, false))
6008         return true;
6009       // Collect the overload only if its hidden.
6010       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
6011         overloadedMethods.push_back(MD);
6012     }
6013   }
6014 
6015   if (foundSameNameMethod)
6016     Data.OverloadedMethods.append(overloadedMethods.begin(),
6017                                    overloadedMethods.end());
6018   return foundSameNameMethod;
6019 }
6020 
6021 /// \brief Add the most overriden methods from MD to Methods
6022 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6023                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6024   if (MD->size_overridden_methods() == 0)
6025     Methods.insert(MD->getCanonicalDecl());
6026   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6027                                       E = MD->end_overridden_methods();
6028        I != E; ++I)
6029     AddMostOverridenMethods(*I, Methods);
6030 }
6031 
6032 /// \brief Check if a method overloads virtual methods in a base class without
6033 /// overriding any.
6034 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6035                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6036   if (!MD->getDeclName().isIdentifier())
6037     return;
6038 
6039   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6040                      /*bool RecordPaths=*/false,
6041                      /*bool DetectVirtual=*/false);
6042   FindHiddenVirtualMethodData Data;
6043   Data.Method = MD;
6044   Data.S = this;
6045 
6046   // Keep the base methods that were overriden or introduced in the subclass
6047   // by 'using' in a set. A base method not in this set is hidden.
6048   CXXRecordDecl *DC = MD->getParent();
6049   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6050   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6051     NamedDecl *ND = *I;
6052     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6053       ND = shad->getTargetDecl();
6054     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6055       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
6056   }
6057 
6058   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6059     OverloadedMethods = Data.OverloadedMethods;
6060 }
6061 
6062 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6063                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6064   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6065     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6066     PartialDiagnostic PD = PDiag(
6067          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6068     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6069     Diag(overloadedMD->getLocation(), PD);
6070   }
6071 }
6072 
6073 /// \brief Diagnose methods which overload virtual methods in a base class
6074 /// without overriding any.
6075 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6076   if (MD->isInvalidDecl())
6077     return;
6078 
6079   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6080     return;
6081 
6082   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6083   FindHiddenVirtualMethods(MD, OverloadedMethods);
6084   if (!OverloadedMethods.empty()) {
6085     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6086       << MD << (OverloadedMethods.size() > 1);
6087 
6088     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6089   }
6090 }
6091 
6092 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6093                                              Decl *TagDecl,
6094                                              SourceLocation LBrac,
6095                                              SourceLocation RBrac,
6096                                              AttributeList *AttrList) {
6097   if (!TagDecl)
6098     return;
6099 
6100   AdjustDeclIfTemplate(TagDecl);
6101 
6102   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6103     if (l->getKind() != AttributeList::AT_Visibility)
6104       continue;
6105     l->setInvalid();
6106     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6107       l->getName();
6108   }
6109 
6110   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6111               // strict aliasing violation!
6112               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6113               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6114 
6115   CheckCompletedCXXClass(
6116                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6117 }
6118 
6119 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6120 /// special functions, such as the default constructor, copy
6121 /// constructor, or destructor, to the given C++ class (C++
6122 /// [special]p1).  This routine can only be executed just before the
6123 /// definition of the class is complete.
6124 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6125   if (!ClassDecl->hasUserDeclaredConstructor())
6126     ++ASTContext::NumImplicitDefaultConstructors;
6127 
6128   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6129     ++ASTContext::NumImplicitCopyConstructors;
6130 
6131     // If the properties or semantics of the copy constructor couldn't be
6132     // determined while the class was being declared, force a declaration
6133     // of it now.
6134     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6135       DeclareImplicitCopyConstructor(ClassDecl);
6136   }
6137 
6138   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6139     ++ASTContext::NumImplicitMoveConstructors;
6140 
6141     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6142       DeclareImplicitMoveConstructor(ClassDecl);
6143   }
6144 
6145   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6146     ++ASTContext::NumImplicitCopyAssignmentOperators;
6147 
6148     // If we have a dynamic class, then the copy assignment operator may be
6149     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6150     // it shows up in the right place in the vtable and that we diagnose
6151     // problems with the implicit exception specification.
6152     if (ClassDecl->isDynamicClass() ||
6153         ClassDecl->needsOverloadResolutionForCopyAssignment())
6154       DeclareImplicitCopyAssignment(ClassDecl);
6155   }
6156 
6157   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6158     ++ASTContext::NumImplicitMoveAssignmentOperators;
6159 
6160     // Likewise for the move assignment operator.
6161     if (ClassDecl->isDynamicClass() ||
6162         ClassDecl->needsOverloadResolutionForMoveAssignment())
6163       DeclareImplicitMoveAssignment(ClassDecl);
6164   }
6165 
6166   if (!ClassDecl->hasUserDeclaredDestructor()) {
6167     ++ASTContext::NumImplicitDestructors;
6168 
6169     // If we have a dynamic class, then the destructor may be virtual, so we
6170     // have to declare the destructor immediately. This ensures that, e.g., it
6171     // shows up in the right place in the vtable and that we diagnose problems
6172     // with the implicit exception specification.
6173     if (ClassDecl->isDynamicClass() ||
6174         ClassDecl->needsOverloadResolutionForDestructor())
6175       DeclareImplicitDestructor(ClassDecl);
6176   }
6177 }
6178 
6179 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6180   if (!D)
6181     return 0;
6182 
6183   // The order of template parameters is not important here. All names
6184   // get added to the same scope.
6185   SmallVector<TemplateParameterList *, 4> ParameterLists;
6186 
6187   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6188     D = TD->getTemplatedDecl();
6189 
6190   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6191     ParameterLists.push_back(PSD->getTemplateParameters());
6192 
6193   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6194     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6195       ParameterLists.push_back(DD->getTemplateParameterList(i));
6196 
6197     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6198       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6199         ParameterLists.push_back(FTD->getTemplateParameters());
6200     }
6201   }
6202 
6203   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6204     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6205       ParameterLists.push_back(TD->getTemplateParameterList(i));
6206 
6207     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6208       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6209         ParameterLists.push_back(CTD->getTemplateParameters());
6210     }
6211   }
6212 
6213   unsigned Count = 0;
6214   for (TemplateParameterList *Params : ParameterLists) {
6215     if (Params->size() > 0)
6216       // Ignore explicit specializations; they don't contribute to the template
6217       // depth.
6218       ++Count;
6219     for (NamedDecl *Param : *Params) {
6220       if (Param->getDeclName()) {
6221         S->AddDecl(Param);
6222         IdResolver.AddDecl(Param);
6223       }
6224     }
6225   }
6226 
6227   return Count;
6228 }
6229 
6230 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6231   if (!RecordD) return;
6232   AdjustDeclIfTemplate(RecordD);
6233   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6234   PushDeclContext(S, Record);
6235 }
6236 
6237 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6238   if (!RecordD) return;
6239   PopDeclContext();
6240 }
6241 
6242 /// This is used to implement the constant expression evaluation part of the
6243 /// attribute enable_if extension. There is nothing in standard C++ which would
6244 /// require reentering parameters.
6245 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6246   if (!Param)
6247     return;
6248 
6249   S->AddDecl(Param);
6250   if (Param->getDeclName())
6251     IdResolver.AddDecl(Param);
6252 }
6253 
6254 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6255 /// parsing a top-level (non-nested) C++ class, and we are now
6256 /// parsing those parts of the given Method declaration that could
6257 /// not be parsed earlier (C++ [class.mem]p2), such as default
6258 /// arguments. This action should enter the scope of the given
6259 /// Method declaration as if we had just parsed the qualified method
6260 /// name. However, it should not bring the parameters into scope;
6261 /// that will be performed by ActOnDelayedCXXMethodParameter.
6262 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6263 }
6264 
6265 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6266 /// C++ method declaration. We're (re-)introducing the given
6267 /// function parameter into scope for use in parsing later parts of
6268 /// the method declaration. For example, we could see an
6269 /// ActOnParamDefaultArgument event for this parameter.
6270 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6271   if (!ParamD)
6272     return;
6273 
6274   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6275 
6276   // If this parameter has an unparsed default argument, clear it out
6277   // to make way for the parsed default argument.
6278   if (Param->hasUnparsedDefaultArg())
6279     Param->setDefaultArg(nullptr);
6280 
6281   S->AddDecl(Param);
6282   if (Param->getDeclName())
6283     IdResolver.AddDecl(Param);
6284 }
6285 
6286 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6287 /// processing the delayed method declaration for Method. The method
6288 /// declaration is now considered finished. There may be a separate
6289 /// ActOnStartOfFunctionDef action later (not necessarily
6290 /// immediately!) for this method, if it was also defined inside the
6291 /// class body.
6292 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6293   if (!MethodD)
6294     return;
6295 
6296   AdjustDeclIfTemplate(MethodD);
6297 
6298   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6299 
6300   // Now that we have our default arguments, check the constructor
6301   // again. It could produce additional diagnostics or affect whether
6302   // the class has implicitly-declared destructors, among other
6303   // things.
6304   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6305     CheckConstructor(Constructor);
6306 
6307   // Check the default arguments, which we may have added.
6308   if (!Method->isInvalidDecl())
6309     CheckCXXDefaultArguments(Method);
6310 }
6311 
6312 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6313 /// the well-formedness of the constructor declarator @p D with type @p
6314 /// R. If there are any errors in the declarator, this routine will
6315 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6316 /// will be updated to reflect a well-formed type for the constructor and
6317 /// returned.
6318 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6319                                           StorageClass &SC) {
6320   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6321 
6322   // C++ [class.ctor]p3:
6323   //   A constructor shall not be virtual (10.3) or static (9.4). A
6324   //   constructor can be invoked for a const, volatile or const
6325   //   volatile object. A constructor shall not be declared const,
6326   //   volatile, or const volatile (9.3.2).
6327   if (isVirtual) {
6328     if (!D.isInvalidType())
6329       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6330         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6331         << SourceRange(D.getIdentifierLoc());
6332     D.setInvalidType();
6333   }
6334   if (SC == SC_Static) {
6335     if (!D.isInvalidType())
6336       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6337         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6338         << SourceRange(D.getIdentifierLoc());
6339     D.setInvalidType();
6340     SC = SC_None;
6341   }
6342 
6343   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6344     diagnoseIgnoredQualifiers(
6345         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6346         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6347         D.getDeclSpec().getRestrictSpecLoc(),
6348         D.getDeclSpec().getAtomicSpecLoc());
6349     D.setInvalidType();
6350   }
6351 
6352   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6353   if (FTI.TypeQuals != 0) {
6354     if (FTI.TypeQuals & Qualifiers::Const)
6355       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6356         << "const" << SourceRange(D.getIdentifierLoc());
6357     if (FTI.TypeQuals & Qualifiers::Volatile)
6358       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6359         << "volatile" << SourceRange(D.getIdentifierLoc());
6360     if (FTI.TypeQuals & Qualifiers::Restrict)
6361       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6362         << "restrict" << SourceRange(D.getIdentifierLoc());
6363     D.setInvalidType();
6364   }
6365 
6366   // C++0x [class.ctor]p4:
6367   //   A constructor shall not be declared with a ref-qualifier.
6368   if (FTI.hasRefQualifier()) {
6369     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6370       << FTI.RefQualifierIsLValueRef
6371       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6372     D.setInvalidType();
6373   }
6374 
6375   // Rebuild the function type "R" without any type qualifiers (in
6376   // case any of the errors above fired) and with "void" as the
6377   // return type, since constructors don't have return types.
6378   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6379   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6380     return R;
6381 
6382   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6383   EPI.TypeQuals = 0;
6384   EPI.RefQualifier = RQ_None;
6385 
6386   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6387 }
6388 
6389 /// CheckConstructor - Checks a fully-formed constructor for
6390 /// well-formedness, issuing any diagnostics required. Returns true if
6391 /// the constructor declarator is invalid.
6392 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6393   CXXRecordDecl *ClassDecl
6394     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6395   if (!ClassDecl)
6396     return Constructor->setInvalidDecl();
6397 
6398   // C++ [class.copy]p3:
6399   //   A declaration of a constructor for a class X is ill-formed if
6400   //   its first parameter is of type (optionally cv-qualified) X and
6401   //   either there are no other parameters or else all other
6402   //   parameters have default arguments.
6403   if (!Constructor->isInvalidDecl() &&
6404       ((Constructor->getNumParams() == 1) ||
6405        (Constructor->getNumParams() > 1 &&
6406         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6407       Constructor->getTemplateSpecializationKind()
6408                                               != TSK_ImplicitInstantiation) {
6409     QualType ParamType = Constructor->getParamDecl(0)->getType();
6410     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6411     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6412       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6413       const char *ConstRef
6414         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6415                                                         : " const &";
6416       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6417         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6418 
6419       // FIXME: Rather that making the constructor invalid, we should endeavor
6420       // to fix the type.
6421       Constructor->setInvalidDecl();
6422     }
6423   }
6424 }
6425 
6426 /// CheckDestructor - Checks a fully-formed destructor definition for
6427 /// well-formedness, issuing any diagnostics required.  Returns true
6428 /// on error.
6429 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6430   CXXRecordDecl *RD = Destructor->getParent();
6431 
6432   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6433     SourceLocation Loc;
6434 
6435     if (!Destructor->isImplicit())
6436       Loc = Destructor->getLocation();
6437     else
6438       Loc = RD->getLocation();
6439 
6440     // If we have a virtual destructor, look up the deallocation function
6441     FunctionDecl *OperatorDelete = nullptr;
6442     DeclarationName Name =
6443     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6444     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6445       return true;
6446     // If there's no class-specific operator delete, look up the global
6447     // non-array delete.
6448     if (!OperatorDelete)
6449       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6450 
6451     MarkFunctionReferenced(Loc, OperatorDelete);
6452 
6453     Destructor->setOperatorDelete(OperatorDelete);
6454   }
6455 
6456   return false;
6457 }
6458 
6459 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6460 /// the well-formednes of the destructor declarator @p D with type @p
6461 /// R. If there are any errors in the declarator, this routine will
6462 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6463 /// will be updated to reflect a well-formed type for the destructor and
6464 /// returned.
6465 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6466                                          StorageClass& SC) {
6467   // C++ [class.dtor]p1:
6468   //   [...] A typedef-name that names a class is a class-name
6469   //   (7.1.3); however, a typedef-name that names a class shall not
6470   //   be used as the identifier in the declarator for a destructor
6471   //   declaration.
6472   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6473   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6474     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6475       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6476   else if (const TemplateSpecializationType *TST =
6477              DeclaratorType->getAs<TemplateSpecializationType>())
6478     if (TST->isTypeAlias())
6479       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6480         << DeclaratorType << 1;
6481 
6482   // C++ [class.dtor]p2:
6483   //   A destructor is used to destroy objects of its class type. A
6484   //   destructor takes no parameters, and no return type can be
6485   //   specified for it (not even void). The address of a destructor
6486   //   shall not be taken. A destructor shall not be static. A
6487   //   destructor can be invoked for a const, volatile or const
6488   //   volatile object. A destructor shall not be declared const,
6489   //   volatile or const volatile (9.3.2).
6490   if (SC == SC_Static) {
6491     if (!D.isInvalidType())
6492       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6493         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6494         << SourceRange(D.getIdentifierLoc())
6495         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6496 
6497     SC = SC_None;
6498   }
6499   if (!D.isInvalidType()) {
6500     // Destructors don't have return types, but the parser will
6501     // happily parse something like:
6502     //
6503     //   class X {
6504     //     float ~X();
6505     //   };
6506     //
6507     // The return type will be eliminated later.
6508     if (D.getDeclSpec().hasTypeSpecifier())
6509       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6510         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6511         << SourceRange(D.getIdentifierLoc());
6512     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6513       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6514                                 SourceLocation(),
6515                                 D.getDeclSpec().getConstSpecLoc(),
6516                                 D.getDeclSpec().getVolatileSpecLoc(),
6517                                 D.getDeclSpec().getRestrictSpecLoc(),
6518                                 D.getDeclSpec().getAtomicSpecLoc());
6519       D.setInvalidType();
6520     }
6521   }
6522 
6523   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6524   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6525     if (FTI.TypeQuals & Qualifiers::Const)
6526       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6527         << "const" << SourceRange(D.getIdentifierLoc());
6528     if (FTI.TypeQuals & Qualifiers::Volatile)
6529       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6530         << "volatile" << SourceRange(D.getIdentifierLoc());
6531     if (FTI.TypeQuals & Qualifiers::Restrict)
6532       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6533         << "restrict" << SourceRange(D.getIdentifierLoc());
6534     D.setInvalidType();
6535   }
6536 
6537   // C++0x [class.dtor]p2:
6538   //   A destructor shall not be declared with a ref-qualifier.
6539   if (FTI.hasRefQualifier()) {
6540     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6541       << FTI.RefQualifierIsLValueRef
6542       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6543     D.setInvalidType();
6544   }
6545 
6546   // Make sure we don't have any parameters.
6547   if (FTIHasNonVoidParameters(FTI)) {
6548     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6549 
6550     // Delete the parameters.
6551     FTI.freeParams();
6552     D.setInvalidType();
6553   }
6554 
6555   // Make sure the destructor isn't variadic.
6556   if (FTI.isVariadic) {
6557     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6558     D.setInvalidType();
6559   }
6560 
6561   // Rebuild the function type "R" without any type qualifiers or
6562   // parameters (in case any of the errors above fired) and with
6563   // "void" as the return type, since destructors don't have return
6564   // types.
6565   if (!D.isInvalidType())
6566     return R;
6567 
6568   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6569   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6570   EPI.Variadic = false;
6571   EPI.TypeQuals = 0;
6572   EPI.RefQualifier = RQ_None;
6573   return Context.getFunctionType(Context.VoidTy, None, EPI);
6574 }
6575 
6576 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6577 /// well-formednes of the conversion function declarator @p D with
6578 /// type @p R. If there are any errors in the declarator, this routine
6579 /// will emit diagnostics and return true. Otherwise, it will return
6580 /// false. Either way, the type @p R will be updated to reflect a
6581 /// well-formed type for the conversion operator.
6582 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6583                                      StorageClass& SC) {
6584   // C++ [class.conv.fct]p1:
6585   //   Neither parameter types nor return type can be specified. The
6586   //   type of a conversion function (8.3.5) is "function taking no
6587   //   parameter returning conversion-type-id."
6588   if (SC == SC_Static) {
6589     if (!D.isInvalidType())
6590       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6591         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6592         << D.getName().getSourceRange();
6593     D.setInvalidType();
6594     SC = SC_None;
6595   }
6596 
6597   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6598 
6599   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6600     // Conversion functions don't have return types, but the parser will
6601     // happily parse something like:
6602     //
6603     //   class X {
6604     //     float operator bool();
6605     //   };
6606     //
6607     // The return type will be changed later anyway.
6608     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6609       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6610       << SourceRange(D.getIdentifierLoc());
6611     D.setInvalidType();
6612   }
6613 
6614   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6615 
6616   // Make sure we don't have any parameters.
6617   if (Proto->getNumParams() > 0) {
6618     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6619 
6620     // Delete the parameters.
6621     D.getFunctionTypeInfo().freeParams();
6622     D.setInvalidType();
6623   } else if (Proto->isVariadic()) {
6624     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6625     D.setInvalidType();
6626   }
6627 
6628   // Diagnose "&operator bool()" and other such nonsense.  This
6629   // is actually a gcc extension which we don't support.
6630   if (Proto->getReturnType() != ConvType) {
6631     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6632         << Proto->getReturnType();
6633     D.setInvalidType();
6634     ConvType = Proto->getReturnType();
6635   }
6636 
6637   // C++ [class.conv.fct]p4:
6638   //   The conversion-type-id shall not represent a function type nor
6639   //   an array type.
6640   if (ConvType->isArrayType()) {
6641     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6642     ConvType = Context.getPointerType(ConvType);
6643     D.setInvalidType();
6644   } else if (ConvType->isFunctionType()) {
6645     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6646     ConvType = Context.getPointerType(ConvType);
6647     D.setInvalidType();
6648   }
6649 
6650   // Rebuild the function type "R" without any parameters (in case any
6651   // of the errors above fired) and with the conversion type as the
6652   // return type.
6653   if (D.isInvalidType())
6654     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6655 
6656   // C++0x explicit conversion operators.
6657   if (D.getDeclSpec().isExplicitSpecified())
6658     Diag(D.getDeclSpec().getExplicitSpecLoc(),
6659          getLangOpts().CPlusPlus11 ?
6660            diag::warn_cxx98_compat_explicit_conversion_functions :
6661            diag::ext_explicit_conversion_functions)
6662       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6663 }
6664 
6665 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6666 /// the declaration of the given C++ conversion function. This routine
6667 /// is responsible for recording the conversion function in the C++
6668 /// class, if possible.
6669 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6670   assert(Conversion && "Expected to receive a conversion function declaration");
6671 
6672   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6673 
6674   // Make sure we aren't redeclaring the conversion function.
6675   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6676 
6677   // C++ [class.conv.fct]p1:
6678   //   [...] A conversion function is never used to convert a
6679   //   (possibly cv-qualified) object to the (possibly cv-qualified)
6680   //   same object type (or a reference to it), to a (possibly
6681   //   cv-qualified) base class of that type (or a reference to it),
6682   //   or to (possibly cv-qualified) void.
6683   // FIXME: Suppress this warning if the conversion function ends up being a
6684   // virtual function that overrides a virtual function in a base class.
6685   QualType ClassType
6686     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6687   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6688     ConvType = ConvTypeRef->getPointeeType();
6689   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6690       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6691     /* Suppress diagnostics for instantiations. */;
6692   else if (ConvType->isRecordType()) {
6693     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6694     if (ConvType == ClassType)
6695       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6696         << ClassType;
6697     else if (IsDerivedFrom(ClassType, ConvType))
6698       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6699         <<  ClassType << ConvType;
6700   } else if (ConvType->isVoidType()) {
6701     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6702       << ClassType << ConvType;
6703   }
6704 
6705   if (FunctionTemplateDecl *ConversionTemplate
6706                                 = Conversion->getDescribedFunctionTemplate())
6707     return ConversionTemplate;
6708 
6709   return Conversion;
6710 }
6711 
6712 //===----------------------------------------------------------------------===//
6713 // Namespace Handling
6714 //===----------------------------------------------------------------------===//
6715 
6716 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6717 /// reopened.
6718 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6719                                             SourceLocation Loc,
6720                                             IdentifierInfo *II, bool *IsInline,
6721                                             NamespaceDecl *PrevNS) {
6722   assert(*IsInline != PrevNS->isInline());
6723 
6724   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6725   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6726   // inline namespaces, with the intention of bringing names into namespace std.
6727   //
6728   // We support this just well enough to get that case working; this is not
6729   // sufficient to support reopening namespaces as inline in general.
6730   if (*IsInline && II && II->getName().startswith("__atomic") &&
6731       S.getSourceManager().isInSystemHeader(Loc)) {
6732     // Mark all prior declarations of the namespace as inline.
6733     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6734          NS = NS->getPreviousDecl())
6735       NS->setInline(*IsInline);
6736     // Patch up the lookup table for the containing namespace. This isn't really
6737     // correct, but it's good enough for this particular case.
6738     for (auto *I : PrevNS->decls())
6739       if (auto *ND = dyn_cast<NamedDecl>(I))
6740         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6741     return;
6742   }
6743 
6744   if (PrevNS->isInline())
6745     // The user probably just forgot the 'inline', so suggest that it
6746     // be added back.
6747     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6748       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6749   else
6750     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
6751 
6752   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6753   *IsInline = PrevNS->isInline();
6754 }
6755 
6756 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6757 /// definition.
6758 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6759                                    SourceLocation InlineLoc,
6760                                    SourceLocation NamespaceLoc,
6761                                    SourceLocation IdentLoc,
6762                                    IdentifierInfo *II,
6763                                    SourceLocation LBrace,
6764                                    AttributeList *AttrList) {
6765   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6766   // For anonymous namespace, take the location of the left brace.
6767   SourceLocation Loc = II ? IdentLoc : LBrace;
6768   bool IsInline = InlineLoc.isValid();
6769   bool IsInvalid = false;
6770   bool IsStd = false;
6771   bool AddToKnown = false;
6772   Scope *DeclRegionScope = NamespcScope->getParent();
6773 
6774   NamespaceDecl *PrevNS = nullptr;
6775   if (II) {
6776     // C++ [namespace.def]p2:
6777     //   The identifier in an original-namespace-definition shall not
6778     //   have been previously defined in the declarative region in
6779     //   which the original-namespace-definition appears. The
6780     //   identifier in an original-namespace-definition is the name of
6781     //   the namespace. Subsequently in that declarative region, it is
6782     //   treated as an original-namespace-name.
6783     //
6784     // Since namespace names are unique in their scope, and we don't
6785     // look through using directives, just look for any ordinary names.
6786 
6787     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6788     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6789     Decl::IDNS_Namespace;
6790     NamedDecl *PrevDecl = nullptr;
6791     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6792     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6793          ++I) {
6794       if ((*I)->getIdentifierNamespace() & IDNS) {
6795         PrevDecl = *I;
6796         break;
6797       }
6798     }
6799 
6800     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6801 
6802     if (PrevNS) {
6803       // This is an extended namespace definition.
6804       if (IsInline != PrevNS->isInline())
6805         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6806                                         &IsInline, PrevNS);
6807     } else if (PrevDecl) {
6808       // This is an invalid name redefinition.
6809       Diag(Loc, diag::err_redefinition_different_kind)
6810         << II;
6811       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6812       IsInvalid = true;
6813       // Continue on to push Namespc as current DeclContext and return it.
6814     } else if (II->isStr("std") &&
6815                CurContext->getRedeclContext()->isTranslationUnit()) {
6816       // This is the first "real" definition of the namespace "std", so update
6817       // our cache of the "std" namespace to point at this definition.
6818       PrevNS = getStdNamespace();
6819       IsStd = true;
6820       AddToKnown = !IsInline;
6821     } else {
6822       // We've seen this namespace for the first time.
6823       AddToKnown = !IsInline;
6824     }
6825   } else {
6826     // Anonymous namespaces.
6827 
6828     // Determine whether the parent already has an anonymous namespace.
6829     DeclContext *Parent = CurContext->getRedeclContext();
6830     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6831       PrevNS = TU->getAnonymousNamespace();
6832     } else {
6833       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6834       PrevNS = ND->getAnonymousNamespace();
6835     }
6836 
6837     if (PrevNS && IsInline != PrevNS->isInline())
6838       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6839                                       &IsInline, PrevNS);
6840   }
6841 
6842   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6843                                                  StartLoc, Loc, II, PrevNS);
6844   if (IsInvalid)
6845     Namespc->setInvalidDecl();
6846 
6847   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6848 
6849   // FIXME: Should we be merging attributes?
6850   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6851     PushNamespaceVisibilityAttr(Attr, Loc);
6852 
6853   if (IsStd)
6854     StdNamespace = Namespc;
6855   if (AddToKnown)
6856     KnownNamespaces[Namespc] = false;
6857 
6858   if (II) {
6859     PushOnScopeChains(Namespc, DeclRegionScope);
6860   } else {
6861     // Link the anonymous namespace into its parent.
6862     DeclContext *Parent = CurContext->getRedeclContext();
6863     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6864       TU->setAnonymousNamespace(Namespc);
6865     } else {
6866       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6867     }
6868 
6869     CurContext->addDecl(Namespc);
6870 
6871     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6872     //   behaves as if it were replaced by
6873     //     namespace unique { /* empty body */ }
6874     //     using namespace unique;
6875     //     namespace unique { namespace-body }
6876     //   where all occurrences of 'unique' in a translation unit are
6877     //   replaced by the same identifier and this identifier differs
6878     //   from all other identifiers in the entire program.
6879 
6880     // We just create the namespace with an empty name and then add an
6881     // implicit using declaration, just like the standard suggests.
6882     //
6883     // CodeGen enforces the "universally unique" aspect by giving all
6884     // declarations semantically contained within an anonymous
6885     // namespace internal linkage.
6886 
6887     if (!PrevNS) {
6888       UsingDirectiveDecl* UD
6889         = UsingDirectiveDecl::Create(Context, Parent,
6890                                      /* 'using' */ LBrace,
6891                                      /* 'namespace' */ SourceLocation(),
6892                                      /* qualifier */ NestedNameSpecifierLoc(),
6893                                      /* identifier */ SourceLocation(),
6894                                      Namespc,
6895                                      /* Ancestor */ Parent);
6896       UD->setImplicit();
6897       Parent->addDecl(UD);
6898     }
6899   }
6900 
6901   ActOnDocumentableDecl(Namespc);
6902 
6903   // Although we could have an invalid decl (i.e. the namespace name is a
6904   // redefinition), push it as current DeclContext and try to continue parsing.
6905   // FIXME: We should be able to push Namespc here, so that the each DeclContext
6906   // for the namespace has the declarations that showed up in that particular
6907   // namespace definition.
6908   PushDeclContext(NamespcScope, Namespc);
6909   return Namespc;
6910 }
6911 
6912 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6913 /// is a namespace alias, returns the namespace it points to.
6914 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6915   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6916     return AD->getNamespace();
6917   return dyn_cast_or_null<NamespaceDecl>(D);
6918 }
6919 
6920 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6921 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6922 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6923   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6924   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6925   Namespc->setRBraceLoc(RBrace);
6926   PopDeclContext();
6927   if (Namespc->hasAttr<VisibilityAttr>())
6928     PopPragmaVisibility(true, RBrace);
6929 }
6930 
6931 CXXRecordDecl *Sema::getStdBadAlloc() const {
6932   return cast_or_null<CXXRecordDecl>(
6933                                   StdBadAlloc.get(Context.getExternalSource()));
6934 }
6935 
6936 NamespaceDecl *Sema::getStdNamespace() const {
6937   return cast_or_null<NamespaceDecl>(
6938                                  StdNamespace.get(Context.getExternalSource()));
6939 }
6940 
6941 /// \brief Retrieve the special "std" namespace, which may require us to
6942 /// implicitly define the namespace.
6943 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6944   if (!StdNamespace) {
6945     // The "std" namespace has not yet been defined, so build one implicitly.
6946     StdNamespace = NamespaceDecl::Create(Context,
6947                                          Context.getTranslationUnitDecl(),
6948                                          /*Inline=*/false,
6949                                          SourceLocation(), SourceLocation(),
6950                                          &PP.getIdentifierTable().get("std"),
6951                                          /*PrevDecl=*/nullptr);
6952     getStdNamespace()->setImplicit(true);
6953   }
6954 
6955   return getStdNamespace();
6956 }
6957 
6958 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6959   assert(getLangOpts().CPlusPlus &&
6960          "Looking for std::initializer_list outside of C++.");
6961 
6962   // We're looking for implicit instantiations of
6963   // template <typename E> class std::initializer_list.
6964 
6965   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6966     return false;
6967 
6968   ClassTemplateDecl *Template = nullptr;
6969   const TemplateArgument *Arguments = nullptr;
6970 
6971   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6972 
6973     ClassTemplateSpecializationDecl *Specialization =
6974         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6975     if (!Specialization)
6976       return false;
6977 
6978     Template = Specialization->getSpecializedTemplate();
6979     Arguments = Specialization->getTemplateArgs().data();
6980   } else if (const TemplateSpecializationType *TST =
6981                  Ty->getAs<TemplateSpecializationType>()) {
6982     Template = dyn_cast_or_null<ClassTemplateDecl>(
6983         TST->getTemplateName().getAsTemplateDecl());
6984     Arguments = TST->getArgs();
6985   }
6986   if (!Template)
6987     return false;
6988 
6989   if (!StdInitializerList) {
6990     // Haven't recognized std::initializer_list yet, maybe this is it.
6991     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6992     if (TemplateClass->getIdentifier() !=
6993             &PP.getIdentifierTable().get("initializer_list") ||
6994         !getStdNamespace()->InEnclosingNamespaceSetOf(
6995             TemplateClass->getDeclContext()))
6996       return false;
6997     // This is a template called std::initializer_list, but is it the right
6998     // template?
6999     TemplateParameterList *Params = Template->getTemplateParameters();
7000     if (Params->getMinRequiredArguments() != 1)
7001       return false;
7002     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7003       return false;
7004 
7005     // It's the right template.
7006     StdInitializerList = Template;
7007   }
7008 
7009   if (Template != StdInitializerList)
7010     return false;
7011 
7012   // This is an instance of std::initializer_list. Find the argument type.
7013   if (Element)
7014     *Element = Arguments[0].getAsType();
7015   return true;
7016 }
7017 
7018 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7019   NamespaceDecl *Std = S.getStdNamespace();
7020   if (!Std) {
7021     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7022     return nullptr;
7023   }
7024 
7025   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7026                       Loc, Sema::LookupOrdinaryName);
7027   if (!S.LookupQualifiedName(Result, Std)) {
7028     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7029     return nullptr;
7030   }
7031   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7032   if (!Template) {
7033     Result.suppressDiagnostics();
7034     // We found something weird. Complain about the first thing we found.
7035     NamedDecl *Found = *Result.begin();
7036     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7037     return nullptr;
7038   }
7039 
7040   // We found some template called std::initializer_list. Now verify that it's
7041   // correct.
7042   TemplateParameterList *Params = Template->getTemplateParameters();
7043   if (Params->getMinRequiredArguments() != 1 ||
7044       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7045     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7046     return nullptr;
7047   }
7048 
7049   return Template;
7050 }
7051 
7052 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7053   if (!StdInitializerList) {
7054     StdInitializerList = LookupStdInitializerList(*this, Loc);
7055     if (!StdInitializerList)
7056       return QualType();
7057   }
7058 
7059   TemplateArgumentListInfo Args(Loc, Loc);
7060   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7061                                        Context.getTrivialTypeSourceInfo(Element,
7062                                                                         Loc)));
7063   return Context.getCanonicalType(
7064       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7065 }
7066 
7067 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7068   // C++ [dcl.init.list]p2:
7069   //   A constructor is an initializer-list constructor if its first parameter
7070   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7071   //   std::initializer_list<E> for some type E, and either there are no other
7072   //   parameters or else all other parameters have default arguments.
7073   if (Ctor->getNumParams() < 1 ||
7074       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7075     return false;
7076 
7077   QualType ArgType = Ctor->getParamDecl(0)->getType();
7078   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7079     ArgType = RT->getPointeeType().getUnqualifiedType();
7080 
7081   return isStdInitializerList(ArgType, nullptr);
7082 }
7083 
7084 /// \brief Determine whether a using statement is in a context where it will be
7085 /// apply in all contexts.
7086 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7087   switch (CurContext->getDeclKind()) {
7088     case Decl::TranslationUnit:
7089       return true;
7090     case Decl::LinkageSpec:
7091       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7092     default:
7093       return false;
7094   }
7095 }
7096 
7097 namespace {
7098 
7099 // Callback to only accept typo corrections that are namespaces.
7100 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7101 public:
7102   bool ValidateCandidate(const TypoCorrection &candidate) override {
7103     if (NamedDecl *ND = candidate.getCorrectionDecl())
7104       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7105     return false;
7106   }
7107 };
7108 
7109 }
7110 
7111 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7112                                        CXXScopeSpec &SS,
7113                                        SourceLocation IdentLoc,
7114                                        IdentifierInfo *Ident) {
7115   NamespaceValidatorCCC Validator;
7116   R.clear();
7117   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
7118                                                R.getLookupKind(), Sc, &SS,
7119                                                Validator,
7120                                                Sema::CTK_ErrorRecovery)) {
7121     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7122       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7123       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7124                               Ident->getName().equals(CorrectedStr);
7125       S.diagnoseTypo(Corrected,
7126                      S.PDiag(diag::err_using_directive_member_suggest)
7127                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7128                      S.PDiag(diag::note_namespace_defined_here));
7129     } else {
7130       S.diagnoseTypo(Corrected,
7131                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7132                      S.PDiag(diag::note_namespace_defined_here));
7133     }
7134     R.addDecl(Corrected.getCorrectionDecl());
7135     return true;
7136   }
7137   return false;
7138 }
7139 
7140 Decl *Sema::ActOnUsingDirective(Scope *S,
7141                                           SourceLocation UsingLoc,
7142                                           SourceLocation NamespcLoc,
7143                                           CXXScopeSpec &SS,
7144                                           SourceLocation IdentLoc,
7145                                           IdentifierInfo *NamespcName,
7146                                           AttributeList *AttrList) {
7147   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7148   assert(NamespcName && "Invalid NamespcName.");
7149   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7150 
7151   // This can only happen along a recovery path.
7152   while (S->getFlags() & Scope::TemplateParamScope)
7153     S = S->getParent();
7154   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7155 
7156   UsingDirectiveDecl *UDir = nullptr;
7157   NestedNameSpecifier *Qualifier = nullptr;
7158   if (SS.isSet())
7159     Qualifier = SS.getScopeRep();
7160 
7161   // Lookup namespace name.
7162   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7163   LookupParsedName(R, S, &SS);
7164   if (R.isAmbiguous())
7165     return nullptr;
7166 
7167   if (R.empty()) {
7168     R.clear();
7169     // Allow "using namespace std;" or "using namespace ::std;" even if
7170     // "std" hasn't been defined yet, for GCC compatibility.
7171     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7172         NamespcName->isStr("std")) {
7173       Diag(IdentLoc, diag::ext_using_undefined_std);
7174       R.addDecl(getOrCreateStdNamespace());
7175       R.resolveKind();
7176     }
7177     // Otherwise, attempt typo correction.
7178     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7179   }
7180 
7181   if (!R.empty()) {
7182     NamedDecl *Named = R.getFoundDecl();
7183     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7184         && "expected namespace decl");
7185     // C++ [namespace.udir]p1:
7186     //   A using-directive specifies that the names in the nominated
7187     //   namespace can be used in the scope in which the
7188     //   using-directive appears after the using-directive. During
7189     //   unqualified name lookup (3.4.1), the names appear as if they
7190     //   were declared in the nearest enclosing namespace which
7191     //   contains both the using-directive and the nominated
7192     //   namespace. [Note: in this context, "contains" means "contains
7193     //   directly or indirectly". ]
7194 
7195     // Find enclosing context containing both using-directive and
7196     // nominated namespace.
7197     NamespaceDecl *NS = getNamespaceDecl(Named);
7198     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7199     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7200       CommonAncestor = CommonAncestor->getParent();
7201 
7202     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7203                                       SS.getWithLocInContext(Context),
7204                                       IdentLoc, Named, CommonAncestor);
7205 
7206     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7207         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7208       Diag(IdentLoc, diag::warn_using_directive_in_header);
7209     }
7210 
7211     PushUsingDirective(S, UDir);
7212   } else {
7213     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7214   }
7215 
7216   if (UDir)
7217     ProcessDeclAttributeList(S, UDir, AttrList);
7218 
7219   return UDir;
7220 }
7221 
7222 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7223   // If the scope has an associated entity and the using directive is at
7224   // namespace or translation unit scope, add the UsingDirectiveDecl into
7225   // its lookup structure so qualified name lookup can find it.
7226   DeclContext *Ctx = S->getEntity();
7227   if (Ctx && !Ctx->isFunctionOrMethod())
7228     Ctx->addDecl(UDir);
7229   else
7230     // Otherwise, it is at block scope. The using-directives will affect lookup
7231     // only to the end of the scope.
7232     S->PushUsingDirective(UDir);
7233 }
7234 
7235 
7236 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7237                                   AccessSpecifier AS,
7238                                   bool HasUsingKeyword,
7239                                   SourceLocation UsingLoc,
7240                                   CXXScopeSpec &SS,
7241                                   UnqualifiedId &Name,
7242                                   AttributeList *AttrList,
7243                                   bool HasTypenameKeyword,
7244                                   SourceLocation TypenameLoc) {
7245   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7246 
7247   switch (Name.getKind()) {
7248   case UnqualifiedId::IK_ImplicitSelfParam:
7249   case UnqualifiedId::IK_Identifier:
7250   case UnqualifiedId::IK_OperatorFunctionId:
7251   case UnqualifiedId::IK_LiteralOperatorId:
7252   case UnqualifiedId::IK_ConversionFunctionId:
7253     break;
7254 
7255   case UnqualifiedId::IK_ConstructorName:
7256   case UnqualifiedId::IK_ConstructorTemplateId:
7257     // C++11 inheriting constructors.
7258     Diag(Name.getLocStart(),
7259          getLangOpts().CPlusPlus11 ?
7260            diag::warn_cxx98_compat_using_decl_constructor :
7261            diag::err_using_decl_constructor)
7262       << SS.getRange();
7263 
7264     if (getLangOpts().CPlusPlus11) break;
7265 
7266     return nullptr;
7267 
7268   case UnqualifiedId::IK_DestructorName:
7269     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7270       << SS.getRange();
7271     return nullptr;
7272 
7273   case UnqualifiedId::IK_TemplateId:
7274     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7275       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7276     return nullptr;
7277   }
7278 
7279   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7280   DeclarationName TargetName = TargetNameInfo.getName();
7281   if (!TargetName)
7282     return nullptr;
7283 
7284   // Warn about access declarations.
7285   if (!HasUsingKeyword) {
7286     Diag(Name.getLocStart(),
7287          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7288                                    : diag::warn_access_decl_deprecated)
7289       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7290   }
7291 
7292   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7293       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7294     return nullptr;
7295 
7296   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7297                                         TargetNameInfo, AttrList,
7298                                         /* IsInstantiation */ false,
7299                                         HasTypenameKeyword, TypenameLoc);
7300   if (UD)
7301     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7302 
7303   return UD;
7304 }
7305 
7306 /// \brief Determine whether a using declaration considers the given
7307 /// declarations as "equivalent", e.g., if they are redeclarations of
7308 /// the same entity or are both typedefs of the same type.
7309 static bool
7310 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7311   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7312     return true;
7313 
7314   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7315     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7316       return Context.hasSameType(TD1->getUnderlyingType(),
7317                                  TD2->getUnderlyingType());
7318 
7319   return false;
7320 }
7321 
7322 
7323 /// Determines whether to create a using shadow decl for a particular
7324 /// decl, given the set of decls existing prior to this using lookup.
7325 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7326                                 const LookupResult &Previous,
7327                                 UsingShadowDecl *&PrevShadow) {
7328   // Diagnose finding a decl which is not from a base class of the
7329   // current class.  We do this now because there are cases where this
7330   // function will silently decide not to build a shadow decl, which
7331   // will pre-empt further diagnostics.
7332   //
7333   // We don't need to do this in C++0x because we do the check once on
7334   // the qualifier.
7335   //
7336   // FIXME: diagnose the following if we care enough:
7337   //   struct A { int foo; };
7338   //   struct B : A { using A::foo; };
7339   //   template <class T> struct C : A {};
7340   //   template <class T> struct D : C<T> { using B::foo; } // <---
7341   // This is invalid (during instantiation) in C++03 because B::foo
7342   // resolves to the using decl in B, which is not a base class of D<T>.
7343   // We can't diagnose it immediately because C<T> is an unknown
7344   // specialization.  The UsingShadowDecl in D<T> then points directly
7345   // to A::foo, which will look well-formed when we instantiate.
7346   // The right solution is to not collapse the shadow-decl chain.
7347   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7348     DeclContext *OrigDC = Orig->getDeclContext();
7349 
7350     // Handle enums and anonymous structs.
7351     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7352     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7353     while (OrigRec->isAnonymousStructOrUnion())
7354       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7355 
7356     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7357       if (OrigDC == CurContext) {
7358         Diag(Using->getLocation(),
7359              diag::err_using_decl_nested_name_specifier_is_current_class)
7360           << Using->getQualifierLoc().getSourceRange();
7361         Diag(Orig->getLocation(), diag::note_using_decl_target);
7362         return true;
7363       }
7364 
7365       Diag(Using->getQualifierLoc().getBeginLoc(),
7366            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7367         << Using->getQualifier()
7368         << cast<CXXRecordDecl>(CurContext)
7369         << Using->getQualifierLoc().getSourceRange();
7370       Diag(Orig->getLocation(), diag::note_using_decl_target);
7371       return true;
7372     }
7373   }
7374 
7375   if (Previous.empty()) return false;
7376 
7377   NamedDecl *Target = Orig;
7378   if (isa<UsingShadowDecl>(Target))
7379     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7380 
7381   // If the target happens to be one of the previous declarations, we
7382   // don't have a conflict.
7383   //
7384   // FIXME: but we might be increasing its access, in which case we
7385   // should redeclare it.
7386   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7387   bool FoundEquivalentDecl = false;
7388   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7389          I != E; ++I) {
7390     NamedDecl *D = (*I)->getUnderlyingDecl();
7391     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7392       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7393         PrevShadow = Shadow;
7394       FoundEquivalentDecl = true;
7395     }
7396 
7397     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7398   }
7399 
7400   if (FoundEquivalentDecl)
7401     return false;
7402 
7403   if (FunctionDecl *FD = Target->getAsFunction()) {
7404     NamedDecl *OldDecl = nullptr;
7405     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7406                           /*IsForUsingDecl*/ true)) {
7407     case Ovl_Overload:
7408       return false;
7409 
7410     case Ovl_NonFunction:
7411       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7412       break;
7413 
7414     // We found a decl with the exact signature.
7415     case Ovl_Match:
7416       // If we're in a record, we want to hide the target, so we
7417       // return true (without a diagnostic) to tell the caller not to
7418       // build a shadow decl.
7419       if (CurContext->isRecord())
7420         return true;
7421 
7422       // If we're not in a record, this is an error.
7423       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7424       break;
7425     }
7426 
7427     Diag(Target->getLocation(), diag::note_using_decl_target);
7428     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7429     return true;
7430   }
7431 
7432   // Target is not a function.
7433 
7434   if (isa<TagDecl>(Target)) {
7435     // No conflict between a tag and a non-tag.
7436     if (!Tag) return false;
7437 
7438     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7439     Diag(Target->getLocation(), diag::note_using_decl_target);
7440     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7441     return true;
7442   }
7443 
7444   // No conflict between a tag and a non-tag.
7445   if (!NonTag) return false;
7446 
7447   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7448   Diag(Target->getLocation(), diag::note_using_decl_target);
7449   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7450   return true;
7451 }
7452 
7453 /// Builds a shadow declaration corresponding to a 'using' declaration.
7454 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7455                                             UsingDecl *UD,
7456                                             NamedDecl *Orig,
7457                                             UsingShadowDecl *PrevDecl) {
7458 
7459   // If we resolved to another shadow declaration, just coalesce them.
7460   NamedDecl *Target = Orig;
7461   if (isa<UsingShadowDecl>(Target)) {
7462     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7463     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7464   }
7465 
7466   UsingShadowDecl *Shadow
7467     = UsingShadowDecl::Create(Context, CurContext,
7468                               UD->getLocation(), UD, Target);
7469   UD->addShadowDecl(Shadow);
7470 
7471   Shadow->setAccess(UD->getAccess());
7472   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7473     Shadow->setInvalidDecl();
7474 
7475   Shadow->setPreviousDecl(PrevDecl);
7476 
7477   if (S)
7478     PushOnScopeChains(Shadow, S);
7479   else
7480     CurContext->addDecl(Shadow);
7481 
7482 
7483   return Shadow;
7484 }
7485 
7486 /// Hides a using shadow declaration.  This is required by the current
7487 /// using-decl implementation when a resolvable using declaration in a
7488 /// class is followed by a declaration which would hide or override
7489 /// one or more of the using decl's targets; for example:
7490 ///
7491 ///   struct Base { void foo(int); };
7492 ///   struct Derived : Base {
7493 ///     using Base::foo;
7494 ///     void foo(int);
7495 ///   };
7496 ///
7497 /// The governing language is C++03 [namespace.udecl]p12:
7498 ///
7499 ///   When a using-declaration brings names from a base class into a
7500 ///   derived class scope, member functions in the derived class
7501 ///   override and/or hide member functions with the same name and
7502 ///   parameter types in a base class (rather than conflicting).
7503 ///
7504 /// There are two ways to implement this:
7505 ///   (1) optimistically create shadow decls when they're not hidden
7506 ///       by existing declarations, or
7507 ///   (2) don't create any shadow decls (or at least don't make them
7508 ///       visible) until we've fully parsed/instantiated the class.
7509 /// The problem with (1) is that we might have to retroactively remove
7510 /// a shadow decl, which requires several O(n) operations because the
7511 /// decl structures are (very reasonably) not designed for removal.
7512 /// (2) avoids this but is very fiddly and phase-dependent.
7513 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7514   if (Shadow->getDeclName().getNameKind() ==
7515         DeclarationName::CXXConversionFunctionName)
7516     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7517 
7518   // Remove it from the DeclContext...
7519   Shadow->getDeclContext()->removeDecl(Shadow);
7520 
7521   // ...and the scope, if applicable...
7522   if (S) {
7523     S->RemoveDecl(Shadow);
7524     IdResolver.RemoveDecl(Shadow);
7525   }
7526 
7527   // ...and the using decl.
7528   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7529 
7530   // TODO: complain somehow if Shadow was used.  It shouldn't
7531   // be possible for this to happen, because...?
7532 }
7533 
7534 /// Find the base specifier for a base class with the given type.
7535 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7536                                                 QualType DesiredBase,
7537                                                 bool &AnyDependentBases) {
7538   // Check whether the named type is a direct base class.
7539   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7540   for (auto &Base : Derived->bases()) {
7541     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7542     if (CanonicalDesiredBase == BaseType)
7543       return &Base;
7544     if (BaseType->isDependentType())
7545       AnyDependentBases = true;
7546   }
7547   return nullptr;
7548 }
7549 
7550 namespace {
7551 class UsingValidatorCCC : public CorrectionCandidateCallback {
7552 public:
7553   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7554                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7555       : HasTypenameKeyword(HasTypenameKeyword),
7556         IsInstantiation(IsInstantiation), OldNNS(NNS),
7557         RequireMemberOf(RequireMemberOf) {}
7558 
7559   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7560     NamedDecl *ND = Candidate.getCorrectionDecl();
7561 
7562     // Keywords are not valid here.
7563     if (!ND || isa<NamespaceDecl>(ND))
7564       return false;
7565 
7566     // Completely unqualified names are invalid for a 'using' declaration.
7567     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7568       return false;
7569 
7570     if (RequireMemberOf) {
7571       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7572       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7573         // No-one ever wants a using-declaration to name an injected-class-name
7574         // of a base class, unless they're declaring an inheriting constructor.
7575         ASTContext &Ctx = ND->getASTContext();
7576         if (!Ctx.getLangOpts().CPlusPlus11)
7577           return false;
7578         QualType FoundType = Ctx.getRecordType(FoundRecord);
7579 
7580         // Check that the injected-class-name is named as a member of its own
7581         // type; we don't want to suggest 'using Derived::Base;', since that
7582         // means something else.
7583         NestedNameSpecifier *Specifier =
7584             Candidate.WillReplaceSpecifier()
7585                 ? Candidate.getCorrectionSpecifier()
7586                 : OldNNS;
7587         if (!Specifier->getAsType() ||
7588             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7589           return false;
7590 
7591         // Check that this inheriting constructor declaration actually names a
7592         // direct base class of the current class.
7593         bool AnyDependentBases = false;
7594         if (!findDirectBaseWithType(RequireMemberOf,
7595                                     Ctx.getRecordType(FoundRecord),
7596                                     AnyDependentBases) &&
7597             !AnyDependentBases)
7598           return false;
7599       } else {
7600         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7601         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7602           return false;
7603 
7604         // FIXME: Check that the base class member is accessible?
7605       }
7606     }
7607 
7608     if (isa<TypeDecl>(ND))
7609       return HasTypenameKeyword || !IsInstantiation;
7610 
7611     return !HasTypenameKeyword;
7612   }
7613 
7614 private:
7615   bool HasTypenameKeyword;
7616   bool IsInstantiation;
7617   NestedNameSpecifier *OldNNS;
7618   CXXRecordDecl *RequireMemberOf;
7619 };
7620 } // end anonymous namespace
7621 
7622 /// Builds a using declaration.
7623 ///
7624 /// \param IsInstantiation - Whether this call arises from an
7625 ///   instantiation of an unresolved using declaration.  We treat
7626 ///   the lookup differently for these declarations.
7627 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7628                                        SourceLocation UsingLoc,
7629                                        CXXScopeSpec &SS,
7630                                        DeclarationNameInfo NameInfo,
7631                                        AttributeList *AttrList,
7632                                        bool IsInstantiation,
7633                                        bool HasTypenameKeyword,
7634                                        SourceLocation TypenameLoc) {
7635   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7636   SourceLocation IdentLoc = NameInfo.getLoc();
7637   assert(IdentLoc.isValid() && "Invalid TargetName location.");
7638 
7639   // FIXME: We ignore attributes for now.
7640 
7641   if (SS.isEmpty()) {
7642     Diag(IdentLoc, diag::err_using_requires_qualname);
7643     return nullptr;
7644   }
7645 
7646   // Do the redeclaration lookup in the current scope.
7647   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7648                         ForRedeclaration);
7649   Previous.setHideTags(false);
7650   if (S) {
7651     LookupName(Previous, S);
7652 
7653     // It is really dumb that we have to do this.
7654     LookupResult::Filter F = Previous.makeFilter();
7655     while (F.hasNext()) {
7656       NamedDecl *D = F.next();
7657       if (!isDeclInScope(D, CurContext, S))
7658         F.erase();
7659       // If we found a local extern declaration that's not ordinarily visible,
7660       // and this declaration is being added to a non-block scope, ignore it.
7661       // We're only checking for scope conflicts here, not also for violations
7662       // of the linkage rules.
7663       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7664                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7665         F.erase();
7666     }
7667     F.done();
7668   } else {
7669     assert(IsInstantiation && "no scope in non-instantiation");
7670     assert(CurContext->isRecord() && "scope not record in instantiation");
7671     LookupQualifiedName(Previous, CurContext);
7672   }
7673 
7674   // Check for invalid redeclarations.
7675   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7676                                   SS, IdentLoc, Previous))
7677     return nullptr;
7678 
7679   // Check for bad qualifiers.
7680   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
7681     return nullptr;
7682 
7683   DeclContext *LookupContext = computeDeclContext(SS);
7684   NamedDecl *D;
7685   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7686   if (!LookupContext) {
7687     if (HasTypenameKeyword) {
7688       // FIXME: not all declaration name kinds are legal here
7689       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7690                                               UsingLoc, TypenameLoc,
7691                                               QualifierLoc,
7692                                               IdentLoc, NameInfo.getName());
7693     } else {
7694       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7695                                            QualifierLoc, NameInfo);
7696     }
7697     D->setAccess(AS);
7698     CurContext->addDecl(D);
7699     return D;
7700   }
7701 
7702   auto Build = [&](bool Invalid) {
7703     UsingDecl *UD =
7704         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7705                           HasTypenameKeyword);
7706     UD->setAccess(AS);
7707     CurContext->addDecl(UD);
7708     UD->setInvalidDecl(Invalid);
7709     return UD;
7710   };
7711   auto BuildInvalid = [&]{ return Build(true); };
7712   auto BuildValid = [&]{ return Build(false); };
7713 
7714   if (RequireCompleteDeclContext(SS, LookupContext))
7715     return BuildInvalid();
7716 
7717   // The normal rules do not apply to inheriting constructor declarations.
7718   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7719     UsingDecl *UD = BuildValid();
7720     CheckInheritingConstructorUsingDecl(UD);
7721     return UD;
7722   }
7723 
7724   // Otherwise, look up the target name.
7725 
7726   LookupResult R(*this, NameInfo, LookupOrdinaryName);
7727 
7728   // Unlike most lookups, we don't always want to hide tag
7729   // declarations: tag names are visible through the using declaration
7730   // even if hidden by ordinary names, *except* in a dependent context
7731   // where it's important for the sanity of two-phase lookup.
7732   if (!IsInstantiation)
7733     R.setHideTags(false);
7734 
7735   // For the purposes of this lookup, we have a base object type
7736   // equal to that of the current context.
7737   if (CurContext->isRecord()) {
7738     R.setBaseObjectType(
7739                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7740   }
7741 
7742   LookupQualifiedName(R, LookupContext);
7743 
7744   // Try to correct typos if possible.
7745   if (R.empty()) {
7746     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
7747                           dyn_cast<CXXRecordDecl>(CurContext));
7748     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7749                                                R.getLookupKind(), S, &SS, CCC,
7750                                                CTK_ErrorRecovery)){
7751       // We reject any correction for which ND would be NULL.
7752       NamedDecl *ND = Corrected.getCorrectionDecl();
7753 
7754       // We reject candidates where DroppedSpecifier == true, hence the
7755       // literal '0' below.
7756       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7757                                 << NameInfo.getName() << LookupContext << 0
7758                                 << SS.getRange());
7759 
7760       // If we corrected to an inheriting constructor, handle it as one.
7761       auto *RD = dyn_cast<CXXRecordDecl>(ND);
7762       if (RD && RD->isInjectedClassName()) {
7763         // Fix up the information we'll use to build the using declaration.
7764         if (Corrected.WillReplaceSpecifier()) {
7765           NestedNameSpecifierLocBuilder Builder;
7766           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7767                               QualifierLoc.getSourceRange());
7768           QualifierLoc = Builder.getWithLocInContext(Context);
7769         }
7770 
7771         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7772             Context.getCanonicalType(Context.getRecordType(RD))));
7773         NameInfo.setNamedTypeInfo(nullptr);
7774 
7775         // Build it and process it as an inheriting constructor.
7776         UsingDecl *UD = BuildValid();
7777         CheckInheritingConstructorUsingDecl(UD);
7778         return UD;
7779       }
7780 
7781       // FIXME: Pick up all the declarations if we found an overloaded function.
7782       R.setLookupName(Corrected.getCorrection());
7783       R.addDecl(ND);
7784     } else {
7785       Diag(IdentLoc, diag::err_no_member)
7786         << NameInfo.getName() << LookupContext << SS.getRange();
7787       return BuildInvalid();
7788     }
7789   }
7790 
7791   if (R.isAmbiguous())
7792     return BuildInvalid();
7793 
7794   if (HasTypenameKeyword) {
7795     // If we asked for a typename and got a non-type decl, error out.
7796     if (!R.getAsSingle<TypeDecl>()) {
7797       Diag(IdentLoc, diag::err_using_typename_non_type);
7798       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7799         Diag((*I)->getUnderlyingDecl()->getLocation(),
7800              diag::note_using_decl_target);
7801       return BuildInvalid();
7802     }
7803   } else {
7804     // If we asked for a non-typename and we got a type, error out,
7805     // but only if this is an instantiation of an unresolved using
7806     // decl.  Otherwise just silently find the type name.
7807     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7808       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7809       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7810       return BuildInvalid();
7811     }
7812   }
7813 
7814   // C++0x N2914 [namespace.udecl]p6:
7815   // A using-declaration shall not name a namespace.
7816   if (R.getAsSingle<NamespaceDecl>()) {
7817     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7818       << SS.getRange();
7819     return BuildInvalid();
7820   }
7821 
7822   UsingDecl *UD = BuildValid();
7823   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7824     UsingShadowDecl *PrevDecl = nullptr;
7825     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7826       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7827   }
7828 
7829   return UD;
7830 }
7831 
7832 /// Additional checks for a using declaration referring to a constructor name.
7833 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7834   assert(!UD->hasTypename() && "expecting a constructor name");
7835 
7836   const Type *SourceType = UD->getQualifier()->getAsType();
7837   assert(SourceType &&
7838          "Using decl naming constructor doesn't have type in scope spec.");
7839   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7840 
7841   // Check whether the named type is a direct base class.
7842   bool AnyDependentBases = false;
7843   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7844                                       AnyDependentBases);
7845   if (!Base && !AnyDependentBases) {
7846     Diag(UD->getUsingLoc(),
7847          diag::err_using_decl_constructor_not_in_direct_base)
7848       << UD->getNameInfo().getSourceRange()
7849       << QualType(SourceType, 0) << TargetClass;
7850     UD->setInvalidDecl();
7851     return true;
7852   }
7853 
7854   if (Base)
7855     Base->setInheritConstructors();
7856 
7857   return false;
7858 }
7859 
7860 /// Checks that the given using declaration is not an invalid
7861 /// redeclaration.  Note that this is checking only for the using decl
7862 /// itself, not for any ill-formedness among the UsingShadowDecls.
7863 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7864                                        bool HasTypenameKeyword,
7865                                        const CXXScopeSpec &SS,
7866                                        SourceLocation NameLoc,
7867                                        const LookupResult &Prev) {
7868   // C++03 [namespace.udecl]p8:
7869   // C++0x [namespace.udecl]p10:
7870   //   A using-declaration is a declaration and can therefore be used
7871   //   repeatedly where (and only where) multiple declarations are
7872   //   allowed.
7873   //
7874   // That's in non-member contexts.
7875   if (!CurContext->getRedeclContext()->isRecord())
7876     return false;
7877 
7878   NestedNameSpecifier *Qual = SS.getScopeRep();
7879 
7880   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7881     NamedDecl *D = *I;
7882 
7883     bool DTypename;
7884     NestedNameSpecifier *DQual;
7885     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7886       DTypename = UD->hasTypename();
7887       DQual = UD->getQualifier();
7888     } else if (UnresolvedUsingValueDecl *UD
7889                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7890       DTypename = false;
7891       DQual = UD->getQualifier();
7892     } else if (UnresolvedUsingTypenameDecl *UD
7893                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7894       DTypename = true;
7895       DQual = UD->getQualifier();
7896     } else continue;
7897 
7898     // using decls differ if one says 'typename' and the other doesn't.
7899     // FIXME: non-dependent using decls?
7900     if (HasTypenameKeyword != DTypename) continue;
7901 
7902     // using decls differ if they name different scopes (but note that
7903     // template instantiation can cause this check to trigger when it
7904     // didn't before instantiation).
7905     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7906         Context.getCanonicalNestedNameSpecifier(DQual))
7907       continue;
7908 
7909     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7910     Diag(D->getLocation(), diag::note_using_decl) << 1;
7911     return true;
7912   }
7913 
7914   return false;
7915 }
7916 
7917 
7918 /// Checks that the given nested-name qualifier used in a using decl
7919 /// in the current context is appropriately related to the current
7920 /// scope.  If an error is found, diagnoses it and returns true.
7921 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7922                                    const CXXScopeSpec &SS,
7923                                    const DeclarationNameInfo &NameInfo,
7924                                    SourceLocation NameLoc) {
7925   DeclContext *NamedContext = computeDeclContext(SS);
7926 
7927   if (!CurContext->isRecord()) {
7928     // C++03 [namespace.udecl]p3:
7929     // C++0x [namespace.udecl]p8:
7930     //   A using-declaration for a class member shall be a member-declaration.
7931 
7932     // If we weren't able to compute a valid scope, it must be a
7933     // dependent class scope.
7934     if (!NamedContext || NamedContext->isRecord()) {
7935       auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7936       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
7937         RD = nullptr;
7938 
7939       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7940         << SS.getRange();
7941 
7942       // If we have a complete, non-dependent source type, try to suggest a
7943       // way to get the same effect.
7944       if (!RD)
7945         return true;
7946 
7947       // Find what this using-declaration was referring to.
7948       LookupResult R(*this, NameInfo, LookupOrdinaryName);
7949       R.setHideTags(false);
7950       R.suppressDiagnostics();
7951       LookupQualifiedName(R, RD);
7952 
7953       if (R.getAsSingle<TypeDecl>()) {
7954         if (getLangOpts().CPlusPlus11) {
7955           // Convert 'using X::Y;' to 'using Y = X::Y;'.
7956           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7957             << 0 // alias declaration
7958             << FixItHint::CreateInsertion(SS.getBeginLoc(),
7959                                           NameInfo.getName().getAsString() +
7960                                               " = ");
7961         } else {
7962           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7963           SourceLocation InsertLoc =
7964               PP.getLocForEndOfToken(NameInfo.getLocEnd());
7965           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7966             << 1 // typedef declaration
7967             << FixItHint::CreateReplacement(UsingLoc, "typedef")
7968             << FixItHint::CreateInsertion(
7969                    InsertLoc, " " + NameInfo.getName().getAsString());
7970         }
7971       } else if (R.getAsSingle<VarDecl>()) {
7972         // Don't provide a fixit outside C++11 mode; we don't want to suggest
7973         // repeating the type of the static data member here.
7974         FixItHint FixIt;
7975         if (getLangOpts().CPlusPlus11) {
7976           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7977           FixIt = FixItHint::CreateReplacement(
7978               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7979         }
7980 
7981         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7982           << 2 // reference declaration
7983           << FixIt;
7984       }
7985       return true;
7986     }
7987 
7988     // Otherwise, everything is known to be fine.
7989     return false;
7990   }
7991 
7992   // The current scope is a record.
7993 
7994   // If the named context is dependent, we can't decide much.
7995   if (!NamedContext) {
7996     // FIXME: in C++0x, we can diagnose if we can prove that the
7997     // nested-name-specifier does not refer to a base class, which is
7998     // still possible in some cases.
7999 
8000     // Otherwise we have to conservatively report that things might be
8001     // okay.
8002     return false;
8003   }
8004 
8005   if (!NamedContext->isRecord()) {
8006     // Ideally this would point at the last name in the specifier,
8007     // but we don't have that level of source info.
8008     Diag(SS.getRange().getBegin(),
8009          diag::err_using_decl_nested_name_specifier_is_not_class)
8010       << SS.getScopeRep() << SS.getRange();
8011     return true;
8012   }
8013 
8014   if (!NamedContext->isDependentContext() &&
8015       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8016     return true;
8017 
8018   if (getLangOpts().CPlusPlus11) {
8019     // C++0x [namespace.udecl]p3:
8020     //   In a using-declaration used as a member-declaration, the
8021     //   nested-name-specifier shall name a base class of the class
8022     //   being defined.
8023 
8024     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8025                                  cast<CXXRecordDecl>(NamedContext))) {
8026       if (CurContext == NamedContext) {
8027         Diag(NameLoc,
8028              diag::err_using_decl_nested_name_specifier_is_current_class)
8029           << SS.getRange();
8030         return true;
8031       }
8032 
8033       Diag(SS.getRange().getBegin(),
8034            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8035         << SS.getScopeRep()
8036         << cast<CXXRecordDecl>(CurContext)
8037         << SS.getRange();
8038       return true;
8039     }
8040 
8041     return false;
8042   }
8043 
8044   // C++03 [namespace.udecl]p4:
8045   //   A using-declaration used as a member-declaration shall refer
8046   //   to a member of a base class of the class being defined [etc.].
8047 
8048   // Salient point: SS doesn't have to name a base class as long as
8049   // lookup only finds members from base classes.  Therefore we can
8050   // diagnose here only if we can prove that that can't happen,
8051   // i.e. if the class hierarchies provably don't intersect.
8052 
8053   // TODO: it would be nice if "definitely valid" results were cached
8054   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8055   // need to be repeated.
8056 
8057   struct UserData {
8058     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8059 
8060     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8061       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8062       Data->Bases.insert(Base);
8063       return true;
8064     }
8065 
8066     bool hasDependentBases(const CXXRecordDecl *Class) {
8067       return !Class->forallBases(collect, this);
8068     }
8069 
8070     /// Returns true if the base is dependent or is one of the
8071     /// accumulated base classes.
8072     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8073       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8074       return !Data->Bases.count(Base);
8075     }
8076 
8077     bool mightShareBases(const CXXRecordDecl *Class) {
8078       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8079     }
8080   };
8081 
8082   UserData Data;
8083 
8084   // Returns false if we find a dependent base.
8085   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8086     return false;
8087 
8088   // Returns false if the class has a dependent base or if it or one
8089   // of its bases is present in the base set of the current context.
8090   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8091     return false;
8092 
8093   Diag(SS.getRange().getBegin(),
8094        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8095     << SS.getScopeRep()
8096     << cast<CXXRecordDecl>(CurContext)
8097     << SS.getRange();
8098 
8099   return true;
8100 }
8101 
8102 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8103                                   AccessSpecifier AS,
8104                                   MultiTemplateParamsArg TemplateParamLists,
8105                                   SourceLocation UsingLoc,
8106                                   UnqualifiedId &Name,
8107                                   AttributeList *AttrList,
8108                                   TypeResult Type) {
8109   // Skip up to the relevant declaration scope.
8110   while (S->getFlags() & Scope::TemplateParamScope)
8111     S = S->getParent();
8112   assert((S->getFlags() & Scope::DeclScope) &&
8113          "got alias-declaration outside of declaration scope");
8114 
8115   if (Type.isInvalid())
8116     return nullptr;
8117 
8118   bool Invalid = false;
8119   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8120   TypeSourceInfo *TInfo = nullptr;
8121   GetTypeFromParser(Type.get(), &TInfo);
8122 
8123   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8124     return nullptr;
8125 
8126   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8127                                       UPPC_DeclarationType)) {
8128     Invalid = true;
8129     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8130                                              TInfo->getTypeLoc().getBeginLoc());
8131   }
8132 
8133   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8134   LookupName(Previous, S);
8135 
8136   // Warn about shadowing the name of a template parameter.
8137   if (Previous.isSingleResult() &&
8138       Previous.getFoundDecl()->isTemplateParameter()) {
8139     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8140     Previous.clear();
8141   }
8142 
8143   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8144          "name in alias declaration must be an identifier");
8145   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8146                                                Name.StartLocation,
8147                                                Name.Identifier, TInfo);
8148 
8149   NewTD->setAccess(AS);
8150 
8151   if (Invalid)
8152     NewTD->setInvalidDecl();
8153 
8154   ProcessDeclAttributeList(S, NewTD, AttrList);
8155 
8156   CheckTypedefForVariablyModifiedType(S, NewTD);
8157   Invalid |= NewTD->isInvalidDecl();
8158 
8159   bool Redeclaration = false;
8160 
8161   NamedDecl *NewND;
8162   if (TemplateParamLists.size()) {
8163     TypeAliasTemplateDecl *OldDecl = nullptr;
8164     TemplateParameterList *OldTemplateParams = nullptr;
8165 
8166     if (TemplateParamLists.size() != 1) {
8167       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8168         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8169          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8170     }
8171     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8172 
8173     // Only consider previous declarations in the same scope.
8174     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8175                          /*ExplicitInstantiationOrSpecialization*/false);
8176     if (!Previous.empty()) {
8177       Redeclaration = true;
8178 
8179       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8180       if (!OldDecl && !Invalid) {
8181         Diag(UsingLoc, diag::err_redefinition_different_kind)
8182           << Name.Identifier;
8183 
8184         NamedDecl *OldD = Previous.getRepresentativeDecl();
8185         if (OldD->getLocation().isValid())
8186           Diag(OldD->getLocation(), diag::note_previous_definition);
8187 
8188         Invalid = true;
8189       }
8190 
8191       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8192         if (TemplateParameterListsAreEqual(TemplateParams,
8193                                            OldDecl->getTemplateParameters(),
8194                                            /*Complain=*/true,
8195                                            TPL_TemplateMatch))
8196           OldTemplateParams = OldDecl->getTemplateParameters();
8197         else
8198           Invalid = true;
8199 
8200         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8201         if (!Invalid &&
8202             !Context.hasSameType(OldTD->getUnderlyingType(),
8203                                  NewTD->getUnderlyingType())) {
8204           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8205           // but we can't reasonably accept it.
8206           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8207             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8208           if (OldTD->getLocation().isValid())
8209             Diag(OldTD->getLocation(), diag::note_previous_definition);
8210           Invalid = true;
8211         }
8212       }
8213     }
8214 
8215     // Merge any previous default template arguments into our parameters,
8216     // and check the parameter list.
8217     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8218                                    TPC_TypeAliasTemplate))
8219       return nullptr;
8220 
8221     TypeAliasTemplateDecl *NewDecl =
8222       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8223                                     Name.Identifier, TemplateParams,
8224                                     NewTD);
8225     NewTD->setDescribedAliasTemplate(NewDecl);
8226 
8227     NewDecl->setAccess(AS);
8228 
8229     if (Invalid)
8230       NewDecl->setInvalidDecl();
8231     else if (OldDecl)
8232       NewDecl->setPreviousDecl(OldDecl);
8233 
8234     NewND = NewDecl;
8235   } else {
8236     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8237     NewND = NewTD;
8238   }
8239 
8240   if (!Redeclaration)
8241     PushOnScopeChains(NewND, S);
8242 
8243   ActOnDocumentableDecl(NewND);
8244   return NewND;
8245 }
8246 
8247 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
8248                                              SourceLocation NamespaceLoc,
8249                                              SourceLocation AliasLoc,
8250                                              IdentifierInfo *Alias,
8251                                              CXXScopeSpec &SS,
8252                                              SourceLocation IdentLoc,
8253                                              IdentifierInfo *Ident) {
8254 
8255   // Lookup the namespace name.
8256   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8257   LookupParsedName(R, S, &SS);
8258 
8259   // Check if we have a previous declaration with the same name.
8260   NamedDecl *PrevDecl
8261     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8262                        ForRedeclaration);
8263   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8264     PrevDecl = nullptr;
8265 
8266   if (PrevDecl) {
8267     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8268       // We already have an alias with the same name that points to the same
8269       // namespace, so don't create a new one.
8270       // FIXME: At some point, we'll want to create the (redundant)
8271       // declaration to maintain better source information.
8272       if (!R.isAmbiguous() && !R.empty() &&
8273           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
8274         return nullptr;
8275     }
8276 
8277     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8278       diag::err_redefinition_different_kind;
8279     Diag(AliasLoc, DiagID) << Alias;
8280     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8281     return nullptr;
8282   }
8283 
8284   if (R.isAmbiguous())
8285     return nullptr;
8286 
8287   if (R.empty()) {
8288     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8289       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8290       return nullptr;
8291     }
8292   }
8293 
8294   NamespaceAliasDecl *AliasDecl =
8295     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8296                                Alias, SS.getWithLocInContext(Context),
8297                                IdentLoc, R.getFoundDecl());
8298 
8299   PushOnScopeChains(AliasDecl, S);
8300   return AliasDecl;
8301 }
8302 
8303 Sema::ImplicitExceptionSpecification
8304 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8305                                                CXXMethodDecl *MD) {
8306   CXXRecordDecl *ClassDecl = MD->getParent();
8307 
8308   // C++ [except.spec]p14:
8309   //   An implicitly declared special member function (Clause 12) shall have an
8310   //   exception-specification. [...]
8311   ImplicitExceptionSpecification ExceptSpec(*this);
8312   if (ClassDecl->isInvalidDecl())
8313     return ExceptSpec;
8314 
8315   // Direct base-class constructors.
8316   for (const auto &B : ClassDecl->bases()) {
8317     if (B.isVirtual()) // Handled below.
8318       continue;
8319 
8320     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8321       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8322       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8323       // If this is a deleted function, add it anyway. This might be conformant
8324       // with the standard. This might not. I'm not sure. It might not matter.
8325       if (Constructor)
8326         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8327     }
8328   }
8329 
8330   // Virtual base-class constructors.
8331   for (const auto &B : ClassDecl->vbases()) {
8332     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8333       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8334       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8335       // If this is a deleted function, add it anyway. This might be conformant
8336       // with the standard. This might not. I'm not sure. It might not matter.
8337       if (Constructor)
8338         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8339     }
8340   }
8341 
8342   // Field constructors.
8343   for (const auto *F : ClassDecl->fields()) {
8344     if (F->hasInClassInitializer()) {
8345       if (Expr *E = F->getInClassInitializer())
8346         ExceptSpec.CalledExpr(E);
8347       else if (!F->isInvalidDecl())
8348         // DR1351:
8349         //   If the brace-or-equal-initializer of a non-static data member
8350         //   invokes a defaulted default constructor of its class or of an
8351         //   enclosing class in a potentially evaluated subexpression, the
8352         //   program is ill-formed.
8353         //
8354         // This resolution is unworkable: the exception specification of the
8355         // default constructor can be needed in an unevaluated context, in
8356         // particular, in the operand of a noexcept-expression, and we can be
8357         // unable to compute an exception specification for an enclosed class.
8358         //
8359         // We do not allow an in-class initializer to require the evaluation
8360         // of the exception specification for any in-class initializer whose
8361         // definition is not lexically complete.
8362         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
8363     } else if (const RecordType *RecordTy
8364               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8365       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8366       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8367       // If this is a deleted function, add it anyway. This might be conformant
8368       // with the standard. This might not. I'm not sure. It might not matter.
8369       // In particular, the problem is that this function never gets called. It
8370       // might just be ill-formed because this function attempts to refer to
8371       // a deleted function here.
8372       if (Constructor)
8373         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8374     }
8375   }
8376 
8377   return ExceptSpec;
8378 }
8379 
8380 Sema::ImplicitExceptionSpecification
8381 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8382   CXXRecordDecl *ClassDecl = CD->getParent();
8383 
8384   // C++ [except.spec]p14:
8385   //   An inheriting constructor [...] shall have an exception-specification. [...]
8386   ImplicitExceptionSpecification ExceptSpec(*this);
8387   if (ClassDecl->isInvalidDecl())
8388     return ExceptSpec;
8389 
8390   // Inherited constructor.
8391   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8392   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8393   // FIXME: Copying or moving the parameters could add extra exceptions to the
8394   // set, as could the default arguments for the inherited constructor. This
8395   // will be addressed when we implement the resolution of core issue 1351.
8396   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8397 
8398   // Direct base-class constructors.
8399   for (const auto &B : ClassDecl->bases()) {
8400     if (B.isVirtual()) // Handled below.
8401       continue;
8402 
8403     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8404       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8405       if (BaseClassDecl == InheritedDecl)
8406         continue;
8407       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8408       if (Constructor)
8409         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8410     }
8411   }
8412 
8413   // Virtual base-class constructors.
8414   for (const auto &B : ClassDecl->vbases()) {
8415     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8416       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8417       if (BaseClassDecl == InheritedDecl)
8418         continue;
8419       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8420       if (Constructor)
8421         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8422     }
8423   }
8424 
8425   // Field constructors.
8426   for (const auto *F : ClassDecl->fields()) {
8427     if (F->hasInClassInitializer()) {
8428       if (Expr *E = F->getInClassInitializer())
8429         ExceptSpec.CalledExpr(E);
8430       else if (!F->isInvalidDecl())
8431         Diag(CD->getLocation(),
8432              diag::err_in_class_initializer_references_def_ctor) << CD;
8433     } else if (const RecordType *RecordTy
8434               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8435       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8436       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8437       if (Constructor)
8438         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8439     }
8440   }
8441 
8442   return ExceptSpec;
8443 }
8444 
8445 namespace {
8446 /// RAII object to register a special member as being currently declared.
8447 struct DeclaringSpecialMember {
8448   Sema &S;
8449   Sema::SpecialMemberDecl D;
8450   bool WasAlreadyBeingDeclared;
8451 
8452   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8453     : S(S), D(RD, CSM) {
8454     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8455     if (WasAlreadyBeingDeclared)
8456       // This almost never happens, but if it does, ensure that our cache
8457       // doesn't contain a stale result.
8458       S.SpecialMemberCache.clear();
8459 
8460     // FIXME: Register a note to be produced if we encounter an error while
8461     // declaring the special member.
8462   }
8463   ~DeclaringSpecialMember() {
8464     if (!WasAlreadyBeingDeclared)
8465       S.SpecialMembersBeingDeclared.erase(D);
8466   }
8467 
8468   /// \brief Are we already trying to declare this special member?
8469   bool isAlreadyBeingDeclared() const {
8470     return WasAlreadyBeingDeclared;
8471   }
8472 };
8473 }
8474 
8475 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8476                                                      CXXRecordDecl *ClassDecl) {
8477   // C++ [class.ctor]p5:
8478   //   A default constructor for a class X is a constructor of class X
8479   //   that can be called without an argument. If there is no
8480   //   user-declared constructor for class X, a default constructor is
8481   //   implicitly declared. An implicitly-declared default constructor
8482   //   is an inline public member of its class.
8483   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8484          "Should not build implicit default constructor!");
8485 
8486   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8487   if (DSM.isAlreadyBeingDeclared())
8488     return nullptr;
8489 
8490   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8491                                                      CXXDefaultConstructor,
8492                                                      false);
8493 
8494   // Create the actual constructor declaration.
8495   CanQualType ClassType
8496     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8497   SourceLocation ClassLoc = ClassDecl->getLocation();
8498   DeclarationName Name
8499     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8500   DeclarationNameInfo NameInfo(Name, ClassLoc);
8501   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8502       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8503       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8504       /*isImplicitlyDeclared=*/true, Constexpr);
8505   DefaultCon->setAccess(AS_public);
8506   DefaultCon->setDefaulted();
8507   DefaultCon->setImplicit();
8508 
8509   // Build an exception specification pointing back at this constructor.
8510   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8511   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8512 
8513   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8514   // constructors is easy to compute.
8515   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8516 
8517   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8518     SetDeclDeleted(DefaultCon, ClassLoc);
8519 
8520   // Note that we have declared this constructor.
8521   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8522 
8523   if (Scope *S = getScopeForContext(ClassDecl))
8524     PushOnScopeChains(DefaultCon, S, false);
8525   ClassDecl->addDecl(DefaultCon);
8526 
8527   return DefaultCon;
8528 }
8529 
8530 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8531                                             CXXConstructorDecl *Constructor) {
8532   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8533           !Constructor->doesThisDeclarationHaveABody() &&
8534           !Constructor->isDeleted()) &&
8535     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8536 
8537   CXXRecordDecl *ClassDecl = Constructor->getParent();
8538   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8539 
8540   SynthesizedFunctionScope Scope(*this, Constructor);
8541   DiagnosticErrorTrap Trap(Diags);
8542   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8543       Trap.hasErrorOccurred()) {
8544     Diag(CurrentLocation, diag::note_member_synthesized_at)
8545       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8546     Constructor->setInvalidDecl();
8547     return;
8548   }
8549 
8550   SourceLocation Loc = Constructor->getLocEnd().isValid()
8551                            ? Constructor->getLocEnd()
8552                            : Constructor->getLocation();
8553   Constructor->setBody(new (Context) CompoundStmt(Loc));
8554 
8555   Constructor->markUsed(Context);
8556   MarkVTableUsed(CurrentLocation, ClassDecl);
8557 
8558   if (ASTMutationListener *L = getASTMutationListener()) {
8559     L->CompletedImplicitDefinition(Constructor);
8560   }
8561 
8562   DiagnoseUninitializedFields(*this, Constructor);
8563 }
8564 
8565 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8566   // Perform any delayed checks on exception specifications.
8567   CheckDelayedMemberExceptionSpecs();
8568 }
8569 
8570 namespace {
8571 /// Information on inheriting constructors to declare.
8572 class InheritingConstructorInfo {
8573 public:
8574   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8575       : SemaRef(SemaRef), Derived(Derived) {
8576     // Mark the constructors that we already have in the derived class.
8577     //
8578     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8579     //   unless there is a user-declared constructor with the same signature in
8580     //   the class where the using-declaration appears.
8581     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8582   }
8583 
8584   void inheritAll(CXXRecordDecl *RD) {
8585     visitAll(RD, &InheritingConstructorInfo::inherit);
8586   }
8587 
8588 private:
8589   /// Information about an inheriting constructor.
8590   struct InheritingConstructor {
8591     InheritingConstructor()
8592       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
8593 
8594     /// If \c true, a constructor with this signature is already declared
8595     /// in the derived class.
8596     bool DeclaredInDerived;
8597 
8598     /// The constructor which is inherited.
8599     const CXXConstructorDecl *BaseCtor;
8600 
8601     /// The derived constructor we declared.
8602     CXXConstructorDecl *DerivedCtor;
8603   };
8604 
8605   /// Inheriting constructors with a given canonical type. There can be at
8606   /// most one such non-template constructor, and any number of templated
8607   /// constructors.
8608   struct InheritingConstructorsForType {
8609     InheritingConstructor NonTemplate;
8610     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8611         Templates;
8612 
8613     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8614       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8615         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8616         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8617           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8618                                                false, S.TPL_TemplateMatch))
8619             return Templates[I].second;
8620         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8621         return Templates.back().second;
8622       }
8623 
8624       return NonTemplate;
8625     }
8626   };
8627 
8628   /// Get or create the inheriting constructor record for a constructor.
8629   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8630                                   QualType CtorType) {
8631     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8632         .getEntry(SemaRef, Ctor);
8633   }
8634 
8635   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8636 
8637   /// Process all constructors for a class.
8638   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8639     for (const auto *Ctor : RD->ctors())
8640       (this->*Callback)(Ctor);
8641     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8642              I(RD->decls_begin()), E(RD->decls_end());
8643          I != E; ++I) {
8644       const FunctionDecl *FD = (*I)->getTemplatedDecl();
8645       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8646         (this->*Callback)(CD);
8647     }
8648   }
8649 
8650   /// Note that a constructor (or constructor template) was declared in Derived.
8651   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8652     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8653   }
8654 
8655   /// Inherit a single constructor.
8656   void inherit(const CXXConstructorDecl *Ctor) {
8657     const FunctionProtoType *CtorType =
8658         Ctor->getType()->castAs<FunctionProtoType>();
8659     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
8660     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8661 
8662     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8663 
8664     // Core issue (no number yet): the ellipsis is always discarded.
8665     if (EPI.Variadic) {
8666       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8667       SemaRef.Diag(Ctor->getLocation(),
8668                    diag::note_using_decl_constructor_ellipsis);
8669       EPI.Variadic = false;
8670     }
8671 
8672     // Declare a constructor for each number of parameters.
8673     //
8674     // C++11 [class.inhctor]p1:
8675     //   The candidate set of inherited constructors from the class X named in
8676     //   the using-declaration consists of [... modulo defects ...] for each
8677     //   constructor or constructor template of X, the set of constructors or
8678     //   constructor templates that results from omitting any ellipsis parameter
8679     //   specification and successively omitting parameters with a default
8680     //   argument from the end of the parameter-type-list
8681     unsigned MinParams = minParamsToInherit(Ctor);
8682     unsigned Params = Ctor->getNumParams();
8683     if (Params >= MinParams) {
8684       do
8685         declareCtor(UsingLoc, Ctor,
8686                     SemaRef.Context.getFunctionType(
8687                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
8688       while (Params > MinParams &&
8689              Ctor->getParamDecl(--Params)->hasDefaultArg());
8690     }
8691   }
8692 
8693   /// Find the using-declaration which specified that we should inherit the
8694   /// constructors of \p Base.
8695   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8696     // No fancy lookup required; just look for the base constructor name
8697     // directly within the derived class.
8698     ASTContext &Context = SemaRef.Context;
8699     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8700         Context.getCanonicalType(Context.getRecordType(Base)));
8701     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8702     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8703   }
8704 
8705   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8706     // C++11 [class.inhctor]p3:
8707     //   [F]or each constructor template in the candidate set of inherited
8708     //   constructors, a constructor template is implicitly declared
8709     if (Ctor->getDescribedFunctionTemplate())
8710       return 0;
8711 
8712     //   For each non-template constructor in the candidate set of inherited
8713     //   constructors other than a constructor having no parameters or a
8714     //   copy/move constructor having a single parameter, a constructor is
8715     //   implicitly declared [...]
8716     if (Ctor->getNumParams() == 0)
8717       return 1;
8718     if (Ctor->isCopyOrMoveConstructor())
8719       return 2;
8720 
8721     // Per discussion on core reflector, never inherit a constructor which
8722     // would become a default, copy, or move constructor of Derived either.
8723     const ParmVarDecl *PD = Ctor->getParamDecl(0);
8724     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8725     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8726   }
8727 
8728   /// Declare a single inheriting constructor, inheriting the specified
8729   /// constructor, with the given type.
8730   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8731                    QualType DerivedType) {
8732     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8733 
8734     // C++11 [class.inhctor]p3:
8735     //   ... a constructor is implicitly declared with the same constructor
8736     //   characteristics unless there is a user-declared constructor with
8737     //   the same signature in the class where the using-declaration appears
8738     if (Entry.DeclaredInDerived)
8739       return;
8740 
8741     // C++11 [class.inhctor]p7:
8742     //   If two using-declarations declare inheriting constructors with the
8743     //   same signature, the program is ill-formed
8744     if (Entry.DerivedCtor) {
8745       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8746         // Only diagnose this once per constructor.
8747         if (Entry.DerivedCtor->isInvalidDecl())
8748           return;
8749         Entry.DerivedCtor->setInvalidDecl();
8750 
8751         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8752         SemaRef.Diag(BaseCtor->getLocation(),
8753                      diag::note_using_decl_constructor_conflict_current_ctor);
8754         SemaRef.Diag(Entry.BaseCtor->getLocation(),
8755                      diag::note_using_decl_constructor_conflict_previous_ctor);
8756         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8757                      diag::note_using_decl_constructor_conflict_previous_using);
8758       } else {
8759         // Core issue (no number): if the same inheriting constructor is
8760         // produced by multiple base class constructors from the same base
8761         // class, the inheriting constructor is defined as deleted.
8762         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8763       }
8764 
8765       return;
8766     }
8767 
8768     ASTContext &Context = SemaRef.Context;
8769     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8770         Context.getCanonicalType(Context.getRecordType(Derived)));
8771     DeclarationNameInfo NameInfo(Name, UsingLoc);
8772 
8773     TemplateParameterList *TemplateParams = nullptr;
8774     if (const FunctionTemplateDecl *FTD =
8775             BaseCtor->getDescribedFunctionTemplate()) {
8776       TemplateParams = FTD->getTemplateParameters();
8777       // We're reusing template parameters from a different DeclContext. This
8778       // is questionable at best, but works out because the template depth in
8779       // both places is guaranteed to be 0.
8780       // FIXME: Rebuild the template parameters in the new context, and
8781       // transform the function type to refer to them.
8782     }
8783 
8784     // Build type source info pointing at the using-declaration. This is
8785     // required by template instantiation.
8786     TypeSourceInfo *TInfo =
8787         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8788     FunctionProtoTypeLoc ProtoLoc =
8789         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8790 
8791     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8792         Context, Derived, UsingLoc, NameInfo, DerivedType,
8793         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8794         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8795 
8796     // Build an unevaluated exception specification for this constructor.
8797     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8798     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8799     EPI.ExceptionSpec.Type = EST_Unevaluated;
8800     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
8801     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
8802                                                  FPT->getParamTypes(), EPI));
8803 
8804     // Build the parameter declarations.
8805     SmallVector<ParmVarDecl *, 16> ParamDecls;
8806     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
8807       TypeSourceInfo *TInfo =
8808           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
8809       ParmVarDecl *PD = ParmVarDecl::Create(
8810           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8811           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
8812       PD->setScopeInfo(0, I);
8813       PD->setImplicit();
8814       ParamDecls.push_back(PD);
8815       ProtoLoc.setParam(I, PD);
8816     }
8817 
8818     // Set up the new constructor.
8819     DerivedCtor->setAccess(BaseCtor->getAccess());
8820     DerivedCtor->setParams(ParamDecls);
8821     DerivedCtor->setInheritedConstructor(BaseCtor);
8822     if (BaseCtor->isDeleted())
8823       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8824 
8825     // If this is a constructor template, build the template declaration.
8826     if (TemplateParams) {
8827       FunctionTemplateDecl *DerivedTemplate =
8828           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8829                                        TemplateParams, DerivedCtor);
8830       DerivedTemplate->setAccess(BaseCtor->getAccess());
8831       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8832       Derived->addDecl(DerivedTemplate);
8833     } else {
8834       Derived->addDecl(DerivedCtor);
8835     }
8836 
8837     Entry.BaseCtor = BaseCtor;
8838     Entry.DerivedCtor = DerivedCtor;
8839   }
8840 
8841   Sema &SemaRef;
8842   CXXRecordDecl *Derived;
8843   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8844   MapType Map;
8845 };
8846 }
8847 
8848 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8849   // Defer declaring the inheriting constructors until the class is
8850   // instantiated.
8851   if (ClassDecl->isDependentContext())
8852     return;
8853 
8854   // Find base classes from which we might inherit constructors.
8855   SmallVector<CXXRecordDecl*, 4> InheritedBases;
8856   for (const auto &BaseIt : ClassDecl->bases())
8857     if (BaseIt.getInheritConstructors())
8858       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
8859 
8860   // Go no further if we're not inheriting any constructors.
8861   if (InheritedBases.empty())
8862     return;
8863 
8864   // Declare the inherited constructors.
8865   InheritingConstructorInfo ICI(*this, ClassDecl);
8866   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8867     ICI.inheritAll(InheritedBases[I]);
8868 }
8869 
8870 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8871                                        CXXConstructorDecl *Constructor) {
8872   CXXRecordDecl *ClassDecl = Constructor->getParent();
8873   assert(Constructor->getInheritedConstructor() &&
8874          !Constructor->doesThisDeclarationHaveABody() &&
8875          !Constructor->isDeleted());
8876 
8877   SynthesizedFunctionScope Scope(*this, Constructor);
8878   DiagnosticErrorTrap Trap(Diags);
8879   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8880       Trap.hasErrorOccurred()) {
8881     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8882       << Context.getTagDeclType(ClassDecl);
8883     Constructor->setInvalidDecl();
8884     return;
8885   }
8886 
8887   SourceLocation Loc = Constructor->getLocation();
8888   Constructor->setBody(new (Context) CompoundStmt(Loc));
8889 
8890   Constructor->markUsed(Context);
8891   MarkVTableUsed(CurrentLocation, ClassDecl);
8892 
8893   if (ASTMutationListener *L = getASTMutationListener()) {
8894     L->CompletedImplicitDefinition(Constructor);
8895   }
8896 }
8897 
8898 
8899 Sema::ImplicitExceptionSpecification
8900 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8901   CXXRecordDecl *ClassDecl = MD->getParent();
8902 
8903   // C++ [except.spec]p14:
8904   //   An implicitly declared special member function (Clause 12) shall have
8905   //   an exception-specification.
8906   ImplicitExceptionSpecification ExceptSpec(*this);
8907   if (ClassDecl->isInvalidDecl())
8908     return ExceptSpec;
8909 
8910   // Direct base-class destructors.
8911   for (const auto &B : ClassDecl->bases()) {
8912     if (B.isVirtual()) // Handled below.
8913       continue;
8914 
8915     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8916       ExceptSpec.CalledDecl(B.getLocStart(),
8917                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8918   }
8919 
8920   // Virtual base-class destructors.
8921   for (const auto &B : ClassDecl->vbases()) {
8922     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8923       ExceptSpec.CalledDecl(B.getLocStart(),
8924                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8925   }
8926 
8927   // Field destructors.
8928   for (const auto *F : ClassDecl->fields()) {
8929     if (const RecordType *RecordTy
8930         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8931       ExceptSpec.CalledDecl(F->getLocation(),
8932                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8933   }
8934 
8935   return ExceptSpec;
8936 }
8937 
8938 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8939   // C++ [class.dtor]p2:
8940   //   If a class has no user-declared destructor, a destructor is
8941   //   declared implicitly. An implicitly-declared destructor is an
8942   //   inline public member of its class.
8943   assert(ClassDecl->needsImplicitDestructor());
8944 
8945   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8946   if (DSM.isAlreadyBeingDeclared())
8947     return nullptr;
8948 
8949   // Create the actual destructor declaration.
8950   CanQualType ClassType
8951     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8952   SourceLocation ClassLoc = ClassDecl->getLocation();
8953   DeclarationName Name
8954     = Context.DeclarationNames.getCXXDestructorName(ClassType);
8955   DeclarationNameInfo NameInfo(Name, ClassLoc);
8956   CXXDestructorDecl *Destructor
8957       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8958                                   QualType(), nullptr, /*isInline=*/true,
8959                                   /*isImplicitlyDeclared=*/true);
8960   Destructor->setAccess(AS_public);
8961   Destructor->setDefaulted();
8962   Destructor->setImplicit();
8963 
8964   // Build an exception specification pointing back at this destructor.
8965   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
8966   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8967 
8968   AddOverriddenMethods(ClassDecl, Destructor);
8969 
8970   // We don't need to use SpecialMemberIsTrivial here; triviality for
8971   // destructors is easy to compute.
8972   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8973 
8974   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8975     SetDeclDeleted(Destructor, ClassLoc);
8976 
8977   // Note that we have declared this destructor.
8978   ++ASTContext::NumImplicitDestructorsDeclared;
8979 
8980   // Introduce this destructor into its scope.
8981   if (Scope *S = getScopeForContext(ClassDecl))
8982     PushOnScopeChains(Destructor, S, false);
8983   ClassDecl->addDecl(Destructor);
8984 
8985   return Destructor;
8986 }
8987 
8988 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8989                                     CXXDestructorDecl *Destructor) {
8990   assert((Destructor->isDefaulted() &&
8991           !Destructor->doesThisDeclarationHaveABody() &&
8992           !Destructor->isDeleted()) &&
8993          "DefineImplicitDestructor - call it for implicit default dtor");
8994   CXXRecordDecl *ClassDecl = Destructor->getParent();
8995   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8996 
8997   if (Destructor->isInvalidDecl())
8998     return;
8999 
9000   SynthesizedFunctionScope Scope(*this, Destructor);
9001 
9002   DiagnosticErrorTrap Trap(Diags);
9003   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9004                                          Destructor->getParent());
9005 
9006   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9007     Diag(CurrentLocation, diag::note_member_synthesized_at)
9008       << CXXDestructor << Context.getTagDeclType(ClassDecl);
9009 
9010     Destructor->setInvalidDecl();
9011     return;
9012   }
9013 
9014   SourceLocation Loc = Destructor->getLocEnd().isValid()
9015                            ? Destructor->getLocEnd()
9016                            : Destructor->getLocation();
9017   Destructor->setBody(new (Context) CompoundStmt(Loc));
9018   Destructor->markUsed(Context);
9019   MarkVTableUsed(CurrentLocation, ClassDecl);
9020 
9021   if (ASTMutationListener *L = getASTMutationListener()) {
9022     L->CompletedImplicitDefinition(Destructor);
9023   }
9024 }
9025 
9026 /// \brief Perform any semantic analysis which needs to be delayed until all
9027 /// pending class member declarations have been parsed.
9028 void Sema::ActOnFinishCXXMemberDecls() {
9029   // If the context is an invalid C++ class, just suppress these checks.
9030   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9031     if (Record->isInvalidDecl()) {
9032       DelayedDefaultedMemberExceptionSpecs.clear();
9033       DelayedDestructorExceptionSpecChecks.clear();
9034       return;
9035     }
9036   }
9037 }
9038 
9039 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9040                                          CXXDestructorDecl *Destructor) {
9041   assert(getLangOpts().CPlusPlus11 &&
9042          "adjusting dtor exception specs was introduced in c++11");
9043 
9044   // C++11 [class.dtor]p3:
9045   //   A declaration of a destructor that does not have an exception-
9046   //   specification is implicitly considered to have the same exception-
9047   //   specification as an implicit declaration.
9048   const FunctionProtoType *DtorType = Destructor->getType()->
9049                                         getAs<FunctionProtoType>();
9050   if (DtorType->hasExceptionSpec())
9051     return;
9052 
9053   // Replace the destructor's type, building off the existing one. Fortunately,
9054   // the only thing of interest in the destructor type is its extended info.
9055   // The return and arguments are fixed.
9056   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9057   EPI.ExceptionSpec.Type = EST_Unevaluated;
9058   EPI.ExceptionSpec.SourceDecl = Destructor;
9059   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9060 
9061   // FIXME: If the destructor has a body that could throw, and the newly created
9062   // spec doesn't allow exceptions, we should emit a warning, because this
9063   // change in behavior can break conforming C++03 programs at runtime.
9064   // However, we don't have a body or an exception specification yet, so it
9065   // needs to be done somewhere else.
9066 }
9067 
9068 namespace {
9069 /// \brief An abstract base class for all helper classes used in building the
9070 //  copy/move operators. These classes serve as factory functions and help us
9071 //  avoid using the same Expr* in the AST twice.
9072 class ExprBuilder {
9073   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9074   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9075 
9076 protected:
9077   static Expr *assertNotNull(Expr *E) {
9078     assert(E && "Expression construction must not fail.");
9079     return E;
9080   }
9081 
9082 public:
9083   ExprBuilder() {}
9084   virtual ~ExprBuilder() {}
9085 
9086   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9087 };
9088 
9089 class RefBuilder: public ExprBuilder {
9090   VarDecl *Var;
9091   QualType VarType;
9092 
9093 public:
9094   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9095     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9096   }
9097 
9098   RefBuilder(VarDecl *Var, QualType VarType)
9099       : Var(Var), VarType(VarType) {}
9100 };
9101 
9102 class ThisBuilder: public ExprBuilder {
9103 public:
9104   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9105     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9106   }
9107 };
9108 
9109 class CastBuilder: public ExprBuilder {
9110   const ExprBuilder &Builder;
9111   QualType Type;
9112   ExprValueKind Kind;
9113   const CXXCastPath &Path;
9114 
9115 public:
9116   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9117     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9118                                              CK_UncheckedDerivedToBase, Kind,
9119                                              &Path).get());
9120   }
9121 
9122   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9123               const CXXCastPath &Path)
9124       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9125 };
9126 
9127 class DerefBuilder: public ExprBuilder {
9128   const ExprBuilder &Builder;
9129 
9130 public:
9131   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9132     return assertNotNull(
9133         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9134   }
9135 
9136   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9137 };
9138 
9139 class MemberBuilder: public ExprBuilder {
9140   const ExprBuilder &Builder;
9141   QualType Type;
9142   CXXScopeSpec SS;
9143   bool IsArrow;
9144   LookupResult &MemberLookup;
9145 
9146 public:
9147   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9148     return assertNotNull(S.BuildMemberReferenceExpr(
9149         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9150         nullptr, MemberLookup, nullptr).get());
9151   }
9152 
9153   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9154                 LookupResult &MemberLookup)
9155       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9156         MemberLookup(MemberLookup) {}
9157 };
9158 
9159 class MoveCastBuilder: public ExprBuilder {
9160   const ExprBuilder &Builder;
9161 
9162 public:
9163   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9164     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9165   }
9166 
9167   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9168 };
9169 
9170 class LvalueConvBuilder: public ExprBuilder {
9171   const ExprBuilder &Builder;
9172 
9173 public:
9174   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9175     return assertNotNull(
9176         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9177   }
9178 
9179   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9180 };
9181 
9182 class SubscriptBuilder: public ExprBuilder {
9183   const ExprBuilder &Base;
9184   const ExprBuilder &Index;
9185 
9186 public:
9187   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9188     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9189         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9190   }
9191 
9192   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9193       : Base(Base), Index(Index) {}
9194 };
9195 
9196 } // end anonymous namespace
9197 
9198 /// When generating a defaulted copy or move assignment operator, if a field
9199 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9200 /// do so. This optimization only applies for arrays of scalars, and for arrays
9201 /// of class type where the selected copy/move-assignment operator is trivial.
9202 static StmtResult
9203 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9204                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9205   // Compute the size of the memory buffer to be copied.
9206   QualType SizeType = S.Context.getSizeType();
9207   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9208                    S.Context.getTypeSizeInChars(T).getQuantity());
9209 
9210   // Take the address of the field references for "from" and "to". We
9211   // directly construct UnaryOperators here because semantic analysis
9212   // does not permit us to take the address of an xvalue.
9213   Expr *From = FromB.build(S, Loc);
9214   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9215                          S.Context.getPointerType(From->getType()),
9216                          VK_RValue, OK_Ordinary, Loc);
9217   Expr *To = ToB.build(S, Loc);
9218   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9219                        S.Context.getPointerType(To->getType()),
9220                        VK_RValue, OK_Ordinary, Loc);
9221 
9222   const Type *E = T->getBaseElementTypeUnsafe();
9223   bool NeedsCollectableMemCpy =
9224     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9225 
9226   // Create a reference to the __builtin_objc_memmove_collectable function
9227   StringRef MemCpyName = NeedsCollectableMemCpy ?
9228     "__builtin_objc_memmove_collectable" :
9229     "__builtin_memcpy";
9230   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9231                  Sema::LookupOrdinaryName);
9232   S.LookupName(R, S.TUScope, true);
9233 
9234   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9235   if (!MemCpy)
9236     // Something went horribly wrong earlier, and we will have complained
9237     // about it.
9238     return StmtError();
9239 
9240   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9241                                             VK_RValue, Loc, nullptr);
9242   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9243 
9244   Expr *CallArgs[] = {
9245     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9246   };
9247   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9248                                     Loc, CallArgs, Loc);
9249 
9250   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9251   return Call.getAs<Stmt>();
9252 }
9253 
9254 /// \brief Builds a statement that copies/moves the given entity from \p From to
9255 /// \c To.
9256 ///
9257 /// This routine is used to copy/move the members of a class with an
9258 /// implicitly-declared copy/move assignment operator. When the entities being
9259 /// copied are arrays, this routine builds for loops to copy them.
9260 ///
9261 /// \param S The Sema object used for type-checking.
9262 ///
9263 /// \param Loc The location where the implicit copy/move is being generated.
9264 ///
9265 /// \param T The type of the expressions being copied/moved. Both expressions
9266 /// must have this type.
9267 ///
9268 /// \param To The expression we are copying/moving to.
9269 ///
9270 /// \param From The expression we are copying/moving from.
9271 ///
9272 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9273 /// Otherwise, it's a non-static member subobject.
9274 ///
9275 /// \param Copying Whether we're copying or moving.
9276 ///
9277 /// \param Depth Internal parameter recording the depth of the recursion.
9278 ///
9279 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9280 /// if a memcpy should be used instead.
9281 static StmtResult
9282 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9283                                  const ExprBuilder &To, const ExprBuilder &From,
9284                                  bool CopyingBaseSubobject, bool Copying,
9285                                  unsigned Depth = 0) {
9286   // C++11 [class.copy]p28:
9287   //   Each subobject is assigned in the manner appropriate to its type:
9288   //
9289   //     - if the subobject is of class type, as if by a call to operator= with
9290   //       the subobject as the object expression and the corresponding
9291   //       subobject of x as a single function argument (as if by explicit
9292   //       qualification; that is, ignoring any possible virtual overriding
9293   //       functions in more derived classes);
9294   //
9295   // C++03 [class.copy]p13:
9296   //     - if the subobject is of class type, the copy assignment operator for
9297   //       the class is used (as if by explicit qualification; that is,
9298   //       ignoring any possible virtual overriding functions in more derived
9299   //       classes);
9300   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9301     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9302 
9303     // Look for operator=.
9304     DeclarationName Name
9305       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9306     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9307     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9308 
9309     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9310     // operator.
9311     if (!S.getLangOpts().CPlusPlus11) {
9312       LookupResult::Filter F = OpLookup.makeFilter();
9313       while (F.hasNext()) {
9314         NamedDecl *D = F.next();
9315         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9316           if (Method->isCopyAssignmentOperator() ||
9317               (!Copying && Method->isMoveAssignmentOperator()))
9318             continue;
9319 
9320         F.erase();
9321       }
9322       F.done();
9323     }
9324 
9325     // Suppress the protected check (C++ [class.protected]) for each of the
9326     // assignment operators we found. This strange dance is required when
9327     // we're assigning via a base classes's copy-assignment operator. To
9328     // ensure that we're getting the right base class subobject (without
9329     // ambiguities), we need to cast "this" to that subobject type; to
9330     // ensure that we don't go through the virtual call mechanism, we need
9331     // to qualify the operator= name with the base class (see below). However,
9332     // this means that if the base class has a protected copy assignment
9333     // operator, the protected member access check will fail. So, we
9334     // rewrite "protected" access to "public" access in this case, since we
9335     // know by construction that we're calling from a derived class.
9336     if (CopyingBaseSubobject) {
9337       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9338            L != LEnd; ++L) {
9339         if (L.getAccess() == AS_protected)
9340           L.setAccess(AS_public);
9341       }
9342     }
9343 
9344     // Create the nested-name-specifier that will be used to qualify the
9345     // reference to operator=; this is required to suppress the virtual
9346     // call mechanism.
9347     CXXScopeSpec SS;
9348     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9349     SS.MakeTrivial(S.Context,
9350                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9351                                                CanonicalT),
9352                    Loc);
9353 
9354     // Create the reference to operator=.
9355     ExprResult OpEqualRef
9356       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9357                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9358                                    /*FirstQualifierInScope=*/nullptr,
9359                                    OpLookup,
9360                                    /*TemplateArgs=*/nullptr,
9361                                    /*SuppressQualifierCheck=*/true);
9362     if (OpEqualRef.isInvalid())
9363       return StmtError();
9364 
9365     // Build the call to the assignment operator.
9366 
9367     Expr *FromInst = From.build(S, Loc);
9368     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9369                                                   OpEqualRef.getAs<Expr>(),
9370                                                   Loc, FromInst, Loc);
9371     if (Call.isInvalid())
9372       return StmtError();
9373 
9374     // If we built a call to a trivial 'operator=' while copying an array,
9375     // bail out. We'll replace the whole shebang with a memcpy.
9376     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9377     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9378       return StmtResult((Stmt*)nullptr);
9379 
9380     // Convert to an expression-statement, and clean up any produced
9381     // temporaries.
9382     return S.ActOnExprStmt(Call);
9383   }
9384 
9385   //     - if the subobject is of scalar type, the built-in assignment
9386   //       operator is used.
9387   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9388   if (!ArrayTy) {
9389     ExprResult Assignment = S.CreateBuiltinBinOp(
9390         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9391     if (Assignment.isInvalid())
9392       return StmtError();
9393     return S.ActOnExprStmt(Assignment);
9394   }
9395 
9396   //     - if the subobject is an array, each element is assigned, in the
9397   //       manner appropriate to the element type;
9398 
9399   // Construct a loop over the array bounds, e.g.,
9400   //
9401   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9402   //
9403   // that will copy each of the array elements.
9404   QualType SizeType = S.Context.getSizeType();
9405 
9406   // Create the iteration variable.
9407   IdentifierInfo *IterationVarName = nullptr;
9408   {
9409     SmallString<8> Str;
9410     llvm::raw_svector_ostream OS(Str);
9411     OS << "__i" << Depth;
9412     IterationVarName = &S.Context.Idents.get(OS.str());
9413   }
9414   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9415                                           IterationVarName, SizeType,
9416                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9417                                           SC_None);
9418 
9419   // Initialize the iteration variable to zero.
9420   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9421   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9422 
9423   // Creates a reference to the iteration variable.
9424   RefBuilder IterationVarRef(IterationVar, SizeType);
9425   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9426 
9427   // Create the DeclStmt that holds the iteration variable.
9428   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9429 
9430   // Subscript the "from" and "to" expressions with the iteration variable.
9431   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9432   MoveCastBuilder FromIndexMove(FromIndexCopy);
9433   const ExprBuilder *FromIndex;
9434   if (Copying)
9435     FromIndex = &FromIndexCopy;
9436   else
9437     FromIndex = &FromIndexMove;
9438 
9439   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9440 
9441   // Build the copy/move for an individual element of the array.
9442   StmtResult Copy =
9443     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9444                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9445                                      Copying, Depth + 1);
9446   // Bail out if copying fails or if we determined that we should use memcpy.
9447   if (Copy.isInvalid() || !Copy.get())
9448     return Copy;
9449 
9450   // Create the comparison against the array bound.
9451   llvm::APInt Upper
9452     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9453   Expr *Comparison
9454     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9455                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9456                                      BO_NE, S.Context.BoolTy,
9457                                      VK_RValue, OK_Ordinary, Loc, false);
9458 
9459   // Create the pre-increment of the iteration variable.
9460   Expr *Increment
9461     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9462                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9463 
9464   // Construct the loop that copies all elements of this array.
9465   return S.ActOnForStmt(Loc, Loc, InitStmt,
9466                         S.MakeFullExpr(Comparison),
9467                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9468                         Loc, Copy.get());
9469 }
9470 
9471 static StmtResult
9472 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9473                       const ExprBuilder &To, const ExprBuilder &From,
9474                       bool CopyingBaseSubobject, bool Copying) {
9475   // Maybe we should use a memcpy?
9476   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9477       T.isTriviallyCopyableType(S.Context))
9478     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9479 
9480   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9481                                                      CopyingBaseSubobject,
9482                                                      Copying, 0));
9483 
9484   // If we ended up picking a trivial assignment operator for an array of a
9485   // non-trivially-copyable class type, just emit a memcpy.
9486   if (!Result.isInvalid() && !Result.get())
9487     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9488 
9489   return Result;
9490 }
9491 
9492 Sema::ImplicitExceptionSpecification
9493 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9494   CXXRecordDecl *ClassDecl = MD->getParent();
9495 
9496   ImplicitExceptionSpecification ExceptSpec(*this);
9497   if (ClassDecl->isInvalidDecl())
9498     return ExceptSpec;
9499 
9500   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9501   assert(T->getNumParams() == 1 && "not a copy assignment op");
9502   unsigned ArgQuals =
9503       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9504 
9505   // C++ [except.spec]p14:
9506   //   An implicitly declared special member function (Clause 12) shall have an
9507   //   exception-specification. [...]
9508 
9509   // It is unspecified whether or not an implicit copy assignment operator
9510   // attempts to deduplicate calls to assignment operators of virtual bases are
9511   // made. As such, this exception specification is effectively unspecified.
9512   // Based on a similar decision made for constness in C++0x, we're erring on
9513   // the side of assuming such calls to be made regardless of whether they
9514   // actually happen.
9515   for (const auto &Base : ClassDecl->bases()) {
9516     if (Base.isVirtual())
9517       continue;
9518 
9519     CXXRecordDecl *BaseClassDecl
9520       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9521     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9522                                                             ArgQuals, false, 0))
9523       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9524   }
9525 
9526   for (const auto &Base : ClassDecl->vbases()) {
9527     CXXRecordDecl *BaseClassDecl
9528       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9529     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9530                                                             ArgQuals, false, 0))
9531       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9532   }
9533 
9534   for (const auto *Field : ClassDecl->fields()) {
9535     QualType FieldType = Context.getBaseElementType(Field->getType());
9536     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9537       if (CXXMethodDecl *CopyAssign =
9538           LookupCopyingAssignment(FieldClassDecl,
9539                                   ArgQuals | FieldType.getCVRQualifiers(),
9540                                   false, 0))
9541         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9542     }
9543   }
9544 
9545   return ExceptSpec;
9546 }
9547 
9548 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9549   // Note: The following rules are largely analoguous to the copy
9550   // constructor rules. Note that virtual bases are not taken into account
9551   // for determining the argument type of the operator. Note also that
9552   // operators taking an object instead of a reference are allowed.
9553   assert(ClassDecl->needsImplicitCopyAssignment());
9554 
9555   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9556   if (DSM.isAlreadyBeingDeclared())
9557     return nullptr;
9558 
9559   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9560   QualType RetType = Context.getLValueReferenceType(ArgType);
9561   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9562   if (Const)
9563     ArgType = ArgType.withConst();
9564   ArgType = Context.getLValueReferenceType(ArgType);
9565 
9566   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9567                                                      CXXCopyAssignment,
9568                                                      Const);
9569 
9570   //   An implicitly-declared copy assignment operator is an inline public
9571   //   member of its class.
9572   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9573   SourceLocation ClassLoc = ClassDecl->getLocation();
9574   DeclarationNameInfo NameInfo(Name, ClassLoc);
9575   CXXMethodDecl *CopyAssignment =
9576       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9577                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9578                             /*isInline=*/true, Constexpr, SourceLocation());
9579   CopyAssignment->setAccess(AS_public);
9580   CopyAssignment->setDefaulted();
9581   CopyAssignment->setImplicit();
9582 
9583   // Build an exception specification pointing back at this member.
9584   FunctionProtoType::ExtProtoInfo EPI =
9585       getImplicitMethodEPI(*this, CopyAssignment);
9586   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9587 
9588   // Add the parameter to the operator.
9589   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9590                                                ClassLoc, ClassLoc,
9591                                                /*Id=*/nullptr, ArgType,
9592                                                /*TInfo=*/nullptr, SC_None,
9593                                                nullptr);
9594   CopyAssignment->setParams(FromParam);
9595 
9596   AddOverriddenMethods(ClassDecl, CopyAssignment);
9597 
9598   CopyAssignment->setTrivial(
9599     ClassDecl->needsOverloadResolutionForCopyAssignment()
9600       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9601       : ClassDecl->hasTrivialCopyAssignment());
9602 
9603   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9604     SetDeclDeleted(CopyAssignment, ClassLoc);
9605 
9606   // Note that we have added this copy-assignment operator.
9607   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9608 
9609   if (Scope *S = getScopeForContext(ClassDecl))
9610     PushOnScopeChains(CopyAssignment, S, false);
9611   ClassDecl->addDecl(CopyAssignment);
9612 
9613   return CopyAssignment;
9614 }
9615 
9616 /// Diagnose an implicit copy operation for a class which is odr-used, but
9617 /// which is deprecated because the class has a user-declared copy constructor,
9618 /// copy assignment operator, or destructor.
9619 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9620                                             SourceLocation UseLoc) {
9621   assert(CopyOp->isImplicit());
9622 
9623   CXXRecordDecl *RD = CopyOp->getParent();
9624   CXXMethodDecl *UserDeclaredOperation = nullptr;
9625 
9626   // In Microsoft mode, assignment operations don't affect constructors and
9627   // vice versa.
9628   if (RD->hasUserDeclaredDestructor()) {
9629     UserDeclaredOperation = RD->getDestructor();
9630   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9631              RD->hasUserDeclaredCopyConstructor() &&
9632              !S.getLangOpts().MSVCCompat) {
9633     // Find any user-declared copy constructor.
9634     for (auto *I : RD->ctors()) {
9635       if (I->isCopyConstructor()) {
9636         UserDeclaredOperation = I;
9637         break;
9638       }
9639     }
9640     assert(UserDeclaredOperation);
9641   } else if (isa<CXXConstructorDecl>(CopyOp) &&
9642              RD->hasUserDeclaredCopyAssignment() &&
9643              !S.getLangOpts().MSVCCompat) {
9644     // Find any user-declared move assignment operator.
9645     for (auto *I : RD->methods()) {
9646       if (I->isCopyAssignmentOperator()) {
9647         UserDeclaredOperation = I;
9648         break;
9649       }
9650     }
9651     assert(UserDeclaredOperation);
9652   }
9653 
9654   if (UserDeclaredOperation) {
9655     S.Diag(UserDeclaredOperation->getLocation(),
9656          diag::warn_deprecated_copy_operation)
9657       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9658       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9659     S.Diag(UseLoc, diag::note_member_synthesized_at)
9660       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9661                                           : Sema::CXXCopyAssignment)
9662       << RD;
9663   }
9664 }
9665 
9666 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9667                                         CXXMethodDecl *CopyAssignOperator) {
9668   assert((CopyAssignOperator->isDefaulted() &&
9669           CopyAssignOperator->isOverloadedOperator() &&
9670           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9671           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9672           !CopyAssignOperator->isDeleted()) &&
9673          "DefineImplicitCopyAssignment called for wrong function");
9674 
9675   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9676 
9677   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9678     CopyAssignOperator->setInvalidDecl();
9679     return;
9680   }
9681 
9682   // C++11 [class.copy]p18:
9683   //   The [definition of an implicitly declared copy assignment operator] is
9684   //   deprecated if the class has a user-declared copy constructor or a
9685   //   user-declared destructor.
9686   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9687     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9688 
9689   CopyAssignOperator->markUsed(Context);
9690 
9691   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9692   DiagnosticErrorTrap Trap(Diags);
9693 
9694   // C++0x [class.copy]p30:
9695   //   The implicitly-defined or explicitly-defaulted copy assignment operator
9696   //   for a non-union class X performs memberwise copy assignment of its
9697   //   subobjects. The direct base classes of X are assigned first, in the
9698   //   order of their declaration in the base-specifier-list, and then the
9699   //   immediate non-static data members of X are assigned, in the order in
9700   //   which they were declared in the class definition.
9701 
9702   // The statements that form the synthesized function body.
9703   SmallVector<Stmt*, 8> Statements;
9704 
9705   // The parameter for the "other" object, which we are copying from.
9706   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9707   Qualifiers OtherQuals = Other->getType().getQualifiers();
9708   QualType OtherRefType = Other->getType();
9709   if (const LValueReferenceType *OtherRef
9710                                 = OtherRefType->getAs<LValueReferenceType>()) {
9711     OtherRefType = OtherRef->getPointeeType();
9712     OtherQuals = OtherRefType.getQualifiers();
9713   }
9714 
9715   // Our location for everything implicitly-generated.
9716   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9717                            ? CopyAssignOperator->getLocEnd()
9718                            : CopyAssignOperator->getLocation();
9719 
9720   // Builds a DeclRefExpr for the "other" object.
9721   RefBuilder OtherRef(Other, OtherRefType);
9722 
9723   // Builds the "this" pointer.
9724   ThisBuilder This;
9725 
9726   // Assign base classes.
9727   bool Invalid = false;
9728   for (auto &Base : ClassDecl->bases()) {
9729     // Form the assignment:
9730     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9731     QualType BaseType = Base.getType().getUnqualifiedType();
9732     if (!BaseType->isRecordType()) {
9733       Invalid = true;
9734       continue;
9735     }
9736 
9737     CXXCastPath BasePath;
9738     BasePath.push_back(&Base);
9739 
9740     // Construct the "from" expression, which is an implicit cast to the
9741     // appropriately-qualified base type.
9742     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9743                      VK_LValue, BasePath);
9744 
9745     // Dereference "this".
9746     DerefBuilder DerefThis(This);
9747     CastBuilder To(DerefThis,
9748                    Context.getCVRQualifiedType(
9749                        BaseType, CopyAssignOperator->getTypeQualifiers()),
9750                    VK_LValue, BasePath);
9751 
9752     // Build the copy.
9753     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9754                                             To, From,
9755                                             /*CopyingBaseSubobject=*/true,
9756                                             /*Copying=*/true);
9757     if (Copy.isInvalid()) {
9758       Diag(CurrentLocation, diag::note_member_synthesized_at)
9759         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9760       CopyAssignOperator->setInvalidDecl();
9761       return;
9762     }
9763 
9764     // Success! Record the copy.
9765     Statements.push_back(Copy.getAs<Expr>());
9766   }
9767 
9768   // Assign non-static members.
9769   for (auto *Field : ClassDecl->fields()) {
9770     if (Field->isUnnamedBitfield())
9771       continue;
9772 
9773     if (Field->isInvalidDecl()) {
9774       Invalid = true;
9775       continue;
9776     }
9777 
9778     // Check for members of reference type; we can't copy those.
9779     if (Field->getType()->isReferenceType()) {
9780       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9781         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9782       Diag(Field->getLocation(), diag::note_declared_at);
9783       Diag(CurrentLocation, diag::note_member_synthesized_at)
9784         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9785       Invalid = true;
9786       continue;
9787     }
9788 
9789     // Check for members of const-qualified, non-class type.
9790     QualType BaseType = Context.getBaseElementType(Field->getType());
9791     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9792       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9793         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9794       Diag(Field->getLocation(), diag::note_declared_at);
9795       Diag(CurrentLocation, diag::note_member_synthesized_at)
9796         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9797       Invalid = true;
9798       continue;
9799     }
9800 
9801     // Suppress assigning zero-width bitfields.
9802     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9803       continue;
9804 
9805     QualType FieldType = Field->getType().getNonReferenceType();
9806     if (FieldType->isIncompleteArrayType()) {
9807       assert(ClassDecl->hasFlexibleArrayMember() &&
9808              "Incomplete array type is not valid");
9809       continue;
9810     }
9811 
9812     // Build references to the field in the object we're copying from and to.
9813     CXXScopeSpec SS; // Intentionally empty
9814     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9815                               LookupMemberName);
9816     MemberLookup.addDecl(Field);
9817     MemberLookup.resolveKind();
9818 
9819     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9820 
9821     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9822 
9823     // Build the copy of this field.
9824     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9825                                             To, From,
9826                                             /*CopyingBaseSubobject=*/false,
9827                                             /*Copying=*/true);
9828     if (Copy.isInvalid()) {
9829       Diag(CurrentLocation, diag::note_member_synthesized_at)
9830         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9831       CopyAssignOperator->setInvalidDecl();
9832       return;
9833     }
9834 
9835     // Success! Record the copy.
9836     Statements.push_back(Copy.getAs<Stmt>());
9837   }
9838 
9839   if (!Invalid) {
9840     // Add a "return *this;"
9841     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9842 
9843     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
9844     if (Return.isInvalid())
9845       Invalid = true;
9846     else {
9847       Statements.push_back(Return.getAs<Stmt>());
9848 
9849       if (Trap.hasErrorOccurred()) {
9850         Diag(CurrentLocation, diag::note_member_synthesized_at)
9851           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9852         Invalid = true;
9853       }
9854     }
9855   }
9856 
9857   if (Invalid) {
9858     CopyAssignOperator->setInvalidDecl();
9859     return;
9860   }
9861 
9862   StmtResult Body;
9863   {
9864     CompoundScopeRAII CompoundScope(*this);
9865     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9866                              /*isStmtExpr=*/false);
9867     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9868   }
9869   CopyAssignOperator->setBody(Body.getAs<Stmt>());
9870 
9871   if (ASTMutationListener *L = getASTMutationListener()) {
9872     L->CompletedImplicitDefinition(CopyAssignOperator);
9873   }
9874 }
9875 
9876 Sema::ImplicitExceptionSpecification
9877 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9878   CXXRecordDecl *ClassDecl = MD->getParent();
9879 
9880   ImplicitExceptionSpecification ExceptSpec(*this);
9881   if (ClassDecl->isInvalidDecl())
9882     return ExceptSpec;
9883 
9884   // C++0x [except.spec]p14:
9885   //   An implicitly declared special member function (Clause 12) shall have an
9886   //   exception-specification. [...]
9887 
9888   // It is unspecified whether or not an implicit move assignment operator
9889   // attempts to deduplicate calls to assignment operators of virtual bases are
9890   // made. As such, this exception specification is effectively unspecified.
9891   // Based on a similar decision made for constness in C++0x, we're erring on
9892   // the side of assuming such calls to be made regardless of whether they
9893   // actually happen.
9894   // Note that a move constructor is not implicitly declared when there are
9895   // virtual bases, but it can still be user-declared and explicitly defaulted.
9896   for (const auto &Base : ClassDecl->bases()) {
9897     if (Base.isVirtual())
9898       continue;
9899 
9900     CXXRecordDecl *BaseClassDecl
9901       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9902     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9903                                                            0, false, 0))
9904       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9905   }
9906 
9907   for (const auto &Base : ClassDecl->vbases()) {
9908     CXXRecordDecl *BaseClassDecl
9909       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9910     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9911                                                            0, false, 0))
9912       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9913   }
9914 
9915   for (const auto *Field : ClassDecl->fields()) {
9916     QualType FieldType = Context.getBaseElementType(Field->getType());
9917     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9918       if (CXXMethodDecl *MoveAssign =
9919               LookupMovingAssignment(FieldClassDecl,
9920                                      FieldType.getCVRQualifiers(),
9921                                      false, 0))
9922         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9923     }
9924   }
9925 
9926   return ExceptSpec;
9927 }
9928 
9929 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9930   assert(ClassDecl->needsImplicitMoveAssignment());
9931 
9932   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9933   if (DSM.isAlreadyBeingDeclared())
9934     return nullptr;
9935 
9936   // Note: The following rules are largely analoguous to the move
9937   // constructor rules.
9938 
9939   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9940   QualType RetType = Context.getLValueReferenceType(ArgType);
9941   ArgType = Context.getRValueReferenceType(ArgType);
9942 
9943   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9944                                                      CXXMoveAssignment,
9945                                                      false);
9946 
9947   //   An implicitly-declared move assignment operator is an inline public
9948   //   member of its class.
9949   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9950   SourceLocation ClassLoc = ClassDecl->getLocation();
9951   DeclarationNameInfo NameInfo(Name, ClassLoc);
9952   CXXMethodDecl *MoveAssignment =
9953       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9954                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9955                             /*isInline=*/true, Constexpr, SourceLocation());
9956   MoveAssignment->setAccess(AS_public);
9957   MoveAssignment->setDefaulted();
9958   MoveAssignment->setImplicit();
9959 
9960   // Build an exception specification pointing back at this member.
9961   FunctionProtoType::ExtProtoInfo EPI =
9962       getImplicitMethodEPI(*this, MoveAssignment);
9963   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9964 
9965   // Add the parameter to the operator.
9966   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9967                                                ClassLoc, ClassLoc,
9968                                                /*Id=*/nullptr, ArgType,
9969                                                /*TInfo=*/nullptr, SC_None,
9970                                                nullptr);
9971   MoveAssignment->setParams(FromParam);
9972 
9973   AddOverriddenMethods(ClassDecl, MoveAssignment);
9974 
9975   MoveAssignment->setTrivial(
9976     ClassDecl->needsOverloadResolutionForMoveAssignment()
9977       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9978       : ClassDecl->hasTrivialMoveAssignment());
9979 
9980   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9981     ClassDecl->setImplicitMoveAssignmentIsDeleted();
9982     SetDeclDeleted(MoveAssignment, ClassLoc);
9983   }
9984 
9985   // Note that we have added this copy-assignment operator.
9986   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9987 
9988   if (Scope *S = getScopeForContext(ClassDecl))
9989     PushOnScopeChains(MoveAssignment, S, false);
9990   ClassDecl->addDecl(MoveAssignment);
9991 
9992   return MoveAssignment;
9993 }
9994 
9995 /// Check if we're implicitly defining a move assignment operator for a class
9996 /// with virtual bases. Such a move assignment might move-assign the virtual
9997 /// base multiple times.
9998 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9999                                                SourceLocation CurrentLocation) {
10000   assert(!Class->isDependentContext() && "should not define dependent move");
10001 
10002   // Only a virtual base could get implicitly move-assigned multiple times.
10003   // Only a non-trivial move assignment can observe this. We only want to
10004   // diagnose if we implicitly define an assignment operator that assigns
10005   // two base classes, both of which move-assign the same virtual base.
10006   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10007       Class->getNumBases() < 2)
10008     return;
10009 
10010   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10011   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10012   VBaseMap VBases;
10013 
10014   for (auto &BI : Class->bases()) {
10015     Worklist.push_back(&BI);
10016     while (!Worklist.empty()) {
10017       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10018       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10019 
10020       // If the base has no non-trivial move assignment operators,
10021       // we don't care about moves from it.
10022       if (!Base->hasNonTrivialMoveAssignment())
10023         continue;
10024 
10025       // If there's nothing virtual here, skip it.
10026       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10027         continue;
10028 
10029       // If we're not actually going to call a move assignment for this base,
10030       // or the selected move assignment is trivial, skip it.
10031       Sema::SpecialMemberOverloadResult *SMOR =
10032         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10033                               /*ConstArg*/false, /*VolatileArg*/false,
10034                               /*RValueThis*/true, /*ConstThis*/false,
10035                               /*VolatileThis*/false);
10036       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10037           !SMOR->getMethod()->isMoveAssignmentOperator())
10038         continue;
10039 
10040       if (BaseSpec->isVirtual()) {
10041         // We're going to move-assign this virtual base, and its move
10042         // assignment operator is not trivial. If this can happen for
10043         // multiple distinct direct bases of Class, diagnose it. (If it
10044         // only happens in one base, we'll diagnose it when synthesizing
10045         // that base class's move assignment operator.)
10046         CXXBaseSpecifier *&Existing =
10047             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10048                 .first->second;
10049         if (Existing && Existing != &BI) {
10050           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10051             << Class << Base;
10052           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10053             << (Base->getCanonicalDecl() ==
10054                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10055             << Base << Existing->getType() << Existing->getSourceRange();
10056           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10057             << (Base->getCanonicalDecl() ==
10058                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10059             << Base << BI.getType() << BaseSpec->getSourceRange();
10060 
10061           // Only diagnose each vbase once.
10062           Existing = nullptr;
10063         }
10064       } else {
10065         // Only walk over bases that have defaulted move assignment operators.
10066         // We assume that any user-provided move assignment operator handles
10067         // the multiple-moves-of-vbase case itself somehow.
10068         if (!SMOR->getMethod()->isDefaulted())
10069           continue;
10070 
10071         // We're going to move the base classes of Base. Add them to the list.
10072         for (auto &BI : Base->bases())
10073           Worklist.push_back(&BI);
10074       }
10075     }
10076   }
10077 }
10078 
10079 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10080                                         CXXMethodDecl *MoveAssignOperator) {
10081   assert((MoveAssignOperator->isDefaulted() &&
10082           MoveAssignOperator->isOverloadedOperator() &&
10083           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10084           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10085           !MoveAssignOperator->isDeleted()) &&
10086          "DefineImplicitMoveAssignment called for wrong function");
10087 
10088   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10089 
10090   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10091     MoveAssignOperator->setInvalidDecl();
10092     return;
10093   }
10094 
10095   MoveAssignOperator->markUsed(Context);
10096 
10097   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10098   DiagnosticErrorTrap Trap(Diags);
10099 
10100   // C++0x [class.copy]p28:
10101   //   The implicitly-defined or move assignment operator for a non-union class
10102   //   X performs memberwise move assignment of its subobjects. The direct base
10103   //   classes of X are assigned first, in the order of their declaration in the
10104   //   base-specifier-list, and then the immediate non-static data members of X
10105   //   are assigned, in the order in which they were declared in the class
10106   //   definition.
10107 
10108   // Issue a warning if our implicit move assignment operator will move
10109   // from a virtual base more than once.
10110   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10111 
10112   // The statements that form the synthesized function body.
10113   SmallVector<Stmt*, 8> Statements;
10114 
10115   // The parameter for the "other" object, which we are move from.
10116   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10117   QualType OtherRefType = Other->getType()->
10118       getAs<RValueReferenceType>()->getPointeeType();
10119   assert(!OtherRefType.getQualifiers() &&
10120          "Bad argument type of defaulted move assignment");
10121 
10122   // Our location for everything implicitly-generated.
10123   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10124                            ? MoveAssignOperator->getLocEnd()
10125                            : MoveAssignOperator->getLocation();
10126 
10127   // Builds a reference to the "other" object.
10128   RefBuilder OtherRef(Other, OtherRefType);
10129   // Cast to rvalue.
10130   MoveCastBuilder MoveOther(OtherRef);
10131 
10132   // Builds the "this" pointer.
10133   ThisBuilder This;
10134 
10135   // Assign base classes.
10136   bool Invalid = false;
10137   for (auto &Base : ClassDecl->bases()) {
10138     // C++11 [class.copy]p28:
10139     //   It is unspecified whether subobjects representing virtual base classes
10140     //   are assigned more than once by the implicitly-defined copy assignment
10141     //   operator.
10142     // FIXME: Do not assign to a vbase that will be assigned by some other base
10143     // class. For a move-assignment, this can result in the vbase being moved
10144     // multiple times.
10145 
10146     // Form the assignment:
10147     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10148     QualType BaseType = Base.getType().getUnqualifiedType();
10149     if (!BaseType->isRecordType()) {
10150       Invalid = true;
10151       continue;
10152     }
10153 
10154     CXXCastPath BasePath;
10155     BasePath.push_back(&Base);
10156 
10157     // Construct the "from" expression, which is an implicit cast to the
10158     // appropriately-qualified base type.
10159     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10160 
10161     // Dereference "this".
10162     DerefBuilder DerefThis(This);
10163 
10164     // Implicitly cast "this" to the appropriately-qualified base type.
10165     CastBuilder To(DerefThis,
10166                    Context.getCVRQualifiedType(
10167                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10168                    VK_LValue, BasePath);
10169 
10170     // Build the move.
10171     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10172                                             To, From,
10173                                             /*CopyingBaseSubobject=*/true,
10174                                             /*Copying=*/false);
10175     if (Move.isInvalid()) {
10176       Diag(CurrentLocation, diag::note_member_synthesized_at)
10177         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10178       MoveAssignOperator->setInvalidDecl();
10179       return;
10180     }
10181 
10182     // Success! Record the move.
10183     Statements.push_back(Move.getAs<Expr>());
10184   }
10185 
10186   // Assign non-static members.
10187   for (auto *Field : ClassDecl->fields()) {
10188     if (Field->isUnnamedBitfield())
10189       continue;
10190 
10191     if (Field->isInvalidDecl()) {
10192       Invalid = true;
10193       continue;
10194     }
10195 
10196     // Check for members of reference type; we can't move those.
10197     if (Field->getType()->isReferenceType()) {
10198       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10199         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10200       Diag(Field->getLocation(), diag::note_declared_at);
10201       Diag(CurrentLocation, diag::note_member_synthesized_at)
10202         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10203       Invalid = true;
10204       continue;
10205     }
10206 
10207     // Check for members of const-qualified, non-class type.
10208     QualType BaseType = Context.getBaseElementType(Field->getType());
10209     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10210       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10211         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10212       Diag(Field->getLocation(), diag::note_declared_at);
10213       Diag(CurrentLocation, diag::note_member_synthesized_at)
10214         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10215       Invalid = true;
10216       continue;
10217     }
10218 
10219     // Suppress assigning zero-width bitfields.
10220     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10221       continue;
10222 
10223     QualType FieldType = Field->getType().getNonReferenceType();
10224     if (FieldType->isIncompleteArrayType()) {
10225       assert(ClassDecl->hasFlexibleArrayMember() &&
10226              "Incomplete array type is not valid");
10227       continue;
10228     }
10229 
10230     // Build references to the field in the object we're copying from and to.
10231     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10232                               LookupMemberName);
10233     MemberLookup.addDecl(Field);
10234     MemberLookup.resolveKind();
10235     MemberBuilder From(MoveOther, OtherRefType,
10236                        /*IsArrow=*/false, MemberLookup);
10237     MemberBuilder To(This, getCurrentThisType(),
10238                      /*IsArrow=*/true, MemberLookup);
10239 
10240     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10241         "Member reference with rvalue base must be rvalue except for reference "
10242         "members, which aren't allowed for move assignment.");
10243 
10244     // Build the move of this field.
10245     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10246                                             To, From,
10247                                             /*CopyingBaseSubobject=*/false,
10248                                             /*Copying=*/false);
10249     if (Move.isInvalid()) {
10250       Diag(CurrentLocation, diag::note_member_synthesized_at)
10251         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10252       MoveAssignOperator->setInvalidDecl();
10253       return;
10254     }
10255 
10256     // Success! Record the copy.
10257     Statements.push_back(Move.getAs<Stmt>());
10258   }
10259 
10260   if (!Invalid) {
10261     // Add a "return *this;"
10262     ExprResult ThisObj =
10263         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10264 
10265     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10266     if (Return.isInvalid())
10267       Invalid = true;
10268     else {
10269       Statements.push_back(Return.getAs<Stmt>());
10270 
10271       if (Trap.hasErrorOccurred()) {
10272         Diag(CurrentLocation, diag::note_member_synthesized_at)
10273           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10274         Invalid = true;
10275       }
10276     }
10277   }
10278 
10279   if (Invalid) {
10280     MoveAssignOperator->setInvalidDecl();
10281     return;
10282   }
10283 
10284   StmtResult Body;
10285   {
10286     CompoundScopeRAII CompoundScope(*this);
10287     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10288                              /*isStmtExpr=*/false);
10289     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10290   }
10291   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10292 
10293   if (ASTMutationListener *L = getASTMutationListener()) {
10294     L->CompletedImplicitDefinition(MoveAssignOperator);
10295   }
10296 }
10297 
10298 Sema::ImplicitExceptionSpecification
10299 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10300   CXXRecordDecl *ClassDecl = MD->getParent();
10301 
10302   ImplicitExceptionSpecification ExceptSpec(*this);
10303   if (ClassDecl->isInvalidDecl())
10304     return ExceptSpec;
10305 
10306   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10307   assert(T->getNumParams() >= 1 && "not a copy ctor");
10308   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10309 
10310   // C++ [except.spec]p14:
10311   //   An implicitly declared special member function (Clause 12) shall have an
10312   //   exception-specification. [...]
10313   for (const auto &Base : ClassDecl->bases()) {
10314     // Virtual bases are handled below.
10315     if (Base.isVirtual())
10316       continue;
10317 
10318     CXXRecordDecl *BaseClassDecl
10319       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10320     if (CXXConstructorDecl *CopyConstructor =
10321           LookupCopyingConstructor(BaseClassDecl, Quals))
10322       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10323   }
10324   for (const auto &Base : ClassDecl->vbases()) {
10325     CXXRecordDecl *BaseClassDecl
10326       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10327     if (CXXConstructorDecl *CopyConstructor =
10328           LookupCopyingConstructor(BaseClassDecl, Quals))
10329       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10330   }
10331   for (const auto *Field : ClassDecl->fields()) {
10332     QualType FieldType = Context.getBaseElementType(Field->getType());
10333     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10334       if (CXXConstructorDecl *CopyConstructor =
10335               LookupCopyingConstructor(FieldClassDecl,
10336                                        Quals | FieldType.getCVRQualifiers()))
10337       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10338     }
10339   }
10340 
10341   return ExceptSpec;
10342 }
10343 
10344 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10345                                                     CXXRecordDecl *ClassDecl) {
10346   // C++ [class.copy]p4:
10347   //   If the class definition does not explicitly declare a copy
10348   //   constructor, one is declared implicitly.
10349   assert(ClassDecl->needsImplicitCopyConstructor());
10350 
10351   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10352   if (DSM.isAlreadyBeingDeclared())
10353     return nullptr;
10354 
10355   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10356   QualType ArgType = ClassType;
10357   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10358   if (Const)
10359     ArgType = ArgType.withConst();
10360   ArgType = Context.getLValueReferenceType(ArgType);
10361 
10362   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10363                                                      CXXCopyConstructor,
10364                                                      Const);
10365 
10366   DeclarationName Name
10367     = Context.DeclarationNames.getCXXConstructorName(
10368                                            Context.getCanonicalType(ClassType));
10369   SourceLocation ClassLoc = ClassDecl->getLocation();
10370   DeclarationNameInfo NameInfo(Name, ClassLoc);
10371 
10372   //   An implicitly-declared copy constructor is an inline public
10373   //   member of its class.
10374   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10375       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10376       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10377       Constexpr);
10378   CopyConstructor->setAccess(AS_public);
10379   CopyConstructor->setDefaulted();
10380 
10381   // Build an exception specification pointing back at this member.
10382   FunctionProtoType::ExtProtoInfo EPI =
10383       getImplicitMethodEPI(*this, CopyConstructor);
10384   CopyConstructor->setType(
10385       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10386 
10387   // Add the parameter to the constructor.
10388   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10389                                                ClassLoc, ClassLoc,
10390                                                /*IdentifierInfo=*/nullptr,
10391                                                ArgType, /*TInfo=*/nullptr,
10392                                                SC_None, nullptr);
10393   CopyConstructor->setParams(FromParam);
10394 
10395   CopyConstructor->setTrivial(
10396     ClassDecl->needsOverloadResolutionForCopyConstructor()
10397       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10398       : ClassDecl->hasTrivialCopyConstructor());
10399 
10400   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10401     SetDeclDeleted(CopyConstructor, ClassLoc);
10402 
10403   // Note that we have declared this constructor.
10404   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10405 
10406   if (Scope *S = getScopeForContext(ClassDecl))
10407     PushOnScopeChains(CopyConstructor, S, false);
10408   ClassDecl->addDecl(CopyConstructor);
10409 
10410   return CopyConstructor;
10411 }
10412 
10413 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10414                                    CXXConstructorDecl *CopyConstructor) {
10415   assert((CopyConstructor->isDefaulted() &&
10416           CopyConstructor->isCopyConstructor() &&
10417           !CopyConstructor->doesThisDeclarationHaveABody() &&
10418           !CopyConstructor->isDeleted()) &&
10419          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10420 
10421   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10422   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10423 
10424   // C++11 [class.copy]p7:
10425   //   The [definition of an implicitly declared copy constructor] is
10426   //   deprecated if the class has a user-declared copy assignment operator
10427   //   or a user-declared destructor.
10428   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10429     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10430 
10431   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10432   DiagnosticErrorTrap Trap(Diags);
10433 
10434   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10435       Trap.hasErrorOccurred()) {
10436     Diag(CurrentLocation, diag::note_member_synthesized_at)
10437       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10438     CopyConstructor->setInvalidDecl();
10439   }  else {
10440     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10441                              ? CopyConstructor->getLocEnd()
10442                              : CopyConstructor->getLocation();
10443     Sema::CompoundScopeRAII CompoundScope(*this);
10444     CopyConstructor->setBody(
10445         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10446   }
10447 
10448   CopyConstructor->markUsed(Context);
10449   MarkVTableUsed(CurrentLocation, ClassDecl);
10450 
10451   if (ASTMutationListener *L = getASTMutationListener()) {
10452     L->CompletedImplicitDefinition(CopyConstructor);
10453   }
10454 }
10455 
10456 Sema::ImplicitExceptionSpecification
10457 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10458   CXXRecordDecl *ClassDecl = MD->getParent();
10459 
10460   // C++ [except.spec]p14:
10461   //   An implicitly declared special member function (Clause 12) shall have an
10462   //   exception-specification. [...]
10463   ImplicitExceptionSpecification ExceptSpec(*this);
10464   if (ClassDecl->isInvalidDecl())
10465     return ExceptSpec;
10466 
10467   // Direct base-class constructors.
10468   for (const auto &B : ClassDecl->bases()) {
10469     if (B.isVirtual()) // Handled below.
10470       continue;
10471 
10472     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10473       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10474       CXXConstructorDecl *Constructor =
10475           LookupMovingConstructor(BaseClassDecl, 0);
10476       // If this is a deleted function, add it anyway. This might be conformant
10477       // with the standard. This might not. I'm not sure. It might not matter.
10478       if (Constructor)
10479         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10480     }
10481   }
10482 
10483   // Virtual base-class constructors.
10484   for (const auto &B : ClassDecl->vbases()) {
10485     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10486       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10487       CXXConstructorDecl *Constructor =
10488           LookupMovingConstructor(BaseClassDecl, 0);
10489       // If this is a deleted function, add it anyway. This might be conformant
10490       // with the standard. This might not. I'm not sure. It might not matter.
10491       if (Constructor)
10492         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10493     }
10494   }
10495 
10496   // Field constructors.
10497   for (const auto *F : ClassDecl->fields()) {
10498     QualType FieldType = Context.getBaseElementType(F->getType());
10499     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10500       CXXConstructorDecl *Constructor =
10501           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10502       // If this is a deleted function, add it anyway. This might be conformant
10503       // with the standard. This might not. I'm not sure. It might not matter.
10504       // In particular, the problem is that this function never gets called. It
10505       // might just be ill-formed because this function attempts to refer to
10506       // a deleted function here.
10507       if (Constructor)
10508         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10509     }
10510   }
10511 
10512   return ExceptSpec;
10513 }
10514 
10515 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10516                                                     CXXRecordDecl *ClassDecl) {
10517   assert(ClassDecl->needsImplicitMoveConstructor());
10518 
10519   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10520   if (DSM.isAlreadyBeingDeclared())
10521     return nullptr;
10522 
10523   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10524   QualType ArgType = Context.getRValueReferenceType(ClassType);
10525 
10526   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10527                                                      CXXMoveConstructor,
10528                                                      false);
10529 
10530   DeclarationName Name
10531     = Context.DeclarationNames.getCXXConstructorName(
10532                                            Context.getCanonicalType(ClassType));
10533   SourceLocation ClassLoc = ClassDecl->getLocation();
10534   DeclarationNameInfo NameInfo(Name, ClassLoc);
10535 
10536   // C++11 [class.copy]p11:
10537   //   An implicitly-declared copy/move constructor is an inline public
10538   //   member of its class.
10539   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10540       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10541       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10542       Constexpr);
10543   MoveConstructor->setAccess(AS_public);
10544   MoveConstructor->setDefaulted();
10545 
10546   // Build an exception specification pointing back at this member.
10547   FunctionProtoType::ExtProtoInfo EPI =
10548       getImplicitMethodEPI(*this, MoveConstructor);
10549   MoveConstructor->setType(
10550       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10551 
10552   // Add the parameter to the constructor.
10553   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10554                                                ClassLoc, ClassLoc,
10555                                                /*IdentifierInfo=*/nullptr,
10556                                                ArgType, /*TInfo=*/nullptr,
10557                                                SC_None, nullptr);
10558   MoveConstructor->setParams(FromParam);
10559 
10560   MoveConstructor->setTrivial(
10561     ClassDecl->needsOverloadResolutionForMoveConstructor()
10562       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10563       : ClassDecl->hasTrivialMoveConstructor());
10564 
10565   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10566     ClassDecl->setImplicitMoveConstructorIsDeleted();
10567     SetDeclDeleted(MoveConstructor, ClassLoc);
10568   }
10569 
10570   // Note that we have declared this constructor.
10571   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10572 
10573   if (Scope *S = getScopeForContext(ClassDecl))
10574     PushOnScopeChains(MoveConstructor, S, false);
10575   ClassDecl->addDecl(MoveConstructor);
10576 
10577   return MoveConstructor;
10578 }
10579 
10580 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10581                                    CXXConstructorDecl *MoveConstructor) {
10582   assert((MoveConstructor->isDefaulted() &&
10583           MoveConstructor->isMoveConstructor() &&
10584           !MoveConstructor->doesThisDeclarationHaveABody() &&
10585           !MoveConstructor->isDeleted()) &&
10586          "DefineImplicitMoveConstructor - call it for implicit move ctor");
10587 
10588   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10589   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10590 
10591   SynthesizedFunctionScope Scope(*this, MoveConstructor);
10592   DiagnosticErrorTrap Trap(Diags);
10593 
10594   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10595       Trap.hasErrorOccurred()) {
10596     Diag(CurrentLocation, diag::note_member_synthesized_at)
10597       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10598     MoveConstructor->setInvalidDecl();
10599   }  else {
10600     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10601                              ? MoveConstructor->getLocEnd()
10602                              : MoveConstructor->getLocation();
10603     Sema::CompoundScopeRAII CompoundScope(*this);
10604     MoveConstructor->setBody(ActOnCompoundStmt(
10605         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
10606   }
10607 
10608   MoveConstructor->markUsed(Context);
10609   MarkVTableUsed(CurrentLocation, ClassDecl);
10610 
10611   if (ASTMutationListener *L = getASTMutationListener()) {
10612     L->CompletedImplicitDefinition(MoveConstructor);
10613   }
10614 }
10615 
10616 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10617   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10618 }
10619 
10620 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10621                             SourceLocation CurrentLocation,
10622                             CXXConversionDecl *Conv) {
10623   CXXRecordDecl *Lambda = Conv->getParent();
10624   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10625   // If we are defining a specialization of a conversion to function-ptr
10626   // cache the deduced template arguments for this specialization
10627   // so that we can use them to retrieve the corresponding call-operator
10628   // and static-invoker.
10629   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10630 
10631   // Retrieve the corresponding call-operator specialization.
10632   if (Lambda->isGenericLambda()) {
10633     assert(Conv->isFunctionTemplateSpecialization());
10634     FunctionTemplateDecl *CallOpTemplate =
10635         CallOp->getDescribedFunctionTemplate();
10636     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10637     void *InsertPos = nullptr;
10638     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10639                                                 DeducedTemplateArgs->asArray(),
10640                                                 InsertPos);
10641     assert(CallOpSpec &&
10642           "Conversion operator must have a corresponding call operator");
10643     CallOp = cast<CXXMethodDecl>(CallOpSpec);
10644   }
10645   // Mark the call operator referenced (and add to pending instantiations
10646   // if necessary).
10647   // For both the conversion and static-invoker template specializations
10648   // we construct their body's in this function, so no need to add them
10649   // to the PendingInstantiations.
10650   MarkFunctionReferenced(CurrentLocation, CallOp);
10651 
10652   SynthesizedFunctionScope Scope(*this, Conv);
10653   DiagnosticErrorTrap Trap(Diags);
10654 
10655   // Retrieve the static invoker...
10656   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10657   // ... and get the corresponding specialization for a generic lambda.
10658   if (Lambda->isGenericLambda()) {
10659     assert(DeducedTemplateArgs &&
10660       "Must have deduced template arguments from Conversion Operator");
10661     FunctionTemplateDecl *InvokeTemplate =
10662                           Invoker->getDescribedFunctionTemplate();
10663     void *InsertPos = nullptr;
10664     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10665                                                 DeducedTemplateArgs->asArray(),
10666                                                 InsertPos);
10667     assert(InvokeSpec &&
10668       "Must have a corresponding static invoker specialization");
10669     Invoker = cast<CXXMethodDecl>(InvokeSpec);
10670   }
10671   // Construct the body of the conversion function { return __invoke; }.
10672   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10673                                         VK_LValue, Conv->getLocation()).get();
10674    assert(FunctionRef && "Can't refer to __invoke function?");
10675    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
10676    Conv->setBody(new (Context) CompoundStmt(Context, Return,
10677                                             Conv->getLocation(),
10678                                             Conv->getLocation()));
10679 
10680   Conv->markUsed(Context);
10681   Conv->setReferenced();
10682 
10683   // Fill in the __invoke function with a dummy implementation. IR generation
10684   // will fill in the actual details.
10685   Invoker->markUsed(Context);
10686   Invoker->setReferenced();
10687   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10688 
10689   if (ASTMutationListener *L = getASTMutationListener()) {
10690     L->CompletedImplicitDefinition(Conv);
10691     L->CompletedImplicitDefinition(Invoker);
10692    }
10693 }
10694 
10695 
10696 
10697 void Sema::DefineImplicitLambdaToBlockPointerConversion(
10698        SourceLocation CurrentLocation,
10699        CXXConversionDecl *Conv)
10700 {
10701   assert(!Conv->getParent()->isGenericLambda());
10702 
10703   Conv->markUsed(Context);
10704 
10705   SynthesizedFunctionScope Scope(*this, Conv);
10706   DiagnosticErrorTrap Trap(Diags);
10707 
10708   // Copy-initialize the lambda object as needed to capture it.
10709   Expr *This = ActOnCXXThis(CurrentLocation).get();
10710   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
10711 
10712   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10713                                                         Conv->getLocation(),
10714                                                         Conv, DerefThis);
10715 
10716   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10717   // behavior.  Note that only the general conversion function does this
10718   // (since it's unusable otherwise); in the case where we inline the
10719   // block literal, it has block literal lifetime semantics.
10720   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10721     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10722                                           CK_CopyAndAutoreleaseBlockObject,
10723                                           BuildBlock.get(), nullptr, VK_RValue);
10724 
10725   if (BuildBlock.isInvalid()) {
10726     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10727     Conv->setInvalidDecl();
10728     return;
10729   }
10730 
10731   // Create the return statement that returns the block from the conversion
10732   // function.
10733   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
10734   if (Return.isInvalid()) {
10735     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10736     Conv->setInvalidDecl();
10737     return;
10738   }
10739 
10740   // Set the body of the conversion function.
10741   Stmt *ReturnS = Return.get();
10742   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10743                                            Conv->getLocation(),
10744                                            Conv->getLocation()));
10745 
10746   // We're done; notify the mutation listener, if any.
10747   if (ASTMutationListener *L = getASTMutationListener()) {
10748     L->CompletedImplicitDefinition(Conv);
10749   }
10750 }
10751 
10752 /// \brief Determine whether the given list arguments contains exactly one
10753 /// "real" (non-default) argument.
10754 static bool hasOneRealArgument(MultiExprArg Args) {
10755   switch (Args.size()) {
10756   case 0:
10757     return false;
10758 
10759   default:
10760     if (!Args[1]->isDefaultArgument())
10761       return false;
10762 
10763     // fall through
10764   case 1:
10765     return !Args[0]->isDefaultArgument();
10766   }
10767 
10768   return false;
10769 }
10770 
10771 ExprResult
10772 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10773                             CXXConstructorDecl *Constructor,
10774                             MultiExprArg ExprArgs,
10775                             bool HadMultipleCandidates,
10776                             bool IsListInitialization,
10777                             bool IsStdInitListInitialization,
10778                             bool RequiresZeroInit,
10779                             unsigned ConstructKind,
10780                             SourceRange ParenRange) {
10781   bool Elidable = false;
10782 
10783   // C++0x [class.copy]p34:
10784   //   When certain criteria are met, an implementation is allowed to
10785   //   omit the copy/move construction of a class object, even if the
10786   //   copy/move constructor and/or destructor for the object have
10787   //   side effects. [...]
10788   //     - when a temporary class object that has not been bound to a
10789   //       reference (12.2) would be copied/moved to a class object
10790   //       with the same cv-unqualified type, the copy/move operation
10791   //       can be omitted by constructing the temporary object
10792   //       directly into the target of the omitted copy/move
10793   if (ConstructKind == CXXConstructExpr::CK_Complete &&
10794       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10795     Expr *SubExpr = ExprArgs[0];
10796     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10797   }
10798 
10799   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10800                                Elidable, ExprArgs, HadMultipleCandidates,
10801                                IsListInitialization,
10802                                IsStdInitListInitialization, RequiresZeroInit,
10803                                ConstructKind, ParenRange);
10804 }
10805 
10806 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
10807 /// including handling of its default argument expressions.
10808 ExprResult
10809 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10810                             CXXConstructorDecl *Constructor, bool Elidable,
10811                             MultiExprArg ExprArgs,
10812                             bool HadMultipleCandidates,
10813                             bool IsListInitialization,
10814                             bool IsStdInitListInitialization,
10815                             bool RequiresZeroInit,
10816                             unsigned ConstructKind,
10817                             SourceRange ParenRange) {
10818   MarkFunctionReferenced(ConstructLoc, Constructor);
10819   return CXXConstructExpr::Create(
10820       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
10821       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
10822       RequiresZeroInit,
10823       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10824       ParenRange);
10825 }
10826 
10827 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10828   if (VD->isInvalidDecl()) return;
10829 
10830   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10831   if (ClassDecl->isInvalidDecl()) return;
10832   if (ClassDecl->hasIrrelevantDestructor()) return;
10833   if (ClassDecl->isDependentContext()) return;
10834 
10835   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10836   MarkFunctionReferenced(VD->getLocation(), Destructor);
10837   CheckDestructorAccess(VD->getLocation(), Destructor,
10838                         PDiag(diag::err_access_dtor_var)
10839                         << VD->getDeclName()
10840                         << VD->getType());
10841   DiagnoseUseOfDecl(Destructor, VD->getLocation());
10842 
10843   if (Destructor->isTrivial()) return;
10844   if (!VD->hasGlobalStorage()) return;
10845 
10846   // Emit warning for non-trivial dtor in global scope (a real global,
10847   // class-static, function-static).
10848   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10849 
10850   // TODO: this should be re-enabled for static locals by !CXAAtExit
10851   if (!VD->isStaticLocal())
10852     Diag(VD->getLocation(), diag::warn_global_destructor);
10853 }
10854 
10855 /// \brief Given a constructor and the set of arguments provided for the
10856 /// constructor, convert the arguments and add any required default arguments
10857 /// to form a proper call to this constructor.
10858 ///
10859 /// \returns true if an error occurred, false otherwise.
10860 bool
10861 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10862                               MultiExprArg ArgsPtr,
10863                               SourceLocation Loc,
10864                               SmallVectorImpl<Expr*> &ConvertedArgs,
10865                               bool AllowExplicit,
10866                               bool IsListInitialization) {
10867   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10868   unsigned NumArgs = ArgsPtr.size();
10869   Expr **Args = ArgsPtr.data();
10870 
10871   const FunctionProtoType *Proto
10872     = Constructor->getType()->getAs<FunctionProtoType>();
10873   assert(Proto && "Constructor without a prototype?");
10874   unsigned NumParams = Proto->getNumParams();
10875 
10876   // If too few arguments are available, we'll fill in the rest with defaults.
10877   if (NumArgs < NumParams)
10878     ConvertedArgs.reserve(NumParams);
10879   else
10880     ConvertedArgs.reserve(NumArgs);
10881 
10882   VariadicCallType CallType =
10883     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10884   SmallVector<Expr *, 8> AllArgs;
10885   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10886                                         Proto, 0,
10887                                         llvm::makeArrayRef(Args, NumArgs),
10888                                         AllArgs,
10889                                         CallType, AllowExplicit,
10890                                         IsListInitialization);
10891   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10892 
10893   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10894 
10895   CheckConstructorCall(Constructor,
10896                        llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10897                                                         AllArgs.size()),
10898                        Proto, Loc);
10899 
10900   return Invalid;
10901 }
10902 
10903 static inline bool
10904 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10905                                        const FunctionDecl *FnDecl) {
10906   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10907   if (isa<NamespaceDecl>(DC)) {
10908     return SemaRef.Diag(FnDecl->getLocation(),
10909                         diag::err_operator_new_delete_declared_in_namespace)
10910       << FnDecl->getDeclName();
10911   }
10912 
10913   if (isa<TranslationUnitDecl>(DC) &&
10914       FnDecl->getStorageClass() == SC_Static) {
10915     return SemaRef.Diag(FnDecl->getLocation(),
10916                         diag::err_operator_new_delete_declared_static)
10917       << FnDecl->getDeclName();
10918   }
10919 
10920   return false;
10921 }
10922 
10923 static inline bool
10924 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10925                             CanQualType ExpectedResultType,
10926                             CanQualType ExpectedFirstParamType,
10927                             unsigned DependentParamTypeDiag,
10928                             unsigned InvalidParamTypeDiag) {
10929   QualType ResultType =
10930       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
10931 
10932   // Check that the result type is not dependent.
10933   if (ResultType->isDependentType())
10934     return SemaRef.Diag(FnDecl->getLocation(),
10935                         diag::err_operator_new_delete_dependent_result_type)
10936     << FnDecl->getDeclName() << ExpectedResultType;
10937 
10938   // Check that the result type is what we expect.
10939   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10940     return SemaRef.Diag(FnDecl->getLocation(),
10941                         diag::err_operator_new_delete_invalid_result_type)
10942     << FnDecl->getDeclName() << ExpectedResultType;
10943 
10944   // A function template must have at least 2 parameters.
10945   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10946     return SemaRef.Diag(FnDecl->getLocation(),
10947                       diag::err_operator_new_delete_template_too_few_parameters)
10948         << FnDecl->getDeclName();
10949 
10950   // The function decl must have at least 1 parameter.
10951   if (FnDecl->getNumParams() == 0)
10952     return SemaRef.Diag(FnDecl->getLocation(),
10953                         diag::err_operator_new_delete_too_few_parameters)
10954       << FnDecl->getDeclName();
10955 
10956   // Check the first parameter type is not dependent.
10957   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10958   if (FirstParamType->isDependentType())
10959     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10960       << FnDecl->getDeclName() << ExpectedFirstParamType;
10961 
10962   // Check that the first parameter type is what we expect.
10963   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10964       ExpectedFirstParamType)
10965     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10966     << FnDecl->getDeclName() << ExpectedFirstParamType;
10967 
10968   return false;
10969 }
10970 
10971 static bool
10972 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10973   // C++ [basic.stc.dynamic.allocation]p1:
10974   //   A program is ill-formed if an allocation function is declared in a
10975   //   namespace scope other than global scope or declared static in global
10976   //   scope.
10977   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10978     return true;
10979 
10980   CanQualType SizeTy =
10981     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10982 
10983   // C++ [basic.stc.dynamic.allocation]p1:
10984   //  The return type shall be void*. The first parameter shall have type
10985   //  std::size_t.
10986   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10987                                   SizeTy,
10988                                   diag::err_operator_new_dependent_param_type,
10989                                   diag::err_operator_new_param_type))
10990     return true;
10991 
10992   // C++ [basic.stc.dynamic.allocation]p1:
10993   //  The first parameter shall not have an associated default argument.
10994   if (FnDecl->getParamDecl(0)->hasDefaultArg())
10995     return SemaRef.Diag(FnDecl->getLocation(),
10996                         diag::err_operator_new_default_arg)
10997       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10998 
10999   return false;
11000 }
11001 
11002 static bool
11003 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11004   // C++ [basic.stc.dynamic.deallocation]p1:
11005   //   A program is ill-formed if deallocation functions are declared in a
11006   //   namespace scope other than global scope or declared static in global
11007   //   scope.
11008   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11009     return true;
11010 
11011   // C++ [basic.stc.dynamic.deallocation]p2:
11012   //   Each deallocation function shall return void and its first parameter
11013   //   shall be void*.
11014   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11015                                   SemaRef.Context.VoidPtrTy,
11016                                  diag::err_operator_delete_dependent_param_type,
11017                                  diag::err_operator_delete_param_type))
11018     return true;
11019 
11020   return false;
11021 }
11022 
11023 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11024 /// of this overloaded operator is well-formed. If so, returns false;
11025 /// otherwise, emits appropriate diagnostics and returns true.
11026 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11027   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11028          "Expected an overloaded operator declaration");
11029 
11030   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11031 
11032   // C++ [over.oper]p5:
11033   //   The allocation and deallocation functions, operator new,
11034   //   operator new[], operator delete and operator delete[], are
11035   //   described completely in 3.7.3. The attributes and restrictions
11036   //   found in the rest of this subclause do not apply to them unless
11037   //   explicitly stated in 3.7.3.
11038   if (Op == OO_Delete || Op == OO_Array_Delete)
11039     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11040 
11041   if (Op == OO_New || Op == OO_Array_New)
11042     return CheckOperatorNewDeclaration(*this, FnDecl);
11043 
11044   // C++ [over.oper]p6:
11045   //   An operator function shall either be a non-static member
11046   //   function or be a non-member function and have at least one
11047   //   parameter whose type is a class, a reference to a class, an
11048   //   enumeration, or a reference to an enumeration.
11049   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11050     if (MethodDecl->isStatic())
11051       return Diag(FnDecl->getLocation(),
11052                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11053   } else {
11054     bool ClassOrEnumParam = false;
11055     for (auto Param : FnDecl->params()) {
11056       QualType ParamType = Param->getType().getNonReferenceType();
11057       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11058           ParamType->isEnumeralType()) {
11059         ClassOrEnumParam = true;
11060         break;
11061       }
11062     }
11063 
11064     if (!ClassOrEnumParam)
11065       return Diag(FnDecl->getLocation(),
11066                   diag::err_operator_overload_needs_class_or_enum)
11067         << FnDecl->getDeclName();
11068   }
11069 
11070   // C++ [over.oper]p8:
11071   //   An operator function cannot have default arguments (8.3.6),
11072   //   except where explicitly stated below.
11073   //
11074   // Only the function-call operator allows default arguments
11075   // (C++ [over.call]p1).
11076   if (Op != OO_Call) {
11077     for (auto Param : FnDecl->params()) {
11078       if (Param->hasDefaultArg())
11079         return Diag(Param->getLocation(),
11080                     diag::err_operator_overload_default_arg)
11081           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11082     }
11083   }
11084 
11085   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11086     { false, false, false }
11087 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11088     , { Unary, Binary, MemberOnly }
11089 #include "clang/Basic/OperatorKinds.def"
11090   };
11091 
11092   bool CanBeUnaryOperator = OperatorUses[Op][0];
11093   bool CanBeBinaryOperator = OperatorUses[Op][1];
11094   bool MustBeMemberOperator = OperatorUses[Op][2];
11095 
11096   // C++ [over.oper]p8:
11097   //   [...] Operator functions cannot have more or fewer parameters
11098   //   than the number required for the corresponding operator, as
11099   //   described in the rest of this subclause.
11100   unsigned NumParams = FnDecl->getNumParams()
11101                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11102   if (Op != OO_Call &&
11103       ((NumParams == 1 && !CanBeUnaryOperator) ||
11104        (NumParams == 2 && !CanBeBinaryOperator) ||
11105        (NumParams < 1) || (NumParams > 2))) {
11106     // We have the wrong number of parameters.
11107     unsigned ErrorKind;
11108     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11109       ErrorKind = 2;  // 2 -> unary or binary.
11110     } else if (CanBeUnaryOperator) {
11111       ErrorKind = 0;  // 0 -> unary
11112     } else {
11113       assert(CanBeBinaryOperator &&
11114              "All non-call overloaded operators are unary or binary!");
11115       ErrorKind = 1;  // 1 -> binary
11116     }
11117 
11118     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11119       << FnDecl->getDeclName() << NumParams << ErrorKind;
11120   }
11121 
11122   // Overloaded operators other than operator() cannot be variadic.
11123   if (Op != OO_Call &&
11124       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11125     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11126       << FnDecl->getDeclName();
11127   }
11128 
11129   // Some operators must be non-static member functions.
11130   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11131     return Diag(FnDecl->getLocation(),
11132                 diag::err_operator_overload_must_be_member)
11133       << FnDecl->getDeclName();
11134   }
11135 
11136   // C++ [over.inc]p1:
11137   //   The user-defined function called operator++ implements the
11138   //   prefix and postfix ++ operator. If this function is a member
11139   //   function with no parameters, or a non-member function with one
11140   //   parameter of class or enumeration type, it defines the prefix
11141   //   increment operator ++ for objects of that type. If the function
11142   //   is a member function with one parameter (which shall be of type
11143   //   int) or a non-member function with two parameters (the second
11144   //   of which shall be of type int), it defines the postfix
11145   //   increment operator ++ for objects of that type.
11146   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11147     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11148     QualType ParamType = LastParam->getType();
11149 
11150     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11151         !ParamType->isDependentType())
11152       return Diag(LastParam->getLocation(),
11153                   diag::err_operator_overload_post_incdec_must_be_int)
11154         << LastParam->getType() << (Op == OO_MinusMinus);
11155   }
11156 
11157   return false;
11158 }
11159 
11160 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11161 /// of this literal operator function is well-formed. If so, returns
11162 /// false; otherwise, emits appropriate diagnostics and returns true.
11163 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11164   if (isa<CXXMethodDecl>(FnDecl)) {
11165     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11166       << FnDecl->getDeclName();
11167     return true;
11168   }
11169 
11170   if (FnDecl->isExternC()) {
11171     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11172     return true;
11173   }
11174 
11175   bool Valid = false;
11176 
11177   // This might be the definition of a literal operator template.
11178   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11179   // This might be a specialization of a literal operator template.
11180   if (!TpDecl)
11181     TpDecl = FnDecl->getPrimaryTemplate();
11182 
11183   // template <char...> type operator "" name() and
11184   // template <class T, T...> type operator "" name() are the only valid
11185   // template signatures, and the only valid signatures with no parameters.
11186   if (TpDecl) {
11187     if (FnDecl->param_size() == 0) {
11188       // Must have one or two template parameters
11189       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11190       if (Params->size() == 1) {
11191         NonTypeTemplateParmDecl *PmDecl =
11192           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11193 
11194         // The template parameter must be a char parameter pack.
11195         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11196             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11197           Valid = true;
11198       } else if (Params->size() == 2) {
11199         TemplateTypeParmDecl *PmType =
11200           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11201         NonTypeTemplateParmDecl *PmArgs =
11202           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11203 
11204         // The second template parameter must be a parameter pack with the
11205         // first template parameter as its type.
11206         if (PmType && PmArgs &&
11207             !PmType->isTemplateParameterPack() &&
11208             PmArgs->isTemplateParameterPack()) {
11209           const TemplateTypeParmType *TArgs =
11210             PmArgs->getType()->getAs<TemplateTypeParmType>();
11211           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11212               TArgs->getIndex() == PmType->getIndex()) {
11213             Valid = true;
11214             if (ActiveTemplateInstantiations.empty())
11215               Diag(FnDecl->getLocation(),
11216                    diag::ext_string_literal_operator_template);
11217           }
11218         }
11219       }
11220     }
11221   } else if (FnDecl->param_size()) {
11222     // Check the first parameter
11223     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11224 
11225     QualType T = (*Param)->getType().getUnqualifiedType();
11226 
11227     // unsigned long long int, long double, and any character type are allowed
11228     // as the only parameters.
11229     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11230         Context.hasSameType(T, Context.LongDoubleTy) ||
11231         Context.hasSameType(T, Context.CharTy) ||
11232         Context.hasSameType(T, Context.WideCharTy) ||
11233         Context.hasSameType(T, Context.Char16Ty) ||
11234         Context.hasSameType(T, Context.Char32Ty)) {
11235       if (++Param == FnDecl->param_end())
11236         Valid = true;
11237       goto FinishedParams;
11238     }
11239 
11240     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11241     const PointerType *PT = T->getAs<PointerType>();
11242     if (!PT)
11243       goto FinishedParams;
11244     T = PT->getPointeeType();
11245     if (!T.isConstQualified() || T.isVolatileQualified())
11246       goto FinishedParams;
11247     T = T.getUnqualifiedType();
11248 
11249     // Move on to the second parameter;
11250     ++Param;
11251 
11252     // If there is no second parameter, the first must be a const char *
11253     if (Param == FnDecl->param_end()) {
11254       if (Context.hasSameType(T, Context.CharTy))
11255         Valid = true;
11256       goto FinishedParams;
11257     }
11258 
11259     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11260     // are allowed as the first parameter to a two-parameter function
11261     if (!(Context.hasSameType(T, Context.CharTy) ||
11262           Context.hasSameType(T, Context.WideCharTy) ||
11263           Context.hasSameType(T, Context.Char16Ty) ||
11264           Context.hasSameType(T, Context.Char32Ty)))
11265       goto FinishedParams;
11266 
11267     // The second and final parameter must be an std::size_t
11268     T = (*Param)->getType().getUnqualifiedType();
11269     if (Context.hasSameType(T, Context.getSizeType()) &&
11270         ++Param == FnDecl->param_end())
11271       Valid = true;
11272   }
11273 
11274   // FIXME: This diagnostic is absolutely terrible.
11275 FinishedParams:
11276   if (!Valid) {
11277     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11278       << FnDecl->getDeclName();
11279     return true;
11280   }
11281 
11282   // A parameter-declaration-clause containing a default argument is not
11283   // equivalent to any of the permitted forms.
11284   for (auto Param : FnDecl->params()) {
11285     if (Param->hasDefaultArg()) {
11286       Diag(Param->getDefaultArgRange().getBegin(),
11287            diag::err_literal_operator_default_argument)
11288         << Param->getDefaultArgRange();
11289       break;
11290     }
11291   }
11292 
11293   StringRef LiteralName
11294     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11295   if (LiteralName[0] != '_') {
11296     // C++11 [usrlit.suffix]p1:
11297     //   Literal suffix identifiers that do not start with an underscore
11298     //   are reserved for future standardization.
11299     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11300       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11301   }
11302 
11303   return false;
11304 }
11305 
11306 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11307 /// linkage specification, including the language and (if present)
11308 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11309 /// language string literal. LBraceLoc, if valid, provides the location of
11310 /// the '{' brace. Otherwise, this linkage specification does not
11311 /// have any braces.
11312 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11313                                            Expr *LangStr,
11314                                            SourceLocation LBraceLoc) {
11315   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11316   if (!Lit->isAscii()) {
11317     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11318       << LangStr->getSourceRange();
11319     return nullptr;
11320   }
11321 
11322   StringRef Lang = Lit->getString();
11323   LinkageSpecDecl::LanguageIDs Language;
11324   if (Lang == "C")
11325     Language = LinkageSpecDecl::lang_c;
11326   else if (Lang == "C++")
11327     Language = LinkageSpecDecl::lang_cxx;
11328   else {
11329     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11330       << LangStr->getSourceRange();
11331     return nullptr;
11332   }
11333 
11334   // FIXME: Add all the various semantics of linkage specifications
11335 
11336   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11337                                                LangStr->getExprLoc(), Language,
11338                                                LBraceLoc.isValid());
11339   CurContext->addDecl(D);
11340   PushDeclContext(S, D);
11341   return D;
11342 }
11343 
11344 /// ActOnFinishLinkageSpecification - Complete the definition of
11345 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11346 /// valid, it's the position of the closing '}' brace in a linkage
11347 /// specification that uses braces.
11348 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11349                                             Decl *LinkageSpec,
11350                                             SourceLocation RBraceLoc) {
11351   if (RBraceLoc.isValid()) {
11352     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11353     LSDecl->setRBraceLoc(RBraceLoc);
11354   }
11355   PopDeclContext();
11356   return LinkageSpec;
11357 }
11358 
11359 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11360                                   AttributeList *AttrList,
11361                                   SourceLocation SemiLoc) {
11362   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11363   // Attribute declarations appertain to empty declaration so we handle
11364   // them here.
11365   if (AttrList)
11366     ProcessDeclAttributeList(S, ED, AttrList);
11367 
11368   CurContext->addDecl(ED);
11369   return ED;
11370 }
11371 
11372 /// \brief Perform semantic analysis for the variable declaration that
11373 /// occurs within a C++ catch clause, returning the newly-created
11374 /// variable.
11375 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11376                                          TypeSourceInfo *TInfo,
11377                                          SourceLocation StartLoc,
11378                                          SourceLocation Loc,
11379                                          IdentifierInfo *Name) {
11380   bool Invalid = false;
11381   QualType ExDeclType = TInfo->getType();
11382 
11383   // Arrays and functions decay.
11384   if (ExDeclType->isArrayType())
11385     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11386   else if (ExDeclType->isFunctionType())
11387     ExDeclType = Context.getPointerType(ExDeclType);
11388 
11389   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11390   // The exception-declaration shall not denote a pointer or reference to an
11391   // incomplete type, other than [cv] void*.
11392   // N2844 forbids rvalue references.
11393   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11394     Diag(Loc, diag::err_catch_rvalue_ref);
11395     Invalid = true;
11396   }
11397 
11398   QualType BaseType = ExDeclType;
11399   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11400   unsigned DK = diag::err_catch_incomplete;
11401   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11402     BaseType = Ptr->getPointeeType();
11403     Mode = 1;
11404     DK = diag::err_catch_incomplete_ptr;
11405   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11406     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11407     BaseType = Ref->getPointeeType();
11408     Mode = 2;
11409     DK = diag::err_catch_incomplete_ref;
11410   }
11411   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11412       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11413     Invalid = true;
11414 
11415   if (!Invalid && !ExDeclType->isDependentType() &&
11416       RequireNonAbstractType(Loc, ExDeclType,
11417                              diag::err_abstract_type_in_decl,
11418                              AbstractVariableType))
11419     Invalid = true;
11420 
11421   // Only the non-fragile NeXT runtime currently supports C++ catches
11422   // of ObjC types, and no runtime supports catching ObjC types by value.
11423   if (!Invalid && getLangOpts().ObjC1) {
11424     QualType T = ExDeclType;
11425     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11426       T = RT->getPointeeType();
11427 
11428     if (T->isObjCObjectType()) {
11429       Diag(Loc, diag::err_objc_object_catch);
11430       Invalid = true;
11431     } else if (T->isObjCObjectPointerType()) {
11432       // FIXME: should this be a test for macosx-fragile specifically?
11433       if (getLangOpts().ObjCRuntime.isFragile())
11434         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11435     }
11436   }
11437 
11438   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11439                                     ExDeclType, TInfo, SC_None);
11440   ExDecl->setExceptionVariable(true);
11441 
11442   // In ARC, infer 'retaining' for variables of retainable type.
11443   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11444     Invalid = true;
11445 
11446   if (!Invalid && !ExDeclType->isDependentType()) {
11447     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11448       // Insulate this from anything else we might currently be parsing.
11449       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11450 
11451       // C++ [except.handle]p16:
11452       //   The object declared in an exception-declaration or, if the
11453       //   exception-declaration does not specify a name, a temporary (12.2) is
11454       //   copy-initialized (8.5) from the exception object. [...]
11455       //   The object is destroyed when the handler exits, after the destruction
11456       //   of any automatic objects initialized within the handler.
11457       //
11458       // We just pretend to initialize the object with itself, then make sure
11459       // it can be destroyed later.
11460       QualType initType = ExDeclType;
11461 
11462       InitializedEntity entity =
11463         InitializedEntity::InitializeVariable(ExDecl);
11464       InitializationKind initKind =
11465         InitializationKind::CreateCopy(Loc, SourceLocation());
11466 
11467       Expr *opaqueValue =
11468         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11469       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11470       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11471       if (result.isInvalid())
11472         Invalid = true;
11473       else {
11474         // If the constructor used was non-trivial, set this as the
11475         // "initializer".
11476         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
11477         if (!construct->getConstructor()->isTrivial()) {
11478           Expr *init = MaybeCreateExprWithCleanups(construct);
11479           ExDecl->setInit(init);
11480         }
11481 
11482         // And make sure it's destructable.
11483         FinalizeVarWithDestructor(ExDecl, recordType);
11484       }
11485     }
11486   }
11487 
11488   if (Invalid)
11489     ExDecl->setInvalidDecl();
11490 
11491   return ExDecl;
11492 }
11493 
11494 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11495 /// handler.
11496 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11497   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11498   bool Invalid = D.isInvalidType();
11499 
11500   // Check for unexpanded parameter packs.
11501   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11502                                       UPPC_ExceptionType)) {
11503     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11504                                              D.getIdentifierLoc());
11505     Invalid = true;
11506   }
11507 
11508   IdentifierInfo *II = D.getIdentifier();
11509   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11510                                              LookupOrdinaryName,
11511                                              ForRedeclaration)) {
11512     // The scope should be freshly made just for us. There is just no way
11513     // it contains any previous declaration, except for function parameters in
11514     // a function-try-block's catch statement.
11515     assert(!S->isDeclScope(PrevDecl));
11516     if (isDeclInScope(PrevDecl, CurContext, S)) {
11517       Diag(D.getIdentifierLoc(), diag::err_redefinition)
11518         << D.getIdentifier();
11519       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11520       Invalid = true;
11521     } else if (PrevDecl->isTemplateParameter())
11522       // Maybe we will complain about the shadowed template parameter.
11523       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11524   }
11525 
11526   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11527     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11528       << D.getCXXScopeSpec().getRange();
11529     Invalid = true;
11530   }
11531 
11532   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11533                                               D.getLocStart(),
11534                                               D.getIdentifierLoc(),
11535                                               D.getIdentifier());
11536   if (Invalid)
11537     ExDecl->setInvalidDecl();
11538 
11539   // Add the exception declaration into this scope.
11540   if (II)
11541     PushOnScopeChains(ExDecl, S);
11542   else
11543     CurContext->addDecl(ExDecl);
11544 
11545   ProcessDeclAttributes(S, ExDecl, D);
11546   return ExDecl;
11547 }
11548 
11549 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11550                                          Expr *AssertExpr,
11551                                          Expr *AssertMessageExpr,
11552                                          SourceLocation RParenLoc) {
11553   StringLiteral *AssertMessage =
11554       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
11555 
11556   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11557     return nullptr;
11558 
11559   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11560                                       AssertMessage, RParenLoc, false);
11561 }
11562 
11563 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11564                                          Expr *AssertExpr,
11565                                          StringLiteral *AssertMessage,
11566                                          SourceLocation RParenLoc,
11567                                          bool Failed) {
11568   assert(AssertExpr != nullptr && "Expected non-null condition");
11569   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11570       !Failed) {
11571     // In a static_assert-declaration, the constant-expression shall be a
11572     // constant expression that can be contextually converted to bool.
11573     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11574     if (Converted.isInvalid())
11575       Failed = true;
11576 
11577     llvm::APSInt Cond;
11578     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11579           diag::err_static_assert_expression_is_not_constant,
11580           /*AllowFold=*/false).isInvalid())
11581       Failed = true;
11582 
11583     if (!Failed && !Cond) {
11584       SmallString<256> MsgBuffer;
11585       llvm::raw_svector_ostream Msg(MsgBuffer);
11586       if (AssertMessage)
11587         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
11588       Diag(StaticAssertLoc, diag::err_static_assert_failed)
11589         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
11590       Failed = true;
11591     }
11592   }
11593 
11594   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11595                                         AssertExpr, AssertMessage, RParenLoc,
11596                                         Failed);
11597 
11598   CurContext->addDecl(Decl);
11599   return Decl;
11600 }
11601 
11602 /// \brief Perform semantic analysis of the given friend type declaration.
11603 ///
11604 /// \returns A friend declaration that.
11605 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11606                                       SourceLocation FriendLoc,
11607                                       TypeSourceInfo *TSInfo) {
11608   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11609 
11610   QualType T = TSInfo->getType();
11611   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11612 
11613   // C++03 [class.friend]p2:
11614   //   An elaborated-type-specifier shall be used in a friend declaration
11615   //   for a class.*
11616   //
11617   //   * The class-key of the elaborated-type-specifier is required.
11618   if (!ActiveTemplateInstantiations.empty()) {
11619     // Do not complain about the form of friend template types during
11620     // template instantiation; we will already have complained when the
11621     // template was declared.
11622   } else {
11623     if (!T->isElaboratedTypeSpecifier()) {
11624       // If we evaluated the type to a record type, suggest putting
11625       // a tag in front.
11626       if (const RecordType *RT = T->getAs<RecordType>()) {
11627         RecordDecl *RD = RT->getDecl();
11628 
11629         SmallString<16> InsertionText(" ");
11630         InsertionText += RD->getKindName();
11631 
11632         Diag(TypeRange.getBegin(),
11633              getLangOpts().CPlusPlus11 ?
11634                diag::warn_cxx98_compat_unelaborated_friend_type :
11635                diag::ext_unelaborated_friend_type)
11636           << (unsigned) RD->getTagKind()
11637           << T
11638           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11639                                         InsertionText);
11640       } else {
11641         Diag(FriendLoc,
11642              getLangOpts().CPlusPlus11 ?
11643                diag::warn_cxx98_compat_nonclass_type_friend :
11644                diag::ext_nonclass_type_friend)
11645           << T
11646           << TypeRange;
11647       }
11648     } else if (T->getAs<EnumType>()) {
11649       Diag(FriendLoc,
11650            getLangOpts().CPlusPlus11 ?
11651              diag::warn_cxx98_compat_enum_friend :
11652              diag::ext_enum_friend)
11653         << T
11654         << TypeRange;
11655     }
11656 
11657     // C++11 [class.friend]p3:
11658     //   A friend declaration that does not declare a function shall have one
11659     //   of the following forms:
11660     //     friend elaborated-type-specifier ;
11661     //     friend simple-type-specifier ;
11662     //     friend typename-specifier ;
11663     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11664       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11665   }
11666 
11667   //   If the type specifier in a friend declaration designates a (possibly
11668   //   cv-qualified) class type, that class is declared as a friend; otherwise,
11669   //   the friend declaration is ignored.
11670   return FriendDecl::Create(Context, CurContext,
11671                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
11672                             FriendLoc);
11673 }
11674 
11675 /// Handle a friend tag declaration where the scope specifier was
11676 /// templated.
11677 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11678                                     unsigned TagSpec, SourceLocation TagLoc,
11679                                     CXXScopeSpec &SS,
11680                                     IdentifierInfo *Name,
11681                                     SourceLocation NameLoc,
11682                                     AttributeList *Attr,
11683                                     MultiTemplateParamsArg TempParamLists) {
11684   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11685 
11686   bool isExplicitSpecialization = false;
11687   bool Invalid = false;
11688 
11689   if (TemplateParameterList *TemplateParams =
11690           MatchTemplateParametersToScopeSpecifier(
11691               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
11692               isExplicitSpecialization, Invalid)) {
11693     if (TemplateParams->size() > 0) {
11694       // This is a declaration of a class template.
11695       if (Invalid)
11696         return nullptr;
11697 
11698       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
11699                                 NameLoc, Attr, TemplateParams, AS_public,
11700                                 /*ModulePrivateLoc=*/SourceLocation(),
11701                                 FriendLoc, TempParamLists.size() - 1,
11702                                 TempParamLists.data()).get();
11703     } else {
11704       // The "template<>" header is extraneous.
11705       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11706         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11707       isExplicitSpecialization = true;
11708     }
11709   }
11710 
11711   if (Invalid) return nullptr;
11712 
11713   bool isAllExplicitSpecializations = true;
11714   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11715     if (TempParamLists[I]->size()) {
11716       isAllExplicitSpecializations = false;
11717       break;
11718     }
11719   }
11720 
11721   // FIXME: don't ignore attributes.
11722 
11723   // If it's explicit specializations all the way down, just forget
11724   // about the template header and build an appropriate non-templated
11725   // friend.  TODO: for source fidelity, remember the headers.
11726   if (isAllExplicitSpecializations) {
11727     if (SS.isEmpty()) {
11728       bool Owned = false;
11729       bool IsDependent = false;
11730       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11731                       Attr, AS_public,
11732                       /*ModulePrivateLoc=*/SourceLocation(),
11733                       MultiTemplateParamsArg(), Owned, IsDependent,
11734                       /*ScopedEnumKWLoc=*/SourceLocation(),
11735                       /*ScopedEnumUsesClassTag=*/false,
11736                       /*UnderlyingType=*/TypeResult(),
11737                       /*IsTypeSpecifier=*/false);
11738     }
11739 
11740     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11741     ElaboratedTypeKeyword Keyword
11742       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11743     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11744                                    *Name, NameLoc);
11745     if (T.isNull())
11746       return nullptr;
11747 
11748     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11749     if (isa<DependentNameType>(T)) {
11750       DependentNameTypeLoc TL =
11751           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11752       TL.setElaboratedKeywordLoc(TagLoc);
11753       TL.setQualifierLoc(QualifierLoc);
11754       TL.setNameLoc(NameLoc);
11755     } else {
11756       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11757       TL.setElaboratedKeywordLoc(TagLoc);
11758       TL.setQualifierLoc(QualifierLoc);
11759       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11760     }
11761 
11762     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11763                                             TSI, FriendLoc, TempParamLists);
11764     Friend->setAccess(AS_public);
11765     CurContext->addDecl(Friend);
11766     return Friend;
11767   }
11768 
11769   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11770 
11771 
11772 
11773   // Handle the case of a templated-scope friend class.  e.g.
11774   //   template <class T> class A<T>::B;
11775   // FIXME: we don't support these right now.
11776   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11777     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
11778   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11779   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11780   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11781   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11782   TL.setElaboratedKeywordLoc(TagLoc);
11783   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11784   TL.setNameLoc(NameLoc);
11785 
11786   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11787                                           TSI, FriendLoc, TempParamLists);
11788   Friend->setAccess(AS_public);
11789   Friend->setUnsupportedFriend(true);
11790   CurContext->addDecl(Friend);
11791   return Friend;
11792 }
11793 
11794 
11795 /// Handle a friend type declaration.  This works in tandem with
11796 /// ActOnTag.
11797 ///
11798 /// Notes on friend class templates:
11799 ///
11800 /// We generally treat friend class declarations as if they were
11801 /// declaring a class.  So, for example, the elaborated type specifier
11802 /// in a friend declaration is required to obey the restrictions of a
11803 /// class-head (i.e. no typedefs in the scope chain), template
11804 /// parameters are required to match up with simple template-ids, &c.
11805 /// However, unlike when declaring a template specialization, it's
11806 /// okay to refer to a template specialization without an empty
11807 /// template parameter declaration, e.g.
11808 ///   friend class A<T>::B<unsigned>;
11809 /// We permit this as a special case; if there are any template
11810 /// parameters present at all, require proper matching, i.e.
11811 ///   template <> template \<class T> friend class A<int>::B;
11812 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11813                                 MultiTemplateParamsArg TempParams) {
11814   SourceLocation Loc = DS.getLocStart();
11815 
11816   assert(DS.isFriendSpecified());
11817   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11818 
11819   // Try to convert the decl specifier to a type.  This works for
11820   // friend templates because ActOnTag never produces a ClassTemplateDecl
11821   // for a TUK_Friend.
11822   Declarator TheDeclarator(DS, Declarator::MemberContext);
11823   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11824   QualType T = TSI->getType();
11825   if (TheDeclarator.isInvalidType())
11826     return nullptr;
11827 
11828   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11829     return nullptr;
11830 
11831   // This is definitely an error in C++98.  It's probably meant to
11832   // be forbidden in C++0x, too, but the specification is just
11833   // poorly written.
11834   //
11835   // The problem is with declarations like the following:
11836   //   template <T> friend A<T>::foo;
11837   // where deciding whether a class C is a friend or not now hinges
11838   // on whether there exists an instantiation of A that causes
11839   // 'foo' to equal C.  There are restrictions on class-heads
11840   // (which we declare (by fiat) elaborated friend declarations to
11841   // be) that makes this tractable.
11842   //
11843   // FIXME: handle "template <> friend class A<T>;", which
11844   // is possibly well-formed?  Who even knows?
11845   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11846     Diag(Loc, diag::err_tagless_friend_type_template)
11847       << DS.getSourceRange();
11848     return nullptr;
11849   }
11850 
11851   // C++98 [class.friend]p1: A friend of a class is a function
11852   //   or class that is not a member of the class . . .
11853   // This is fixed in DR77, which just barely didn't make the C++03
11854   // deadline.  It's also a very silly restriction that seriously
11855   // affects inner classes and which nobody else seems to implement;
11856   // thus we never diagnose it, not even in -pedantic.
11857   //
11858   // But note that we could warn about it: it's always useless to
11859   // friend one of your own members (it's not, however, worthless to
11860   // friend a member of an arbitrary specialization of your template).
11861 
11862   Decl *D;
11863   if (unsigned NumTempParamLists = TempParams.size())
11864     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11865                                    NumTempParamLists,
11866                                    TempParams.data(),
11867                                    TSI,
11868                                    DS.getFriendSpecLoc());
11869   else
11870     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11871 
11872   if (!D)
11873     return nullptr;
11874 
11875   D->setAccess(AS_public);
11876   CurContext->addDecl(D);
11877 
11878   return D;
11879 }
11880 
11881 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11882                                         MultiTemplateParamsArg TemplateParams) {
11883   const DeclSpec &DS = D.getDeclSpec();
11884 
11885   assert(DS.isFriendSpecified());
11886   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11887 
11888   SourceLocation Loc = D.getIdentifierLoc();
11889   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11890 
11891   // C++ [class.friend]p1
11892   //   A friend of a class is a function or class....
11893   // Note that this sees through typedefs, which is intended.
11894   // It *doesn't* see through dependent types, which is correct
11895   // according to [temp.arg.type]p3:
11896   //   If a declaration acquires a function type through a
11897   //   type dependent on a template-parameter and this causes
11898   //   a declaration that does not use the syntactic form of a
11899   //   function declarator to have a function type, the program
11900   //   is ill-formed.
11901   if (!TInfo->getType()->isFunctionType()) {
11902     Diag(Loc, diag::err_unexpected_friend);
11903 
11904     // It might be worthwhile to try to recover by creating an
11905     // appropriate declaration.
11906     return nullptr;
11907   }
11908 
11909   // C++ [namespace.memdef]p3
11910   //  - If a friend declaration in a non-local class first declares a
11911   //    class or function, the friend class or function is a member
11912   //    of the innermost enclosing namespace.
11913   //  - The name of the friend is not found by simple name lookup
11914   //    until a matching declaration is provided in that namespace
11915   //    scope (either before or after the class declaration granting
11916   //    friendship).
11917   //  - If a friend function is called, its name may be found by the
11918   //    name lookup that considers functions from namespaces and
11919   //    classes associated with the types of the function arguments.
11920   //  - When looking for a prior declaration of a class or a function
11921   //    declared as a friend, scopes outside the innermost enclosing
11922   //    namespace scope are not considered.
11923 
11924   CXXScopeSpec &SS = D.getCXXScopeSpec();
11925   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11926   DeclarationName Name = NameInfo.getName();
11927   assert(Name);
11928 
11929   // Check for unexpanded parameter packs.
11930   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11931       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11932       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11933     return nullptr;
11934 
11935   // The context we found the declaration in, or in which we should
11936   // create the declaration.
11937   DeclContext *DC;
11938   Scope *DCScope = S;
11939   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11940                         ForRedeclaration);
11941 
11942   // There are five cases here.
11943   //   - There's no scope specifier and we're in a local class. Only look
11944   //     for functions declared in the immediately-enclosing block scope.
11945   // We recover from invalid scope qualifiers as if they just weren't there.
11946   FunctionDecl *FunctionContainingLocalClass = nullptr;
11947   if ((SS.isInvalid() || !SS.isSet()) &&
11948       (FunctionContainingLocalClass =
11949            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11950     // C++11 [class.friend]p11:
11951     //   If a friend declaration appears in a local class and the name
11952     //   specified is an unqualified name, a prior declaration is
11953     //   looked up without considering scopes that are outside the
11954     //   innermost enclosing non-class scope. For a friend function
11955     //   declaration, if there is no prior declaration, the program is
11956     //   ill-formed.
11957 
11958     // Find the innermost enclosing non-class scope. This is the block
11959     // scope containing the local class definition (or for a nested class,
11960     // the outer local class).
11961     DCScope = S->getFnParent();
11962 
11963     // Look up the function name in the scope.
11964     Previous.clear(LookupLocalFriendName);
11965     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11966 
11967     if (!Previous.empty()) {
11968       // All possible previous declarations must have the same context:
11969       // either they were declared at block scope or they are members of
11970       // one of the enclosing local classes.
11971       DC = Previous.getRepresentativeDecl()->getDeclContext();
11972     } else {
11973       // This is ill-formed, but provide the context that we would have
11974       // declared the function in, if we were permitted to, for error recovery.
11975       DC = FunctionContainingLocalClass;
11976     }
11977     adjustContextForLocalExternDecl(DC);
11978 
11979     // C++ [class.friend]p6:
11980     //   A function can be defined in a friend declaration of a class if and
11981     //   only if the class is a non-local class (9.8), the function name is
11982     //   unqualified, and the function has namespace scope.
11983     if (D.isFunctionDefinition()) {
11984       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11985     }
11986 
11987   //   - There's no scope specifier, in which case we just go to the
11988   //     appropriate scope and look for a function or function template
11989   //     there as appropriate.
11990   } else if (SS.isInvalid() || !SS.isSet()) {
11991     // C++11 [namespace.memdef]p3:
11992     //   If the name in a friend declaration is neither qualified nor
11993     //   a template-id and the declaration is a function or an
11994     //   elaborated-type-specifier, the lookup to determine whether
11995     //   the entity has been previously declared shall not consider
11996     //   any scopes outside the innermost enclosing namespace.
11997     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11998 
11999     // Find the appropriate context according to the above.
12000     DC = CurContext;
12001 
12002     // Skip class contexts.  If someone can cite chapter and verse
12003     // for this behavior, that would be nice --- it's what GCC and
12004     // EDG do, and it seems like a reasonable intent, but the spec
12005     // really only says that checks for unqualified existing
12006     // declarations should stop at the nearest enclosing namespace,
12007     // not that they should only consider the nearest enclosing
12008     // namespace.
12009     while (DC->isRecord())
12010       DC = DC->getParent();
12011 
12012     DeclContext *LookupDC = DC;
12013     while (LookupDC->isTransparentContext())
12014       LookupDC = LookupDC->getParent();
12015 
12016     while (true) {
12017       LookupQualifiedName(Previous, LookupDC);
12018 
12019       if (!Previous.empty()) {
12020         DC = LookupDC;
12021         break;
12022       }
12023 
12024       if (isTemplateId) {
12025         if (isa<TranslationUnitDecl>(LookupDC)) break;
12026       } else {
12027         if (LookupDC->isFileContext()) break;
12028       }
12029       LookupDC = LookupDC->getParent();
12030     }
12031 
12032     DCScope = getScopeForDeclContext(S, DC);
12033 
12034   //   - There's a non-dependent scope specifier, in which case we
12035   //     compute it and do a previous lookup there for a function
12036   //     or function template.
12037   } else if (!SS.getScopeRep()->isDependent()) {
12038     DC = computeDeclContext(SS);
12039     if (!DC) return nullptr;
12040 
12041     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12042 
12043     LookupQualifiedName(Previous, DC);
12044 
12045     // Ignore things found implicitly in the wrong scope.
12046     // TODO: better diagnostics for this case.  Suggesting the right
12047     // qualified scope would be nice...
12048     LookupResult::Filter F = Previous.makeFilter();
12049     while (F.hasNext()) {
12050       NamedDecl *D = F.next();
12051       if (!DC->InEnclosingNamespaceSetOf(
12052               D->getDeclContext()->getRedeclContext()))
12053         F.erase();
12054     }
12055     F.done();
12056 
12057     if (Previous.empty()) {
12058       D.setInvalidType();
12059       Diag(Loc, diag::err_qualified_friend_not_found)
12060           << Name << TInfo->getType();
12061       return nullptr;
12062     }
12063 
12064     // C++ [class.friend]p1: A friend of a class is a function or
12065     //   class that is not a member of the class . . .
12066     if (DC->Equals(CurContext))
12067       Diag(DS.getFriendSpecLoc(),
12068            getLangOpts().CPlusPlus11 ?
12069              diag::warn_cxx98_compat_friend_is_member :
12070              diag::err_friend_is_member);
12071 
12072     if (D.isFunctionDefinition()) {
12073       // C++ [class.friend]p6:
12074       //   A function can be defined in a friend declaration of a class if and
12075       //   only if the class is a non-local class (9.8), the function name is
12076       //   unqualified, and the function has namespace scope.
12077       SemaDiagnosticBuilder DB
12078         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12079 
12080       DB << SS.getScopeRep();
12081       if (DC->isFileContext())
12082         DB << FixItHint::CreateRemoval(SS.getRange());
12083       SS.clear();
12084     }
12085 
12086   //   - There's a scope specifier that does not match any template
12087   //     parameter lists, in which case we use some arbitrary context,
12088   //     create a method or method template, and wait for instantiation.
12089   //   - There's a scope specifier that does match some template
12090   //     parameter lists, which we don't handle right now.
12091   } else {
12092     if (D.isFunctionDefinition()) {
12093       // C++ [class.friend]p6:
12094       //   A function can be defined in a friend declaration of a class if and
12095       //   only if the class is a non-local class (9.8), the function name is
12096       //   unqualified, and the function has namespace scope.
12097       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12098         << SS.getScopeRep();
12099     }
12100 
12101     DC = CurContext;
12102     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12103   }
12104 
12105   if (!DC->isRecord()) {
12106     // This implies that it has to be an operator or function.
12107     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12108         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12109         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12110       Diag(Loc, diag::err_introducing_special_friend) <<
12111         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12112          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12113       return nullptr;
12114     }
12115   }
12116 
12117   // FIXME: This is an egregious hack to cope with cases where the scope stack
12118   // does not contain the declaration context, i.e., in an out-of-line
12119   // definition of a class.
12120   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12121   if (!DCScope) {
12122     FakeDCScope.setEntity(DC);
12123     DCScope = &FakeDCScope;
12124   }
12125 
12126   bool AddToScope = true;
12127   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12128                                           TemplateParams, AddToScope);
12129   if (!ND) return nullptr;
12130 
12131   assert(ND->getLexicalDeclContext() == CurContext);
12132 
12133   // If we performed typo correction, we might have added a scope specifier
12134   // and changed the decl context.
12135   DC = ND->getDeclContext();
12136 
12137   // Add the function declaration to the appropriate lookup tables,
12138   // adjusting the redeclarations list as necessary.  We don't
12139   // want to do this yet if the friending class is dependent.
12140   //
12141   // Also update the scope-based lookup if the target context's
12142   // lookup context is in lexical scope.
12143   if (!CurContext->isDependentContext()) {
12144     DC = DC->getRedeclContext();
12145     DC->makeDeclVisibleInContext(ND);
12146     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12147       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12148   }
12149 
12150   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12151                                        D.getIdentifierLoc(), ND,
12152                                        DS.getFriendSpecLoc());
12153   FrD->setAccess(AS_public);
12154   CurContext->addDecl(FrD);
12155 
12156   if (ND->isInvalidDecl()) {
12157     FrD->setInvalidDecl();
12158   } else {
12159     if (DC->isRecord()) CheckFriendAccess(ND);
12160 
12161     FunctionDecl *FD;
12162     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12163       FD = FTD->getTemplatedDecl();
12164     else
12165       FD = cast<FunctionDecl>(ND);
12166 
12167     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12168     // default argument expression, that declaration shall be a definition
12169     // and shall be the only declaration of the function or function
12170     // template in the translation unit.
12171     if (functionDeclHasDefaultArgument(FD)) {
12172       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12173         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12174         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12175       } else if (!D.isFunctionDefinition())
12176         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12177     }
12178 
12179     // Mark templated-scope function declarations as unsupported.
12180     if (FD->getNumTemplateParameterLists())
12181       FrD->setUnsupportedFriend(true);
12182   }
12183 
12184   return ND;
12185 }
12186 
12187 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12188   AdjustDeclIfTemplate(Dcl);
12189 
12190   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12191   if (!Fn) {
12192     Diag(DelLoc, diag::err_deleted_non_function);
12193     return;
12194   }
12195 
12196   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12197     // Don't consider the implicit declaration we generate for explicit
12198     // specializations. FIXME: Do not generate these implicit declarations.
12199     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12200          Prev->getPreviousDecl()) &&
12201         !Prev->isDefined()) {
12202       Diag(DelLoc, diag::err_deleted_decl_not_first);
12203       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12204            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12205                               : diag::note_previous_declaration);
12206     }
12207     // If the declaration wasn't the first, we delete the function anyway for
12208     // recovery.
12209     Fn = Fn->getCanonicalDecl();
12210   }
12211 
12212   // dllimport/dllexport cannot be deleted.
12213   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12214     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12215     Fn->setInvalidDecl();
12216   }
12217 
12218   if (Fn->isDeleted())
12219     return;
12220 
12221   // See if we're deleting a function which is already known to override a
12222   // non-deleted virtual function.
12223   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12224     bool IssuedDiagnostic = false;
12225     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12226                                         E = MD->end_overridden_methods();
12227          I != E; ++I) {
12228       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12229         if (!IssuedDiagnostic) {
12230           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12231           IssuedDiagnostic = true;
12232         }
12233         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12234       }
12235     }
12236   }
12237 
12238   // C++11 [basic.start.main]p3:
12239   //   A program that defines main as deleted [...] is ill-formed.
12240   if (Fn->isMain())
12241     Diag(DelLoc, diag::err_deleted_main);
12242 
12243   Fn->setDeletedAsWritten();
12244 }
12245 
12246 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12247   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12248 
12249   if (MD) {
12250     if (MD->getParent()->isDependentType()) {
12251       MD->setDefaulted();
12252       MD->setExplicitlyDefaulted();
12253       return;
12254     }
12255 
12256     CXXSpecialMember Member = getSpecialMember(MD);
12257     if (Member == CXXInvalid) {
12258       if (!MD->isInvalidDecl())
12259         Diag(DefaultLoc, diag::err_default_special_members);
12260       return;
12261     }
12262 
12263     MD->setDefaulted();
12264     MD->setExplicitlyDefaulted();
12265 
12266     // If this definition appears within the record, do the checking when
12267     // the record is complete.
12268     const FunctionDecl *Primary = MD;
12269     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12270       // Find the uninstantiated declaration that actually had the '= default'
12271       // on it.
12272       Pattern->isDefined(Primary);
12273 
12274     // If the method was defaulted on its first declaration, we will have
12275     // already performed the checking in CheckCompletedCXXClass. Such a
12276     // declaration doesn't trigger an implicit definition.
12277     if (Primary == Primary->getCanonicalDecl())
12278       return;
12279 
12280     CheckExplicitlyDefaultedSpecialMember(MD);
12281 
12282     // The exception specification is needed because we are defining the
12283     // function.
12284     ResolveExceptionSpec(DefaultLoc,
12285                          MD->getType()->castAs<FunctionProtoType>());
12286 
12287     if (MD->isInvalidDecl())
12288       return;
12289 
12290     switch (Member) {
12291     case CXXDefaultConstructor:
12292       DefineImplicitDefaultConstructor(DefaultLoc,
12293                                        cast<CXXConstructorDecl>(MD));
12294       break;
12295     case CXXCopyConstructor:
12296       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12297       break;
12298     case CXXCopyAssignment:
12299       DefineImplicitCopyAssignment(DefaultLoc, MD);
12300       break;
12301     case CXXDestructor:
12302       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12303       break;
12304     case CXXMoveConstructor:
12305       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12306       break;
12307     case CXXMoveAssignment:
12308       DefineImplicitMoveAssignment(DefaultLoc, MD);
12309       break;
12310     case CXXInvalid:
12311       llvm_unreachable("Invalid special member.");
12312     }
12313   } else {
12314     Diag(DefaultLoc, diag::err_default_special_members);
12315   }
12316 }
12317 
12318 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12319   for (Stmt::child_range CI = S->children(); CI; ++CI) {
12320     Stmt *SubStmt = *CI;
12321     if (!SubStmt)
12322       continue;
12323     if (isa<ReturnStmt>(SubStmt))
12324       Self.Diag(SubStmt->getLocStart(),
12325            diag::err_return_in_constructor_handler);
12326     if (!isa<Expr>(SubStmt))
12327       SearchForReturnInStmt(Self, SubStmt);
12328   }
12329 }
12330 
12331 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12332   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12333     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12334     SearchForReturnInStmt(*this, Handler);
12335   }
12336 }
12337 
12338 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12339                                              const CXXMethodDecl *Old) {
12340   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12341   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12342 
12343   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12344 
12345   // If the calling conventions match, everything is fine
12346   if (NewCC == OldCC)
12347     return false;
12348 
12349   // If the calling conventions mismatch because the new function is static,
12350   // suppress the calling convention mismatch error; the error about static
12351   // function override (err_static_overrides_virtual from
12352   // Sema::CheckFunctionDeclaration) is more clear.
12353   if (New->getStorageClass() == SC_Static)
12354     return false;
12355 
12356   Diag(New->getLocation(),
12357        diag::err_conflicting_overriding_cc_attributes)
12358     << New->getDeclName() << New->getType() << Old->getType();
12359   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12360   return true;
12361 }
12362 
12363 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12364                                              const CXXMethodDecl *Old) {
12365   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12366   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12367 
12368   if (Context.hasSameType(NewTy, OldTy) ||
12369       NewTy->isDependentType() || OldTy->isDependentType())
12370     return false;
12371 
12372   // Check if the return types are covariant
12373   QualType NewClassTy, OldClassTy;
12374 
12375   /// Both types must be pointers or references to classes.
12376   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12377     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12378       NewClassTy = NewPT->getPointeeType();
12379       OldClassTy = OldPT->getPointeeType();
12380     }
12381   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12382     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12383       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12384         NewClassTy = NewRT->getPointeeType();
12385         OldClassTy = OldRT->getPointeeType();
12386       }
12387     }
12388   }
12389 
12390   // The return types aren't either both pointers or references to a class type.
12391   if (NewClassTy.isNull()) {
12392     Diag(New->getLocation(),
12393          diag::err_different_return_type_for_overriding_virtual_function)
12394         << New->getDeclName() << NewTy << OldTy
12395         << New->getReturnTypeSourceRange();
12396     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12397         << Old->getReturnTypeSourceRange();
12398 
12399     return true;
12400   }
12401 
12402   // C++ [class.virtual]p6:
12403   //   If the return type of D::f differs from the return type of B::f, the
12404   //   class type in the return type of D::f shall be complete at the point of
12405   //   declaration of D::f or shall be the class type D.
12406   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12407     if (!RT->isBeingDefined() &&
12408         RequireCompleteType(New->getLocation(), NewClassTy,
12409                             diag::err_covariant_return_incomplete,
12410                             New->getDeclName()))
12411     return true;
12412   }
12413 
12414   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12415     // Check if the new class derives from the old class.
12416     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12417       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12418           << New->getDeclName() << NewTy << OldTy
12419           << New->getReturnTypeSourceRange();
12420       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12421           << Old->getReturnTypeSourceRange();
12422       return true;
12423     }
12424 
12425     // Check if we the conversion from derived to base is valid.
12426     if (CheckDerivedToBaseConversion(
12427             NewClassTy, OldClassTy,
12428             diag::err_covariant_return_inaccessible_base,
12429             diag::err_covariant_return_ambiguous_derived_to_base_conv,
12430             New->getLocation(), New->getReturnTypeSourceRange(),
12431             New->getDeclName(), nullptr)) {
12432       // FIXME: this note won't trigger for delayed access control
12433       // diagnostics, and it's impossible to get an undelayed error
12434       // here from access control during the original parse because
12435       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12436       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12437           << Old->getReturnTypeSourceRange();
12438       return true;
12439     }
12440   }
12441 
12442   // The qualifiers of the return types must be the same.
12443   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12444     Diag(New->getLocation(),
12445          diag::err_covariant_return_type_different_qualifications)
12446         << New->getDeclName() << NewTy << OldTy
12447         << New->getReturnTypeSourceRange();
12448     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12449         << Old->getReturnTypeSourceRange();
12450     return true;
12451   };
12452 
12453 
12454   // The new class type must have the same or less qualifiers as the old type.
12455   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12456     Diag(New->getLocation(),
12457          diag::err_covariant_return_type_class_type_more_qualified)
12458         << New->getDeclName() << NewTy << OldTy
12459         << New->getReturnTypeSourceRange();
12460     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12461         << Old->getReturnTypeSourceRange();
12462     return true;
12463   };
12464 
12465   return false;
12466 }
12467 
12468 /// \brief Mark the given method pure.
12469 ///
12470 /// \param Method the method to be marked pure.
12471 ///
12472 /// \param InitRange the source range that covers the "0" initializer.
12473 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12474   SourceLocation EndLoc = InitRange.getEnd();
12475   if (EndLoc.isValid())
12476     Method->setRangeEnd(EndLoc);
12477 
12478   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12479     Method->setPure();
12480     return false;
12481   }
12482 
12483   if (!Method->isInvalidDecl())
12484     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12485       << Method->getDeclName() << InitRange;
12486   return true;
12487 }
12488 
12489 /// \brief Determine whether the given declaration is a static data member.
12490 static bool isStaticDataMember(const Decl *D) {
12491   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12492     return Var->isStaticDataMember();
12493 
12494   return false;
12495 }
12496 
12497 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12498 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12499 /// is a fresh scope pushed for just this purpose.
12500 ///
12501 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12502 /// static data member of class X, names should be looked up in the scope of
12503 /// class X.
12504 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12505   // If there is no declaration, there was an error parsing it.
12506   if (!D || D->isInvalidDecl())
12507     return;
12508 
12509   // We will always have a nested name specifier here, but this declaration
12510   // might not be out of line if the specifier names the current namespace:
12511   //   extern int n;
12512   //   int ::n = 0;
12513   if (D->isOutOfLine())
12514     EnterDeclaratorContext(S, D->getDeclContext());
12515 
12516   // If we are parsing the initializer for a static data member, push a
12517   // new expression evaluation context that is associated with this static
12518   // data member.
12519   if (isStaticDataMember(D))
12520     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12521 }
12522 
12523 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12524 /// initializer for the out-of-line declaration 'D'.
12525 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12526   // If there is no declaration, there was an error parsing it.
12527   if (!D || D->isInvalidDecl())
12528     return;
12529 
12530   if (isStaticDataMember(D))
12531     PopExpressionEvaluationContext();
12532 
12533   if (D->isOutOfLine())
12534     ExitDeclaratorContext(S);
12535 }
12536 
12537 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12538 /// C++ if/switch/while/for statement.
12539 /// e.g: "if (int x = f()) {...}"
12540 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12541   // C++ 6.4p2:
12542   // The declarator shall not specify a function or an array.
12543   // The type-specifier-seq shall not contain typedef and shall not declare a
12544   // new class or enumeration.
12545   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12546          "Parser allowed 'typedef' as storage class of condition decl.");
12547 
12548   Decl *Dcl = ActOnDeclarator(S, D);
12549   if (!Dcl)
12550     return true;
12551 
12552   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12553     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12554       << D.getSourceRange();
12555     return true;
12556   }
12557 
12558   return Dcl;
12559 }
12560 
12561 void Sema::LoadExternalVTableUses() {
12562   if (!ExternalSource)
12563     return;
12564 
12565   SmallVector<ExternalVTableUse, 4> VTables;
12566   ExternalSource->ReadUsedVTables(VTables);
12567   SmallVector<VTableUse, 4> NewUses;
12568   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12569     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12570       = VTablesUsed.find(VTables[I].Record);
12571     // Even if a definition wasn't required before, it may be required now.
12572     if (Pos != VTablesUsed.end()) {
12573       if (!Pos->second && VTables[I].DefinitionRequired)
12574         Pos->second = true;
12575       continue;
12576     }
12577 
12578     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12579     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12580   }
12581 
12582   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12583 }
12584 
12585 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12586                           bool DefinitionRequired) {
12587   // Ignore any vtable uses in unevaluated operands or for classes that do
12588   // not have a vtable.
12589   if (!Class->isDynamicClass() || Class->isDependentContext() ||
12590       CurContext->isDependentContext() || isUnevaluatedContext())
12591     return;
12592 
12593   // Try to insert this class into the map.
12594   LoadExternalVTableUses();
12595   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12596   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12597     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12598   if (!Pos.second) {
12599     // If we already had an entry, check to see if we are promoting this vtable
12600     // to required a definition. If so, we need to reappend to the VTableUses
12601     // list, since we may have already processed the first entry.
12602     if (DefinitionRequired && !Pos.first->second) {
12603       Pos.first->second = true;
12604     } else {
12605       // Otherwise, we can early exit.
12606       return;
12607     }
12608   } else {
12609     // The Microsoft ABI requires that we perform the destructor body
12610     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12611     // the deleting destructor is emitted with the vtable, not with the
12612     // destructor definition as in the Itanium ABI.
12613     // If it has a definition, we do the check at that point instead.
12614     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12615         Class->hasUserDeclaredDestructor() &&
12616         !Class->getDestructor()->isDefined() &&
12617         !Class->getDestructor()->isDeleted()) {
12618       CXXDestructorDecl *DD = Class->getDestructor();
12619       ContextRAII SavedContext(*this, DD);
12620       CheckDestructor(DD);
12621     }
12622   }
12623 
12624   // Local classes need to have their virtual members marked
12625   // immediately. For all other classes, we mark their virtual members
12626   // at the end of the translation unit.
12627   if (Class->isLocalClass())
12628     MarkVirtualMembersReferenced(Loc, Class);
12629   else
12630     VTableUses.push_back(std::make_pair(Class, Loc));
12631 }
12632 
12633 bool Sema::DefineUsedVTables() {
12634   LoadExternalVTableUses();
12635   if (VTableUses.empty())
12636     return false;
12637 
12638   // Note: The VTableUses vector could grow as a result of marking
12639   // the members of a class as "used", so we check the size each
12640   // time through the loop and prefer indices (which are stable) to
12641   // iterators (which are not).
12642   bool DefinedAnything = false;
12643   for (unsigned I = 0; I != VTableUses.size(); ++I) {
12644     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12645     if (!Class)
12646       continue;
12647 
12648     SourceLocation Loc = VTableUses[I].second;
12649 
12650     bool DefineVTable = true;
12651 
12652     // If this class has a key function, but that key function is
12653     // defined in another translation unit, we don't need to emit the
12654     // vtable even though we're using it.
12655     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12656     if (KeyFunction && !KeyFunction->hasBody()) {
12657       // The key function is in another translation unit.
12658       DefineVTable = false;
12659       TemplateSpecializationKind TSK =
12660           KeyFunction->getTemplateSpecializationKind();
12661       assert(TSK != TSK_ExplicitInstantiationDefinition &&
12662              TSK != TSK_ImplicitInstantiation &&
12663              "Instantiations don't have key functions");
12664       (void)TSK;
12665     } else if (!KeyFunction) {
12666       // If we have a class with no key function that is the subject
12667       // of an explicit instantiation declaration, suppress the
12668       // vtable; it will live with the explicit instantiation
12669       // definition.
12670       bool IsExplicitInstantiationDeclaration
12671         = Class->getTemplateSpecializationKind()
12672                                       == TSK_ExplicitInstantiationDeclaration;
12673       for (auto R : Class->redecls()) {
12674         TemplateSpecializationKind TSK
12675           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
12676         if (TSK == TSK_ExplicitInstantiationDeclaration)
12677           IsExplicitInstantiationDeclaration = true;
12678         else if (TSK == TSK_ExplicitInstantiationDefinition) {
12679           IsExplicitInstantiationDeclaration = false;
12680           break;
12681         }
12682       }
12683 
12684       if (IsExplicitInstantiationDeclaration)
12685         DefineVTable = false;
12686     }
12687 
12688     // The exception specifications for all virtual members may be needed even
12689     // if we are not providing an authoritative form of the vtable in this TU.
12690     // We may choose to emit it available_externally anyway.
12691     if (!DefineVTable) {
12692       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12693       continue;
12694     }
12695 
12696     // Mark all of the virtual members of this class as referenced, so
12697     // that we can build a vtable. Then, tell the AST consumer that a
12698     // vtable for this class is required.
12699     DefinedAnything = true;
12700     MarkVirtualMembersReferenced(Loc, Class);
12701     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12702     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12703 
12704     // Optionally warn if we're emitting a weak vtable.
12705     if (Class->isExternallyVisible() &&
12706         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12707       const FunctionDecl *KeyFunctionDef = nullptr;
12708       if (!KeyFunction ||
12709           (KeyFunction->hasBody(KeyFunctionDef) &&
12710            KeyFunctionDef->isInlined()))
12711         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12712              TSK_ExplicitInstantiationDefinition
12713              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12714           << Class;
12715     }
12716   }
12717   VTableUses.clear();
12718 
12719   return DefinedAnything;
12720 }
12721 
12722 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12723                                                  const CXXRecordDecl *RD) {
12724   for (const auto *I : RD->methods())
12725     if (I->isVirtual() && !I->isPure())
12726       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
12727 }
12728 
12729 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12730                                         const CXXRecordDecl *RD) {
12731   // Mark all functions which will appear in RD's vtable as used.
12732   CXXFinalOverriderMap FinalOverriders;
12733   RD->getFinalOverriders(FinalOverriders);
12734   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12735                                             E = FinalOverriders.end();
12736        I != E; ++I) {
12737     for (OverridingMethods::const_iterator OI = I->second.begin(),
12738                                            OE = I->second.end();
12739          OI != OE; ++OI) {
12740       assert(OI->second.size() > 0 && "no final overrider");
12741       CXXMethodDecl *Overrider = OI->second.front().Method;
12742 
12743       // C++ [basic.def.odr]p2:
12744       //   [...] A virtual member function is used if it is not pure. [...]
12745       if (!Overrider->isPure())
12746         MarkFunctionReferenced(Loc, Overrider);
12747     }
12748   }
12749 
12750   // Only classes that have virtual bases need a VTT.
12751   if (RD->getNumVBases() == 0)
12752     return;
12753 
12754   for (const auto &I : RD->bases()) {
12755     const CXXRecordDecl *Base =
12756         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
12757     if (Base->getNumVBases() == 0)
12758       continue;
12759     MarkVirtualMembersReferenced(Loc, Base);
12760   }
12761 }
12762 
12763 /// SetIvarInitializers - This routine builds initialization ASTs for the
12764 /// Objective-C implementation whose ivars need be initialized.
12765 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12766   if (!getLangOpts().CPlusPlus)
12767     return;
12768   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12769     SmallVector<ObjCIvarDecl*, 8> ivars;
12770     CollectIvarsToConstructOrDestruct(OID, ivars);
12771     if (ivars.empty())
12772       return;
12773     SmallVector<CXXCtorInitializer*, 32> AllToInit;
12774     for (unsigned i = 0; i < ivars.size(); i++) {
12775       FieldDecl *Field = ivars[i];
12776       if (Field->isInvalidDecl())
12777         continue;
12778 
12779       CXXCtorInitializer *Member;
12780       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12781       InitializationKind InitKind =
12782         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12783 
12784       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12785       ExprResult MemberInit =
12786         InitSeq.Perform(*this, InitEntity, InitKind, None);
12787       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12788       // Note, MemberInit could actually come back empty if no initialization
12789       // is required (e.g., because it would call a trivial default constructor)
12790       if (!MemberInit.get() || MemberInit.isInvalid())
12791         continue;
12792 
12793       Member =
12794         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12795                                          SourceLocation(),
12796                                          MemberInit.getAs<Expr>(),
12797                                          SourceLocation());
12798       AllToInit.push_back(Member);
12799 
12800       // Be sure that the destructor is accessible and is marked as referenced.
12801       if (const RecordType *RecordTy
12802                   = Context.getBaseElementType(Field->getType())
12803                                                         ->getAs<RecordType>()) {
12804                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12805         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12806           MarkFunctionReferenced(Field->getLocation(), Destructor);
12807           CheckDestructorAccess(Field->getLocation(), Destructor,
12808                             PDiag(diag::err_access_dtor_ivar)
12809                               << Context.getBaseElementType(Field->getType()));
12810         }
12811       }
12812     }
12813     ObjCImplementation->setIvarInitializers(Context,
12814                                             AllToInit.data(), AllToInit.size());
12815   }
12816 }
12817 
12818 static
12819 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12820                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12821                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12822                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12823                            Sema &S) {
12824   if (Ctor->isInvalidDecl())
12825     return;
12826 
12827   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12828 
12829   // Target may not be determinable yet, for instance if this is a dependent
12830   // call in an uninstantiated template.
12831   if (Target) {
12832     const FunctionDecl *FNTarget = nullptr;
12833     (void)Target->hasBody(FNTarget);
12834     Target = const_cast<CXXConstructorDecl*>(
12835       cast_or_null<CXXConstructorDecl>(FNTarget));
12836   }
12837 
12838   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12839                      // Avoid dereferencing a null pointer here.
12840                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
12841 
12842   if (!Current.insert(Canonical))
12843     return;
12844 
12845   // We know that beyond here, we aren't chaining into a cycle.
12846   if (!Target || !Target->isDelegatingConstructor() ||
12847       Target->isInvalidDecl() || Valid.count(TCanonical)) {
12848     Valid.insert(Current.begin(), Current.end());
12849     Current.clear();
12850   // We've hit a cycle.
12851   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12852              Current.count(TCanonical)) {
12853     // If we haven't diagnosed this cycle yet, do so now.
12854     if (!Invalid.count(TCanonical)) {
12855       S.Diag((*Ctor->init_begin())->getSourceLocation(),
12856              diag::warn_delegating_ctor_cycle)
12857         << Ctor;
12858 
12859       // Don't add a note for a function delegating directly to itself.
12860       if (TCanonical != Canonical)
12861         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12862 
12863       CXXConstructorDecl *C = Target;
12864       while (C->getCanonicalDecl() != Canonical) {
12865         const FunctionDecl *FNTarget = nullptr;
12866         (void)C->getTargetConstructor()->hasBody(FNTarget);
12867         assert(FNTarget && "Ctor cycle through bodiless function");
12868 
12869         C = const_cast<CXXConstructorDecl*>(
12870           cast<CXXConstructorDecl>(FNTarget));
12871         S.Diag(C->getLocation(), diag::note_which_delegates_to);
12872       }
12873     }
12874 
12875     Invalid.insert(Current.begin(), Current.end());
12876     Current.clear();
12877   } else {
12878     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12879   }
12880 }
12881 
12882 
12883 void Sema::CheckDelegatingCtorCycles() {
12884   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12885 
12886   for (DelegatingCtorDeclsType::iterator
12887          I = DelegatingCtorDecls.begin(ExternalSource),
12888          E = DelegatingCtorDecls.end();
12889        I != E; ++I)
12890     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12891 
12892   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12893                                                          CE = Invalid.end();
12894        CI != CE; ++CI)
12895     (*CI)->setInvalidDecl();
12896 }
12897 
12898 namespace {
12899   /// \brief AST visitor that finds references to the 'this' expression.
12900   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12901     Sema &S;
12902 
12903   public:
12904     explicit FindCXXThisExpr(Sema &S) : S(S) { }
12905 
12906     bool VisitCXXThisExpr(CXXThisExpr *E) {
12907       S.Diag(E->getLocation(), diag::err_this_static_member_func)
12908         << E->isImplicit();
12909       return false;
12910     }
12911   };
12912 }
12913 
12914 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12915   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12916   if (!TSInfo)
12917     return false;
12918 
12919   TypeLoc TL = TSInfo->getTypeLoc();
12920   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12921   if (!ProtoTL)
12922     return false;
12923 
12924   // C++11 [expr.prim.general]p3:
12925   //   [The expression this] shall not appear before the optional
12926   //   cv-qualifier-seq and it shall not appear within the declaration of a
12927   //   static member function (although its type and value category are defined
12928   //   within a static member function as they are within a non-static member
12929   //   function). [ Note: this is because declaration matching does not occur
12930   //  until the complete declarator is known. - end note ]
12931   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12932   FindCXXThisExpr Finder(*this);
12933 
12934   // If the return type came after the cv-qualifier-seq, check it now.
12935   if (Proto->hasTrailingReturn() &&
12936       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
12937     return true;
12938 
12939   // Check the exception specification.
12940   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12941     return true;
12942 
12943   return checkThisInStaticMemberFunctionAttributes(Method);
12944 }
12945 
12946 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12947   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12948   if (!TSInfo)
12949     return false;
12950 
12951   TypeLoc TL = TSInfo->getTypeLoc();
12952   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12953   if (!ProtoTL)
12954     return false;
12955 
12956   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12957   FindCXXThisExpr Finder(*this);
12958 
12959   switch (Proto->getExceptionSpecType()) {
12960   case EST_Uninstantiated:
12961   case EST_Unevaluated:
12962   case EST_BasicNoexcept:
12963   case EST_DynamicNone:
12964   case EST_MSAny:
12965   case EST_None:
12966     break;
12967 
12968   case EST_ComputedNoexcept:
12969     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12970       return true;
12971 
12972   case EST_Dynamic:
12973     for (const auto &E : Proto->exceptions()) {
12974       if (!Finder.TraverseType(E))
12975         return true;
12976     }
12977     break;
12978   }
12979 
12980   return false;
12981 }
12982 
12983 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12984   FindCXXThisExpr Finder(*this);
12985 
12986   // Check attributes.
12987   for (const auto *A : Method->attrs()) {
12988     // FIXME: This should be emitted by tblgen.
12989     Expr *Arg = nullptr;
12990     ArrayRef<Expr *> Args;
12991     if (const auto *G = dyn_cast<GuardedByAttr>(A))
12992       Arg = G->getArg();
12993     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
12994       Arg = G->getArg();
12995     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
12996       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
12997     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
12998       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
12999     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13000       Arg = ETLF->getSuccessValue();
13001       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13002     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13003       Arg = STLF->getSuccessValue();
13004       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13005     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13006       Arg = LR->getArg();
13007     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13008       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13009     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13010       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13011     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13012       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13013     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13014       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13015     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13016       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13017 
13018     if (Arg && !Finder.TraverseStmt(Arg))
13019       return true;
13020 
13021     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13022       if (!Finder.TraverseStmt(Args[I]))
13023         return true;
13024     }
13025   }
13026 
13027   return false;
13028 }
13029 
13030 void
13031 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
13032                                   ArrayRef<ParsedType> DynamicExceptions,
13033                                   ArrayRef<SourceRange> DynamicExceptionRanges,
13034                                   Expr *NoexceptExpr,
13035                                   SmallVectorImpl<QualType> &Exceptions,
13036                                   FunctionProtoType::ExceptionSpecInfo &ESI) {
13037   Exceptions.clear();
13038   ESI.Type = EST;
13039   if (EST == EST_Dynamic) {
13040     Exceptions.reserve(DynamicExceptions.size());
13041     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13042       // FIXME: Preserve type source info.
13043       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13044 
13045       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13046       collectUnexpandedParameterPacks(ET, Unexpanded);
13047       if (!Unexpanded.empty()) {
13048         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
13049                                          UPPC_ExceptionType,
13050                                          Unexpanded);
13051         continue;
13052       }
13053 
13054       // Check that the type is valid for an exception spec, and
13055       // drop it if not.
13056       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13057         Exceptions.push_back(ET);
13058     }
13059     ESI.Exceptions = Exceptions;
13060     return;
13061   }
13062 
13063   if (EST == EST_ComputedNoexcept) {
13064     // If an error occurred, there's no expression here.
13065     if (NoexceptExpr) {
13066       assert((NoexceptExpr->isTypeDependent() ||
13067               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13068               Context.BoolTy) &&
13069              "Parser should have made sure that the expression is boolean");
13070       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13071         ESI.Type = EST_BasicNoexcept;
13072         return;
13073       }
13074 
13075       if (!NoexceptExpr->isValueDependent())
13076         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13077                          diag::err_noexcept_needs_constant_expression,
13078                          /*AllowFold*/ false).get();
13079       ESI.NoexceptExpr = NoexceptExpr;
13080     }
13081     return;
13082   }
13083 }
13084 
13085 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
13086 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
13087   // Implicitly declared functions (e.g. copy constructors) are
13088   // __host__ __device__
13089   if (D->isImplicit())
13090     return CFT_HostDevice;
13091 
13092   if (D->hasAttr<CUDAGlobalAttr>())
13093     return CFT_Global;
13094 
13095   if (D->hasAttr<CUDADeviceAttr>()) {
13096     if (D->hasAttr<CUDAHostAttr>())
13097       return CFT_HostDevice;
13098     return CFT_Device;
13099   }
13100 
13101   return CFT_Host;
13102 }
13103 
13104 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
13105                            CUDAFunctionTarget CalleeTarget) {
13106   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
13107   // Callable from the device only."
13108   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
13109     return true;
13110 
13111   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
13112   // Callable from the host only."
13113   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
13114   // Callable from the host only."
13115   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
13116       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
13117     return true;
13118 
13119   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
13120     return true;
13121 
13122   return false;
13123 }
13124 
13125 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13126 ///
13127 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13128                                        SourceLocation DeclStart,
13129                                        Declarator &D, Expr *BitWidth,
13130                                        InClassInitStyle InitStyle,
13131                                        AccessSpecifier AS,
13132                                        AttributeList *MSPropertyAttr) {
13133   IdentifierInfo *II = D.getIdentifier();
13134   if (!II) {
13135     Diag(DeclStart, diag::err_anonymous_property);
13136     return nullptr;
13137   }
13138   SourceLocation Loc = D.getIdentifierLoc();
13139 
13140   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13141   QualType T = TInfo->getType();
13142   if (getLangOpts().CPlusPlus) {
13143     CheckExtraCXXDefaultArguments(D);
13144 
13145     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13146                                         UPPC_DataMemberType)) {
13147       D.setInvalidType();
13148       T = Context.IntTy;
13149       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13150     }
13151   }
13152 
13153   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13154 
13155   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13156     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13157          diag::err_invalid_thread)
13158       << DeclSpec::getSpecifierName(TSCS);
13159 
13160   // Check to see if this name was declared as a member previously
13161   NamedDecl *PrevDecl = nullptr;
13162   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13163   LookupName(Previous, S);
13164   switch (Previous.getResultKind()) {
13165   case LookupResult::Found:
13166   case LookupResult::FoundUnresolvedValue:
13167     PrevDecl = Previous.getAsSingle<NamedDecl>();
13168     break;
13169 
13170   case LookupResult::FoundOverloaded:
13171     PrevDecl = Previous.getRepresentativeDecl();
13172     break;
13173 
13174   case LookupResult::NotFound:
13175   case LookupResult::NotFoundInCurrentInstantiation:
13176   case LookupResult::Ambiguous:
13177     break;
13178   }
13179 
13180   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13181     // Maybe we will complain about the shadowed template parameter.
13182     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13183     // Just pretend that we didn't see the previous declaration.
13184     PrevDecl = nullptr;
13185   }
13186 
13187   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13188     PrevDecl = nullptr;
13189 
13190   SourceLocation TSSL = D.getLocStart();
13191   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13192   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13193       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13194   ProcessDeclAttributes(TUScope, NewPD, D);
13195   NewPD->setAccess(AS);
13196 
13197   if (NewPD->isInvalidDecl())
13198     Record->setInvalidDecl();
13199 
13200   if (D.getDeclSpec().isModulePrivateSpecified())
13201     NewPD->setModulePrivate();
13202 
13203   if (NewPD->isInvalidDecl() && PrevDecl) {
13204     // Don't introduce NewFD into scope; there's already something
13205     // with the same name in the same scope.
13206   } else if (II) {
13207     PushOnScopeChains(NewPD, S);
13208   } else
13209     Record->addDecl(NewPD);
13210 
13211   return NewPD;
13212 }
13213