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     // The declaration context corresponding to the scope is the semantic
450     // parent, unless this is a local function declaration, in which case
451     // it is that surrounding function.
452     DeclContext *ScopeDC = New->isLocalExternDecl()
453                                ? New->getLexicalDeclContext()
454                                : New->getDeclContext();
455     if (S && !isDeclInScope(Old, ScopeDC, S) &&
456         !New->getDeclContext()->isRecord())
457       // Ignore default parameters of old decl if they are not in
458       // the same scope and this is not an out-of-line definition of
459       // a member function.
460       OldParamHasDfl = false;
461     if (New->isLocalExternDecl() != Old->isLocalExternDecl())
462       // If only one of these is a local function declaration, then they are
463       // declared in different scopes, even though isDeclInScope may think
464       // they're in the same scope. (If both are local, the scope check is
465       // sufficent, and if neither is local, then they are in the same scope.)
466       OldParamHasDfl = false;
467 
468     if (OldParamHasDfl && NewParamHasDfl) {
469 
470       unsigned DiagDefaultParamID =
471         diag::err_param_default_argument_redefinition;
472 
473       // MSVC accepts that default parameters be redefined for member functions
474       // of template class. The new default parameter's value is ignored.
475       Invalid = true;
476       if (getLangOpts().MicrosoftExt) {
477         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
478         if (MD && MD->getParent()->getDescribedClassTemplate()) {
479           // Merge the old default argument into the new parameter.
480           NewParam->setHasInheritedDefaultArg();
481           if (OldParam->hasUninstantiatedDefaultArg())
482             NewParam->setUninstantiatedDefaultArg(
483                                       OldParam->getUninstantiatedDefaultArg());
484           else
485             NewParam->setDefaultArg(OldParam->getInit());
486           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
487           Invalid = false;
488         }
489       }
490 
491       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
492       // hint here. Alternatively, we could walk the type-source information
493       // for NewParam to find the last source location in the type... but it
494       // isn't worth the effort right now. This is the kind of test case that
495       // is hard to get right:
496       //   int f(int);
497       //   void g(int (*fp)(int) = f);
498       //   void g(int (*fp)(int) = &f);
499       Diag(NewParam->getLocation(), DiagDefaultParamID)
500         << NewParam->getDefaultArgRange();
501 
502       // Look for the function declaration where the default argument was
503       // actually written, which may be a declaration prior to Old.
504       for (FunctionDecl *Older = Old->getPreviousDecl();
505            Older; Older = Older->getPreviousDecl()) {
506         if (!Older->getParamDecl(p)->hasDefaultArg())
507           break;
508 
509         OldParam = Older->getParamDecl(p);
510       }
511 
512       Diag(OldParam->getLocation(), diag::note_previous_definition)
513         << OldParam->getDefaultArgRange();
514     } else if (OldParamHasDfl) {
515       // Merge the old default argument into the new parameter.
516       // It's important to use getInit() here;  getDefaultArg()
517       // strips off any top-level ExprWithCleanups.
518       NewParam->setHasInheritedDefaultArg();
519       if (OldParam->hasUninstantiatedDefaultArg())
520         NewParam->setUninstantiatedDefaultArg(
521                                       OldParam->getUninstantiatedDefaultArg());
522       else
523         NewParam->setDefaultArg(OldParam->getInit());
524     } else if (NewParamHasDfl) {
525       if (New->getDescribedFunctionTemplate()) {
526         // Paragraph 4, quoted above, only applies to non-template functions.
527         Diag(NewParam->getLocation(),
528              diag::err_param_default_argument_template_redecl)
529           << NewParam->getDefaultArgRange();
530         Diag(Old->getLocation(), diag::note_template_prev_declaration)
531           << false;
532       } else if (New->getTemplateSpecializationKind()
533                    != TSK_ImplicitInstantiation &&
534                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
535         // C++ [temp.expr.spec]p21:
536         //   Default function arguments shall not be specified in a declaration
537         //   or a definition for one of the following explicit specializations:
538         //     - the explicit specialization of a function template;
539         //     - the explicit specialization of a member function template;
540         //     - the explicit specialization of a member function of a class
541         //       template where the class template specialization to which the
542         //       member function specialization belongs is implicitly
543         //       instantiated.
544         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
545           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
546           << New->getDeclName()
547           << NewParam->getDefaultArgRange();
548       } else if (New->getDeclContext()->isDependentContext()) {
549         // C++ [dcl.fct.default]p6 (DR217):
550         //   Default arguments for a member function of a class template shall
551         //   be specified on the initial declaration of the member function
552         //   within the class template.
553         //
554         // Reading the tea leaves a bit in DR217 and its reference to DR205
555         // leads me to the conclusion that one cannot add default function
556         // arguments for an out-of-line definition of a member function of a
557         // dependent type.
558         int WhichKind = 2;
559         if (CXXRecordDecl *Record
560               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
561           if (Record->getDescribedClassTemplate())
562             WhichKind = 0;
563           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
564             WhichKind = 1;
565           else
566             WhichKind = 2;
567         }
568 
569         Diag(NewParam->getLocation(),
570              diag::err_param_default_argument_member_template_redecl)
571           << WhichKind
572           << NewParam->getDefaultArgRange();
573       }
574     }
575   }
576 
577   // DR1344: If a default argument is added outside a class definition and that
578   // default argument makes the function a special member function, the program
579   // is ill-formed. This can only happen for constructors.
580   if (isa<CXXConstructorDecl>(New) &&
581       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
582     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
583                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
584     if (NewSM != OldSM) {
585       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
586       assert(NewParam->hasDefaultArg());
587       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
588         << NewParam->getDefaultArgRange() << NewSM;
589       Diag(Old->getLocation(), diag::note_previous_declaration);
590     }
591   }
592 
593   const FunctionDecl *Def;
594   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
595   // template has a constexpr specifier then all its declarations shall
596   // contain the constexpr specifier.
597   if (New->isConstexpr() != Old->isConstexpr()) {
598     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
599       << New << New->isConstexpr();
600     Diag(Old->getLocation(), diag::note_previous_declaration);
601     Invalid = true;
602   } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
603     // C++11 [dcl.fcn.spec]p4:
604     //   If the definition of a function appears in a translation unit before its
605     //   first declaration as inline, the program is ill-formed.
606     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
607     Diag(Def->getLocation(), diag::note_previous_definition);
608     Invalid = true;
609   }
610 
611   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
612   // argument expression, that declaration shall be a definition and shall be
613   // the only declaration of the function or function template in the
614   // translation unit.
615   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
616       functionDeclHasDefaultArgument(Old)) {
617     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
618     Diag(Old->getLocation(), diag::note_previous_declaration);
619     Invalid = true;
620   }
621 
622   if (CheckEquivalentExceptionSpec(Old, New))
623     Invalid = true;
624 
625   return Invalid;
626 }
627 
628 /// \brief Merge the exception specifications of two variable declarations.
629 ///
630 /// This is called when there's a redeclaration of a VarDecl. The function
631 /// checks if the redeclaration might have an exception specification and
632 /// validates compatibility and merges the specs if necessary.
633 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
634   // Shortcut if exceptions are disabled.
635   if (!getLangOpts().CXXExceptions)
636     return;
637 
638   assert(Context.hasSameType(New->getType(), Old->getType()) &&
639          "Should only be called if types are otherwise the same.");
640 
641   QualType NewType = New->getType();
642   QualType OldType = Old->getType();
643 
644   // We're only interested in pointers and references to functions, as well
645   // as pointers to member functions.
646   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
647     NewType = R->getPointeeType();
648     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
649   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
650     NewType = P->getPointeeType();
651     OldType = OldType->getAs<PointerType>()->getPointeeType();
652   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
653     NewType = M->getPointeeType();
654     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
655   }
656 
657   if (!NewType->isFunctionProtoType())
658     return;
659 
660   // There's lots of special cases for functions. For function pointers, system
661   // libraries are hopefully not as broken so that we don't need these
662   // workarounds.
663   if (CheckEquivalentExceptionSpec(
664         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
665         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
666     New->setInvalidDecl();
667   }
668 }
669 
670 /// CheckCXXDefaultArguments - Verify that the default arguments for a
671 /// function declaration are well-formed according to C++
672 /// [dcl.fct.default].
673 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
674   unsigned NumParams = FD->getNumParams();
675   unsigned p;
676 
677   // Find first parameter with a default argument
678   for (p = 0; p < NumParams; ++p) {
679     ParmVarDecl *Param = FD->getParamDecl(p);
680     if (Param->hasDefaultArg())
681       break;
682   }
683 
684   // C++ [dcl.fct.default]p4:
685   //   In a given function declaration, all parameters
686   //   subsequent to a parameter with a default argument shall
687   //   have default arguments supplied in this or previous
688   //   declarations. A default argument shall not be redefined
689   //   by a later declaration (not even to the same value).
690   unsigned LastMissingDefaultArg = 0;
691   for (; p < NumParams; ++p) {
692     ParmVarDecl *Param = FD->getParamDecl(p);
693     if (!Param->hasDefaultArg()) {
694       if (Param->isInvalidDecl())
695         /* We already complained about this parameter. */;
696       else if (Param->getIdentifier())
697         Diag(Param->getLocation(),
698              diag::err_param_default_argument_missing_name)
699           << Param->getIdentifier();
700       else
701         Diag(Param->getLocation(),
702              diag::err_param_default_argument_missing);
703 
704       LastMissingDefaultArg = p;
705     }
706   }
707 
708   if (LastMissingDefaultArg > 0) {
709     // Some default arguments were missing. Clear out all of the
710     // default arguments up to (and including) the last missing
711     // default argument, so that we leave the function parameters
712     // in a semantically valid state.
713     for (p = 0; p <= LastMissingDefaultArg; ++p) {
714       ParmVarDecl *Param = FD->getParamDecl(p);
715       if (Param->hasDefaultArg()) {
716         Param->setDefaultArg(nullptr);
717       }
718     }
719   }
720 }
721 
722 // CheckConstexprParameterTypes - Check whether a function's parameter types
723 // are all literal types. If so, return true. If not, produce a suitable
724 // diagnostic and return false.
725 static bool CheckConstexprParameterTypes(Sema &SemaRef,
726                                          const FunctionDecl *FD) {
727   unsigned ArgIndex = 0;
728   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
729   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
730                                               e = FT->param_type_end();
731        i != e; ++i, ++ArgIndex) {
732     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
733     SourceLocation ParamLoc = PD->getLocation();
734     if (!(*i)->isDependentType() &&
735         SemaRef.RequireLiteralType(ParamLoc, *i,
736                                    diag::err_constexpr_non_literal_param,
737                                    ArgIndex+1, PD->getSourceRange(),
738                                    isa<CXXConstructorDecl>(FD)))
739       return false;
740   }
741   return true;
742 }
743 
744 /// \brief Get diagnostic %select index for tag kind for
745 /// record diagnostic message.
746 /// WARNING: Indexes apply to particular diagnostics only!
747 ///
748 /// \returns diagnostic %select index.
749 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
750   switch (Tag) {
751   case TTK_Struct: return 0;
752   case TTK_Interface: return 1;
753   case TTK_Class:  return 2;
754   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
755   }
756 }
757 
758 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
759 // the requirements of a constexpr function definition or a constexpr
760 // constructor definition. If so, return true. If not, produce appropriate
761 // diagnostics and return false.
762 //
763 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
764 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
765   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
766   if (MD && MD->isInstance()) {
767     // C++11 [dcl.constexpr]p4:
768     //  The definition of a constexpr constructor shall satisfy the following
769     //  constraints:
770     //  - the class shall not have any virtual base classes;
771     const CXXRecordDecl *RD = MD->getParent();
772     if (RD->getNumVBases()) {
773       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
774         << isa<CXXConstructorDecl>(NewFD)
775         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
776       for (const auto &I : RD->vbases())
777         Diag(I.getLocStart(),
778              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
779       return false;
780     }
781   }
782 
783   if (!isa<CXXConstructorDecl>(NewFD)) {
784     // C++11 [dcl.constexpr]p3:
785     //  The definition of a constexpr function shall satisfy the following
786     //  constraints:
787     // - it shall not be virtual;
788     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
789     if (Method && Method->isVirtual()) {
790       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
791 
792       // If it's not obvious why this function is virtual, find an overridden
793       // function which uses the 'virtual' keyword.
794       const CXXMethodDecl *WrittenVirtual = Method;
795       while (!WrittenVirtual->isVirtualAsWritten())
796         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
797       if (WrittenVirtual != Method)
798         Diag(WrittenVirtual->getLocation(),
799              diag::note_overridden_virtual_function);
800       return false;
801     }
802 
803     // - its return type shall be a literal type;
804     QualType RT = NewFD->getReturnType();
805     if (!RT->isDependentType() &&
806         RequireLiteralType(NewFD->getLocation(), RT,
807                            diag::err_constexpr_non_literal_return))
808       return false;
809   }
810 
811   // - each of its parameter types shall be a literal type;
812   if (!CheckConstexprParameterTypes(*this, NewFD))
813     return false;
814 
815   return true;
816 }
817 
818 /// Check the given declaration statement is legal within a constexpr function
819 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
820 ///
821 /// \return true if the body is OK (maybe only as an extension), false if we
822 ///         have diagnosed a problem.
823 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
824                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
825   // C++11 [dcl.constexpr]p3 and p4:
826   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
827   //  contain only
828   for (const auto *DclIt : DS->decls()) {
829     switch (DclIt->getKind()) {
830     case Decl::StaticAssert:
831     case Decl::Using:
832     case Decl::UsingShadow:
833     case Decl::UsingDirective:
834     case Decl::UnresolvedUsingTypename:
835     case Decl::UnresolvedUsingValue:
836       //   - static_assert-declarations
837       //   - using-declarations,
838       //   - using-directives,
839       continue;
840 
841     case Decl::Typedef:
842     case Decl::TypeAlias: {
843       //   - typedef declarations and alias-declarations that do not define
844       //     classes or enumerations,
845       const auto *TN = cast<TypedefNameDecl>(DclIt);
846       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
847         // Don't allow variably-modified types in constexpr functions.
848         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
849         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
850           << TL.getSourceRange() << TL.getType()
851           << isa<CXXConstructorDecl>(Dcl);
852         return false;
853       }
854       continue;
855     }
856 
857     case Decl::Enum:
858     case Decl::CXXRecord:
859       // C++1y allows types to be defined, not just declared.
860       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
861         SemaRef.Diag(DS->getLocStart(),
862                      SemaRef.getLangOpts().CPlusPlus14
863                        ? diag::warn_cxx11_compat_constexpr_type_definition
864                        : diag::ext_constexpr_type_definition)
865           << isa<CXXConstructorDecl>(Dcl);
866       continue;
867 
868     case Decl::EnumConstant:
869     case Decl::IndirectField:
870     case Decl::ParmVar:
871       // These can only appear with other declarations which are banned in
872       // C++11 and permitted in C++1y, so ignore them.
873       continue;
874 
875     case Decl::Var: {
876       // C++1y [dcl.constexpr]p3 allows anything except:
877       //   a definition of a variable of non-literal type or of static or
878       //   thread storage duration or for which no initialization is performed.
879       const auto *VD = cast<VarDecl>(DclIt);
880       if (VD->isThisDeclarationADefinition()) {
881         if (VD->isStaticLocal()) {
882           SemaRef.Diag(VD->getLocation(),
883                        diag::err_constexpr_local_var_static)
884             << isa<CXXConstructorDecl>(Dcl)
885             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
886           return false;
887         }
888         if (!VD->getType()->isDependentType() &&
889             SemaRef.RequireLiteralType(
890               VD->getLocation(), VD->getType(),
891               diag::err_constexpr_local_var_non_literal_type,
892               isa<CXXConstructorDecl>(Dcl)))
893           return false;
894         if (!VD->getType()->isDependentType() &&
895             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
896           SemaRef.Diag(VD->getLocation(),
897                        diag::err_constexpr_local_var_no_init)
898             << isa<CXXConstructorDecl>(Dcl);
899           return false;
900         }
901       }
902       SemaRef.Diag(VD->getLocation(),
903                    SemaRef.getLangOpts().CPlusPlus14
904                     ? diag::warn_cxx11_compat_constexpr_local_var
905                     : diag::ext_constexpr_local_var)
906         << isa<CXXConstructorDecl>(Dcl);
907       continue;
908     }
909 
910     case Decl::NamespaceAlias:
911     case Decl::Function:
912       // These are disallowed in C++11 and permitted in C++1y. Allow them
913       // everywhere as an extension.
914       if (!Cxx1yLoc.isValid())
915         Cxx1yLoc = DS->getLocStart();
916       continue;
917 
918     default:
919       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
920         << isa<CXXConstructorDecl>(Dcl);
921       return false;
922     }
923   }
924 
925   return true;
926 }
927 
928 /// Check that the given field is initialized within a constexpr constructor.
929 ///
930 /// \param Dcl The constexpr constructor being checked.
931 /// \param Field The field being checked. This may be a member of an anonymous
932 ///        struct or union nested within the class being checked.
933 /// \param Inits All declarations, including anonymous struct/union members and
934 ///        indirect members, for which any initialization was provided.
935 /// \param Diagnosed Set to true if an error is produced.
936 static void CheckConstexprCtorInitializer(Sema &SemaRef,
937                                           const FunctionDecl *Dcl,
938                                           FieldDecl *Field,
939                                           llvm::SmallSet<Decl*, 16> &Inits,
940                                           bool &Diagnosed) {
941   if (Field->isInvalidDecl())
942     return;
943 
944   if (Field->isUnnamedBitfield())
945     return;
946 
947   // Anonymous unions with no variant members and empty anonymous structs do not
948   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
949   // indirect fields don't need initializing.
950   if (Field->isAnonymousStructOrUnion() &&
951       (Field->getType()->isUnionType()
952            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
953            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
954     return;
955 
956   if (!Inits.count(Field)) {
957     if (!Diagnosed) {
958       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
959       Diagnosed = true;
960     }
961     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
962   } else if (Field->isAnonymousStructOrUnion()) {
963     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
964     for (auto *I : RD->fields())
965       // If an anonymous union contains an anonymous struct of which any member
966       // is initialized, all members must be initialized.
967       if (!RD->isUnion() || Inits.count(I))
968         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
969   }
970 }
971 
972 /// Check the provided statement is allowed in a constexpr function
973 /// definition.
974 static bool
975 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
976                            SmallVectorImpl<SourceLocation> &ReturnStmts,
977                            SourceLocation &Cxx1yLoc) {
978   // - its function-body shall be [...] a compound-statement that contains only
979   switch (S->getStmtClass()) {
980   case Stmt::NullStmtClass:
981     //   - null statements,
982     return true;
983 
984   case Stmt::DeclStmtClass:
985     //   - static_assert-declarations
986     //   - using-declarations,
987     //   - using-directives,
988     //   - typedef declarations and alias-declarations that do not define
989     //     classes or enumerations,
990     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
991       return false;
992     return true;
993 
994   case Stmt::ReturnStmtClass:
995     //   - and exactly one return statement;
996     if (isa<CXXConstructorDecl>(Dcl)) {
997       // C++1y allows return statements in constexpr constructors.
998       if (!Cxx1yLoc.isValid())
999         Cxx1yLoc = S->getLocStart();
1000       return true;
1001     }
1002 
1003     ReturnStmts.push_back(S->getLocStart());
1004     return true;
1005 
1006   case Stmt::CompoundStmtClass: {
1007     // C++1y allows compound-statements.
1008     if (!Cxx1yLoc.isValid())
1009       Cxx1yLoc = S->getLocStart();
1010 
1011     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1012     for (auto *BodyIt : CompStmt->body()) {
1013       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1014                                       Cxx1yLoc))
1015         return false;
1016     }
1017     return true;
1018   }
1019 
1020   case Stmt::AttributedStmtClass:
1021     if (!Cxx1yLoc.isValid())
1022       Cxx1yLoc = S->getLocStart();
1023     return true;
1024 
1025   case Stmt::IfStmtClass: {
1026     // C++1y allows if-statements.
1027     if (!Cxx1yLoc.isValid())
1028       Cxx1yLoc = S->getLocStart();
1029 
1030     IfStmt *If = cast<IfStmt>(S);
1031     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1032                                     Cxx1yLoc))
1033       return false;
1034     if (If->getElse() &&
1035         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1036                                     Cxx1yLoc))
1037       return false;
1038     return true;
1039   }
1040 
1041   case Stmt::WhileStmtClass:
1042   case Stmt::DoStmtClass:
1043   case Stmt::ForStmtClass:
1044   case Stmt::CXXForRangeStmtClass:
1045   case Stmt::ContinueStmtClass:
1046     // C++1y allows all of these. We don't allow them as extensions in C++11,
1047     // because they don't make sense without variable mutation.
1048     if (!SemaRef.getLangOpts().CPlusPlus14)
1049       break;
1050     if (!Cxx1yLoc.isValid())
1051       Cxx1yLoc = S->getLocStart();
1052     for (Stmt::child_range Children = S->children(); Children; ++Children)
1053       if (*Children &&
1054           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1055                                       Cxx1yLoc))
1056         return false;
1057     return true;
1058 
1059   case Stmt::SwitchStmtClass:
1060   case Stmt::CaseStmtClass:
1061   case Stmt::DefaultStmtClass:
1062   case Stmt::BreakStmtClass:
1063     // C++1y allows switch-statements, and since they don't need variable
1064     // mutation, we can reasonably allow them in C++11 as an extension.
1065     if (!Cxx1yLoc.isValid())
1066       Cxx1yLoc = S->getLocStart();
1067     for (Stmt::child_range Children = S->children(); Children; ++Children)
1068       if (*Children &&
1069           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1070                                       Cxx1yLoc))
1071         return false;
1072     return true;
1073 
1074   default:
1075     if (!isa<Expr>(S))
1076       break;
1077 
1078     // C++1y allows expression-statements.
1079     if (!Cxx1yLoc.isValid())
1080       Cxx1yLoc = S->getLocStart();
1081     return true;
1082   }
1083 
1084   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1085     << isa<CXXConstructorDecl>(Dcl);
1086   return false;
1087 }
1088 
1089 /// Check the body for the given constexpr function declaration only contains
1090 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1091 ///
1092 /// \return true if the body is OK, false if we have diagnosed a problem.
1093 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1094   if (isa<CXXTryStmt>(Body)) {
1095     // C++11 [dcl.constexpr]p3:
1096     //  The definition of a constexpr function shall satisfy the following
1097     //  constraints: [...]
1098     // - its function-body shall be = delete, = default, or a
1099     //   compound-statement
1100     //
1101     // C++11 [dcl.constexpr]p4:
1102     //  In the definition of a constexpr constructor, [...]
1103     // - its function-body shall not be a function-try-block;
1104     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1105       << isa<CXXConstructorDecl>(Dcl);
1106     return false;
1107   }
1108 
1109   SmallVector<SourceLocation, 4> ReturnStmts;
1110 
1111   // - its function-body shall be [...] a compound-statement that contains only
1112   //   [... list of cases ...]
1113   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1114   SourceLocation Cxx1yLoc;
1115   for (auto *BodyIt : CompBody->body()) {
1116     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1117       return false;
1118   }
1119 
1120   if (Cxx1yLoc.isValid())
1121     Diag(Cxx1yLoc,
1122          getLangOpts().CPlusPlus14
1123            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1124            : diag::ext_constexpr_body_invalid_stmt)
1125       << isa<CXXConstructorDecl>(Dcl);
1126 
1127   if (const CXXConstructorDecl *Constructor
1128         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1129     const CXXRecordDecl *RD = Constructor->getParent();
1130     // DR1359:
1131     // - every non-variant non-static data member and base class sub-object
1132     //   shall be initialized;
1133     // DR1460:
1134     // - if the class is a union having variant members, exactly one of them
1135     //   shall be initialized;
1136     if (RD->isUnion()) {
1137       if (Constructor->getNumCtorInitializers() == 0 &&
1138           RD->hasVariantMembers()) {
1139         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1140         return false;
1141       }
1142     } else if (!Constructor->isDependentContext() &&
1143                !Constructor->isDelegatingConstructor()) {
1144       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1145 
1146       // Skip detailed checking if we have enough initializers, and we would
1147       // allow at most one initializer per member.
1148       bool AnyAnonStructUnionMembers = false;
1149       unsigned Fields = 0;
1150       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1151            E = RD->field_end(); I != E; ++I, ++Fields) {
1152         if (I->isAnonymousStructOrUnion()) {
1153           AnyAnonStructUnionMembers = true;
1154           break;
1155         }
1156       }
1157       // DR1460:
1158       // - if the class is a union-like class, but is not a union, for each of
1159       //   its anonymous union members having variant members, exactly one of
1160       //   them shall be initialized;
1161       if (AnyAnonStructUnionMembers ||
1162           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1163         // Check initialization of non-static data members. Base classes are
1164         // always initialized so do not need to be checked. Dependent bases
1165         // might not have initializers in the member initializer list.
1166         llvm::SmallSet<Decl*, 16> Inits;
1167         for (const auto *I: Constructor->inits()) {
1168           if (FieldDecl *FD = I->getMember())
1169             Inits.insert(FD);
1170           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1171             Inits.insert(ID->chain_begin(), ID->chain_end());
1172         }
1173 
1174         bool Diagnosed = false;
1175         for (auto *I : RD->fields())
1176           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1177         if (Diagnosed)
1178           return false;
1179       }
1180     }
1181   } else {
1182     if (ReturnStmts.empty()) {
1183       // C++1y doesn't require constexpr functions to contain a 'return'
1184       // statement. We still do, unless the return type might be void, because
1185       // otherwise if there's no return statement, the function cannot
1186       // be used in a core constant expression.
1187       bool OK = getLangOpts().CPlusPlus14 &&
1188                 (Dcl->getReturnType()->isVoidType() ||
1189                  Dcl->getReturnType()->isDependentType());
1190       Diag(Dcl->getLocation(),
1191            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1192               : diag::err_constexpr_body_no_return);
1193       return OK;
1194     }
1195     if (ReturnStmts.size() > 1) {
1196       Diag(ReturnStmts.back(),
1197            getLangOpts().CPlusPlus14
1198              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1199              : diag::ext_constexpr_body_multiple_return);
1200       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1201         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1202     }
1203   }
1204 
1205   // C++11 [dcl.constexpr]p5:
1206   //   if no function argument values exist such that the function invocation
1207   //   substitution would produce a constant expression, the program is
1208   //   ill-formed; no diagnostic required.
1209   // C++11 [dcl.constexpr]p3:
1210   //   - every constructor call and implicit conversion used in initializing the
1211   //     return value shall be one of those allowed in a constant expression.
1212   // C++11 [dcl.constexpr]p4:
1213   //   - every constructor involved in initializing non-static data members and
1214   //     base class sub-objects shall be a constexpr constructor.
1215   SmallVector<PartialDiagnosticAt, 8> Diags;
1216   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1217     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1218       << isa<CXXConstructorDecl>(Dcl);
1219     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1220       Diag(Diags[I].first, Diags[I].second);
1221     // Don't return false here: we allow this for compatibility in
1222     // system headers.
1223   }
1224 
1225   return true;
1226 }
1227 
1228 /// isCurrentClassName - Determine whether the identifier II is the
1229 /// name of the class type currently being defined. In the case of
1230 /// nested classes, this will only return true if II is the name of
1231 /// the innermost class.
1232 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1233                               const CXXScopeSpec *SS) {
1234   assert(getLangOpts().CPlusPlus && "No class names in C!");
1235 
1236   CXXRecordDecl *CurDecl;
1237   if (SS && SS->isSet() && !SS->isInvalid()) {
1238     DeclContext *DC = computeDeclContext(*SS, true);
1239     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1240   } else
1241     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1242 
1243   if (CurDecl && CurDecl->getIdentifier())
1244     return &II == CurDecl->getIdentifier();
1245   return false;
1246 }
1247 
1248 /// \brief Determine whether the identifier II is a typo for the name of
1249 /// the class type currently being defined. If so, update it to the identifier
1250 /// that should have been used.
1251 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1252   assert(getLangOpts().CPlusPlus && "No class names in C!");
1253 
1254   if (!getLangOpts().SpellChecking)
1255     return false;
1256 
1257   CXXRecordDecl *CurDecl;
1258   if (SS && SS->isSet() && !SS->isInvalid()) {
1259     DeclContext *DC = computeDeclContext(*SS, true);
1260     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1261   } else
1262     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1263 
1264   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1265       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1266           < II->getLength()) {
1267     II = CurDecl->getIdentifier();
1268     return true;
1269   }
1270 
1271   return false;
1272 }
1273 
1274 /// \brief Determine whether the given class is a base class of the given
1275 /// class, including looking at dependent bases.
1276 static bool findCircularInheritance(const CXXRecordDecl *Class,
1277                                     const CXXRecordDecl *Current) {
1278   SmallVector<const CXXRecordDecl*, 8> Queue;
1279 
1280   Class = Class->getCanonicalDecl();
1281   while (true) {
1282     for (const auto &I : Current->bases()) {
1283       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1284       if (!Base)
1285         continue;
1286 
1287       Base = Base->getDefinition();
1288       if (!Base)
1289         continue;
1290 
1291       if (Base->getCanonicalDecl() == Class)
1292         return true;
1293 
1294       Queue.push_back(Base);
1295     }
1296 
1297     if (Queue.empty())
1298       return false;
1299 
1300     Current = Queue.pop_back_val();
1301   }
1302 
1303   return false;
1304 }
1305 
1306 /// \brief Perform propagation of DLL attributes from a derived class to a
1307 /// templated base class for MS compatibility.
1308 static void propagateDLLAttrToBaseClassTemplate(
1309     Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1310     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1311   if (getDLLAttr(
1312           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1313     // If the base class template has a DLL attribute, don't try to change it.
1314     return;
1315   }
1316 
1317   if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1318     // If the base class is not already specialized, we can do the propagation.
1319     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1320     NewAttr->setInherited(true);
1321     BaseTemplateSpec->addAttr(NewAttr);
1322     return;
1323   }
1324 
1325   bool DifferentAttribute = false;
1326   if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1327     if (!SpecializationAttr->isInherited()) {
1328       // The template has previously been specialized or instantiated with an
1329       // explicit attribute. We should not try to change it.
1330       return;
1331     }
1332     if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1333       // The specialization already has the right attribute.
1334       return;
1335     }
1336     DifferentAttribute = true;
1337   }
1338 
1339   // The template was previously instantiated or explicitly specialized without
1340   // a dll attribute, or the template was previously instantiated with a
1341   // different inherited attribute. It's too late for us to change the
1342   // attribute, so warn that this is unsupported.
1343   S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1344       << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1345   S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1346   if (BaseTemplateSpec->isExplicitSpecialization()) {
1347     S.Diag(BaseTemplateSpec->getLocation(),
1348            diag::note_template_class_explicit_specialization_was_here)
1349         << BaseTemplateSpec;
1350   } else {
1351     S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1352            diag::note_template_class_instantiation_was_here)
1353         << BaseTemplateSpec;
1354   }
1355 }
1356 
1357 /// \brief Check the validity of a C++ base class specifier.
1358 ///
1359 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1360 /// and returns NULL otherwise.
1361 CXXBaseSpecifier *
1362 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1363                          SourceRange SpecifierRange,
1364                          bool Virtual, AccessSpecifier Access,
1365                          TypeSourceInfo *TInfo,
1366                          SourceLocation EllipsisLoc) {
1367   QualType BaseType = TInfo->getType();
1368 
1369   // C++ [class.union]p1:
1370   //   A union shall not have base classes.
1371   if (Class->isUnion()) {
1372     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1373       << SpecifierRange;
1374     return nullptr;
1375   }
1376 
1377   if (EllipsisLoc.isValid() &&
1378       !TInfo->getType()->containsUnexpandedParameterPack()) {
1379     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1380       << TInfo->getTypeLoc().getSourceRange();
1381     EllipsisLoc = SourceLocation();
1382   }
1383 
1384   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1385 
1386   if (BaseType->isDependentType()) {
1387     // Make sure that we don't have circular inheritance among our dependent
1388     // bases. For non-dependent bases, the check for completeness below handles
1389     // this.
1390     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1391       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1392           ((BaseDecl = BaseDecl->getDefinition()) &&
1393            findCircularInheritance(Class, BaseDecl))) {
1394         Diag(BaseLoc, diag::err_circular_inheritance)
1395           << BaseType << Context.getTypeDeclType(Class);
1396 
1397         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1398           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1399             << BaseType;
1400 
1401         return nullptr;
1402       }
1403     }
1404 
1405     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1406                                           Class->getTagKind() == TTK_Class,
1407                                           Access, TInfo, EllipsisLoc);
1408   }
1409 
1410   // Base specifiers must be record types.
1411   if (!BaseType->isRecordType()) {
1412     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1413     return nullptr;
1414   }
1415 
1416   // C++ [class.union]p1:
1417   //   A union shall not be used as a base class.
1418   if (BaseType->isUnionType()) {
1419     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1420     return nullptr;
1421   }
1422 
1423   // For the MS ABI, propagate DLL attributes to base class templates.
1424   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1425     if (Attr *ClassAttr = getDLLAttr(Class)) {
1426       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1427               BaseType->getAsCXXRecordDecl())) {
1428         propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1429                                             BaseTemplate, BaseLoc);
1430       }
1431     }
1432   }
1433 
1434   // C++ [class.derived]p2:
1435   //   The class-name in a base-specifier shall not be an incompletely
1436   //   defined class.
1437   if (RequireCompleteType(BaseLoc, BaseType,
1438                           diag::err_incomplete_base_class, SpecifierRange)) {
1439     Class->setInvalidDecl();
1440     return nullptr;
1441   }
1442 
1443   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1444   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1445   assert(BaseDecl && "Record type has no declaration");
1446   BaseDecl = BaseDecl->getDefinition();
1447   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1448   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1449   assert(CXXBaseDecl && "Base type is not a C++ type");
1450 
1451   // A class which contains a flexible array member is not suitable for use as a
1452   // base class:
1453   //   - If the layout determines that a base comes before another base,
1454   //     the flexible array member would index into the subsequent base.
1455   //   - If the layout determines that base comes before the derived class,
1456   //     the flexible array member would index into the derived class.
1457   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1458     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1459       << CXXBaseDecl->getDeclName();
1460     return nullptr;
1461   }
1462 
1463   // C++ [class]p3:
1464   //   If a class is marked final and it appears as a base-type-specifier in
1465   //   base-clause, the program is ill-formed.
1466   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1467     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1468       << CXXBaseDecl->getDeclName()
1469       << FA->isSpelledAsSealed();
1470     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1471         << CXXBaseDecl->getDeclName() << FA->getRange();
1472     return nullptr;
1473   }
1474 
1475   if (BaseDecl->isInvalidDecl())
1476     Class->setInvalidDecl();
1477 
1478   // Create the base specifier.
1479   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1480                                         Class->getTagKind() == TTK_Class,
1481                                         Access, TInfo, EllipsisLoc);
1482 }
1483 
1484 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1485 /// one entry in the base class list of a class specifier, for
1486 /// example:
1487 ///    class foo : public bar, virtual private baz {
1488 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1489 BaseResult
1490 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1491                          ParsedAttributes &Attributes,
1492                          bool Virtual, AccessSpecifier Access,
1493                          ParsedType basetype, SourceLocation BaseLoc,
1494                          SourceLocation EllipsisLoc) {
1495   if (!classdecl)
1496     return true;
1497 
1498   AdjustDeclIfTemplate(classdecl);
1499   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1500   if (!Class)
1501     return true;
1502 
1503   // We haven't yet attached the base specifiers.
1504   Class->setIsParsingBaseSpecifiers();
1505 
1506   // We do not support any C++11 attributes on base-specifiers yet.
1507   // Diagnose any attributes we see.
1508   if (!Attributes.empty()) {
1509     for (AttributeList *Attr = Attributes.getList(); Attr;
1510          Attr = Attr->getNext()) {
1511       if (Attr->isInvalid() ||
1512           Attr->getKind() == AttributeList::IgnoredAttribute)
1513         continue;
1514       Diag(Attr->getLoc(),
1515            Attr->getKind() == AttributeList::UnknownAttribute
1516              ? diag::warn_unknown_attribute_ignored
1517              : diag::err_base_specifier_attribute)
1518         << Attr->getName();
1519     }
1520   }
1521 
1522   TypeSourceInfo *TInfo = nullptr;
1523   GetTypeFromParser(basetype, &TInfo);
1524 
1525   if (EllipsisLoc.isInvalid() &&
1526       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1527                                       UPPC_BaseType))
1528     return true;
1529 
1530   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1531                                                       Virtual, Access, TInfo,
1532                                                       EllipsisLoc))
1533     return BaseSpec;
1534   else
1535     Class->setInvalidDecl();
1536 
1537   return true;
1538 }
1539 
1540 /// \brief Performs the actual work of attaching the given base class
1541 /// specifiers to a C++ class.
1542 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1543                                 unsigned NumBases) {
1544  if (NumBases == 0)
1545     return false;
1546 
1547   // Used to keep track of which base types we have already seen, so
1548   // that we can properly diagnose redundant direct base types. Note
1549   // that the key is always the unqualified canonical type of the base
1550   // class.
1551   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1552 
1553   // Copy non-redundant base specifiers into permanent storage.
1554   unsigned NumGoodBases = 0;
1555   bool Invalid = false;
1556   for (unsigned idx = 0; idx < NumBases; ++idx) {
1557     QualType NewBaseType
1558       = Context.getCanonicalType(Bases[idx]->getType());
1559     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1560 
1561     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1562     if (KnownBase) {
1563       // C++ [class.mi]p3:
1564       //   A class shall not be specified as a direct base class of a
1565       //   derived class more than once.
1566       Diag(Bases[idx]->getLocStart(),
1567            diag::err_duplicate_base_class)
1568         << KnownBase->getType()
1569         << Bases[idx]->getSourceRange();
1570 
1571       // Delete the duplicate base class specifier; we're going to
1572       // overwrite its pointer later.
1573       Context.Deallocate(Bases[idx]);
1574 
1575       Invalid = true;
1576     } else {
1577       // Okay, add this new base class.
1578       KnownBase = Bases[idx];
1579       Bases[NumGoodBases++] = Bases[idx];
1580       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1581         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1582         if (Class->isInterface() &&
1583               (!RD->isInterface() ||
1584                KnownBase->getAccessSpecifier() != AS_public)) {
1585           // The Microsoft extension __interface does not permit bases that
1586           // are not themselves public interfaces.
1587           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1588             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1589             << RD->getSourceRange();
1590           Invalid = true;
1591         }
1592         if (RD->hasAttr<WeakAttr>())
1593           Class->addAttr(WeakAttr::CreateImplicit(Context));
1594       }
1595     }
1596   }
1597 
1598   // Attach the remaining base class specifiers to the derived class.
1599   Class->setBases(Bases, NumGoodBases);
1600 
1601   // Delete the remaining (good) base class specifiers, since their
1602   // data has been copied into the CXXRecordDecl.
1603   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1604     Context.Deallocate(Bases[idx]);
1605 
1606   return Invalid;
1607 }
1608 
1609 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1610 /// class, after checking whether there are any duplicate base
1611 /// classes.
1612 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1613                                unsigned NumBases) {
1614   if (!ClassDecl || !Bases || !NumBases)
1615     return;
1616 
1617   AdjustDeclIfTemplate(ClassDecl);
1618   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1619 }
1620 
1621 /// \brief Determine whether the type \p Derived is a C++ class that is
1622 /// derived from the type \p Base.
1623 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1624   if (!getLangOpts().CPlusPlus)
1625     return false;
1626 
1627   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1628   if (!DerivedRD)
1629     return false;
1630 
1631   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1632   if (!BaseRD)
1633     return false;
1634 
1635   // If either the base or the derived type is invalid, don't try to
1636   // check whether one is derived from the other.
1637   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1638     return false;
1639 
1640   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1641   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1642 }
1643 
1644 /// \brief Determine whether the type \p Derived is a C++ class that is
1645 /// derived from the type \p Base.
1646 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1647   if (!getLangOpts().CPlusPlus)
1648     return false;
1649 
1650   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1651   if (!DerivedRD)
1652     return false;
1653 
1654   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1655   if (!BaseRD)
1656     return false;
1657 
1658   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1659 }
1660 
1661 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1662                               CXXCastPath &BasePathArray) {
1663   assert(BasePathArray.empty() && "Base path array must be empty!");
1664   assert(Paths.isRecordingPaths() && "Must record paths!");
1665 
1666   const CXXBasePath &Path = Paths.front();
1667 
1668   // We first go backward and check if we have a virtual base.
1669   // FIXME: It would be better if CXXBasePath had the base specifier for
1670   // the nearest virtual base.
1671   unsigned Start = 0;
1672   for (unsigned I = Path.size(); I != 0; --I) {
1673     if (Path[I - 1].Base->isVirtual()) {
1674       Start = I - 1;
1675       break;
1676     }
1677   }
1678 
1679   // Now add all bases.
1680   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1681     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1682 }
1683 
1684 /// \brief Determine whether the given base path includes a virtual
1685 /// base class.
1686 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1687   for (CXXCastPath::const_iterator B = BasePath.begin(),
1688                                 BEnd = BasePath.end();
1689        B != BEnd; ++B)
1690     if ((*B)->isVirtual())
1691       return true;
1692 
1693   return false;
1694 }
1695 
1696 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1697 /// conversion (where Derived and Base are class types) is
1698 /// well-formed, meaning that the conversion is unambiguous (and
1699 /// that all of the base classes are accessible). Returns true
1700 /// and emits a diagnostic if the code is ill-formed, returns false
1701 /// otherwise. Loc is the location where this routine should point to
1702 /// if there is an error, and Range is the source range to highlight
1703 /// if there is an error.
1704 bool
1705 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1706                                    unsigned InaccessibleBaseID,
1707                                    unsigned AmbigiousBaseConvID,
1708                                    SourceLocation Loc, SourceRange Range,
1709                                    DeclarationName Name,
1710                                    CXXCastPath *BasePath) {
1711   // First, determine whether the path from Derived to Base is
1712   // ambiguous. This is slightly more expensive than checking whether
1713   // the Derived to Base conversion exists, because here we need to
1714   // explore multiple paths to determine if there is an ambiguity.
1715   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1716                      /*DetectVirtual=*/false);
1717   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1718   assert(DerivationOkay &&
1719          "Can only be used with a derived-to-base conversion");
1720   (void)DerivationOkay;
1721 
1722   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1723     if (InaccessibleBaseID) {
1724       // Check that the base class can be accessed.
1725       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1726                                    InaccessibleBaseID)) {
1727         case AR_inaccessible:
1728           return true;
1729         case AR_accessible:
1730         case AR_dependent:
1731         case AR_delayed:
1732           break;
1733       }
1734     }
1735 
1736     // Build a base path if necessary.
1737     if (BasePath)
1738       BuildBasePathArray(Paths, *BasePath);
1739     return false;
1740   }
1741 
1742   if (AmbigiousBaseConvID) {
1743     // We know that the derived-to-base conversion is ambiguous, and
1744     // we're going to produce a diagnostic. Perform the derived-to-base
1745     // search just one more time to compute all of the possible paths so
1746     // that we can print them out. This is more expensive than any of
1747     // the previous derived-to-base checks we've done, but at this point
1748     // performance isn't as much of an issue.
1749     Paths.clear();
1750     Paths.setRecordingPaths(true);
1751     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1752     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1753     (void)StillOkay;
1754 
1755     // Build up a textual representation of the ambiguous paths, e.g.,
1756     // D -> B -> A, that will be used to illustrate the ambiguous
1757     // conversions in the diagnostic. We only print one of the paths
1758     // to each base class subobject.
1759     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1760 
1761     Diag(Loc, AmbigiousBaseConvID)
1762     << Derived << Base << PathDisplayStr << Range << Name;
1763   }
1764   return true;
1765 }
1766 
1767 bool
1768 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1769                                    SourceLocation Loc, SourceRange Range,
1770                                    CXXCastPath *BasePath,
1771                                    bool IgnoreAccess) {
1772   return CheckDerivedToBaseConversion(Derived, Base,
1773                                       IgnoreAccess ? 0
1774                                        : diag::err_upcast_to_inaccessible_base,
1775                                       diag::err_ambiguous_derived_to_base_conv,
1776                                       Loc, Range, DeclarationName(),
1777                                       BasePath);
1778 }
1779 
1780 
1781 /// @brief Builds a string representing ambiguous paths from a
1782 /// specific derived class to different subobjects of the same base
1783 /// class.
1784 ///
1785 /// This function builds a string that can be used in error messages
1786 /// to show the different paths that one can take through the
1787 /// inheritance hierarchy to go from the derived class to different
1788 /// subobjects of a base class. The result looks something like this:
1789 /// @code
1790 /// struct D -> struct B -> struct A
1791 /// struct D -> struct C -> struct A
1792 /// @endcode
1793 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1794   std::string PathDisplayStr;
1795   std::set<unsigned> DisplayedPaths;
1796   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1797        Path != Paths.end(); ++Path) {
1798     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1799       // We haven't displayed a path to this particular base
1800       // class subobject yet.
1801       PathDisplayStr += "\n    ";
1802       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1803       for (CXXBasePath::const_iterator Element = Path->begin();
1804            Element != Path->end(); ++Element)
1805         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1806     }
1807   }
1808 
1809   return PathDisplayStr;
1810 }
1811 
1812 //===----------------------------------------------------------------------===//
1813 // C++ class member Handling
1814 //===----------------------------------------------------------------------===//
1815 
1816 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1817 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1818                                 SourceLocation ASLoc,
1819                                 SourceLocation ColonLoc,
1820                                 AttributeList *Attrs) {
1821   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1822   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1823                                                   ASLoc, ColonLoc);
1824   CurContext->addHiddenDecl(ASDecl);
1825   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1826 }
1827 
1828 /// CheckOverrideControl - Check C++11 override control semantics.
1829 void Sema::CheckOverrideControl(NamedDecl *D) {
1830   if (D->isInvalidDecl())
1831     return;
1832 
1833   // We only care about "override" and "final" declarations.
1834   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1835     return;
1836 
1837   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1838 
1839   // We can't check dependent instance methods.
1840   if (MD && MD->isInstance() &&
1841       (MD->getParent()->hasAnyDependentBases() ||
1842        MD->getType()->isDependentType()))
1843     return;
1844 
1845   if (MD && !MD->isVirtual()) {
1846     // If we have a non-virtual method, check if if hides a virtual method.
1847     // (In that case, it's most likely the method has the wrong type.)
1848     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1849     FindHiddenVirtualMethods(MD, OverloadedMethods);
1850 
1851     if (!OverloadedMethods.empty()) {
1852       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1853         Diag(OA->getLocation(),
1854              diag::override_keyword_hides_virtual_member_function)
1855           << "override" << (OverloadedMethods.size() > 1);
1856       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1857         Diag(FA->getLocation(),
1858              diag::override_keyword_hides_virtual_member_function)
1859           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1860           << (OverloadedMethods.size() > 1);
1861       }
1862       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1863       MD->setInvalidDecl();
1864       return;
1865     }
1866     // Fall through into the general case diagnostic.
1867     // FIXME: We might want to attempt typo correction here.
1868   }
1869 
1870   if (!MD || !MD->isVirtual()) {
1871     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1872       Diag(OA->getLocation(),
1873            diag::override_keyword_only_allowed_on_virtual_member_functions)
1874         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1875       D->dropAttr<OverrideAttr>();
1876     }
1877     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1878       Diag(FA->getLocation(),
1879            diag::override_keyword_only_allowed_on_virtual_member_functions)
1880         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1881         << FixItHint::CreateRemoval(FA->getLocation());
1882       D->dropAttr<FinalAttr>();
1883     }
1884     return;
1885   }
1886 
1887   // C++11 [class.virtual]p5:
1888   //   If a virtual function is marked with the virt-specifier override and
1889   //   does not override a member function of a base class, the program is
1890   //   ill-formed.
1891   bool HasOverriddenMethods =
1892     MD->begin_overridden_methods() != MD->end_overridden_methods();
1893   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1894     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1895       << MD->getDeclName();
1896 }
1897 
1898 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1899 /// function overrides a virtual member function marked 'final', according to
1900 /// C++11 [class.virtual]p4.
1901 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1902                                                   const CXXMethodDecl *Old) {
1903   FinalAttr *FA = Old->getAttr<FinalAttr>();
1904   if (!FA)
1905     return false;
1906 
1907   Diag(New->getLocation(), diag::err_final_function_overridden)
1908     << New->getDeclName()
1909     << FA->isSpelledAsSealed();
1910   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1911   return true;
1912 }
1913 
1914 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1915   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1916   // FIXME: Destruction of ObjC lifetime types has side-effects.
1917   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1918     return !RD->isCompleteDefinition() ||
1919            !RD->hasTrivialDefaultConstructor() ||
1920            !RD->hasTrivialDestructor();
1921   return false;
1922 }
1923 
1924 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1925   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1926     if (it->isDeclspecPropertyAttribute())
1927       return it;
1928   return nullptr;
1929 }
1930 
1931 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1932 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1933 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1934 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1935 /// present (but parsing it has been deferred).
1936 NamedDecl *
1937 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1938                                MultiTemplateParamsArg TemplateParameterLists,
1939                                Expr *BW, const VirtSpecifiers &VS,
1940                                InClassInitStyle InitStyle) {
1941   const DeclSpec &DS = D.getDeclSpec();
1942   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1943   DeclarationName Name = NameInfo.getName();
1944   SourceLocation Loc = NameInfo.getLoc();
1945 
1946   // For anonymous bitfields, the location should point to the type.
1947   if (Loc.isInvalid())
1948     Loc = D.getLocStart();
1949 
1950   Expr *BitWidth = static_cast<Expr*>(BW);
1951 
1952   assert(isa<CXXRecordDecl>(CurContext));
1953   assert(!DS.isFriendSpecified());
1954 
1955   bool isFunc = D.isDeclarationOfFunction();
1956 
1957   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1958     // The Microsoft extension __interface only permits public member functions
1959     // and prohibits constructors, destructors, operators, non-public member
1960     // functions, static methods and data members.
1961     unsigned InvalidDecl;
1962     bool ShowDeclName = true;
1963     if (!isFunc)
1964       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1965     else if (AS != AS_public)
1966       InvalidDecl = 2;
1967     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1968       InvalidDecl = 3;
1969     else switch (Name.getNameKind()) {
1970       case DeclarationName::CXXConstructorName:
1971         InvalidDecl = 4;
1972         ShowDeclName = false;
1973         break;
1974 
1975       case DeclarationName::CXXDestructorName:
1976         InvalidDecl = 5;
1977         ShowDeclName = false;
1978         break;
1979 
1980       case DeclarationName::CXXOperatorName:
1981       case DeclarationName::CXXConversionFunctionName:
1982         InvalidDecl = 6;
1983         break;
1984 
1985       default:
1986         InvalidDecl = 0;
1987         break;
1988     }
1989 
1990     if (InvalidDecl) {
1991       if (ShowDeclName)
1992         Diag(Loc, diag::err_invalid_member_in_interface)
1993           << (InvalidDecl-1) << Name;
1994       else
1995         Diag(Loc, diag::err_invalid_member_in_interface)
1996           << (InvalidDecl-1) << "";
1997       return nullptr;
1998     }
1999   }
2000 
2001   // C++ 9.2p6: A member shall not be declared to have automatic storage
2002   // duration (auto, register) or with the extern storage-class-specifier.
2003   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2004   // data members and cannot be applied to names declared const or static,
2005   // and cannot be applied to reference members.
2006   switch (DS.getStorageClassSpec()) {
2007   case DeclSpec::SCS_unspecified:
2008   case DeclSpec::SCS_typedef:
2009   case DeclSpec::SCS_static:
2010     break;
2011   case DeclSpec::SCS_mutable:
2012     if (isFunc) {
2013       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2014 
2015       // FIXME: It would be nicer if the keyword was ignored only for this
2016       // declarator. Otherwise we could get follow-up errors.
2017       D.getMutableDeclSpec().ClearStorageClassSpecs();
2018     }
2019     break;
2020   default:
2021     Diag(DS.getStorageClassSpecLoc(),
2022          diag::err_storageclass_invalid_for_member);
2023     D.getMutableDeclSpec().ClearStorageClassSpecs();
2024     break;
2025   }
2026 
2027   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2028                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2029                       !isFunc);
2030 
2031   if (DS.isConstexprSpecified() && isInstField) {
2032     SemaDiagnosticBuilder B =
2033         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2034     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2035     if (InitStyle == ICIS_NoInit) {
2036       B << 0 << 0;
2037       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2038         B << FixItHint::CreateRemoval(ConstexprLoc);
2039       else {
2040         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2041         D.getMutableDeclSpec().ClearConstexprSpec();
2042         const char *PrevSpec;
2043         unsigned DiagID;
2044         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2045             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2046         (void)Failed;
2047         assert(!Failed && "Making a constexpr member const shouldn't fail");
2048       }
2049     } else {
2050       B << 1;
2051       const char *PrevSpec;
2052       unsigned DiagID;
2053       if (D.getMutableDeclSpec().SetStorageClassSpec(
2054           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2055           Context.getPrintingPolicy())) {
2056         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2057                "This is the only DeclSpec that should fail to be applied");
2058         B << 1;
2059       } else {
2060         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2061         isInstField = false;
2062       }
2063     }
2064   }
2065 
2066   NamedDecl *Member;
2067   if (isInstField) {
2068     CXXScopeSpec &SS = D.getCXXScopeSpec();
2069 
2070     // Data members must have identifiers for names.
2071     if (!Name.isIdentifier()) {
2072       Diag(Loc, diag::err_bad_variable_name)
2073         << Name;
2074       return nullptr;
2075     }
2076 
2077     IdentifierInfo *II = Name.getAsIdentifierInfo();
2078 
2079     // Member field could not be with "template" keyword.
2080     // So TemplateParameterLists should be empty in this case.
2081     if (TemplateParameterLists.size()) {
2082       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2083       if (TemplateParams->size()) {
2084         // There is no such thing as a member field template.
2085         Diag(D.getIdentifierLoc(), diag::err_template_member)
2086             << II
2087             << SourceRange(TemplateParams->getTemplateLoc(),
2088                 TemplateParams->getRAngleLoc());
2089       } else {
2090         // There is an extraneous 'template<>' for this member.
2091         Diag(TemplateParams->getTemplateLoc(),
2092             diag::err_template_member_noparams)
2093             << II
2094             << SourceRange(TemplateParams->getTemplateLoc(),
2095                 TemplateParams->getRAngleLoc());
2096       }
2097       return nullptr;
2098     }
2099 
2100     if (SS.isSet() && !SS.isInvalid()) {
2101       // The user provided a superfluous scope specifier inside a class
2102       // definition:
2103       //
2104       // class X {
2105       //   int X::member;
2106       // };
2107       if (DeclContext *DC = computeDeclContext(SS, false))
2108         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2109       else
2110         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2111           << Name << SS.getRange();
2112 
2113       SS.clear();
2114     }
2115 
2116     AttributeList *MSPropertyAttr =
2117       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2118     if (MSPropertyAttr) {
2119       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2120                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2121       if (!Member)
2122         return nullptr;
2123       isInstField = false;
2124     } else {
2125       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2126                                 BitWidth, InitStyle, AS);
2127       assert(Member && "HandleField never returns null");
2128     }
2129   } else {
2130     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2131 
2132     Member = HandleDeclarator(S, D, TemplateParameterLists);
2133     if (!Member)
2134       return nullptr;
2135 
2136     // Non-instance-fields can't have a bitfield.
2137     if (BitWidth) {
2138       if (Member->isInvalidDecl()) {
2139         // don't emit another diagnostic.
2140       } else if (isa<VarDecl>(Member)) {
2141         // C++ 9.6p3: A bit-field shall not be a static member.
2142         // "static member 'A' cannot be a bit-field"
2143         Diag(Loc, diag::err_static_not_bitfield)
2144           << Name << BitWidth->getSourceRange();
2145       } else if (isa<TypedefDecl>(Member)) {
2146         // "typedef member 'x' cannot be a bit-field"
2147         Diag(Loc, diag::err_typedef_not_bitfield)
2148           << Name << BitWidth->getSourceRange();
2149       } else {
2150         // A function typedef ("typedef int f(); f a;").
2151         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2152         Diag(Loc, diag::err_not_integral_type_bitfield)
2153           << Name << cast<ValueDecl>(Member)->getType()
2154           << BitWidth->getSourceRange();
2155       }
2156 
2157       BitWidth = nullptr;
2158       Member->setInvalidDecl();
2159     }
2160 
2161     Member->setAccess(AS);
2162 
2163     // If we have declared a member function template or static data member
2164     // template, set the access of the templated declaration as well.
2165     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2166       FunTmpl->getTemplatedDecl()->setAccess(AS);
2167     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2168       VarTmpl->getTemplatedDecl()->setAccess(AS);
2169   }
2170 
2171   if (VS.isOverrideSpecified())
2172     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2173   if (VS.isFinalSpecified())
2174     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2175                                             VS.isFinalSpelledSealed()));
2176 
2177   if (VS.getLastLocation().isValid()) {
2178     // Update the end location of a method that has a virt-specifiers.
2179     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2180       MD->setRangeEnd(VS.getLastLocation());
2181   }
2182 
2183   CheckOverrideControl(Member);
2184 
2185   assert((Name || isInstField) && "No identifier for non-field ?");
2186 
2187   if (isInstField) {
2188     FieldDecl *FD = cast<FieldDecl>(Member);
2189     FieldCollector->Add(FD);
2190 
2191     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2192       // Remember all explicit private FieldDecls that have a name, no side
2193       // effects and are not part of a dependent type declaration.
2194       if (!FD->isImplicit() && FD->getDeclName() &&
2195           FD->getAccess() == AS_private &&
2196           !FD->hasAttr<UnusedAttr>() &&
2197           !FD->getParent()->isDependentContext() &&
2198           !InitializationHasSideEffects(*FD))
2199         UnusedPrivateFields.insert(FD);
2200     }
2201   }
2202 
2203   return Member;
2204 }
2205 
2206 namespace {
2207   class UninitializedFieldVisitor
2208       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2209     Sema &S;
2210     // List of Decls to generate a warning on.  Also remove Decls that become
2211     // initialized.
2212     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2213     // Vector of decls to be removed from the Decl set prior to visiting the
2214     // nodes.  These Decls may have been initialized in the prior initializer.
2215     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2216     // If non-null, add a note to the warning pointing back to the constructor.
2217     const CXXConstructorDecl *Constructor;
2218   public:
2219     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2220     UninitializedFieldVisitor(Sema &S,
2221                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls)
2222       : Inherited(S.Context), S(S), Decls(Decls) { }
2223 
2224     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
2225       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2226         return;
2227 
2228       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2229       // or union.
2230       MemberExpr *FieldME = ME;
2231 
2232       Expr *Base = ME;
2233       while (isa<MemberExpr>(Base)) {
2234         ME = cast<MemberExpr>(Base);
2235 
2236         if (isa<VarDecl>(ME->getMemberDecl()))
2237           return;
2238 
2239         if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2240           if (!FD->isAnonymousStructOrUnion())
2241             FieldME = ME;
2242 
2243         Base = ME->getBase();
2244       }
2245 
2246       if (!isa<CXXThisExpr>(Base))
2247         return;
2248 
2249       ValueDecl* FoundVD = FieldME->getMemberDecl();
2250 
2251       if (!Decls.count(FoundVD))
2252         return;
2253 
2254       const bool IsReference = FoundVD->getType()->isReferenceType();
2255 
2256       // Prevent double warnings on use of unbounded references.
2257       if (IsReference != CheckReferenceOnly)
2258         return;
2259 
2260       unsigned diag = IsReference
2261           ? diag::warn_reference_field_is_uninit
2262           : diag::warn_field_is_uninit;
2263       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2264       if (Constructor)
2265         S.Diag(Constructor->getLocation(),
2266                diag::note_uninit_in_this_constructor)
2267           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2268 
2269     }
2270 
2271     void HandleValue(Expr *E) {
2272       E = E->IgnoreParens();
2273 
2274       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2275         HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2276         return;
2277       }
2278 
2279       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2280         HandleValue(CO->getTrueExpr());
2281         HandleValue(CO->getFalseExpr());
2282         return;
2283       }
2284 
2285       if (BinaryConditionalOperator *BCO =
2286               dyn_cast<BinaryConditionalOperator>(E)) {
2287         HandleValue(BCO->getFalseExpr());
2288         return;
2289       }
2290 
2291       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2292         HandleValue(OVE->getSourceExpr());
2293         return;
2294       }
2295 
2296       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2297         switch (BO->getOpcode()) {
2298         default:
2299           return;
2300         case(BO_PtrMemD):
2301         case(BO_PtrMemI):
2302           HandleValue(BO->getLHS());
2303           return;
2304         case(BO_Comma):
2305           HandleValue(BO->getRHS());
2306           return;
2307         }
2308       }
2309     }
2310 
2311     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2312                           FieldDecl *Field) {
2313       // Remove Decls that may have been initialized in the previous
2314       // initializer.
2315       for (ValueDecl* VD : DeclsToRemove)
2316         Decls.erase(VD);
2317 
2318       DeclsToRemove.clear();
2319       Constructor = FieldConstructor;
2320       Visit(E);
2321       if (Field)
2322         Decls.erase(Field);
2323     }
2324 
2325     void VisitMemberExpr(MemberExpr *ME) {
2326       // All uses of unbounded reference fields will warn.
2327       HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
2328 
2329       Inherited::VisitMemberExpr(ME);
2330     }
2331 
2332     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2333       if (E->getCastKind() == CK_LValueToRValue)
2334         HandleValue(E->getSubExpr());
2335 
2336       Inherited::VisitImplicitCastExpr(E);
2337     }
2338 
2339     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2340       if (E->getConstructor()->isCopyConstructor()) {
2341         Expr *ArgExpr = E->getArg(0);
2342         if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) {
2343           if (ICE->getCastKind() == CK_NoOp) {
2344             ArgExpr = ICE->getSubExpr();
2345           }
2346         }
2347 
2348         if (MemberExpr *ME = dyn_cast<MemberExpr>(ArgExpr)) {
2349           HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2350         }
2351       }
2352       Inherited::VisitCXXConstructExpr(E);
2353     }
2354 
2355     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2356       Expr *Callee = E->getCallee();
2357       if (isa<MemberExpr>(Callee))
2358         HandleValue(Callee);
2359 
2360       Inherited::VisitCXXMemberCallExpr(E);
2361     }
2362 
2363     void VisitCallExpr(CallExpr *E) {
2364       // Treat std::move as a use.
2365       if (E->getNumArgs() == 1) {
2366         if (FunctionDecl *FD = E->getDirectCallee()) {
2367           if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
2368             HandleValue(E->getArg(0));
2369           }
2370         }
2371       }
2372 
2373       Inherited::VisitCallExpr(E);
2374     }
2375 
2376     void VisitBinaryOperator(BinaryOperator *E) {
2377       // If a field assignment is detected, remove the field from the
2378       // uninitiailized field set.
2379       if (E->getOpcode() == BO_Assign)
2380         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2381           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2382             if (!FD->getType()->isReferenceType())
2383               DeclsToRemove.push_back(FD);
2384 
2385       Inherited::VisitBinaryOperator(E);
2386     }
2387   };
2388 
2389   // Diagnose value-uses of fields to initialize themselves, e.g.
2390   //   foo(foo)
2391   // where foo is not also a parameter to the constructor.
2392   // Also diagnose across field uninitialized use such as
2393   //   x(y), y(x)
2394   // TODO: implement -Wuninitialized and fold this into that framework.
2395   static void DiagnoseUninitializedFields(
2396       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2397 
2398     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2399                                            Constructor->getLocation())) {
2400       return;
2401     }
2402 
2403     if (Constructor->isInvalidDecl())
2404       return;
2405 
2406     const CXXRecordDecl *RD = Constructor->getParent();
2407 
2408     // Holds fields that are uninitialized.
2409     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2410 
2411     // At the beginning, all fields are uninitialized.
2412     for (auto *I : RD->decls()) {
2413       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2414         UninitializedFields.insert(FD);
2415       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2416         UninitializedFields.insert(IFD->getAnonField());
2417       }
2418     }
2419 
2420     if (UninitializedFields.empty())
2421       return;
2422 
2423     UninitializedFieldVisitor UninitializedChecker(SemaRef,
2424                                                    UninitializedFields);
2425 
2426     for (const auto *FieldInit : Constructor->inits()) {
2427       if (UninitializedFields.empty())
2428         break;
2429 
2430       Expr *InitExpr = FieldInit->getInit();
2431       if (!InitExpr)
2432         continue;
2433 
2434       if (CXXDefaultInitExpr *Default =
2435               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2436         InitExpr = Default->getExpr();
2437         if (!InitExpr)
2438           continue;
2439         // In class initializers will point to the constructor.
2440         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2441                                               FieldInit->getAnyMember());
2442       } else {
2443         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2444                                               FieldInit->getAnyMember());
2445       }
2446     }
2447   }
2448 } // namespace
2449 
2450 /// \brief Enter a new C++ default initializer scope. After calling this, the
2451 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2452 /// parsing or instantiating the initializer failed.
2453 void Sema::ActOnStartCXXInClassMemberInitializer() {
2454   // Create a synthetic function scope to represent the call to the constructor
2455   // that notionally surrounds a use of this initializer.
2456   PushFunctionScope();
2457 }
2458 
2459 /// \brief This is invoked after parsing an in-class initializer for a
2460 /// non-static C++ class member, and after instantiating an in-class initializer
2461 /// in a class template. Such actions are deferred until the class is complete.
2462 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2463                                                   SourceLocation InitLoc,
2464                                                   Expr *InitExpr) {
2465   // Pop the notional constructor scope we created earlier.
2466   PopFunctionScopeInfo(nullptr, D);
2467 
2468   FieldDecl *FD = cast<FieldDecl>(D);
2469   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2470          "must set init style when field is created");
2471 
2472   if (!InitExpr) {
2473     FD->setInvalidDecl();
2474     FD->removeInClassInitializer();
2475     return;
2476   }
2477 
2478   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2479     FD->setInvalidDecl();
2480     FD->removeInClassInitializer();
2481     return;
2482   }
2483 
2484   ExprResult Init = InitExpr;
2485   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2486     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2487     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2488         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2489         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2490     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2491     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2492     if (Init.isInvalid()) {
2493       FD->setInvalidDecl();
2494       return;
2495     }
2496   }
2497 
2498   // C++11 [class.base.init]p7:
2499   //   The initialization of each base and member constitutes a
2500   //   full-expression.
2501   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2502   if (Init.isInvalid()) {
2503     FD->setInvalidDecl();
2504     return;
2505   }
2506 
2507   InitExpr = Init.get();
2508 
2509   FD->setInClassInitializer(InitExpr);
2510 }
2511 
2512 /// \brief Find the direct and/or virtual base specifiers that
2513 /// correspond to the given base type, for use in base initialization
2514 /// within a constructor.
2515 static bool FindBaseInitializer(Sema &SemaRef,
2516                                 CXXRecordDecl *ClassDecl,
2517                                 QualType BaseType,
2518                                 const CXXBaseSpecifier *&DirectBaseSpec,
2519                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2520   // First, check for a direct base class.
2521   DirectBaseSpec = nullptr;
2522   for (const auto &Base : ClassDecl->bases()) {
2523     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2524       // We found a direct base of this type. That's what we're
2525       // initializing.
2526       DirectBaseSpec = &Base;
2527       break;
2528     }
2529   }
2530 
2531   // Check for a virtual base class.
2532   // FIXME: We might be able to short-circuit this if we know in advance that
2533   // there are no virtual bases.
2534   VirtualBaseSpec = nullptr;
2535   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2536     // We haven't found a base yet; search the class hierarchy for a
2537     // virtual base class.
2538     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2539                        /*DetectVirtual=*/false);
2540     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2541                               BaseType, Paths)) {
2542       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2543            Path != Paths.end(); ++Path) {
2544         if (Path->back().Base->isVirtual()) {
2545           VirtualBaseSpec = Path->back().Base;
2546           break;
2547         }
2548       }
2549     }
2550   }
2551 
2552   return DirectBaseSpec || VirtualBaseSpec;
2553 }
2554 
2555 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2556 MemInitResult
2557 Sema::ActOnMemInitializer(Decl *ConstructorD,
2558                           Scope *S,
2559                           CXXScopeSpec &SS,
2560                           IdentifierInfo *MemberOrBase,
2561                           ParsedType TemplateTypeTy,
2562                           const DeclSpec &DS,
2563                           SourceLocation IdLoc,
2564                           Expr *InitList,
2565                           SourceLocation EllipsisLoc) {
2566   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2567                              DS, IdLoc, InitList,
2568                              EllipsisLoc);
2569 }
2570 
2571 /// \brief Handle a C++ member initializer using parentheses syntax.
2572 MemInitResult
2573 Sema::ActOnMemInitializer(Decl *ConstructorD,
2574                           Scope *S,
2575                           CXXScopeSpec &SS,
2576                           IdentifierInfo *MemberOrBase,
2577                           ParsedType TemplateTypeTy,
2578                           const DeclSpec &DS,
2579                           SourceLocation IdLoc,
2580                           SourceLocation LParenLoc,
2581                           ArrayRef<Expr *> Args,
2582                           SourceLocation RParenLoc,
2583                           SourceLocation EllipsisLoc) {
2584   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2585                                            Args, RParenLoc);
2586   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2587                              DS, IdLoc, List, EllipsisLoc);
2588 }
2589 
2590 namespace {
2591 
2592 // Callback to only accept typo corrections that can be a valid C++ member
2593 // intializer: either a non-static field member or a base class.
2594 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2595 public:
2596   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2597       : ClassDecl(ClassDecl) {}
2598 
2599   bool ValidateCandidate(const TypoCorrection &candidate) override {
2600     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2601       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2602         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2603       return isa<TypeDecl>(ND);
2604     }
2605     return false;
2606   }
2607 
2608 private:
2609   CXXRecordDecl *ClassDecl;
2610 };
2611 
2612 }
2613 
2614 /// \brief Handle a C++ member initializer.
2615 MemInitResult
2616 Sema::BuildMemInitializer(Decl *ConstructorD,
2617                           Scope *S,
2618                           CXXScopeSpec &SS,
2619                           IdentifierInfo *MemberOrBase,
2620                           ParsedType TemplateTypeTy,
2621                           const DeclSpec &DS,
2622                           SourceLocation IdLoc,
2623                           Expr *Init,
2624                           SourceLocation EllipsisLoc) {
2625   if (!ConstructorD)
2626     return true;
2627 
2628   AdjustDeclIfTemplate(ConstructorD);
2629 
2630   CXXConstructorDecl *Constructor
2631     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2632   if (!Constructor) {
2633     // The user wrote a constructor initializer on a function that is
2634     // not a C++ constructor. Ignore the error for now, because we may
2635     // have more member initializers coming; we'll diagnose it just
2636     // once in ActOnMemInitializers.
2637     return true;
2638   }
2639 
2640   CXXRecordDecl *ClassDecl = Constructor->getParent();
2641 
2642   // C++ [class.base.init]p2:
2643   //   Names in a mem-initializer-id are looked up in the scope of the
2644   //   constructor's class and, if not found in that scope, are looked
2645   //   up in the scope containing the constructor's definition.
2646   //   [Note: if the constructor's class contains a member with the
2647   //   same name as a direct or virtual base class of the class, a
2648   //   mem-initializer-id naming the member or base class and composed
2649   //   of a single identifier refers to the class member. A
2650   //   mem-initializer-id for the hidden base class may be specified
2651   //   using a qualified name. ]
2652   if (!SS.getScopeRep() && !TemplateTypeTy) {
2653     // Look for a member, first.
2654     DeclContext::lookup_result Result
2655       = ClassDecl->lookup(MemberOrBase);
2656     if (!Result.empty()) {
2657       ValueDecl *Member;
2658       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2659           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2660         if (EllipsisLoc.isValid())
2661           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2662             << MemberOrBase
2663             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2664 
2665         return BuildMemberInitializer(Member, Init, IdLoc);
2666       }
2667     }
2668   }
2669   // It didn't name a member, so see if it names a class.
2670   QualType BaseType;
2671   TypeSourceInfo *TInfo = nullptr;
2672 
2673   if (TemplateTypeTy) {
2674     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2675   } else if (DS.getTypeSpecType() == TST_decltype) {
2676     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2677   } else {
2678     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2679     LookupParsedName(R, S, &SS);
2680 
2681     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2682     if (!TyD) {
2683       if (R.isAmbiguous()) return true;
2684 
2685       // We don't want access-control diagnostics here.
2686       R.suppressDiagnostics();
2687 
2688       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2689         bool NotUnknownSpecialization = false;
2690         DeclContext *DC = computeDeclContext(SS, false);
2691         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2692           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2693 
2694         if (!NotUnknownSpecialization) {
2695           // When the scope specifier can refer to a member of an unknown
2696           // specialization, we take it as a type name.
2697           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2698                                        SS.getWithLocInContext(Context),
2699                                        *MemberOrBase, IdLoc);
2700           if (BaseType.isNull())
2701             return true;
2702 
2703           R.clear();
2704           R.setLookupName(MemberOrBase);
2705         }
2706       }
2707 
2708       // If no results were found, try to correct typos.
2709       TypoCorrection Corr;
2710       MemInitializerValidatorCCC Validator(ClassDecl);
2711       if (R.empty() && BaseType.isNull() &&
2712           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2713                               Validator, CTK_ErrorRecovery, ClassDecl))) {
2714         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2715           // We have found a non-static data member with a similar
2716           // name to what was typed; complain and initialize that
2717           // member.
2718           diagnoseTypo(Corr,
2719                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2720                          << MemberOrBase << true);
2721           return BuildMemberInitializer(Member, Init, IdLoc);
2722         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2723           const CXXBaseSpecifier *DirectBaseSpec;
2724           const CXXBaseSpecifier *VirtualBaseSpec;
2725           if (FindBaseInitializer(*this, ClassDecl,
2726                                   Context.getTypeDeclType(Type),
2727                                   DirectBaseSpec, VirtualBaseSpec)) {
2728             // We have found a direct or virtual base class with a
2729             // similar name to what was typed; complain and initialize
2730             // that base class.
2731             diagnoseTypo(Corr,
2732                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2733                            << MemberOrBase << false,
2734                          PDiag() /*Suppress note, we provide our own.*/);
2735 
2736             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2737                                                               : VirtualBaseSpec;
2738             Diag(BaseSpec->getLocStart(),
2739                  diag::note_base_class_specified_here)
2740               << BaseSpec->getType()
2741               << BaseSpec->getSourceRange();
2742 
2743             TyD = Type;
2744           }
2745         }
2746       }
2747 
2748       if (!TyD && BaseType.isNull()) {
2749         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2750           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2751         return true;
2752       }
2753     }
2754 
2755     if (BaseType.isNull()) {
2756       BaseType = Context.getTypeDeclType(TyD);
2757       if (SS.isSet())
2758         // FIXME: preserve source range information
2759         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2760                                              BaseType);
2761     }
2762   }
2763 
2764   if (!TInfo)
2765     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2766 
2767   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2768 }
2769 
2770 /// Checks a member initializer expression for cases where reference (or
2771 /// pointer) members are bound to by-value parameters (or their addresses).
2772 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2773                                                Expr *Init,
2774                                                SourceLocation IdLoc) {
2775   QualType MemberTy = Member->getType();
2776 
2777   // We only handle pointers and references currently.
2778   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2779   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2780     return;
2781 
2782   const bool IsPointer = MemberTy->isPointerType();
2783   if (IsPointer) {
2784     if (const UnaryOperator *Op
2785           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2786       // The only case we're worried about with pointers requires taking the
2787       // address.
2788       if (Op->getOpcode() != UO_AddrOf)
2789         return;
2790 
2791       Init = Op->getSubExpr();
2792     } else {
2793       // We only handle address-of expression initializers for pointers.
2794       return;
2795     }
2796   }
2797 
2798   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2799     // We only warn when referring to a non-reference parameter declaration.
2800     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2801     if (!Parameter || Parameter->getType()->isReferenceType())
2802       return;
2803 
2804     S.Diag(Init->getExprLoc(),
2805            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2806                      : diag::warn_bind_ref_member_to_parameter)
2807       << Member << Parameter << Init->getSourceRange();
2808   } else {
2809     // Other initializers are fine.
2810     return;
2811   }
2812 
2813   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2814     << (unsigned)IsPointer;
2815 }
2816 
2817 MemInitResult
2818 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2819                              SourceLocation IdLoc) {
2820   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2821   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2822   assert((DirectMember || IndirectMember) &&
2823          "Member must be a FieldDecl or IndirectFieldDecl");
2824 
2825   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2826     return true;
2827 
2828   if (Member->isInvalidDecl())
2829     return true;
2830 
2831   MultiExprArg Args;
2832   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2833     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2834   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2835     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2836   } else {
2837     // Template instantiation doesn't reconstruct ParenListExprs for us.
2838     Args = Init;
2839   }
2840 
2841   SourceRange InitRange = Init->getSourceRange();
2842 
2843   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2844     // Can't check initialization for a member of dependent type or when
2845     // any of the arguments are type-dependent expressions.
2846     DiscardCleanupsInEvaluationContext();
2847   } else {
2848     bool InitList = false;
2849     if (isa<InitListExpr>(Init)) {
2850       InitList = true;
2851       Args = Init;
2852     }
2853 
2854     // Initialize the member.
2855     InitializedEntity MemberEntity =
2856       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2857                    : InitializedEntity::InitializeMember(IndirectMember,
2858                                                          nullptr);
2859     InitializationKind Kind =
2860       InitList ? InitializationKind::CreateDirectList(IdLoc)
2861                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2862                                                   InitRange.getEnd());
2863 
2864     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2865     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2866                                             nullptr);
2867     if (MemberInit.isInvalid())
2868       return true;
2869 
2870     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2871 
2872     // C++11 [class.base.init]p7:
2873     //   The initialization of each base and member constitutes a
2874     //   full-expression.
2875     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2876     if (MemberInit.isInvalid())
2877       return true;
2878 
2879     Init = MemberInit.get();
2880   }
2881 
2882   if (DirectMember) {
2883     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2884                                             InitRange.getBegin(), Init,
2885                                             InitRange.getEnd());
2886   } else {
2887     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2888                                             InitRange.getBegin(), Init,
2889                                             InitRange.getEnd());
2890   }
2891 }
2892 
2893 MemInitResult
2894 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2895                                  CXXRecordDecl *ClassDecl) {
2896   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2897   if (!LangOpts.CPlusPlus11)
2898     return Diag(NameLoc, diag::err_delegating_ctor)
2899       << TInfo->getTypeLoc().getLocalSourceRange();
2900   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2901 
2902   bool InitList = true;
2903   MultiExprArg Args = Init;
2904   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2905     InitList = false;
2906     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2907   }
2908 
2909   SourceRange InitRange = Init->getSourceRange();
2910   // Initialize the object.
2911   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2912                                      QualType(ClassDecl->getTypeForDecl(), 0));
2913   InitializationKind Kind =
2914     InitList ? InitializationKind::CreateDirectList(NameLoc)
2915              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2916                                                 InitRange.getEnd());
2917   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2918   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2919                                               Args, nullptr);
2920   if (DelegationInit.isInvalid())
2921     return true;
2922 
2923   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2924          "Delegating constructor with no target?");
2925 
2926   // C++11 [class.base.init]p7:
2927   //   The initialization of each base and member constitutes a
2928   //   full-expression.
2929   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2930                                        InitRange.getBegin());
2931   if (DelegationInit.isInvalid())
2932     return true;
2933 
2934   // If we are in a dependent context, template instantiation will
2935   // perform this type-checking again. Just save the arguments that we
2936   // received in a ParenListExpr.
2937   // FIXME: This isn't quite ideal, since our ASTs don't capture all
2938   // of the information that we have about the base
2939   // initializer. However, deconstructing the ASTs is a dicey process,
2940   // and this approach is far more likely to get the corner cases right.
2941   if (CurContext->isDependentContext())
2942     DelegationInit = Init;
2943 
2944   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2945                                           DelegationInit.getAs<Expr>(),
2946                                           InitRange.getEnd());
2947 }
2948 
2949 MemInitResult
2950 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2951                            Expr *Init, CXXRecordDecl *ClassDecl,
2952                            SourceLocation EllipsisLoc) {
2953   SourceLocation BaseLoc
2954     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2955 
2956   if (!BaseType->isDependentType() && !BaseType->isRecordType())
2957     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2958              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2959 
2960   // C++ [class.base.init]p2:
2961   //   [...] Unless the mem-initializer-id names a nonstatic data
2962   //   member of the constructor's class or a direct or virtual base
2963   //   of that class, the mem-initializer is ill-formed. A
2964   //   mem-initializer-list can initialize a base class using any
2965   //   name that denotes that base class type.
2966   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2967 
2968   SourceRange InitRange = Init->getSourceRange();
2969   if (EllipsisLoc.isValid()) {
2970     // This is a pack expansion.
2971     if (!BaseType->containsUnexpandedParameterPack())  {
2972       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2973         << SourceRange(BaseLoc, InitRange.getEnd());
2974 
2975       EllipsisLoc = SourceLocation();
2976     }
2977   } else {
2978     // Check for any unexpanded parameter packs.
2979     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2980       return true;
2981 
2982     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2983       return true;
2984   }
2985 
2986   // Check for direct and virtual base classes.
2987   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2988   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
2989   if (!Dependent) {
2990     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2991                                        BaseType))
2992       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2993 
2994     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2995                         VirtualBaseSpec);
2996 
2997     // C++ [base.class.init]p2:
2998     // Unless the mem-initializer-id names a nonstatic data member of the
2999     // constructor's class or a direct or virtual base of that class, the
3000     // mem-initializer is ill-formed.
3001     if (!DirectBaseSpec && !VirtualBaseSpec) {
3002       // If the class has any dependent bases, then it's possible that
3003       // one of those types will resolve to the same type as
3004       // BaseType. Therefore, just treat this as a dependent base
3005       // class initialization.  FIXME: Should we try to check the
3006       // initialization anyway? It seems odd.
3007       if (ClassDecl->hasAnyDependentBases())
3008         Dependent = true;
3009       else
3010         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3011           << BaseType << Context.getTypeDeclType(ClassDecl)
3012           << BaseTInfo->getTypeLoc().getLocalSourceRange();
3013     }
3014   }
3015 
3016   if (Dependent) {
3017     DiscardCleanupsInEvaluationContext();
3018 
3019     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3020                                             /*IsVirtual=*/false,
3021                                             InitRange.getBegin(), Init,
3022                                             InitRange.getEnd(), EllipsisLoc);
3023   }
3024 
3025   // C++ [base.class.init]p2:
3026   //   If a mem-initializer-id is ambiguous because it designates both
3027   //   a direct non-virtual base class and an inherited virtual base
3028   //   class, the mem-initializer is ill-formed.
3029   if (DirectBaseSpec && VirtualBaseSpec)
3030     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3031       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3032 
3033   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3034   if (!BaseSpec)
3035     BaseSpec = VirtualBaseSpec;
3036 
3037   // Initialize the base.
3038   bool InitList = true;
3039   MultiExprArg Args = Init;
3040   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3041     InitList = false;
3042     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3043   }
3044 
3045   InitializedEntity BaseEntity =
3046     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3047   InitializationKind Kind =
3048     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3049              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3050                                                 InitRange.getEnd());
3051   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3052   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3053   if (BaseInit.isInvalid())
3054     return true;
3055 
3056   // C++11 [class.base.init]p7:
3057   //   The initialization of each base and member constitutes a
3058   //   full-expression.
3059   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3060   if (BaseInit.isInvalid())
3061     return true;
3062 
3063   // If we are in a dependent context, template instantiation will
3064   // perform this type-checking again. Just save the arguments that we
3065   // received in a ParenListExpr.
3066   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3067   // of the information that we have about the base
3068   // initializer. However, deconstructing the ASTs is a dicey process,
3069   // and this approach is far more likely to get the corner cases right.
3070   if (CurContext->isDependentContext())
3071     BaseInit = Init;
3072 
3073   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3074                                           BaseSpec->isVirtual(),
3075                                           InitRange.getBegin(),
3076                                           BaseInit.getAs<Expr>(),
3077                                           InitRange.getEnd(), EllipsisLoc);
3078 }
3079 
3080 // Create a static_cast\<T&&>(expr).
3081 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3082   if (T.isNull()) T = E->getType();
3083   QualType TargetType = SemaRef.BuildReferenceType(
3084       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3085   SourceLocation ExprLoc = E->getLocStart();
3086   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3087       TargetType, ExprLoc);
3088 
3089   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3090                                    SourceRange(ExprLoc, ExprLoc),
3091                                    E->getSourceRange()).get();
3092 }
3093 
3094 /// ImplicitInitializerKind - How an implicit base or member initializer should
3095 /// initialize its base or member.
3096 enum ImplicitInitializerKind {
3097   IIK_Default,
3098   IIK_Copy,
3099   IIK_Move,
3100   IIK_Inherit
3101 };
3102 
3103 static bool
3104 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3105                              ImplicitInitializerKind ImplicitInitKind,
3106                              CXXBaseSpecifier *BaseSpec,
3107                              bool IsInheritedVirtualBase,
3108                              CXXCtorInitializer *&CXXBaseInit) {
3109   InitializedEntity InitEntity
3110     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3111                                         IsInheritedVirtualBase);
3112 
3113   ExprResult BaseInit;
3114 
3115   switch (ImplicitInitKind) {
3116   case IIK_Inherit: {
3117     const CXXRecordDecl *Inherited =
3118         Constructor->getInheritedConstructor()->getParent();
3119     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3120     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3121       // C++11 [class.inhctor]p8:
3122       //   Each expression in the expression-list is of the form
3123       //   static_cast<T&&>(p), where p is the name of the corresponding
3124       //   constructor parameter and T is the declared type of p.
3125       SmallVector<Expr*, 16> Args;
3126       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3127         ParmVarDecl *PD = Constructor->getParamDecl(I);
3128         ExprResult ArgExpr =
3129             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3130                                      VK_LValue, SourceLocation());
3131         if (ArgExpr.isInvalid())
3132           return true;
3133         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3134       }
3135 
3136       InitializationKind InitKind = InitializationKind::CreateDirect(
3137           Constructor->getLocation(), SourceLocation(), SourceLocation());
3138       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3139       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3140       break;
3141     }
3142   }
3143   // Fall through.
3144   case IIK_Default: {
3145     InitializationKind InitKind
3146       = InitializationKind::CreateDefault(Constructor->getLocation());
3147     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3148     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3149     break;
3150   }
3151 
3152   case IIK_Move:
3153   case IIK_Copy: {
3154     bool Moving = ImplicitInitKind == IIK_Move;
3155     ParmVarDecl *Param = Constructor->getParamDecl(0);
3156     QualType ParamType = Param->getType().getNonReferenceType();
3157 
3158     Expr *CopyCtorArg =
3159       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3160                           SourceLocation(), Param, false,
3161                           Constructor->getLocation(), ParamType,
3162                           VK_LValue, nullptr);
3163 
3164     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3165 
3166     // Cast to the base class to avoid ambiguities.
3167     QualType ArgTy =
3168       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3169                                        ParamType.getQualifiers());
3170 
3171     if (Moving) {
3172       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3173     }
3174 
3175     CXXCastPath BasePath;
3176     BasePath.push_back(BaseSpec);
3177     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3178                                             CK_UncheckedDerivedToBase,
3179                                             Moving ? VK_XValue : VK_LValue,
3180                                             &BasePath).get();
3181 
3182     InitializationKind InitKind
3183       = InitializationKind::CreateDirect(Constructor->getLocation(),
3184                                          SourceLocation(), SourceLocation());
3185     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3186     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3187     break;
3188   }
3189   }
3190 
3191   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3192   if (BaseInit.isInvalid())
3193     return true;
3194 
3195   CXXBaseInit =
3196     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3197                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3198                                                         SourceLocation()),
3199                                              BaseSpec->isVirtual(),
3200                                              SourceLocation(),
3201                                              BaseInit.getAs<Expr>(),
3202                                              SourceLocation(),
3203                                              SourceLocation());
3204 
3205   return false;
3206 }
3207 
3208 static bool RefersToRValueRef(Expr *MemRef) {
3209   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3210   return Referenced->getType()->isRValueReferenceType();
3211 }
3212 
3213 static bool
3214 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3215                                ImplicitInitializerKind ImplicitInitKind,
3216                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3217                                CXXCtorInitializer *&CXXMemberInit) {
3218   if (Field->isInvalidDecl())
3219     return true;
3220 
3221   SourceLocation Loc = Constructor->getLocation();
3222 
3223   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3224     bool Moving = ImplicitInitKind == IIK_Move;
3225     ParmVarDecl *Param = Constructor->getParamDecl(0);
3226     QualType ParamType = Param->getType().getNonReferenceType();
3227 
3228     // Suppress copying zero-width bitfields.
3229     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3230       return false;
3231 
3232     Expr *MemberExprBase =
3233       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3234                           SourceLocation(), Param, false,
3235                           Loc, ParamType, VK_LValue, nullptr);
3236 
3237     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3238 
3239     if (Moving) {
3240       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3241     }
3242 
3243     // Build a reference to this field within the parameter.
3244     CXXScopeSpec SS;
3245     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3246                               Sema::LookupMemberName);
3247     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3248                                   : cast<ValueDecl>(Field), AS_public);
3249     MemberLookup.resolveKind();
3250     ExprResult CtorArg
3251       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3252                                          ParamType, Loc,
3253                                          /*IsArrow=*/false,
3254                                          SS,
3255                                          /*TemplateKWLoc=*/SourceLocation(),
3256                                          /*FirstQualifierInScope=*/nullptr,
3257                                          MemberLookup,
3258                                          /*TemplateArgs=*/nullptr);
3259     if (CtorArg.isInvalid())
3260       return true;
3261 
3262     // C++11 [class.copy]p15:
3263     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3264     //     with static_cast<T&&>(x.m);
3265     if (RefersToRValueRef(CtorArg.get())) {
3266       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3267     }
3268 
3269     // When the field we are copying is an array, create index variables for
3270     // each dimension of the array. We use these index variables to subscript
3271     // the source array, and other clients (e.g., CodeGen) will perform the
3272     // necessary iteration with these index variables.
3273     SmallVector<VarDecl *, 4> IndexVariables;
3274     QualType BaseType = Field->getType();
3275     QualType SizeType = SemaRef.Context.getSizeType();
3276     bool InitializingArray = false;
3277     while (const ConstantArrayType *Array
3278                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3279       InitializingArray = true;
3280       // Create the iteration variable for this array index.
3281       IdentifierInfo *IterationVarName = nullptr;
3282       {
3283         SmallString<8> Str;
3284         llvm::raw_svector_ostream OS(Str);
3285         OS << "__i" << IndexVariables.size();
3286         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3287       }
3288       VarDecl *IterationVar
3289         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3290                           IterationVarName, SizeType,
3291                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3292                           SC_None);
3293       IndexVariables.push_back(IterationVar);
3294 
3295       // Create a reference to the iteration variable.
3296       ExprResult IterationVarRef
3297         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3298       assert(!IterationVarRef.isInvalid() &&
3299              "Reference to invented variable cannot fail!");
3300       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3301       assert(!IterationVarRef.isInvalid() &&
3302              "Conversion of invented variable cannot fail!");
3303 
3304       // Subscript the array with this iteration variable.
3305       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3306                                                         IterationVarRef.get(),
3307                                                         Loc);
3308       if (CtorArg.isInvalid())
3309         return true;
3310 
3311       BaseType = Array->getElementType();
3312     }
3313 
3314     // The array subscript expression is an lvalue, which is wrong for moving.
3315     if (Moving && InitializingArray)
3316       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3317 
3318     // Construct the entity that we will be initializing. For an array, this
3319     // will be first element in the array, which may require several levels
3320     // of array-subscript entities.
3321     SmallVector<InitializedEntity, 4> Entities;
3322     Entities.reserve(1 + IndexVariables.size());
3323     if (Indirect)
3324       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3325     else
3326       Entities.push_back(InitializedEntity::InitializeMember(Field));
3327     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3328       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3329                                                               0,
3330                                                               Entities.back()));
3331 
3332     // Direct-initialize to use the copy constructor.
3333     InitializationKind InitKind =
3334       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3335 
3336     Expr *CtorArgE = CtorArg.getAs<Expr>();
3337     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3338 
3339     ExprResult MemberInit
3340       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3341                         MultiExprArg(&CtorArgE, 1));
3342     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3343     if (MemberInit.isInvalid())
3344       return true;
3345 
3346     if (Indirect) {
3347       assert(IndexVariables.size() == 0 &&
3348              "Indirect field improperly initialized");
3349       CXXMemberInit
3350         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3351                                                    Loc, Loc,
3352                                                    MemberInit.getAs<Expr>(),
3353                                                    Loc);
3354     } else
3355       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3356                                                  Loc, MemberInit.getAs<Expr>(),
3357                                                  Loc,
3358                                                  IndexVariables.data(),
3359                                                  IndexVariables.size());
3360     return false;
3361   }
3362 
3363   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3364          "Unhandled implicit init kind!");
3365 
3366   QualType FieldBaseElementType =
3367     SemaRef.Context.getBaseElementType(Field->getType());
3368 
3369   if (FieldBaseElementType->isRecordType()) {
3370     InitializedEntity InitEntity
3371       = Indirect? InitializedEntity::InitializeMember(Indirect)
3372                 : InitializedEntity::InitializeMember(Field);
3373     InitializationKind InitKind =
3374       InitializationKind::CreateDefault(Loc);
3375 
3376     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3377     ExprResult MemberInit =
3378       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3379 
3380     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3381     if (MemberInit.isInvalid())
3382       return true;
3383 
3384     if (Indirect)
3385       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3386                                                                Indirect, Loc,
3387                                                                Loc,
3388                                                                MemberInit.get(),
3389                                                                Loc);
3390     else
3391       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3392                                                                Field, Loc, Loc,
3393                                                                MemberInit.get(),
3394                                                                Loc);
3395     return false;
3396   }
3397 
3398   if (!Field->getParent()->isUnion()) {
3399     if (FieldBaseElementType->isReferenceType()) {
3400       SemaRef.Diag(Constructor->getLocation(),
3401                    diag::err_uninitialized_member_in_ctor)
3402       << (int)Constructor->isImplicit()
3403       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3404       << 0 << Field->getDeclName();
3405       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3406       return true;
3407     }
3408 
3409     if (FieldBaseElementType.isConstQualified()) {
3410       SemaRef.Diag(Constructor->getLocation(),
3411                    diag::err_uninitialized_member_in_ctor)
3412       << (int)Constructor->isImplicit()
3413       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3414       << 1 << Field->getDeclName();
3415       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3416       return true;
3417     }
3418   }
3419 
3420   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3421       FieldBaseElementType->isObjCRetainableType() &&
3422       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3423       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3424     // ARC:
3425     //   Default-initialize Objective-C pointers to NULL.
3426     CXXMemberInit
3427       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3428                                                  Loc, Loc,
3429                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3430                                                  Loc);
3431     return false;
3432   }
3433 
3434   // Nothing to initialize.
3435   CXXMemberInit = nullptr;
3436   return false;
3437 }
3438 
3439 namespace {
3440 struct BaseAndFieldInfo {
3441   Sema &S;
3442   CXXConstructorDecl *Ctor;
3443   bool AnyErrorsInInits;
3444   ImplicitInitializerKind IIK;
3445   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3446   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3447   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3448 
3449   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3450     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3451     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3452     if (Generated && Ctor->isCopyConstructor())
3453       IIK = IIK_Copy;
3454     else if (Generated && Ctor->isMoveConstructor())
3455       IIK = IIK_Move;
3456     else if (Ctor->getInheritedConstructor())
3457       IIK = IIK_Inherit;
3458     else
3459       IIK = IIK_Default;
3460   }
3461 
3462   bool isImplicitCopyOrMove() const {
3463     switch (IIK) {
3464     case IIK_Copy:
3465     case IIK_Move:
3466       return true;
3467 
3468     case IIK_Default:
3469     case IIK_Inherit:
3470       return false;
3471     }
3472 
3473     llvm_unreachable("Invalid ImplicitInitializerKind!");
3474   }
3475 
3476   bool addFieldInitializer(CXXCtorInitializer *Init) {
3477     AllToInit.push_back(Init);
3478 
3479     // Check whether this initializer makes the field "used".
3480     if (Init->getInit()->HasSideEffects(S.Context))
3481       S.UnusedPrivateFields.remove(Init->getAnyMember());
3482 
3483     return false;
3484   }
3485 
3486   bool isInactiveUnionMember(FieldDecl *Field) {
3487     RecordDecl *Record = Field->getParent();
3488     if (!Record->isUnion())
3489       return false;
3490 
3491     if (FieldDecl *Active =
3492             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3493       return Active != Field->getCanonicalDecl();
3494 
3495     // In an implicit copy or move constructor, ignore any in-class initializer.
3496     if (isImplicitCopyOrMove())
3497       return true;
3498 
3499     // If there's no explicit initialization, the field is active only if it
3500     // has an in-class initializer...
3501     if (Field->hasInClassInitializer())
3502       return false;
3503     // ... or it's an anonymous struct or union whose class has an in-class
3504     // initializer.
3505     if (!Field->isAnonymousStructOrUnion())
3506       return true;
3507     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3508     return !FieldRD->hasInClassInitializer();
3509   }
3510 
3511   /// \brief Determine whether the given field is, or is within, a union member
3512   /// that is inactive (because there was an initializer given for a different
3513   /// member of the union, or because the union was not initialized at all).
3514   bool isWithinInactiveUnionMember(FieldDecl *Field,
3515                                    IndirectFieldDecl *Indirect) {
3516     if (!Indirect)
3517       return isInactiveUnionMember(Field);
3518 
3519     for (auto *C : Indirect->chain()) {
3520       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3521       if (Field && isInactiveUnionMember(Field))
3522         return true;
3523     }
3524     return false;
3525   }
3526 };
3527 }
3528 
3529 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3530 /// array type.
3531 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3532   if (T->isIncompleteArrayType())
3533     return true;
3534 
3535   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3536     if (!ArrayT->getSize())
3537       return true;
3538 
3539     T = ArrayT->getElementType();
3540   }
3541 
3542   return false;
3543 }
3544 
3545 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3546                                     FieldDecl *Field,
3547                                     IndirectFieldDecl *Indirect = nullptr) {
3548   if (Field->isInvalidDecl())
3549     return false;
3550 
3551   // Overwhelmingly common case: we have a direct initializer for this field.
3552   if (CXXCtorInitializer *Init =
3553           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3554     return Info.addFieldInitializer(Init);
3555 
3556   // C++11 [class.base.init]p8:
3557   //   if the entity is a non-static data member that has a
3558   //   brace-or-equal-initializer and either
3559   //   -- the constructor's class is a union and no other variant member of that
3560   //      union is designated by a mem-initializer-id or
3561   //   -- the constructor's class is not a union, and, if the entity is a member
3562   //      of an anonymous union, no other member of that union is designated by
3563   //      a mem-initializer-id,
3564   //   the entity is initialized as specified in [dcl.init].
3565   //
3566   // We also apply the same rules to handle anonymous structs within anonymous
3567   // unions.
3568   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3569     return false;
3570 
3571   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3572     Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3573                                            Info.Ctor->getLocation(), Field);
3574     CXXCtorInitializer *Init;
3575     if (Indirect)
3576       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3577                                                       SourceLocation(),
3578                                                       SourceLocation(), DIE,
3579                                                       SourceLocation());
3580     else
3581       Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3582                                                       SourceLocation(),
3583                                                       SourceLocation(), DIE,
3584                                                       SourceLocation());
3585     return Info.addFieldInitializer(Init);
3586   }
3587 
3588   // Don't initialize incomplete or zero-length arrays.
3589   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3590     return false;
3591 
3592   // Don't try to build an implicit initializer if there were semantic
3593   // errors in any of the initializers (and therefore we might be
3594   // missing some that the user actually wrote).
3595   if (Info.AnyErrorsInInits)
3596     return false;
3597 
3598   CXXCtorInitializer *Init = nullptr;
3599   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3600                                      Indirect, Init))
3601     return true;
3602 
3603   if (!Init)
3604     return false;
3605 
3606   return Info.addFieldInitializer(Init);
3607 }
3608 
3609 bool
3610 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3611                                CXXCtorInitializer *Initializer) {
3612   assert(Initializer->isDelegatingInitializer());
3613   Constructor->setNumCtorInitializers(1);
3614   CXXCtorInitializer **initializer =
3615     new (Context) CXXCtorInitializer*[1];
3616   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3617   Constructor->setCtorInitializers(initializer);
3618 
3619   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3620     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3621     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3622   }
3623 
3624   DelegatingCtorDecls.push_back(Constructor);
3625 
3626   return false;
3627 }
3628 
3629 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3630                                ArrayRef<CXXCtorInitializer *> Initializers) {
3631   if (Constructor->isDependentContext()) {
3632     // Just store the initializers as written, they will be checked during
3633     // instantiation.
3634     if (!Initializers.empty()) {
3635       Constructor->setNumCtorInitializers(Initializers.size());
3636       CXXCtorInitializer **baseOrMemberInitializers =
3637         new (Context) CXXCtorInitializer*[Initializers.size()];
3638       memcpy(baseOrMemberInitializers, Initializers.data(),
3639              Initializers.size() * sizeof(CXXCtorInitializer*));
3640       Constructor->setCtorInitializers(baseOrMemberInitializers);
3641     }
3642 
3643     // Let template instantiation know whether we had errors.
3644     if (AnyErrors)
3645       Constructor->setInvalidDecl();
3646 
3647     return false;
3648   }
3649 
3650   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3651 
3652   // We need to build the initializer AST according to order of construction
3653   // and not what user specified in the Initializers list.
3654   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3655   if (!ClassDecl)
3656     return true;
3657 
3658   bool HadError = false;
3659 
3660   for (unsigned i = 0; i < Initializers.size(); i++) {
3661     CXXCtorInitializer *Member = Initializers[i];
3662 
3663     if (Member->isBaseInitializer())
3664       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3665     else {
3666       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3667 
3668       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3669         for (auto *C : F->chain()) {
3670           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3671           if (FD && FD->getParent()->isUnion())
3672             Info.ActiveUnionMember.insert(std::make_pair(
3673                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3674         }
3675       } else if (FieldDecl *FD = Member->getMember()) {
3676         if (FD->getParent()->isUnion())
3677           Info.ActiveUnionMember.insert(std::make_pair(
3678               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3679       }
3680     }
3681   }
3682 
3683   // Keep track of the direct virtual bases.
3684   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3685   for (auto &I : ClassDecl->bases()) {
3686     if (I.isVirtual())
3687       DirectVBases.insert(&I);
3688   }
3689 
3690   // Push virtual bases before others.
3691   for (auto &VBase : ClassDecl->vbases()) {
3692     if (CXXCtorInitializer *Value
3693         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3694       // [class.base.init]p7, per DR257:
3695       //   A mem-initializer where the mem-initializer-id names a virtual base
3696       //   class is ignored during execution of a constructor of any class that
3697       //   is not the most derived class.
3698       if (ClassDecl->isAbstract()) {
3699         // FIXME: Provide a fixit to remove the base specifier. This requires
3700         // tracking the location of the associated comma for a base specifier.
3701         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3702           << VBase.getType() << ClassDecl;
3703         DiagnoseAbstractType(ClassDecl);
3704       }
3705 
3706       Info.AllToInit.push_back(Value);
3707     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3708       // [class.base.init]p8, per DR257:
3709       //   If a given [...] base class is not named by a mem-initializer-id
3710       //   [...] and the entity is not a virtual base class of an abstract
3711       //   class, then [...] the entity is default-initialized.
3712       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3713       CXXCtorInitializer *CXXBaseInit;
3714       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3715                                        &VBase, IsInheritedVirtualBase,
3716                                        CXXBaseInit)) {
3717         HadError = true;
3718         continue;
3719       }
3720 
3721       Info.AllToInit.push_back(CXXBaseInit);
3722     }
3723   }
3724 
3725   // Non-virtual bases.
3726   for (auto &Base : ClassDecl->bases()) {
3727     // Virtuals are in the virtual base list and already constructed.
3728     if (Base.isVirtual())
3729       continue;
3730 
3731     if (CXXCtorInitializer *Value
3732           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3733       Info.AllToInit.push_back(Value);
3734     } else if (!AnyErrors) {
3735       CXXCtorInitializer *CXXBaseInit;
3736       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3737                                        &Base, /*IsInheritedVirtualBase=*/false,
3738                                        CXXBaseInit)) {
3739         HadError = true;
3740         continue;
3741       }
3742 
3743       Info.AllToInit.push_back(CXXBaseInit);
3744     }
3745   }
3746 
3747   // Fields.
3748   for (auto *Mem : ClassDecl->decls()) {
3749     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3750       // C++ [class.bit]p2:
3751       //   A declaration for a bit-field that omits the identifier declares an
3752       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3753       //   initialized.
3754       if (F->isUnnamedBitfield())
3755         continue;
3756 
3757       // If we're not generating the implicit copy/move constructor, then we'll
3758       // handle anonymous struct/union fields based on their individual
3759       // indirect fields.
3760       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3761         continue;
3762 
3763       if (CollectFieldInitializer(*this, Info, F))
3764         HadError = true;
3765       continue;
3766     }
3767 
3768     // Beyond this point, we only consider default initialization.
3769     if (Info.isImplicitCopyOrMove())
3770       continue;
3771 
3772     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
3773       if (F->getType()->isIncompleteArrayType()) {
3774         assert(ClassDecl->hasFlexibleArrayMember() &&
3775                "Incomplete array type is not valid");
3776         continue;
3777       }
3778 
3779       // Initialize each field of an anonymous struct individually.
3780       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3781         HadError = true;
3782 
3783       continue;
3784     }
3785   }
3786 
3787   unsigned NumInitializers = Info.AllToInit.size();
3788   if (NumInitializers > 0) {
3789     Constructor->setNumCtorInitializers(NumInitializers);
3790     CXXCtorInitializer **baseOrMemberInitializers =
3791       new (Context) CXXCtorInitializer*[NumInitializers];
3792     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3793            NumInitializers * sizeof(CXXCtorInitializer*));
3794     Constructor->setCtorInitializers(baseOrMemberInitializers);
3795 
3796     // Constructors implicitly reference the base and member
3797     // destructors.
3798     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3799                                            Constructor->getParent());
3800   }
3801 
3802   return HadError;
3803 }
3804 
3805 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3806   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3807     const RecordDecl *RD = RT->getDecl();
3808     if (RD->isAnonymousStructOrUnion()) {
3809       for (auto *Field : RD->fields())
3810         PopulateKeysForFields(Field, IdealInits);
3811       return;
3812     }
3813   }
3814   IdealInits.push_back(Field->getCanonicalDecl());
3815 }
3816 
3817 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3818   return Context.getCanonicalType(BaseType).getTypePtr();
3819 }
3820 
3821 static const void *GetKeyForMember(ASTContext &Context,
3822                                    CXXCtorInitializer *Member) {
3823   if (!Member->isAnyMemberInitializer())
3824     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3825 
3826   return Member->getAnyMember()->getCanonicalDecl();
3827 }
3828 
3829 static void DiagnoseBaseOrMemInitializerOrder(
3830     Sema &SemaRef, const CXXConstructorDecl *Constructor,
3831     ArrayRef<CXXCtorInitializer *> Inits) {
3832   if (Constructor->getDeclContext()->isDependentContext())
3833     return;
3834 
3835   // Don't check initializers order unless the warning is enabled at the
3836   // location of at least one initializer.
3837   bool ShouldCheckOrder = false;
3838   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3839     CXXCtorInitializer *Init = Inits[InitIndex];
3840     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3841                                  Init->getSourceLocation())) {
3842       ShouldCheckOrder = true;
3843       break;
3844     }
3845   }
3846   if (!ShouldCheckOrder)
3847     return;
3848 
3849   // Build the list of bases and members in the order that they'll
3850   // actually be initialized.  The explicit initializers should be in
3851   // this same order but may be missing things.
3852   SmallVector<const void*, 32> IdealInitKeys;
3853 
3854   const CXXRecordDecl *ClassDecl = Constructor->getParent();
3855 
3856   // 1. Virtual bases.
3857   for (const auto &VBase : ClassDecl->vbases())
3858     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
3859 
3860   // 2. Non-virtual bases.
3861   for (const auto &Base : ClassDecl->bases()) {
3862     if (Base.isVirtual())
3863       continue;
3864     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
3865   }
3866 
3867   // 3. Direct fields.
3868   for (auto *Field : ClassDecl->fields()) {
3869     if (Field->isUnnamedBitfield())
3870       continue;
3871 
3872     PopulateKeysForFields(Field, IdealInitKeys);
3873   }
3874 
3875   unsigned NumIdealInits = IdealInitKeys.size();
3876   unsigned IdealIndex = 0;
3877 
3878   CXXCtorInitializer *PrevInit = nullptr;
3879   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3880     CXXCtorInitializer *Init = Inits[InitIndex];
3881     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3882 
3883     // Scan forward to try to find this initializer in the idealized
3884     // initializers list.
3885     for (; IdealIndex != NumIdealInits; ++IdealIndex)
3886       if (InitKey == IdealInitKeys[IdealIndex])
3887         break;
3888 
3889     // If we didn't find this initializer, it must be because we
3890     // scanned past it on a previous iteration.  That can only
3891     // happen if we're out of order;  emit a warning.
3892     if (IdealIndex == NumIdealInits && PrevInit) {
3893       Sema::SemaDiagnosticBuilder D =
3894         SemaRef.Diag(PrevInit->getSourceLocation(),
3895                      diag::warn_initializer_out_of_order);
3896 
3897       if (PrevInit->isAnyMemberInitializer())
3898         D << 0 << PrevInit->getAnyMember()->getDeclName();
3899       else
3900         D << 1 << PrevInit->getTypeSourceInfo()->getType();
3901 
3902       if (Init->isAnyMemberInitializer())
3903         D << 0 << Init->getAnyMember()->getDeclName();
3904       else
3905         D << 1 << Init->getTypeSourceInfo()->getType();
3906 
3907       // Move back to the initializer's location in the ideal list.
3908       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3909         if (InitKey == IdealInitKeys[IdealIndex])
3910           break;
3911 
3912       assert(IdealIndex != NumIdealInits &&
3913              "initializer not found in initializer list");
3914     }
3915 
3916     PrevInit = Init;
3917   }
3918 }
3919 
3920 namespace {
3921 bool CheckRedundantInit(Sema &S,
3922                         CXXCtorInitializer *Init,
3923                         CXXCtorInitializer *&PrevInit) {
3924   if (!PrevInit) {
3925     PrevInit = Init;
3926     return false;
3927   }
3928 
3929   if (FieldDecl *Field = Init->getAnyMember())
3930     S.Diag(Init->getSourceLocation(),
3931            diag::err_multiple_mem_initialization)
3932       << Field->getDeclName()
3933       << Init->getSourceRange();
3934   else {
3935     const Type *BaseClass = Init->getBaseClass();
3936     assert(BaseClass && "neither field nor base");
3937     S.Diag(Init->getSourceLocation(),
3938            diag::err_multiple_base_initialization)
3939       << QualType(BaseClass, 0)
3940       << Init->getSourceRange();
3941   }
3942   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3943     << 0 << PrevInit->getSourceRange();
3944 
3945   return true;
3946 }
3947 
3948 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3949 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3950 
3951 bool CheckRedundantUnionInit(Sema &S,
3952                              CXXCtorInitializer *Init,
3953                              RedundantUnionMap &Unions) {
3954   FieldDecl *Field = Init->getAnyMember();
3955   RecordDecl *Parent = Field->getParent();
3956   NamedDecl *Child = Field;
3957 
3958   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3959     if (Parent->isUnion()) {
3960       UnionEntry &En = Unions[Parent];
3961       if (En.first && En.first != Child) {
3962         S.Diag(Init->getSourceLocation(),
3963                diag::err_multiple_mem_union_initialization)
3964           << Field->getDeclName()
3965           << Init->getSourceRange();
3966         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3967           << 0 << En.second->getSourceRange();
3968         return true;
3969       }
3970       if (!En.first) {
3971         En.first = Child;
3972         En.second = Init;
3973       }
3974       if (!Parent->isAnonymousStructOrUnion())
3975         return false;
3976     }
3977 
3978     Child = Parent;
3979     Parent = cast<RecordDecl>(Parent->getDeclContext());
3980   }
3981 
3982   return false;
3983 }
3984 }
3985 
3986 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3987 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3988                                 SourceLocation ColonLoc,
3989                                 ArrayRef<CXXCtorInitializer*> MemInits,
3990                                 bool AnyErrors) {
3991   if (!ConstructorDecl)
3992     return;
3993 
3994   AdjustDeclIfTemplate(ConstructorDecl);
3995 
3996   CXXConstructorDecl *Constructor
3997     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3998 
3999   if (!Constructor) {
4000     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4001     return;
4002   }
4003 
4004   // Mapping for the duplicate initializers check.
4005   // For member initializers, this is keyed with a FieldDecl*.
4006   // For base initializers, this is keyed with a Type*.
4007   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4008 
4009   // Mapping for the inconsistent anonymous-union initializers check.
4010   RedundantUnionMap MemberUnions;
4011 
4012   bool HadError = false;
4013   for (unsigned i = 0; i < MemInits.size(); i++) {
4014     CXXCtorInitializer *Init = MemInits[i];
4015 
4016     // Set the source order index.
4017     Init->setSourceOrder(i);
4018 
4019     if (Init->isAnyMemberInitializer()) {
4020       const void *Key = GetKeyForMember(Context, Init);
4021       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4022           CheckRedundantUnionInit(*this, Init, MemberUnions))
4023         HadError = true;
4024     } else if (Init->isBaseInitializer()) {
4025       const void *Key = GetKeyForMember(Context, Init);
4026       if (CheckRedundantInit(*this, Init, Members[Key]))
4027         HadError = true;
4028     } else {
4029       assert(Init->isDelegatingInitializer());
4030       // This must be the only initializer
4031       if (MemInits.size() != 1) {
4032         Diag(Init->getSourceLocation(),
4033              diag::err_delegating_initializer_alone)
4034           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4035         // We will treat this as being the only initializer.
4036       }
4037       SetDelegatingInitializer(Constructor, MemInits[i]);
4038       // Return immediately as the initializer is set.
4039       return;
4040     }
4041   }
4042 
4043   if (HadError)
4044     return;
4045 
4046   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4047 
4048   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4049 
4050   DiagnoseUninitializedFields(*this, Constructor);
4051 }
4052 
4053 void
4054 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4055                                              CXXRecordDecl *ClassDecl) {
4056   // Ignore dependent contexts. Also ignore unions, since their members never
4057   // have destructors implicitly called.
4058   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4059     return;
4060 
4061   // FIXME: all the access-control diagnostics are positioned on the
4062   // field/base declaration.  That's probably good; that said, the
4063   // user might reasonably want to know why the destructor is being
4064   // emitted, and we currently don't say.
4065 
4066   // Non-static data members.
4067   for (auto *Field : ClassDecl->fields()) {
4068     if (Field->isInvalidDecl())
4069       continue;
4070 
4071     // Don't destroy incomplete or zero-length arrays.
4072     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4073       continue;
4074 
4075     QualType FieldType = Context.getBaseElementType(Field->getType());
4076 
4077     const RecordType* RT = FieldType->getAs<RecordType>();
4078     if (!RT)
4079       continue;
4080 
4081     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4082     if (FieldClassDecl->isInvalidDecl())
4083       continue;
4084     if (FieldClassDecl->hasIrrelevantDestructor())
4085       continue;
4086     // The destructor for an implicit anonymous union member is never invoked.
4087     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4088       continue;
4089 
4090     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4091     assert(Dtor && "No dtor found for FieldClassDecl!");
4092     CheckDestructorAccess(Field->getLocation(), Dtor,
4093                           PDiag(diag::err_access_dtor_field)
4094                             << Field->getDeclName()
4095                             << FieldType);
4096 
4097     MarkFunctionReferenced(Location, Dtor);
4098     DiagnoseUseOfDecl(Dtor, Location);
4099   }
4100 
4101   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4102 
4103   // Bases.
4104   for (const auto &Base : ClassDecl->bases()) {
4105     // Bases are always records in a well-formed non-dependent class.
4106     const RecordType *RT = Base.getType()->getAs<RecordType>();
4107 
4108     // Remember direct virtual bases.
4109     if (Base.isVirtual())
4110       DirectVirtualBases.insert(RT);
4111 
4112     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4113     // If our base class is invalid, we probably can't get its dtor anyway.
4114     if (BaseClassDecl->isInvalidDecl())
4115       continue;
4116     if (BaseClassDecl->hasIrrelevantDestructor())
4117       continue;
4118 
4119     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4120     assert(Dtor && "No dtor found for BaseClassDecl!");
4121 
4122     // FIXME: caret should be on the start of the class name
4123     CheckDestructorAccess(Base.getLocStart(), Dtor,
4124                           PDiag(diag::err_access_dtor_base)
4125                             << Base.getType()
4126                             << Base.getSourceRange(),
4127                           Context.getTypeDeclType(ClassDecl));
4128 
4129     MarkFunctionReferenced(Location, Dtor);
4130     DiagnoseUseOfDecl(Dtor, Location);
4131   }
4132 
4133   // Virtual bases.
4134   for (const auto &VBase : ClassDecl->vbases()) {
4135     // Bases are always records in a well-formed non-dependent class.
4136     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4137 
4138     // Ignore direct virtual bases.
4139     if (DirectVirtualBases.count(RT))
4140       continue;
4141 
4142     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4143     // If our base class is invalid, we probably can't get its dtor anyway.
4144     if (BaseClassDecl->isInvalidDecl())
4145       continue;
4146     if (BaseClassDecl->hasIrrelevantDestructor())
4147       continue;
4148 
4149     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4150     assert(Dtor && "No dtor found for BaseClassDecl!");
4151     if (CheckDestructorAccess(
4152             ClassDecl->getLocation(), Dtor,
4153             PDiag(diag::err_access_dtor_vbase)
4154                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4155             Context.getTypeDeclType(ClassDecl)) ==
4156         AR_accessible) {
4157       CheckDerivedToBaseConversion(
4158           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4159           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4160           SourceRange(), DeclarationName(), nullptr);
4161     }
4162 
4163     MarkFunctionReferenced(Location, Dtor);
4164     DiagnoseUseOfDecl(Dtor, Location);
4165   }
4166 }
4167 
4168 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4169   if (!CDtorDecl)
4170     return;
4171 
4172   if (CXXConstructorDecl *Constructor
4173       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4174     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4175     DiagnoseUninitializedFields(*this, Constructor);
4176   }
4177 }
4178 
4179 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4180                                   unsigned DiagID, AbstractDiagSelID SelID) {
4181   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4182     unsigned DiagID;
4183     AbstractDiagSelID SelID;
4184 
4185   public:
4186     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4187       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4188 
4189     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4190       if (Suppressed) return;
4191       if (SelID == -1)
4192         S.Diag(Loc, DiagID) << T;
4193       else
4194         S.Diag(Loc, DiagID) << SelID << T;
4195     }
4196   } Diagnoser(DiagID, SelID);
4197 
4198   return RequireNonAbstractType(Loc, T, Diagnoser);
4199 }
4200 
4201 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4202                                   TypeDiagnoser &Diagnoser) {
4203   if (!getLangOpts().CPlusPlus)
4204     return false;
4205 
4206   if (const ArrayType *AT = Context.getAsArrayType(T))
4207     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4208 
4209   if (const PointerType *PT = T->getAs<PointerType>()) {
4210     // Find the innermost pointer type.
4211     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4212       PT = T;
4213 
4214     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4215       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4216   }
4217 
4218   const RecordType *RT = T->getAs<RecordType>();
4219   if (!RT)
4220     return false;
4221 
4222   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4223 
4224   // We can't answer whether something is abstract until it has a
4225   // definition.  If it's currently being defined, we'll walk back
4226   // over all the declarations when we have a full definition.
4227   const CXXRecordDecl *Def = RD->getDefinition();
4228   if (!Def || Def->isBeingDefined())
4229     return false;
4230 
4231   if (!RD->isAbstract())
4232     return false;
4233 
4234   Diagnoser.diagnose(*this, Loc, T);
4235   DiagnoseAbstractType(RD);
4236 
4237   return true;
4238 }
4239 
4240 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4241   // Check if we've already emitted the list of pure virtual functions
4242   // for this class.
4243   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4244     return;
4245 
4246   // If the diagnostic is suppressed, don't emit the notes. We're only
4247   // going to emit them once, so try to attach them to a diagnostic we're
4248   // actually going to show.
4249   if (Diags.isLastDiagnosticIgnored())
4250     return;
4251 
4252   CXXFinalOverriderMap FinalOverriders;
4253   RD->getFinalOverriders(FinalOverriders);
4254 
4255   // Keep a set of seen pure methods so we won't diagnose the same method
4256   // more than once.
4257   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4258 
4259   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4260                                    MEnd = FinalOverriders.end();
4261        M != MEnd;
4262        ++M) {
4263     for (OverridingMethods::iterator SO = M->second.begin(),
4264                                   SOEnd = M->second.end();
4265          SO != SOEnd; ++SO) {
4266       // C++ [class.abstract]p4:
4267       //   A class is abstract if it contains or inherits at least one
4268       //   pure virtual function for which the final overrider is pure
4269       //   virtual.
4270 
4271       //
4272       if (SO->second.size() != 1)
4273         continue;
4274 
4275       if (!SO->second.front().Method->isPure())
4276         continue;
4277 
4278       if (!SeenPureMethods.insert(SO->second.front().Method))
4279         continue;
4280 
4281       Diag(SO->second.front().Method->getLocation(),
4282            diag::note_pure_virtual_function)
4283         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4284     }
4285   }
4286 
4287   if (!PureVirtualClassDiagSet)
4288     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4289   PureVirtualClassDiagSet->insert(RD);
4290 }
4291 
4292 namespace {
4293 struct AbstractUsageInfo {
4294   Sema &S;
4295   CXXRecordDecl *Record;
4296   CanQualType AbstractType;
4297   bool Invalid;
4298 
4299   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4300     : S(S), Record(Record),
4301       AbstractType(S.Context.getCanonicalType(
4302                    S.Context.getTypeDeclType(Record))),
4303       Invalid(false) {}
4304 
4305   void DiagnoseAbstractType() {
4306     if (Invalid) return;
4307     S.DiagnoseAbstractType(Record);
4308     Invalid = true;
4309   }
4310 
4311   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4312 };
4313 
4314 struct CheckAbstractUsage {
4315   AbstractUsageInfo &Info;
4316   const NamedDecl *Ctx;
4317 
4318   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4319     : Info(Info), Ctx(Ctx) {}
4320 
4321   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4322     switch (TL.getTypeLocClass()) {
4323 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4324 #define TYPELOC(CLASS, PARENT) \
4325     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4326 #include "clang/AST/TypeLocNodes.def"
4327     }
4328   }
4329 
4330   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4331     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4332     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4333       if (!TL.getParam(I))
4334         continue;
4335 
4336       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4337       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4338     }
4339   }
4340 
4341   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4342     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4343   }
4344 
4345   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4346     // Visit the type parameters from a permissive context.
4347     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4348       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4349       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4350         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4351           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4352       // TODO: other template argument types?
4353     }
4354   }
4355 
4356   // Visit pointee types from a permissive context.
4357 #define CheckPolymorphic(Type) \
4358   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4359     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4360   }
4361   CheckPolymorphic(PointerTypeLoc)
4362   CheckPolymorphic(ReferenceTypeLoc)
4363   CheckPolymorphic(MemberPointerTypeLoc)
4364   CheckPolymorphic(BlockPointerTypeLoc)
4365   CheckPolymorphic(AtomicTypeLoc)
4366 
4367   /// Handle all the types we haven't given a more specific
4368   /// implementation for above.
4369   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4370     // Every other kind of type that we haven't called out already
4371     // that has an inner type is either (1) sugar or (2) contains that
4372     // inner type in some way as a subobject.
4373     if (TypeLoc Next = TL.getNextTypeLoc())
4374       return Visit(Next, Sel);
4375 
4376     // If there's no inner type and we're in a permissive context,
4377     // don't diagnose.
4378     if (Sel == Sema::AbstractNone) return;
4379 
4380     // Check whether the type matches the abstract type.
4381     QualType T = TL.getType();
4382     if (T->isArrayType()) {
4383       Sel = Sema::AbstractArrayType;
4384       T = Info.S.Context.getBaseElementType(T);
4385     }
4386     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4387     if (CT != Info.AbstractType) return;
4388 
4389     // It matched; do some magic.
4390     if (Sel == Sema::AbstractArrayType) {
4391       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4392         << T << TL.getSourceRange();
4393     } else {
4394       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4395         << Sel << T << TL.getSourceRange();
4396     }
4397     Info.DiagnoseAbstractType();
4398   }
4399 };
4400 
4401 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4402                                   Sema::AbstractDiagSelID Sel) {
4403   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4404 }
4405 
4406 }
4407 
4408 /// Check for invalid uses of an abstract type in a method declaration.
4409 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4410                                     CXXMethodDecl *MD) {
4411   // No need to do the check on definitions, which require that
4412   // the return/param types be complete.
4413   if (MD->doesThisDeclarationHaveABody())
4414     return;
4415 
4416   // For safety's sake, just ignore it if we don't have type source
4417   // information.  This should never happen for non-implicit methods,
4418   // but...
4419   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4420     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4421 }
4422 
4423 /// Check for invalid uses of an abstract type within a class definition.
4424 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4425                                     CXXRecordDecl *RD) {
4426   for (auto *D : RD->decls()) {
4427     if (D->isImplicit()) continue;
4428 
4429     // Methods and method templates.
4430     if (isa<CXXMethodDecl>(D)) {
4431       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4432     } else if (isa<FunctionTemplateDecl>(D)) {
4433       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4434       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4435 
4436     // Fields and static variables.
4437     } else if (isa<FieldDecl>(D)) {
4438       FieldDecl *FD = cast<FieldDecl>(D);
4439       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4440         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4441     } else if (isa<VarDecl>(D)) {
4442       VarDecl *VD = cast<VarDecl>(D);
4443       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4444         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4445 
4446     // Nested classes and class templates.
4447     } else if (isa<CXXRecordDecl>(D)) {
4448       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4449     } else if (isa<ClassTemplateDecl>(D)) {
4450       CheckAbstractClassUsage(Info,
4451                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4452     }
4453   }
4454 }
4455 
4456 /// \brief Check class-level dllimport/dllexport attribute.
4457 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4458   Attr *ClassAttr = getDLLAttr(Class);
4459 
4460   // MSVC inherits DLL attributes to partial class template specializations.
4461   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4462     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4463       if (Attr *TemplateAttr =
4464               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4465         auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4466         A->setInherited(true);
4467         ClassAttr = A;
4468       }
4469     }
4470   }
4471 
4472   if (!ClassAttr)
4473     return;
4474 
4475   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4476       !ClassAttr->isInherited()) {
4477     // Diagnose dll attributes on members of class with dll attribute.
4478     for (Decl *Member : Class->decls()) {
4479       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4480         continue;
4481       InheritableAttr *MemberAttr = getDLLAttr(Member);
4482       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4483         continue;
4484 
4485       S.Diag(MemberAttr->getLocation(),
4486              diag::err_attribute_dll_member_of_dll_class)
4487           << MemberAttr << ClassAttr;
4488       S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4489       Member->setInvalidDecl();
4490     }
4491   }
4492 
4493   if (Class->getDescribedClassTemplate())
4494     // Don't inherit dll attribute until the template is instantiated.
4495     return;
4496 
4497   bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4498 
4499   // Force declaration of implicit members so they can inherit the attribute.
4500   S.ForceDeclarationOfImplicitMembers(Class);
4501 
4502   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4503   // seem to be true in practice?
4504 
4505   TemplateSpecializationKind TSK =
4506     Class->getTemplateSpecializationKind();
4507 
4508   for (Decl *Member : Class->decls()) {
4509     VarDecl *VD = dyn_cast<VarDecl>(Member);
4510     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4511 
4512     // Only methods and static fields inherit the attributes.
4513     if (!VD && !MD)
4514       continue;
4515 
4516     // Don't process deleted methods.
4517     if (MD && MD->isDeleted())
4518       continue;
4519 
4520     if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4521         MD->isInlined()) {
4522       // Current MSVC versions don't export the move assignment operators, so
4523       // don't attempt to import them if we have a definition.
4524       continue;
4525     }
4526 
4527     if (!getDLLAttr(Member)) {
4528       auto *NewAttr =
4529           cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4530       NewAttr->setInherited(true);
4531       Member->addAttr(NewAttr);
4532     }
4533 
4534     if (MD && ClassExported) {
4535       if (MD->isUserProvided()) {
4536         // Instantiate non-default methods..
4537 
4538         // .. except for certain kinds of template specializations.
4539         if (TSK == TSK_ExplicitInstantiationDeclaration)
4540           continue;
4541         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4542           continue;
4543 
4544         S.MarkFunctionReferenced(Class->getLocation(), MD);
4545       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4546                  MD->isCopyAssignmentOperator() ||
4547                  MD->isMoveAssignmentOperator()) {
4548         // Instantiate non-trivial or explicitly defaulted methods, and the
4549         // copy assignment / move assignment operators.
4550         S.MarkFunctionReferenced(Class->getLocation(), MD);
4551         // Resolve its exception specification; CodeGen needs it.
4552         auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4553         S.ResolveExceptionSpec(Class->getLocation(), FPT);
4554         S.ActOnFinishInlineMethodDef(MD);
4555       }
4556     }
4557   }
4558 }
4559 
4560 /// \brief Perform semantic checks on a class definition that has been
4561 /// completing, introducing implicitly-declared members, checking for
4562 /// abstract types, etc.
4563 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4564   if (!Record)
4565     return;
4566 
4567   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4568     AbstractUsageInfo Info(*this, Record);
4569     CheckAbstractClassUsage(Info, Record);
4570   }
4571 
4572   // If this is not an aggregate type and has no user-declared constructor,
4573   // complain about any non-static data members of reference or const scalar
4574   // type, since they will never get initializers.
4575   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4576       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4577       !Record->isLambda()) {
4578     bool Complained = false;
4579     for (const auto *F : Record->fields()) {
4580       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4581         continue;
4582 
4583       if (F->getType()->isReferenceType() ||
4584           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4585         if (!Complained) {
4586           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4587             << Record->getTagKind() << Record;
4588           Complained = true;
4589         }
4590 
4591         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4592           << F->getType()->isReferenceType()
4593           << F->getDeclName();
4594       }
4595     }
4596   }
4597 
4598   if (Record->isDynamicClass() && !Record->isDependentType())
4599     DynamicClasses.push_back(Record);
4600 
4601   if (Record->getIdentifier()) {
4602     // C++ [class.mem]p13:
4603     //   If T is the name of a class, then each of the following shall have a
4604     //   name different from T:
4605     //     - every member of every anonymous union that is a member of class T.
4606     //
4607     // C++ [class.mem]p14:
4608     //   In addition, if class T has a user-declared constructor (12.1), every
4609     //   non-static data member of class T shall have a name different from T.
4610     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4611     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4612          ++I) {
4613       NamedDecl *D = *I;
4614       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4615           isa<IndirectFieldDecl>(D)) {
4616         Diag(D->getLocation(), diag::err_member_name_of_class)
4617           << D->getDeclName();
4618         break;
4619       }
4620     }
4621   }
4622 
4623   // Warn if the class has virtual methods but non-virtual public destructor.
4624   if (Record->isPolymorphic() && !Record->isDependentType()) {
4625     CXXDestructorDecl *dtor = Record->getDestructor();
4626     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4627         !Record->hasAttr<FinalAttr>())
4628       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4629            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4630   }
4631 
4632   if (Record->isAbstract()) {
4633     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4634       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4635         << FA->isSpelledAsSealed();
4636       DiagnoseAbstractType(Record);
4637     }
4638   }
4639 
4640   if (!Record->isDependentType()) {
4641     for (auto *M : Record->methods()) {
4642       // See if a method overloads virtual methods in a base
4643       // class without overriding any.
4644       if (!M->isStatic())
4645         DiagnoseHiddenVirtualMethods(M);
4646 
4647       // Check whether the explicitly-defaulted special members are valid.
4648       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4649         CheckExplicitlyDefaultedSpecialMember(M);
4650 
4651       // For an explicitly defaulted or deleted special member, we defer
4652       // determining triviality until the class is complete. That time is now!
4653       if (!M->isImplicit() && !M->isUserProvided()) {
4654         CXXSpecialMember CSM = getSpecialMember(M);
4655         if (CSM != CXXInvalid) {
4656           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
4657 
4658           // Inform the class that we've finished declaring this member.
4659           Record->finishedDefaultedOrDeletedMember(M);
4660         }
4661       }
4662     }
4663   }
4664 
4665   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4666   // function that is not a constructor declares that member function to be
4667   // const. [...] The class of which that function is a member shall be
4668   // a literal type.
4669   //
4670   // If the class has virtual bases, any constexpr members will already have
4671   // been diagnosed by the checks performed on the member declaration, so
4672   // suppress this (less useful) diagnostic.
4673   //
4674   // We delay this until we know whether an explicitly-defaulted (or deleted)
4675   // destructor for the class is trivial.
4676   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4677       !Record->isLiteral() && !Record->getNumVBases()) {
4678     for (const auto *M : Record->methods()) {
4679       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
4680         switch (Record->getTemplateSpecializationKind()) {
4681         case TSK_ImplicitInstantiation:
4682         case TSK_ExplicitInstantiationDeclaration:
4683         case TSK_ExplicitInstantiationDefinition:
4684           // If a template instantiates to a non-literal type, but its members
4685           // instantiate to constexpr functions, the template is technically
4686           // ill-formed, but we allow it for sanity.
4687           continue;
4688 
4689         case TSK_Undeclared:
4690         case TSK_ExplicitSpecialization:
4691           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4692                              diag::err_constexpr_method_non_literal);
4693           break;
4694         }
4695 
4696         // Only produce one error per class.
4697         break;
4698       }
4699     }
4700   }
4701 
4702   // ms_struct is a request to use the same ABI rules as MSVC.  Check
4703   // whether this class uses any C++ features that are implemented
4704   // completely differently in MSVC, and if so, emit a diagnostic.
4705   // That diagnostic defaults to an error, but we allow projects to
4706   // map it down to a warning (or ignore it).  It's a fairly common
4707   // practice among users of the ms_struct pragma to mass-annotate
4708   // headers, sweeping up a bunch of types that the project doesn't
4709   // really rely on MSVC-compatible layout for.  We must therefore
4710   // support "ms_struct except for C++ stuff" as a secondary ABI.
4711   if (Record->isMsStruct(Context) &&
4712       (Record->isPolymorphic() || Record->getNumBases())) {
4713     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
4714   }
4715 
4716   // Declare inheriting constructors. We do this eagerly here because:
4717   // - The standard requires an eager diagnostic for conflicting inheriting
4718   //   constructors from different classes.
4719   // - The lazy declaration of the other implicit constructors is so as to not
4720   //   waste space and performance on classes that are not meant to be
4721   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4722   //   have inheriting constructors.
4723   DeclareInheritingConstructors(Record);
4724 
4725   checkDLLAttribute(*this, Record);
4726 }
4727 
4728 /// Look up the special member function that would be called by a special
4729 /// member function for a subobject of class type.
4730 ///
4731 /// \param Class The class type of the subobject.
4732 /// \param CSM The kind of special member function.
4733 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4734 /// \param ConstRHS True if this is a copy operation with a const object
4735 ///        on its RHS, that is, if the argument to the outer special member
4736 ///        function is 'const' and this is not a field marked 'mutable'.
4737 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4738     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4739     unsigned FieldQuals, bool ConstRHS) {
4740   unsigned LHSQuals = 0;
4741   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4742     LHSQuals = FieldQuals;
4743 
4744   unsigned RHSQuals = FieldQuals;
4745   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4746     RHSQuals = 0;
4747   else if (ConstRHS)
4748     RHSQuals |= Qualifiers::Const;
4749 
4750   return S.LookupSpecialMember(Class, CSM,
4751                                RHSQuals & Qualifiers::Const,
4752                                RHSQuals & Qualifiers::Volatile,
4753                                false,
4754                                LHSQuals & Qualifiers::Const,
4755                                LHSQuals & Qualifiers::Volatile);
4756 }
4757 
4758 /// Is the special member function which would be selected to perform the
4759 /// specified operation on the specified class type a constexpr constructor?
4760 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4761                                      Sema::CXXSpecialMember CSM,
4762                                      unsigned Quals, bool ConstRHS) {
4763   Sema::SpecialMemberOverloadResult *SMOR =
4764       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
4765   if (!SMOR || !SMOR->getMethod())
4766     // A constructor we wouldn't select can't be "involved in initializing"
4767     // anything.
4768     return true;
4769   return SMOR->getMethod()->isConstexpr();
4770 }
4771 
4772 /// Determine whether the specified special member function would be constexpr
4773 /// if it were implicitly defined.
4774 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4775                                               Sema::CXXSpecialMember CSM,
4776                                               bool ConstArg) {
4777   if (!S.getLangOpts().CPlusPlus11)
4778     return false;
4779 
4780   // C++11 [dcl.constexpr]p4:
4781   // In the definition of a constexpr constructor [...]
4782   bool Ctor = true;
4783   switch (CSM) {
4784   case Sema::CXXDefaultConstructor:
4785     // Since default constructor lookup is essentially trivial (and cannot
4786     // involve, for instance, template instantiation), we compute whether a
4787     // defaulted default constructor is constexpr directly within CXXRecordDecl.
4788     //
4789     // This is important for performance; we need to know whether the default
4790     // constructor is constexpr to determine whether the type is a literal type.
4791     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4792 
4793   case Sema::CXXCopyConstructor:
4794   case Sema::CXXMoveConstructor:
4795     // For copy or move constructors, we need to perform overload resolution.
4796     break;
4797 
4798   case Sema::CXXCopyAssignment:
4799   case Sema::CXXMoveAssignment:
4800     if (!S.getLangOpts().CPlusPlus14)
4801       return false;
4802     // In C++1y, we need to perform overload resolution.
4803     Ctor = false;
4804     break;
4805 
4806   case Sema::CXXDestructor:
4807   case Sema::CXXInvalid:
4808     return false;
4809   }
4810 
4811   //   -- if the class is a non-empty union, or for each non-empty anonymous
4812   //      union member of a non-union class, exactly one non-static data member
4813   //      shall be initialized; [DR1359]
4814   //
4815   // If we squint, this is guaranteed, since exactly one non-static data member
4816   // will be initialized (if the constructor isn't deleted), we just don't know
4817   // which one.
4818   if (Ctor && ClassDecl->isUnion())
4819     return true;
4820 
4821   //   -- the class shall not have any virtual base classes;
4822   if (Ctor && ClassDecl->getNumVBases())
4823     return false;
4824 
4825   // C++1y [class.copy]p26:
4826   //   -- [the class] is a literal type, and
4827   if (!Ctor && !ClassDecl->isLiteral())
4828     return false;
4829 
4830   //   -- every constructor involved in initializing [...] base class
4831   //      sub-objects shall be a constexpr constructor;
4832   //   -- the assignment operator selected to copy/move each direct base
4833   //      class is a constexpr function, and
4834   for (const auto &B : ClassDecl->bases()) {
4835     const RecordType *BaseType = B.getType()->getAs<RecordType>();
4836     if (!BaseType) continue;
4837 
4838     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4839     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
4840       return false;
4841   }
4842 
4843   //   -- every constructor involved in initializing non-static data members
4844   //      [...] shall be a constexpr constructor;
4845   //   -- every non-static data member and base class sub-object shall be
4846   //      initialized
4847   //   -- for each non-static data member of X that is of class type (or array
4848   //      thereof), the assignment operator selected to copy/move that member is
4849   //      a constexpr function
4850   for (const auto *F : ClassDecl->fields()) {
4851     if (F->isInvalidDecl())
4852       continue;
4853     QualType BaseType = S.Context.getBaseElementType(F->getType());
4854     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
4855       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4856       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4857                                     BaseType.getCVRQualifiers(),
4858                                     ConstArg && !F->isMutable()))
4859         return false;
4860     }
4861   }
4862 
4863   // All OK, it's constexpr!
4864   return true;
4865 }
4866 
4867 static Sema::ImplicitExceptionSpecification
4868 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4869   switch (S.getSpecialMember(MD)) {
4870   case Sema::CXXDefaultConstructor:
4871     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4872   case Sema::CXXCopyConstructor:
4873     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4874   case Sema::CXXCopyAssignment:
4875     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4876   case Sema::CXXMoveConstructor:
4877     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4878   case Sema::CXXMoveAssignment:
4879     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4880   case Sema::CXXDestructor:
4881     return S.ComputeDefaultedDtorExceptionSpec(MD);
4882   case Sema::CXXInvalid:
4883     break;
4884   }
4885   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4886          "only special members have implicit exception specs");
4887   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4888 }
4889 
4890 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4891                                                             CXXMethodDecl *MD) {
4892   FunctionProtoType::ExtProtoInfo EPI;
4893 
4894   // Build an exception specification pointing back at this member.
4895   EPI.ExceptionSpec.Type = EST_Unevaluated;
4896   EPI.ExceptionSpec.SourceDecl = MD;
4897 
4898   // Set the calling convention to the default for C++ instance methods.
4899   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4900       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4901                                             /*IsCXXMethod=*/true));
4902   return EPI;
4903 }
4904 
4905 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4906   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4907   if (FPT->getExceptionSpecType() != EST_Unevaluated)
4908     return;
4909 
4910   // Evaluate the exception specification.
4911   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
4912 
4913   // Update the type of the special member to use it.
4914   UpdateExceptionSpec(MD, ESI);
4915 
4916   // A user-provided destructor can be defined outside the class. When that
4917   // happens, be sure to update the exception specification on both
4918   // declarations.
4919   const FunctionProtoType *CanonicalFPT =
4920     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4921   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4922     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
4923 }
4924 
4925 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4926   CXXRecordDecl *RD = MD->getParent();
4927   CXXSpecialMember CSM = getSpecialMember(MD);
4928 
4929   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4930          "not an explicitly-defaulted special member");
4931 
4932   // Whether this was the first-declared instance of the constructor.
4933   // This affects whether we implicitly add an exception spec and constexpr.
4934   bool First = MD == MD->getCanonicalDecl();
4935 
4936   bool HadError = false;
4937 
4938   // C++11 [dcl.fct.def.default]p1:
4939   //   A function that is explicitly defaulted shall
4940   //     -- be a special member function (checked elsewhere),
4941   //     -- have the same type (except for ref-qualifiers, and except that a
4942   //        copy operation can take a non-const reference) as an implicit
4943   //        declaration, and
4944   //     -- not have default arguments.
4945   unsigned ExpectedParams = 1;
4946   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4947     ExpectedParams = 0;
4948   if (MD->getNumParams() != ExpectedParams) {
4949     // This also checks for default arguments: a copy or move constructor with a
4950     // default argument is classified as a default constructor, and assignment
4951     // operations and destructors can't have default arguments.
4952     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4953       << CSM << MD->getSourceRange();
4954     HadError = true;
4955   } else if (MD->isVariadic()) {
4956     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4957       << CSM << MD->getSourceRange();
4958     HadError = true;
4959   }
4960 
4961   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4962 
4963   bool CanHaveConstParam = false;
4964   if (CSM == CXXCopyConstructor)
4965     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4966   else if (CSM == CXXCopyAssignment)
4967     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4968 
4969   QualType ReturnType = Context.VoidTy;
4970   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4971     // Check for return type matching.
4972     ReturnType = Type->getReturnType();
4973     QualType ExpectedReturnType =
4974         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4975     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4976       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4977         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4978       HadError = true;
4979     }
4980 
4981     // A defaulted special member cannot have cv-qualifiers.
4982     if (Type->getTypeQuals()) {
4983       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4984         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
4985       HadError = true;
4986     }
4987   }
4988 
4989   // Check for parameter type matching.
4990   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
4991   bool HasConstParam = false;
4992   if (ExpectedParams && ArgType->isReferenceType()) {
4993     // Argument must be reference to possibly-const T.
4994     QualType ReferentType = ArgType->getPointeeType();
4995     HasConstParam = ReferentType.isConstQualified();
4996 
4997     if (ReferentType.isVolatileQualified()) {
4998       Diag(MD->getLocation(),
4999            diag::err_defaulted_special_member_volatile_param) << CSM;
5000       HadError = true;
5001     }
5002 
5003     if (HasConstParam && !CanHaveConstParam) {
5004       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5005         Diag(MD->getLocation(),
5006              diag::err_defaulted_special_member_copy_const_param)
5007           << (CSM == CXXCopyAssignment);
5008         // FIXME: Explain why this special member can't be const.
5009       } else {
5010         Diag(MD->getLocation(),
5011              diag::err_defaulted_special_member_move_const_param)
5012           << (CSM == CXXMoveAssignment);
5013       }
5014       HadError = true;
5015     }
5016   } else if (ExpectedParams) {
5017     // A copy assignment operator can take its argument by value, but a
5018     // defaulted one cannot.
5019     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5020     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5021     HadError = true;
5022   }
5023 
5024   // C++11 [dcl.fct.def.default]p2:
5025   //   An explicitly-defaulted function may be declared constexpr only if it
5026   //   would have been implicitly declared as constexpr,
5027   // Do not apply this rule to members of class templates, since core issue 1358
5028   // makes such functions always instantiate to constexpr functions. For
5029   // functions which cannot be constexpr (for non-constructors in C++11 and for
5030   // destructors in C++1y), this is checked elsewhere.
5031   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5032                                                      HasConstParam);
5033   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5034                                  : isa<CXXConstructorDecl>(MD)) &&
5035       MD->isConstexpr() && !Constexpr &&
5036       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5037     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5038     // FIXME: Explain why the special member can't be constexpr.
5039     HadError = true;
5040   }
5041 
5042   //   and may have an explicit exception-specification only if it is compatible
5043   //   with the exception-specification on the implicit declaration.
5044   if (Type->hasExceptionSpec()) {
5045     // Delay the check if this is the first declaration of the special member,
5046     // since we may not have parsed some necessary in-class initializers yet.
5047     if (First) {
5048       // If the exception specification needs to be instantiated, do so now,
5049       // before we clobber it with an EST_Unevaluated specification below.
5050       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5051         InstantiateExceptionSpec(MD->getLocStart(), MD);
5052         Type = MD->getType()->getAs<FunctionProtoType>();
5053       }
5054       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5055     } else
5056       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5057   }
5058 
5059   //   If a function is explicitly defaulted on its first declaration,
5060   if (First) {
5061     //  -- it is implicitly considered to be constexpr if the implicit
5062     //     definition would be,
5063     MD->setConstexpr(Constexpr);
5064 
5065     //  -- it is implicitly considered to have the same exception-specification
5066     //     as if it had been implicitly declared,
5067     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5068     EPI.ExceptionSpec.Type = EST_Unevaluated;
5069     EPI.ExceptionSpec.SourceDecl = MD;
5070     MD->setType(Context.getFunctionType(ReturnType,
5071                                         llvm::makeArrayRef(&ArgType,
5072                                                            ExpectedParams),
5073                                         EPI));
5074   }
5075 
5076   if (ShouldDeleteSpecialMember(MD, CSM)) {
5077     if (First) {
5078       SetDeclDeleted(MD, MD->getLocation());
5079     } else {
5080       // C++11 [dcl.fct.def.default]p4:
5081       //   [For a] user-provided explicitly-defaulted function [...] if such a
5082       //   function is implicitly defined as deleted, the program is ill-formed.
5083       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5084       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5085       HadError = true;
5086     }
5087   }
5088 
5089   if (HadError)
5090     MD->setInvalidDecl();
5091 }
5092 
5093 /// Check whether the exception specification provided for an
5094 /// explicitly-defaulted special member matches the exception specification
5095 /// that would have been generated for an implicit special member, per
5096 /// C++11 [dcl.fct.def.default]p2.
5097 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5098     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5099   // Compute the implicit exception specification.
5100   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5101                                                        /*IsCXXMethod=*/true);
5102   FunctionProtoType::ExtProtoInfo EPI(CC);
5103   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5104                           .getExceptionSpec();
5105   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5106     Context.getFunctionType(Context.VoidTy, None, EPI));
5107 
5108   // Ensure that it matches.
5109   CheckEquivalentExceptionSpec(
5110     PDiag(diag::err_incorrect_defaulted_exception_spec)
5111       << getSpecialMember(MD), PDiag(),
5112     ImplicitType, SourceLocation(),
5113     SpecifiedType, MD->getLocation());
5114 }
5115 
5116 void Sema::CheckDelayedMemberExceptionSpecs() {
5117   SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5118               2> Checks;
5119   SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
5120 
5121   std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5122   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5123 
5124   // Perform any deferred checking of exception specifications for virtual
5125   // destructors.
5126   for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5127     const CXXDestructorDecl *Dtor = Checks[i].first;
5128     assert(!Dtor->getParent()->isDependentType() &&
5129            "Should not ever add destructors of templates into the list.");
5130     CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5131   }
5132 
5133   // Check that any explicitly-defaulted methods have exception specifications
5134   // compatible with their implicit exception specifications.
5135   for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5136     CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5137                                                 Specs[I].second);
5138 }
5139 
5140 namespace {
5141 struct SpecialMemberDeletionInfo {
5142   Sema &S;
5143   CXXMethodDecl *MD;
5144   Sema::CXXSpecialMember CSM;
5145   bool Diagnose;
5146 
5147   // Properties of the special member, computed for convenience.
5148   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5149   SourceLocation Loc;
5150 
5151   bool AllFieldsAreConst;
5152 
5153   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5154                             Sema::CXXSpecialMember CSM, bool Diagnose)
5155     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5156       IsConstructor(false), IsAssignment(false), IsMove(false),
5157       ConstArg(false), Loc(MD->getLocation()),
5158       AllFieldsAreConst(true) {
5159     switch (CSM) {
5160       case Sema::CXXDefaultConstructor:
5161       case Sema::CXXCopyConstructor:
5162         IsConstructor = true;
5163         break;
5164       case Sema::CXXMoveConstructor:
5165         IsConstructor = true;
5166         IsMove = true;
5167         break;
5168       case Sema::CXXCopyAssignment:
5169         IsAssignment = true;
5170         break;
5171       case Sema::CXXMoveAssignment:
5172         IsAssignment = true;
5173         IsMove = true;
5174         break;
5175       case Sema::CXXDestructor:
5176         break;
5177       case Sema::CXXInvalid:
5178         llvm_unreachable("invalid special member kind");
5179     }
5180 
5181     if (MD->getNumParams()) {
5182       if (const ReferenceType *RT =
5183               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5184         ConstArg = RT->getPointeeType().isConstQualified();
5185     }
5186   }
5187 
5188   bool inUnion() const { return MD->getParent()->isUnion(); }
5189 
5190   /// Look up the corresponding special member in the given class.
5191   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5192                                               unsigned Quals, bool IsMutable) {
5193     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5194                                        ConstArg && !IsMutable);
5195   }
5196 
5197   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5198 
5199   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5200   bool shouldDeleteForField(FieldDecl *FD);
5201   bool shouldDeleteForAllConstMembers();
5202 
5203   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5204                                      unsigned Quals);
5205   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5206                                     Sema::SpecialMemberOverloadResult *SMOR,
5207                                     bool IsDtorCallInCtor);
5208 
5209   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5210 };
5211 }
5212 
5213 /// Is the given special member inaccessible when used on the given
5214 /// sub-object.
5215 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5216                                              CXXMethodDecl *target) {
5217   /// If we're operating on a base class, the object type is the
5218   /// type of this special member.
5219   QualType objectTy;
5220   AccessSpecifier access = target->getAccess();
5221   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5222     objectTy = S.Context.getTypeDeclType(MD->getParent());
5223     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5224 
5225   // If we're operating on a field, the object type is the type of the field.
5226   } else {
5227     objectTy = S.Context.getTypeDeclType(target->getParent());
5228   }
5229 
5230   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5231 }
5232 
5233 /// Check whether we should delete a special member due to the implicit
5234 /// definition containing a call to a special member of a subobject.
5235 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5236     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5237     bool IsDtorCallInCtor) {
5238   CXXMethodDecl *Decl = SMOR->getMethod();
5239   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5240 
5241   int DiagKind = -1;
5242 
5243   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5244     DiagKind = !Decl ? 0 : 1;
5245   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5246     DiagKind = 2;
5247   else if (!isAccessible(Subobj, Decl))
5248     DiagKind = 3;
5249   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5250            !Decl->isTrivial()) {
5251     // A member of a union must have a trivial corresponding special member.
5252     // As a weird special case, a destructor call from a union's constructor
5253     // must be accessible and non-deleted, but need not be trivial. Such a
5254     // destructor is never actually called, but is semantically checked as
5255     // if it were.
5256     DiagKind = 4;
5257   }
5258 
5259   if (DiagKind == -1)
5260     return false;
5261 
5262   if (Diagnose) {
5263     if (Field) {
5264       S.Diag(Field->getLocation(),
5265              diag::note_deleted_special_member_class_subobject)
5266         << CSM << MD->getParent() << /*IsField*/true
5267         << Field << DiagKind << IsDtorCallInCtor;
5268     } else {
5269       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5270       S.Diag(Base->getLocStart(),
5271              diag::note_deleted_special_member_class_subobject)
5272         << CSM << MD->getParent() << /*IsField*/false
5273         << Base->getType() << DiagKind << IsDtorCallInCtor;
5274     }
5275 
5276     if (DiagKind == 1)
5277       S.NoteDeletedFunction(Decl);
5278     // FIXME: Explain inaccessibility if DiagKind == 3.
5279   }
5280 
5281   return true;
5282 }
5283 
5284 /// Check whether we should delete a special member function due to having a
5285 /// direct or virtual base class or non-static data member of class type M.
5286 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5287     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5288   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5289   bool IsMutable = Field && Field->isMutable();
5290 
5291   // C++11 [class.ctor]p5:
5292   // -- any direct or virtual base class, or non-static data member with no
5293   //    brace-or-equal-initializer, has class type M (or array thereof) and
5294   //    either M has no default constructor or overload resolution as applied
5295   //    to M's default constructor results in an ambiguity or in a function
5296   //    that is deleted or inaccessible
5297   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5298   // -- a direct or virtual base class B that cannot be copied/moved because
5299   //    overload resolution, as applied to B's corresponding special member,
5300   //    results in an ambiguity or a function that is deleted or inaccessible
5301   //    from the defaulted special member
5302   // C++11 [class.dtor]p5:
5303   // -- any direct or virtual base class [...] has a type with a destructor
5304   //    that is deleted or inaccessible
5305   if (!(CSM == Sema::CXXDefaultConstructor &&
5306         Field && Field->hasInClassInitializer()) &&
5307       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5308                                    false))
5309     return true;
5310 
5311   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5312   // -- any direct or virtual base class or non-static data member has a
5313   //    type with a destructor that is deleted or inaccessible
5314   if (IsConstructor) {
5315     Sema::SpecialMemberOverloadResult *SMOR =
5316         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5317                               false, false, false, false, false);
5318     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5319       return true;
5320   }
5321 
5322   return false;
5323 }
5324 
5325 /// Check whether we should delete a special member function due to the class
5326 /// having a particular direct or virtual base class.
5327 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5328   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5329   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5330 }
5331 
5332 /// Check whether we should delete a special member function due to the class
5333 /// having a particular non-static data member.
5334 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5335   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5336   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5337 
5338   if (CSM == Sema::CXXDefaultConstructor) {
5339     // For a default constructor, all references must be initialized in-class
5340     // and, if a union, it must have a non-const member.
5341     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5342       if (Diagnose)
5343         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5344           << MD->getParent() << FD << FieldType << /*Reference*/0;
5345       return true;
5346     }
5347     // C++11 [class.ctor]p5: any non-variant non-static data member of
5348     // const-qualified type (or array thereof) with no
5349     // brace-or-equal-initializer does not have a user-provided default
5350     // constructor.
5351     if (!inUnion() && FieldType.isConstQualified() &&
5352         !FD->hasInClassInitializer() &&
5353         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5354       if (Diagnose)
5355         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5356           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5357       return true;
5358     }
5359 
5360     if (inUnion() && !FieldType.isConstQualified())
5361       AllFieldsAreConst = false;
5362   } else if (CSM == Sema::CXXCopyConstructor) {
5363     // For a copy constructor, data members must not be of rvalue reference
5364     // type.
5365     if (FieldType->isRValueReferenceType()) {
5366       if (Diagnose)
5367         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5368           << MD->getParent() << FD << FieldType;
5369       return true;
5370     }
5371   } else if (IsAssignment) {
5372     // For an assignment operator, data members must not be of reference type.
5373     if (FieldType->isReferenceType()) {
5374       if (Diagnose)
5375         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5376           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5377       return true;
5378     }
5379     if (!FieldRecord && FieldType.isConstQualified()) {
5380       // C++11 [class.copy]p23:
5381       // -- a non-static data member of const non-class type (or array thereof)
5382       if (Diagnose)
5383         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5384           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5385       return true;
5386     }
5387   }
5388 
5389   if (FieldRecord) {
5390     // Some additional restrictions exist on the variant members.
5391     if (!inUnion() && FieldRecord->isUnion() &&
5392         FieldRecord->isAnonymousStructOrUnion()) {
5393       bool AllVariantFieldsAreConst = true;
5394 
5395       // FIXME: Handle anonymous unions declared within anonymous unions.
5396       for (auto *UI : FieldRecord->fields()) {
5397         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5398 
5399         if (!UnionFieldType.isConstQualified())
5400           AllVariantFieldsAreConst = false;
5401 
5402         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5403         if (UnionFieldRecord &&
5404             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5405                                           UnionFieldType.getCVRQualifiers()))
5406           return true;
5407       }
5408 
5409       // At least one member in each anonymous union must be non-const
5410       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5411           !FieldRecord->field_empty()) {
5412         if (Diagnose)
5413           S.Diag(FieldRecord->getLocation(),
5414                  diag::note_deleted_default_ctor_all_const)
5415             << MD->getParent() << /*anonymous union*/1;
5416         return true;
5417       }
5418 
5419       // Don't check the implicit member of the anonymous union type.
5420       // This is technically non-conformant, but sanity demands it.
5421       return false;
5422     }
5423 
5424     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5425                                       FieldType.getCVRQualifiers()))
5426       return true;
5427   }
5428 
5429   return false;
5430 }
5431 
5432 /// C++11 [class.ctor] p5:
5433 ///   A defaulted default constructor for a class X is defined as deleted if
5434 /// X is a union and all of its variant members are of const-qualified type.
5435 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5436   // This is a silly definition, because it gives an empty union a deleted
5437   // default constructor. Don't do that.
5438   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5439       !MD->getParent()->field_empty()) {
5440     if (Diagnose)
5441       S.Diag(MD->getParent()->getLocation(),
5442              diag::note_deleted_default_ctor_all_const)
5443         << MD->getParent() << /*not anonymous union*/0;
5444     return true;
5445   }
5446   return false;
5447 }
5448 
5449 /// Determine whether a defaulted special member function should be defined as
5450 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5451 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5452 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5453                                      bool Diagnose) {
5454   if (MD->isInvalidDecl())
5455     return false;
5456   CXXRecordDecl *RD = MD->getParent();
5457   assert(!RD->isDependentType() && "do deletion after instantiation");
5458   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5459     return false;
5460 
5461   // C++11 [expr.lambda.prim]p19:
5462   //   The closure type associated with a lambda-expression has a
5463   //   deleted (8.4.3) default constructor and a deleted copy
5464   //   assignment operator.
5465   if (RD->isLambda() &&
5466       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5467     if (Diagnose)
5468       Diag(RD->getLocation(), diag::note_lambda_decl);
5469     return true;
5470   }
5471 
5472   // For an anonymous struct or union, the copy and assignment special members
5473   // will never be used, so skip the check. For an anonymous union declared at
5474   // namespace scope, the constructor and destructor are used.
5475   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5476       RD->isAnonymousStructOrUnion())
5477     return false;
5478 
5479   // C++11 [class.copy]p7, p18:
5480   //   If the class definition declares a move constructor or move assignment
5481   //   operator, an implicitly declared copy constructor or copy assignment
5482   //   operator is defined as deleted.
5483   if (MD->isImplicit() &&
5484       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5485     CXXMethodDecl *UserDeclaredMove = nullptr;
5486 
5487     // In Microsoft mode, a user-declared move only causes the deletion of the
5488     // corresponding copy operation, not both copy operations.
5489     if (RD->hasUserDeclaredMoveConstructor() &&
5490         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5491       if (!Diagnose) return true;
5492 
5493       // Find any user-declared move constructor.
5494       for (auto *I : RD->ctors()) {
5495         if (I->isMoveConstructor()) {
5496           UserDeclaredMove = I;
5497           break;
5498         }
5499       }
5500       assert(UserDeclaredMove);
5501     } else if (RD->hasUserDeclaredMoveAssignment() &&
5502                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5503       if (!Diagnose) return true;
5504 
5505       // Find any user-declared move assignment operator.
5506       for (auto *I : RD->methods()) {
5507         if (I->isMoveAssignmentOperator()) {
5508           UserDeclaredMove = I;
5509           break;
5510         }
5511       }
5512       assert(UserDeclaredMove);
5513     }
5514 
5515     if (UserDeclaredMove) {
5516       Diag(UserDeclaredMove->getLocation(),
5517            diag::note_deleted_copy_user_declared_move)
5518         << (CSM == CXXCopyAssignment) << RD
5519         << UserDeclaredMove->isMoveAssignmentOperator();
5520       return true;
5521     }
5522   }
5523 
5524   // Do access control from the special member function
5525   ContextRAII MethodContext(*this, MD);
5526 
5527   // C++11 [class.dtor]p5:
5528   // -- for a virtual destructor, lookup of the non-array deallocation function
5529   //    results in an ambiguity or in a function that is deleted or inaccessible
5530   if (CSM == CXXDestructor && MD->isVirtual()) {
5531     FunctionDecl *OperatorDelete = nullptr;
5532     DeclarationName Name =
5533       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5534     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5535                                  OperatorDelete, false)) {
5536       if (Diagnose)
5537         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5538       return true;
5539     }
5540   }
5541 
5542   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5543 
5544   for (auto &BI : RD->bases())
5545     if (!BI.isVirtual() &&
5546         SMI.shouldDeleteForBase(&BI))
5547       return true;
5548 
5549   // Per DR1611, do not consider virtual bases of constructors of abstract
5550   // classes, since we are not going to construct them.
5551   if (!RD->isAbstract() || !SMI.IsConstructor) {
5552     for (auto &BI : RD->vbases())
5553       if (SMI.shouldDeleteForBase(&BI))
5554         return true;
5555   }
5556 
5557   for (auto *FI : RD->fields())
5558     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5559         SMI.shouldDeleteForField(FI))
5560       return true;
5561 
5562   if (SMI.shouldDeleteForAllConstMembers())
5563     return true;
5564 
5565   return false;
5566 }
5567 
5568 /// Perform lookup for a special member of the specified kind, and determine
5569 /// whether it is trivial. If the triviality can be determined without the
5570 /// lookup, skip it. This is intended for use when determining whether a
5571 /// special member of a containing object is trivial, and thus does not ever
5572 /// perform overload resolution for default constructors.
5573 ///
5574 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5575 /// member that was most likely to be intended to be trivial, if any.
5576 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5577                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5578                                      bool ConstRHS, CXXMethodDecl **Selected) {
5579   if (Selected)
5580     *Selected = nullptr;
5581 
5582   switch (CSM) {
5583   case Sema::CXXInvalid:
5584     llvm_unreachable("not a special member");
5585 
5586   case Sema::CXXDefaultConstructor:
5587     // C++11 [class.ctor]p5:
5588     //   A default constructor is trivial if:
5589     //    - all the [direct subobjects] have trivial default constructors
5590     //
5591     // Note, no overload resolution is performed in this case.
5592     if (RD->hasTrivialDefaultConstructor())
5593       return true;
5594 
5595     if (Selected) {
5596       // If there's a default constructor which could have been trivial, dig it
5597       // out. Otherwise, if there's any user-provided default constructor, point
5598       // to that as an example of why there's not a trivial one.
5599       CXXConstructorDecl *DefCtor = nullptr;
5600       if (RD->needsImplicitDefaultConstructor())
5601         S.DeclareImplicitDefaultConstructor(RD);
5602       for (auto *CI : RD->ctors()) {
5603         if (!CI->isDefaultConstructor())
5604           continue;
5605         DefCtor = CI;
5606         if (!DefCtor->isUserProvided())
5607           break;
5608       }
5609 
5610       *Selected = DefCtor;
5611     }
5612 
5613     return false;
5614 
5615   case Sema::CXXDestructor:
5616     // C++11 [class.dtor]p5:
5617     //   A destructor is trivial if:
5618     //    - all the direct [subobjects] have trivial destructors
5619     if (RD->hasTrivialDestructor())
5620       return true;
5621 
5622     if (Selected) {
5623       if (RD->needsImplicitDestructor())
5624         S.DeclareImplicitDestructor(RD);
5625       *Selected = RD->getDestructor();
5626     }
5627 
5628     return false;
5629 
5630   case Sema::CXXCopyConstructor:
5631     // C++11 [class.copy]p12:
5632     //   A copy constructor is trivial if:
5633     //    - the constructor selected to copy each direct [subobject] is trivial
5634     if (RD->hasTrivialCopyConstructor()) {
5635       if (Quals == Qualifiers::Const)
5636         // We must either select the trivial copy constructor or reach an
5637         // ambiguity; no need to actually perform overload resolution.
5638         return true;
5639     } else if (!Selected) {
5640       return false;
5641     }
5642     // In C++98, we are not supposed to perform overload resolution here, but we
5643     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5644     // cases like B as having a non-trivial copy constructor:
5645     //   struct A { template<typename T> A(T&); };
5646     //   struct B { mutable A a; };
5647     goto NeedOverloadResolution;
5648 
5649   case Sema::CXXCopyAssignment:
5650     // C++11 [class.copy]p25:
5651     //   A copy assignment operator is trivial if:
5652     //    - the assignment operator selected to copy each direct [subobject] is
5653     //      trivial
5654     if (RD->hasTrivialCopyAssignment()) {
5655       if (Quals == Qualifiers::Const)
5656         return true;
5657     } else if (!Selected) {
5658       return false;
5659     }
5660     // In C++98, we are not supposed to perform overload resolution here, but we
5661     // treat that as a language defect.
5662     goto NeedOverloadResolution;
5663 
5664   case Sema::CXXMoveConstructor:
5665   case Sema::CXXMoveAssignment:
5666   NeedOverloadResolution:
5667     Sema::SpecialMemberOverloadResult *SMOR =
5668         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5669 
5670     // The standard doesn't describe how to behave if the lookup is ambiguous.
5671     // We treat it as not making the member non-trivial, just like the standard
5672     // mandates for the default constructor. This should rarely matter, because
5673     // the member will also be deleted.
5674     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5675       return true;
5676 
5677     if (!SMOR->getMethod()) {
5678       assert(SMOR->getKind() ==
5679              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5680       return false;
5681     }
5682 
5683     // We deliberately don't check if we found a deleted special member. We're
5684     // not supposed to!
5685     if (Selected)
5686       *Selected = SMOR->getMethod();
5687     return SMOR->getMethod()->isTrivial();
5688   }
5689 
5690   llvm_unreachable("unknown special method kind");
5691 }
5692 
5693 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5694   for (auto *CI : RD->ctors())
5695     if (!CI->isImplicit())
5696       return CI;
5697 
5698   // Look for constructor templates.
5699   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5700   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5701     if (CXXConstructorDecl *CD =
5702           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5703       return CD;
5704   }
5705 
5706   return nullptr;
5707 }
5708 
5709 /// The kind of subobject we are checking for triviality. The values of this
5710 /// enumeration are used in diagnostics.
5711 enum TrivialSubobjectKind {
5712   /// The subobject is a base class.
5713   TSK_BaseClass,
5714   /// The subobject is a non-static data member.
5715   TSK_Field,
5716   /// The object is actually the complete object.
5717   TSK_CompleteObject
5718 };
5719 
5720 /// Check whether the special member selected for a given type would be trivial.
5721 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5722                                       QualType SubType, bool ConstRHS,
5723                                       Sema::CXXSpecialMember CSM,
5724                                       TrivialSubobjectKind Kind,
5725                                       bool Diagnose) {
5726   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5727   if (!SubRD)
5728     return true;
5729 
5730   CXXMethodDecl *Selected;
5731   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5732                                ConstRHS, Diagnose ? &Selected : nullptr))
5733     return true;
5734 
5735   if (Diagnose) {
5736     if (ConstRHS)
5737       SubType.addConst();
5738 
5739     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5740       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5741         << Kind << SubType.getUnqualifiedType();
5742       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5743         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5744     } else if (!Selected)
5745       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5746         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5747     else if (Selected->isUserProvided()) {
5748       if (Kind == TSK_CompleteObject)
5749         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5750           << Kind << SubType.getUnqualifiedType() << CSM;
5751       else {
5752         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5753           << Kind << SubType.getUnqualifiedType() << CSM;
5754         S.Diag(Selected->getLocation(), diag::note_declared_at);
5755       }
5756     } else {
5757       if (Kind != TSK_CompleteObject)
5758         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5759           << Kind << SubType.getUnqualifiedType() << CSM;
5760 
5761       // Explain why the defaulted or deleted special member isn't trivial.
5762       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5763     }
5764   }
5765 
5766   return false;
5767 }
5768 
5769 /// Check whether the members of a class type allow a special member to be
5770 /// trivial.
5771 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5772                                      Sema::CXXSpecialMember CSM,
5773                                      bool ConstArg, bool Diagnose) {
5774   for (const auto *FI : RD->fields()) {
5775     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5776       continue;
5777 
5778     QualType FieldType = S.Context.getBaseElementType(FI->getType());
5779 
5780     // Pretend anonymous struct or union members are members of this class.
5781     if (FI->isAnonymousStructOrUnion()) {
5782       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5783                                     CSM, ConstArg, Diagnose))
5784         return false;
5785       continue;
5786     }
5787 
5788     // C++11 [class.ctor]p5:
5789     //   A default constructor is trivial if [...]
5790     //    -- no non-static data member of its class has a
5791     //       brace-or-equal-initializer
5792     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5793       if (Diagnose)
5794         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
5795       return false;
5796     }
5797 
5798     // Objective C ARC 4.3.5:
5799     //   [...] nontrivally ownership-qualified types are [...] not trivially
5800     //   default constructible, copy constructible, move constructible, copy
5801     //   assignable, move assignable, or destructible [...]
5802     if (S.getLangOpts().ObjCAutoRefCount &&
5803         FieldType.hasNonTrivialObjCLifetime()) {
5804       if (Diagnose)
5805         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5806           << RD << FieldType.getObjCLifetime();
5807       return false;
5808     }
5809 
5810     bool ConstRHS = ConstArg && !FI->isMutable();
5811     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5812                                    CSM, TSK_Field, Diagnose))
5813       return false;
5814   }
5815 
5816   return true;
5817 }
5818 
5819 /// Diagnose why the specified class does not have a trivial special member of
5820 /// the given kind.
5821 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5822   QualType Ty = Context.getRecordType(RD);
5823 
5824   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5825   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
5826                             TSK_CompleteObject, /*Diagnose*/true);
5827 }
5828 
5829 /// Determine whether a defaulted or deleted special member function is trivial,
5830 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5831 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5832 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5833                                   bool Diagnose) {
5834   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5835 
5836   CXXRecordDecl *RD = MD->getParent();
5837 
5838   bool ConstArg = false;
5839 
5840   // C++11 [class.copy]p12, p25: [DR1593]
5841   //   A [special member] is trivial if [...] its parameter-type-list is
5842   //   equivalent to the parameter-type-list of an implicit declaration [...]
5843   switch (CSM) {
5844   case CXXDefaultConstructor:
5845   case CXXDestructor:
5846     // Trivial default constructors and destructors cannot have parameters.
5847     break;
5848 
5849   case CXXCopyConstructor:
5850   case CXXCopyAssignment: {
5851     // Trivial copy operations always have const, non-volatile parameter types.
5852     ConstArg = true;
5853     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5854     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5855     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5856       if (Diagnose)
5857         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5858           << Param0->getSourceRange() << Param0->getType()
5859           << Context.getLValueReferenceType(
5860                Context.getRecordType(RD).withConst());
5861       return false;
5862     }
5863     break;
5864   }
5865 
5866   case CXXMoveConstructor:
5867   case CXXMoveAssignment: {
5868     // Trivial move operations always have non-cv-qualified parameters.
5869     const ParmVarDecl *Param0 = MD->getParamDecl(0);
5870     const RValueReferenceType *RT =
5871       Param0->getType()->getAs<RValueReferenceType>();
5872     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5873       if (Diagnose)
5874         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5875           << Param0->getSourceRange() << Param0->getType()
5876           << Context.getRValueReferenceType(Context.getRecordType(RD));
5877       return false;
5878     }
5879     break;
5880   }
5881 
5882   case CXXInvalid:
5883     llvm_unreachable("not a special member");
5884   }
5885 
5886   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5887     if (Diagnose)
5888       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5889            diag::note_nontrivial_default_arg)
5890         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5891     return false;
5892   }
5893   if (MD->isVariadic()) {
5894     if (Diagnose)
5895       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5896     return false;
5897   }
5898 
5899   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5900   //   A copy/move [constructor or assignment operator] is trivial if
5901   //    -- the [member] selected to copy/move each direct base class subobject
5902   //       is trivial
5903   //
5904   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5905   //   A [default constructor or destructor] is trivial if
5906   //    -- all the direct base classes have trivial [default constructors or
5907   //       destructors]
5908   for (const auto &BI : RD->bases())
5909     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
5910                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
5911       return false;
5912 
5913   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5914   //   A copy/move [constructor or assignment operator] for a class X is
5915   //   trivial if
5916   //    -- for each non-static data member of X that is of class type (or array
5917   //       thereof), the constructor selected to copy/move that member is
5918   //       trivial
5919   //
5920   // C++11 [class.copy]p12, C++11 [class.copy]p25:
5921   //   A [default constructor or destructor] is trivial if
5922   //    -- for all of the non-static data members of its class that are of class
5923   //       type (or array thereof), each such class has a trivial [default
5924   //       constructor or destructor]
5925   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5926     return false;
5927 
5928   // C++11 [class.dtor]p5:
5929   //   A destructor is trivial if [...]
5930   //    -- the destructor is not virtual
5931   if (CSM == CXXDestructor && MD->isVirtual()) {
5932     if (Diagnose)
5933       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5934     return false;
5935   }
5936 
5937   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5938   //   A [special member] for class X is trivial if [...]
5939   //    -- class X has no virtual functions and no virtual base classes
5940   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5941     if (!Diagnose)
5942       return false;
5943 
5944     if (RD->getNumVBases()) {
5945       // Check for virtual bases. We already know that the corresponding
5946       // member in all bases is trivial, so vbases must all be direct.
5947       CXXBaseSpecifier &BS = *RD->vbases_begin();
5948       assert(BS.isVirtual());
5949       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5950       return false;
5951     }
5952 
5953     // Must have a virtual method.
5954     for (const auto *MI : RD->methods()) {
5955       if (MI->isVirtual()) {
5956         SourceLocation MLoc = MI->getLocStart();
5957         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5958         return false;
5959       }
5960     }
5961 
5962     llvm_unreachable("dynamic class with no vbases and no virtual functions");
5963   }
5964 
5965   // Looks like it's trivial!
5966   return true;
5967 }
5968 
5969 /// \brief Data used with FindHiddenVirtualMethod
5970 namespace {
5971   struct FindHiddenVirtualMethodData {
5972     Sema *S;
5973     CXXMethodDecl *Method;
5974     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5975     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5976   };
5977 }
5978 
5979 /// \brief Check whether any most overriden method from MD in Methods
5980 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5981                   const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
5982   if (MD->size_overridden_methods() == 0)
5983     return Methods.count(MD->getCanonicalDecl());
5984   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5985                                       E = MD->end_overridden_methods();
5986        I != E; ++I)
5987     if (CheckMostOverridenMethods(*I, Methods))
5988       return true;
5989   return false;
5990 }
5991 
5992 /// \brief Member lookup function that determines whether a given C++
5993 /// method overloads virtual methods in a base class without overriding any,
5994 /// to be used with CXXRecordDecl::lookupInBases().
5995 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5996                                     CXXBasePath &Path,
5997                                     void *UserData) {
5998   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5999 
6000   FindHiddenVirtualMethodData &Data
6001     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6002 
6003   DeclarationName Name = Data.Method->getDeclName();
6004   assert(Name.getNameKind() == DeclarationName::Identifier);
6005 
6006   bool foundSameNameMethod = false;
6007   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6008   for (Path.Decls = BaseRecord->lookup(Name);
6009        !Path.Decls.empty();
6010        Path.Decls = Path.Decls.slice(1)) {
6011     NamedDecl *D = Path.Decls.front();
6012     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6013       MD = MD->getCanonicalDecl();
6014       foundSameNameMethod = true;
6015       // Interested only in hidden virtual methods.
6016       if (!MD->isVirtual())
6017         continue;
6018       // If the method we are checking overrides a method from its base
6019       // don't warn about the other overloaded methods. Clang deviates from GCC
6020       // by only diagnosing overloads of inherited virtual functions that do not
6021       // override any other virtual functions in the base. GCC's
6022       // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6023       // function from a base class. These cases may be better served by a
6024       // warning (not specific to virtual functions) on call sites when the call
6025       // would select a different function from the base class, were it visible.
6026       // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6027       if (!Data.S->IsOverload(Data.Method, MD, false))
6028         return true;
6029       // Collect the overload only if its hidden.
6030       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
6031         overloadedMethods.push_back(MD);
6032     }
6033   }
6034 
6035   if (foundSameNameMethod)
6036     Data.OverloadedMethods.append(overloadedMethods.begin(),
6037                                    overloadedMethods.end());
6038   return foundSameNameMethod;
6039 }
6040 
6041 /// \brief Add the most overriden methods from MD to Methods
6042 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6043                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6044   if (MD->size_overridden_methods() == 0)
6045     Methods.insert(MD->getCanonicalDecl());
6046   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6047                                       E = MD->end_overridden_methods();
6048        I != E; ++I)
6049     AddMostOverridenMethods(*I, Methods);
6050 }
6051 
6052 /// \brief Check if a method overloads virtual methods in a base class without
6053 /// overriding any.
6054 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6055                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6056   if (!MD->getDeclName().isIdentifier())
6057     return;
6058 
6059   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6060                      /*bool RecordPaths=*/false,
6061                      /*bool DetectVirtual=*/false);
6062   FindHiddenVirtualMethodData Data;
6063   Data.Method = MD;
6064   Data.S = this;
6065 
6066   // Keep the base methods that were overriden or introduced in the subclass
6067   // by 'using' in a set. A base method not in this set is hidden.
6068   CXXRecordDecl *DC = MD->getParent();
6069   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6070   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6071     NamedDecl *ND = *I;
6072     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6073       ND = shad->getTargetDecl();
6074     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6075       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
6076   }
6077 
6078   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6079     OverloadedMethods = Data.OverloadedMethods;
6080 }
6081 
6082 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6083                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6084   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6085     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6086     PartialDiagnostic PD = PDiag(
6087          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6088     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6089     Diag(overloadedMD->getLocation(), PD);
6090   }
6091 }
6092 
6093 /// \brief Diagnose methods which overload virtual methods in a base class
6094 /// without overriding any.
6095 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6096   if (MD->isInvalidDecl())
6097     return;
6098 
6099   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6100     return;
6101 
6102   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6103   FindHiddenVirtualMethods(MD, OverloadedMethods);
6104   if (!OverloadedMethods.empty()) {
6105     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6106       << MD << (OverloadedMethods.size() > 1);
6107 
6108     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6109   }
6110 }
6111 
6112 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6113                                              Decl *TagDecl,
6114                                              SourceLocation LBrac,
6115                                              SourceLocation RBrac,
6116                                              AttributeList *AttrList) {
6117   if (!TagDecl)
6118     return;
6119 
6120   AdjustDeclIfTemplate(TagDecl);
6121 
6122   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6123     if (l->getKind() != AttributeList::AT_Visibility)
6124       continue;
6125     l->setInvalid();
6126     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6127       l->getName();
6128   }
6129 
6130   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6131               // strict aliasing violation!
6132               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6133               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6134 
6135   CheckCompletedCXXClass(
6136                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6137 }
6138 
6139 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6140 /// special functions, such as the default constructor, copy
6141 /// constructor, or destructor, to the given C++ class (C++
6142 /// [special]p1).  This routine can only be executed just before the
6143 /// definition of the class is complete.
6144 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6145   if (!ClassDecl->hasUserDeclaredConstructor())
6146     ++ASTContext::NumImplicitDefaultConstructors;
6147 
6148   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6149     ++ASTContext::NumImplicitCopyConstructors;
6150 
6151     // If the properties or semantics of the copy constructor couldn't be
6152     // determined while the class was being declared, force a declaration
6153     // of it now.
6154     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6155       DeclareImplicitCopyConstructor(ClassDecl);
6156   }
6157 
6158   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6159     ++ASTContext::NumImplicitMoveConstructors;
6160 
6161     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6162       DeclareImplicitMoveConstructor(ClassDecl);
6163   }
6164 
6165   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6166     ++ASTContext::NumImplicitCopyAssignmentOperators;
6167 
6168     // If we have a dynamic class, then the copy assignment operator may be
6169     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6170     // it shows up in the right place in the vtable and that we diagnose
6171     // problems with the implicit exception specification.
6172     if (ClassDecl->isDynamicClass() ||
6173         ClassDecl->needsOverloadResolutionForCopyAssignment())
6174       DeclareImplicitCopyAssignment(ClassDecl);
6175   }
6176 
6177   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6178     ++ASTContext::NumImplicitMoveAssignmentOperators;
6179 
6180     // Likewise for the move assignment operator.
6181     if (ClassDecl->isDynamicClass() ||
6182         ClassDecl->needsOverloadResolutionForMoveAssignment())
6183       DeclareImplicitMoveAssignment(ClassDecl);
6184   }
6185 
6186   if (!ClassDecl->hasUserDeclaredDestructor()) {
6187     ++ASTContext::NumImplicitDestructors;
6188 
6189     // If we have a dynamic class, then the destructor may be virtual, so we
6190     // have to declare the destructor immediately. This ensures that, e.g., it
6191     // shows up in the right place in the vtable and that we diagnose problems
6192     // with the implicit exception specification.
6193     if (ClassDecl->isDynamicClass() ||
6194         ClassDecl->needsOverloadResolutionForDestructor())
6195       DeclareImplicitDestructor(ClassDecl);
6196   }
6197 }
6198 
6199 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6200   if (!D)
6201     return 0;
6202 
6203   // The order of template parameters is not important here. All names
6204   // get added to the same scope.
6205   SmallVector<TemplateParameterList *, 4> ParameterLists;
6206 
6207   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6208     D = TD->getTemplatedDecl();
6209 
6210   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6211     ParameterLists.push_back(PSD->getTemplateParameters());
6212 
6213   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6214     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6215       ParameterLists.push_back(DD->getTemplateParameterList(i));
6216 
6217     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6218       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6219         ParameterLists.push_back(FTD->getTemplateParameters());
6220     }
6221   }
6222 
6223   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6224     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6225       ParameterLists.push_back(TD->getTemplateParameterList(i));
6226 
6227     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6228       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6229         ParameterLists.push_back(CTD->getTemplateParameters());
6230     }
6231   }
6232 
6233   unsigned Count = 0;
6234   for (TemplateParameterList *Params : ParameterLists) {
6235     if (Params->size() > 0)
6236       // Ignore explicit specializations; they don't contribute to the template
6237       // depth.
6238       ++Count;
6239     for (NamedDecl *Param : *Params) {
6240       if (Param->getDeclName()) {
6241         S->AddDecl(Param);
6242         IdResolver.AddDecl(Param);
6243       }
6244     }
6245   }
6246 
6247   return Count;
6248 }
6249 
6250 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6251   if (!RecordD) return;
6252   AdjustDeclIfTemplate(RecordD);
6253   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6254   PushDeclContext(S, Record);
6255 }
6256 
6257 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6258   if (!RecordD) return;
6259   PopDeclContext();
6260 }
6261 
6262 /// This is used to implement the constant expression evaluation part of the
6263 /// attribute enable_if extension. There is nothing in standard C++ which would
6264 /// require reentering parameters.
6265 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6266   if (!Param)
6267     return;
6268 
6269   S->AddDecl(Param);
6270   if (Param->getDeclName())
6271     IdResolver.AddDecl(Param);
6272 }
6273 
6274 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6275 /// parsing a top-level (non-nested) C++ class, and we are now
6276 /// parsing those parts of the given Method declaration that could
6277 /// not be parsed earlier (C++ [class.mem]p2), such as default
6278 /// arguments. This action should enter the scope of the given
6279 /// Method declaration as if we had just parsed the qualified method
6280 /// name. However, it should not bring the parameters into scope;
6281 /// that will be performed by ActOnDelayedCXXMethodParameter.
6282 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6283 }
6284 
6285 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6286 /// C++ method declaration. We're (re-)introducing the given
6287 /// function parameter into scope for use in parsing later parts of
6288 /// the method declaration. For example, we could see an
6289 /// ActOnParamDefaultArgument event for this parameter.
6290 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6291   if (!ParamD)
6292     return;
6293 
6294   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6295 
6296   // If this parameter has an unparsed default argument, clear it out
6297   // to make way for the parsed default argument.
6298   if (Param->hasUnparsedDefaultArg())
6299     Param->setDefaultArg(nullptr);
6300 
6301   S->AddDecl(Param);
6302   if (Param->getDeclName())
6303     IdResolver.AddDecl(Param);
6304 }
6305 
6306 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6307 /// processing the delayed method declaration for Method. The method
6308 /// declaration is now considered finished. There may be a separate
6309 /// ActOnStartOfFunctionDef action later (not necessarily
6310 /// immediately!) for this method, if it was also defined inside the
6311 /// class body.
6312 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6313   if (!MethodD)
6314     return;
6315 
6316   AdjustDeclIfTemplate(MethodD);
6317 
6318   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6319 
6320   // Now that we have our default arguments, check the constructor
6321   // again. It could produce additional diagnostics or affect whether
6322   // the class has implicitly-declared destructors, among other
6323   // things.
6324   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6325     CheckConstructor(Constructor);
6326 
6327   // Check the default arguments, which we may have added.
6328   if (!Method->isInvalidDecl())
6329     CheckCXXDefaultArguments(Method);
6330 }
6331 
6332 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6333 /// the well-formedness of the constructor declarator @p D with type @p
6334 /// R. If there are any errors in the declarator, this routine will
6335 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6336 /// will be updated to reflect a well-formed type for the constructor and
6337 /// returned.
6338 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6339                                           StorageClass &SC) {
6340   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6341 
6342   // C++ [class.ctor]p3:
6343   //   A constructor shall not be virtual (10.3) or static (9.4). A
6344   //   constructor can be invoked for a const, volatile or const
6345   //   volatile object. A constructor shall not be declared const,
6346   //   volatile, or const volatile (9.3.2).
6347   if (isVirtual) {
6348     if (!D.isInvalidType())
6349       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6350         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6351         << SourceRange(D.getIdentifierLoc());
6352     D.setInvalidType();
6353   }
6354   if (SC == SC_Static) {
6355     if (!D.isInvalidType())
6356       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6357         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6358         << SourceRange(D.getIdentifierLoc());
6359     D.setInvalidType();
6360     SC = SC_None;
6361   }
6362 
6363   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6364     diagnoseIgnoredQualifiers(
6365         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6366         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6367         D.getDeclSpec().getRestrictSpecLoc(),
6368         D.getDeclSpec().getAtomicSpecLoc());
6369     D.setInvalidType();
6370   }
6371 
6372   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6373   if (FTI.TypeQuals != 0) {
6374     if (FTI.TypeQuals & Qualifiers::Const)
6375       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6376         << "const" << SourceRange(D.getIdentifierLoc());
6377     if (FTI.TypeQuals & Qualifiers::Volatile)
6378       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6379         << "volatile" << SourceRange(D.getIdentifierLoc());
6380     if (FTI.TypeQuals & Qualifiers::Restrict)
6381       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6382         << "restrict" << SourceRange(D.getIdentifierLoc());
6383     D.setInvalidType();
6384   }
6385 
6386   // C++0x [class.ctor]p4:
6387   //   A constructor shall not be declared with a ref-qualifier.
6388   if (FTI.hasRefQualifier()) {
6389     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6390       << FTI.RefQualifierIsLValueRef
6391       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6392     D.setInvalidType();
6393   }
6394 
6395   // Rebuild the function type "R" without any type qualifiers (in
6396   // case any of the errors above fired) and with "void" as the
6397   // return type, since constructors don't have return types.
6398   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6399   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6400     return R;
6401 
6402   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6403   EPI.TypeQuals = 0;
6404   EPI.RefQualifier = RQ_None;
6405 
6406   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6407 }
6408 
6409 /// CheckConstructor - Checks a fully-formed constructor for
6410 /// well-formedness, issuing any diagnostics required. Returns true if
6411 /// the constructor declarator is invalid.
6412 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6413   CXXRecordDecl *ClassDecl
6414     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6415   if (!ClassDecl)
6416     return Constructor->setInvalidDecl();
6417 
6418   // C++ [class.copy]p3:
6419   //   A declaration of a constructor for a class X is ill-formed if
6420   //   its first parameter is of type (optionally cv-qualified) X and
6421   //   either there are no other parameters or else all other
6422   //   parameters have default arguments.
6423   if (!Constructor->isInvalidDecl() &&
6424       ((Constructor->getNumParams() == 1) ||
6425        (Constructor->getNumParams() > 1 &&
6426         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6427       Constructor->getTemplateSpecializationKind()
6428                                               != TSK_ImplicitInstantiation) {
6429     QualType ParamType = Constructor->getParamDecl(0)->getType();
6430     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6431     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6432       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6433       const char *ConstRef
6434         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6435                                                         : " const &";
6436       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6437         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6438 
6439       // FIXME: Rather that making the constructor invalid, we should endeavor
6440       // to fix the type.
6441       Constructor->setInvalidDecl();
6442     }
6443   }
6444 }
6445 
6446 /// CheckDestructor - Checks a fully-formed destructor definition for
6447 /// well-formedness, issuing any diagnostics required.  Returns true
6448 /// on error.
6449 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6450   CXXRecordDecl *RD = Destructor->getParent();
6451 
6452   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6453     SourceLocation Loc;
6454 
6455     if (!Destructor->isImplicit())
6456       Loc = Destructor->getLocation();
6457     else
6458       Loc = RD->getLocation();
6459 
6460     // If we have a virtual destructor, look up the deallocation function
6461     FunctionDecl *OperatorDelete = nullptr;
6462     DeclarationName Name =
6463     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6464     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6465       return true;
6466     // If there's no class-specific operator delete, look up the global
6467     // non-array delete.
6468     if (!OperatorDelete)
6469       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6470 
6471     MarkFunctionReferenced(Loc, OperatorDelete);
6472 
6473     Destructor->setOperatorDelete(OperatorDelete);
6474   }
6475 
6476   return false;
6477 }
6478 
6479 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6480 /// the well-formednes of the destructor declarator @p D with type @p
6481 /// R. If there are any errors in the declarator, this routine will
6482 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6483 /// will be updated to reflect a well-formed type for the destructor and
6484 /// returned.
6485 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6486                                          StorageClass& SC) {
6487   // C++ [class.dtor]p1:
6488   //   [...] A typedef-name that names a class is a class-name
6489   //   (7.1.3); however, a typedef-name that names a class shall not
6490   //   be used as the identifier in the declarator for a destructor
6491   //   declaration.
6492   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6493   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6494     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6495       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6496   else if (const TemplateSpecializationType *TST =
6497              DeclaratorType->getAs<TemplateSpecializationType>())
6498     if (TST->isTypeAlias())
6499       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6500         << DeclaratorType << 1;
6501 
6502   // C++ [class.dtor]p2:
6503   //   A destructor is used to destroy objects of its class type. A
6504   //   destructor takes no parameters, and no return type can be
6505   //   specified for it (not even void). The address of a destructor
6506   //   shall not be taken. A destructor shall not be static. A
6507   //   destructor can be invoked for a const, volatile or const
6508   //   volatile object. A destructor shall not be declared const,
6509   //   volatile or const volatile (9.3.2).
6510   if (SC == SC_Static) {
6511     if (!D.isInvalidType())
6512       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6513         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6514         << SourceRange(D.getIdentifierLoc())
6515         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6516 
6517     SC = SC_None;
6518   }
6519   if (!D.isInvalidType()) {
6520     // Destructors don't have return types, but the parser will
6521     // happily parse something like:
6522     //
6523     //   class X {
6524     //     float ~X();
6525     //   };
6526     //
6527     // The return type will be eliminated later.
6528     if (D.getDeclSpec().hasTypeSpecifier())
6529       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6530         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6531         << SourceRange(D.getIdentifierLoc());
6532     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6533       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6534                                 SourceLocation(),
6535                                 D.getDeclSpec().getConstSpecLoc(),
6536                                 D.getDeclSpec().getVolatileSpecLoc(),
6537                                 D.getDeclSpec().getRestrictSpecLoc(),
6538                                 D.getDeclSpec().getAtomicSpecLoc());
6539       D.setInvalidType();
6540     }
6541   }
6542 
6543   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6544   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6545     if (FTI.TypeQuals & Qualifiers::Const)
6546       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6547         << "const" << SourceRange(D.getIdentifierLoc());
6548     if (FTI.TypeQuals & Qualifiers::Volatile)
6549       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6550         << "volatile" << SourceRange(D.getIdentifierLoc());
6551     if (FTI.TypeQuals & Qualifiers::Restrict)
6552       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6553         << "restrict" << SourceRange(D.getIdentifierLoc());
6554     D.setInvalidType();
6555   }
6556 
6557   // C++0x [class.dtor]p2:
6558   //   A destructor shall not be declared with a ref-qualifier.
6559   if (FTI.hasRefQualifier()) {
6560     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6561       << FTI.RefQualifierIsLValueRef
6562       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6563     D.setInvalidType();
6564   }
6565 
6566   // Make sure we don't have any parameters.
6567   if (FTIHasNonVoidParameters(FTI)) {
6568     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6569 
6570     // Delete the parameters.
6571     FTI.freeParams();
6572     D.setInvalidType();
6573   }
6574 
6575   // Make sure the destructor isn't variadic.
6576   if (FTI.isVariadic) {
6577     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6578     D.setInvalidType();
6579   }
6580 
6581   // Rebuild the function type "R" without any type qualifiers or
6582   // parameters (in case any of the errors above fired) and with
6583   // "void" as the return type, since destructors don't have return
6584   // types.
6585   if (!D.isInvalidType())
6586     return R;
6587 
6588   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6589   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6590   EPI.Variadic = false;
6591   EPI.TypeQuals = 0;
6592   EPI.RefQualifier = RQ_None;
6593   return Context.getFunctionType(Context.VoidTy, None, EPI);
6594 }
6595 
6596 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6597 /// well-formednes of the conversion function declarator @p D with
6598 /// type @p R. If there are any errors in the declarator, this routine
6599 /// will emit diagnostics and return true. Otherwise, it will return
6600 /// false. Either way, the type @p R will be updated to reflect a
6601 /// well-formed type for the conversion operator.
6602 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6603                                      StorageClass& SC) {
6604   // C++ [class.conv.fct]p1:
6605   //   Neither parameter types nor return type can be specified. The
6606   //   type of a conversion function (8.3.5) is "function taking no
6607   //   parameter returning conversion-type-id."
6608   if (SC == SC_Static) {
6609     if (!D.isInvalidType())
6610       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6611         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6612         << D.getName().getSourceRange();
6613     D.setInvalidType();
6614     SC = SC_None;
6615   }
6616 
6617   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6618 
6619   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6620     // Conversion functions don't have return types, but the parser will
6621     // happily parse something like:
6622     //
6623     //   class X {
6624     //     float operator bool();
6625     //   };
6626     //
6627     // The return type will be changed later anyway.
6628     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6629       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6630       << SourceRange(D.getIdentifierLoc());
6631     D.setInvalidType();
6632   }
6633 
6634   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6635 
6636   // Make sure we don't have any parameters.
6637   if (Proto->getNumParams() > 0) {
6638     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6639 
6640     // Delete the parameters.
6641     D.getFunctionTypeInfo().freeParams();
6642     D.setInvalidType();
6643   } else if (Proto->isVariadic()) {
6644     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6645     D.setInvalidType();
6646   }
6647 
6648   // Diagnose "&operator bool()" and other such nonsense.  This
6649   // is actually a gcc extension which we don't support.
6650   if (Proto->getReturnType() != ConvType) {
6651     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6652         << Proto->getReturnType();
6653     D.setInvalidType();
6654     ConvType = Proto->getReturnType();
6655   }
6656 
6657   // C++ [class.conv.fct]p4:
6658   //   The conversion-type-id shall not represent a function type nor
6659   //   an array type.
6660   if (ConvType->isArrayType()) {
6661     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6662     ConvType = Context.getPointerType(ConvType);
6663     D.setInvalidType();
6664   } else if (ConvType->isFunctionType()) {
6665     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6666     ConvType = Context.getPointerType(ConvType);
6667     D.setInvalidType();
6668   }
6669 
6670   // Rebuild the function type "R" without any parameters (in case any
6671   // of the errors above fired) and with the conversion type as the
6672   // return type.
6673   if (D.isInvalidType())
6674     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6675 
6676   // C++0x explicit conversion operators.
6677   if (D.getDeclSpec().isExplicitSpecified())
6678     Diag(D.getDeclSpec().getExplicitSpecLoc(),
6679          getLangOpts().CPlusPlus11 ?
6680            diag::warn_cxx98_compat_explicit_conversion_functions :
6681            diag::ext_explicit_conversion_functions)
6682       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6683 }
6684 
6685 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6686 /// the declaration of the given C++ conversion function. This routine
6687 /// is responsible for recording the conversion function in the C++
6688 /// class, if possible.
6689 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6690   assert(Conversion && "Expected to receive a conversion function declaration");
6691 
6692   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6693 
6694   // Make sure we aren't redeclaring the conversion function.
6695   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6696 
6697   // C++ [class.conv.fct]p1:
6698   //   [...] A conversion function is never used to convert a
6699   //   (possibly cv-qualified) object to the (possibly cv-qualified)
6700   //   same object type (or a reference to it), to a (possibly
6701   //   cv-qualified) base class of that type (or a reference to it),
6702   //   or to (possibly cv-qualified) void.
6703   // FIXME: Suppress this warning if the conversion function ends up being a
6704   // virtual function that overrides a virtual function in a base class.
6705   QualType ClassType
6706     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6707   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6708     ConvType = ConvTypeRef->getPointeeType();
6709   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6710       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6711     /* Suppress diagnostics for instantiations. */;
6712   else if (ConvType->isRecordType()) {
6713     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6714     if (ConvType == ClassType)
6715       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6716         << ClassType;
6717     else if (IsDerivedFrom(ClassType, ConvType))
6718       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6719         <<  ClassType << ConvType;
6720   } else if (ConvType->isVoidType()) {
6721     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6722       << ClassType << ConvType;
6723   }
6724 
6725   if (FunctionTemplateDecl *ConversionTemplate
6726                                 = Conversion->getDescribedFunctionTemplate())
6727     return ConversionTemplate;
6728 
6729   return Conversion;
6730 }
6731 
6732 //===----------------------------------------------------------------------===//
6733 // Namespace Handling
6734 //===----------------------------------------------------------------------===//
6735 
6736 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6737 /// reopened.
6738 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6739                                             SourceLocation Loc,
6740                                             IdentifierInfo *II, bool *IsInline,
6741                                             NamespaceDecl *PrevNS) {
6742   assert(*IsInline != PrevNS->isInline());
6743 
6744   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6745   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6746   // inline namespaces, with the intention of bringing names into namespace std.
6747   //
6748   // We support this just well enough to get that case working; this is not
6749   // sufficient to support reopening namespaces as inline in general.
6750   if (*IsInline && II && II->getName().startswith("__atomic") &&
6751       S.getSourceManager().isInSystemHeader(Loc)) {
6752     // Mark all prior declarations of the namespace as inline.
6753     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6754          NS = NS->getPreviousDecl())
6755       NS->setInline(*IsInline);
6756     // Patch up the lookup table for the containing namespace. This isn't really
6757     // correct, but it's good enough for this particular case.
6758     for (auto *I : PrevNS->decls())
6759       if (auto *ND = dyn_cast<NamedDecl>(I))
6760         PrevNS->getParent()->makeDeclVisibleInContext(ND);
6761     return;
6762   }
6763 
6764   if (PrevNS->isInline())
6765     // The user probably just forgot the 'inline', so suggest that it
6766     // be added back.
6767     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6768       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6769   else
6770     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
6771 
6772   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6773   *IsInline = PrevNS->isInline();
6774 }
6775 
6776 /// ActOnStartNamespaceDef - This is called at the start of a namespace
6777 /// definition.
6778 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6779                                    SourceLocation InlineLoc,
6780                                    SourceLocation NamespaceLoc,
6781                                    SourceLocation IdentLoc,
6782                                    IdentifierInfo *II,
6783                                    SourceLocation LBrace,
6784                                    AttributeList *AttrList) {
6785   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6786   // For anonymous namespace, take the location of the left brace.
6787   SourceLocation Loc = II ? IdentLoc : LBrace;
6788   bool IsInline = InlineLoc.isValid();
6789   bool IsInvalid = false;
6790   bool IsStd = false;
6791   bool AddToKnown = false;
6792   Scope *DeclRegionScope = NamespcScope->getParent();
6793 
6794   NamespaceDecl *PrevNS = nullptr;
6795   if (II) {
6796     // C++ [namespace.def]p2:
6797     //   The identifier in an original-namespace-definition shall not
6798     //   have been previously defined in the declarative region in
6799     //   which the original-namespace-definition appears. The
6800     //   identifier in an original-namespace-definition is the name of
6801     //   the namespace. Subsequently in that declarative region, it is
6802     //   treated as an original-namespace-name.
6803     //
6804     // Since namespace names are unique in their scope, and we don't
6805     // look through using directives, just look for any ordinary names.
6806 
6807     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6808     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6809     Decl::IDNS_Namespace;
6810     NamedDecl *PrevDecl = nullptr;
6811     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6812     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6813          ++I) {
6814       if ((*I)->getIdentifierNamespace() & IDNS) {
6815         PrevDecl = *I;
6816         break;
6817       }
6818     }
6819 
6820     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6821 
6822     if (PrevNS) {
6823       // This is an extended namespace definition.
6824       if (IsInline != PrevNS->isInline())
6825         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6826                                         &IsInline, PrevNS);
6827     } else if (PrevDecl) {
6828       // This is an invalid name redefinition.
6829       Diag(Loc, diag::err_redefinition_different_kind)
6830         << II;
6831       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6832       IsInvalid = true;
6833       // Continue on to push Namespc as current DeclContext and return it.
6834     } else if (II->isStr("std") &&
6835                CurContext->getRedeclContext()->isTranslationUnit()) {
6836       // This is the first "real" definition of the namespace "std", so update
6837       // our cache of the "std" namespace to point at this definition.
6838       PrevNS = getStdNamespace();
6839       IsStd = true;
6840       AddToKnown = !IsInline;
6841     } else {
6842       // We've seen this namespace for the first time.
6843       AddToKnown = !IsInline;
6844     }
6845   } else {
6846     // Anonymous namespaces.
6847 
6848     // Determine whether the parent already has an anonymous namespace.
6849     DeclContext *Parent = CurContext->getRedeclContext();
6850     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6851       PrevNS = TU->getAnonymousNamespace();
6852     } else {
6853       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6854       PrevNS = ND->getAnonymousNamespace();
6855     }
6856 
6857     if (PrevNS && IsInline != PrevNS->isInline())
6858       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6859                                       &IsInline, PrevNS);
6860   }
6861 
6862   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6863                                                  StartLoc, Loc, II, PrevNS);
6864   if (IsInvalid)
6865     Namespc->setInvalidDecl();
6866 
6867   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6868 
6869   // FIXME: Should we be merging attributes?
6870   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6871     PushNamespaceVisibilityAttr(Attr, Loc);
6872 
6873   if (IsStd)
6874     StdNamespace = Namespc;
6875   if (AddToKnown)
6876     KnownNamespaces[Namespc] = false;
6877 
6878   if (II) {
6879     PushOnScopeChains(Namespc, DeclRegionScope);
6880   } else {
6881     // Link the anonymous namespace into its parent.
6882     DeclContext *Parent = CurContext->getRedeclContext();
6883     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6884       TU->setAnonymousNamespace(Namespc);
6885     } else {
6886       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6887     }
6888 
6889     CurContext->addDecl(Namespc);
6890 
6891     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6892     //   behaves as if it were replaced by
6893     //     namespace unique { /* empty body */ }
6894     //     using namespace unique;
6895     //     namespace unique { namespace-body }
6896     //   where all occurrences of 'unique' in a translation unit are
6897     //   replaced by the same identifier and this identifier differs
6898     //   from all other identifiers in the entire program.
6899 
6900     // We just create the namespace with an empty name and then add an
6901     // implicit using declaration, just like the standard suggests.
6902     //
6903     // CodeGen enforces the "universally unique" aspect by giving all
6904     // declarations semantically contained within an anonymous
6905     // namespace internal linkage.
6906 
6907     if (!PrevNS) {
6908       UsingDirectiveDecl* UD
6909         = UsingDirectiveDecl::Create(Context, Parent,
6910                                      /* 'using' */ LBrace,
6911                                      /* 'namespace' */ SourceLocation(),
6912                                      /* qualifier */ NestedNameSpecifierLoc(),
6913                                      /* identifier */ SourceLocation(),
6914                                      Namespc,
6915                                      /* Ancestor */ Parent);
6916       UD->setImplicit();
6917       Parent->addDecl(UD);
6918     }
6919   }
6920 
6921   ActOnDocumentableDecl(Namespc);
6922 
6923   // Although we could have an invalid decl (i.e. the namespace name is a
6924   // redefinition), push it as current DeclContext and try to continue parsing.
6925   // FIXME: We should be able to push Namespc here, so that the each DeclContext
6926   // for the namespace has the declarations that showed up in that particular
6927   // namespace definition.
6928   PushDeclContext(NamespcScope, Namespc);
6929   return Namespc;
6930 }
6931 
6932 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6933 /// is a namespace alias, returns the namespace it points to.
6934 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6935   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6936     return AD->getNamespace();
6937   return dyn_cast_or_null<NamespaceDecl>(D);
6938 }
6939 
6940 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
6941 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6942 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6943   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6944   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6945   Namespc->setRBraceLoc(RBrace);
6946   PopDeclContext();
6947   if (Namespc->hasAttr<VisibilityAttr>())
6948     PopPragmaVisibility(true, RBrace);
6949 }
6950 
6951 CXXRecordDecl *Sema::getStdBadAlloc() const {
6952   return cast_or_null<CXXRecordDecl>(
6953                                   StdBadAlloc.get(Context.getExternalSource()));
6954 }
6955 
6956 NamespaceDecl *Sema::getStdNamespace() const {
6957   return cast_or_null<NamespaceDecl>(
6958                                  StdNamespace.get(Context.getExternalSource()));
6959 }
6960 
6961 /// \brief Retrieve the special "std" namespace, which may require us to
6962 /// implicitly define the namespace.
6963 NamespaceDecl *Sema::getOrCreateStdNamespace() {
6964   if (!StdNamespace) {
6965     // The "std" namespace has not yet been defined, so build one implicitly.
6966     StdNamespace = NamespaceDecl::Create(Context,
6967                                          Context.getTranslationUnitDecl(),
6968                                          /*Inline=*/false,
6969                                          SourceLocation(), SourceLocation(),
6970                                          &PP.getIdentifierTable().get("std"),
6971                                          /*PrevDecl=*/nullptr);
6972     getStdNamespace()->setImplicit(true);
6973   }
6974 
6975   return getStdNamespace();
6976 }
6977 
6978 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6979   assert(getLangOpts().CPlusPlus &&
6980          "Looking for std::initializer_list outside of C++.");
6981 
6982   // We're looking for implicit instantiations of
6983   // template <typename E> class std::initializer_list.
6984 
6985   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6986     return false;
6987 
6988   ClassTemplateDecl *Template = nullptr;
6989   const TemplateArgument *Arguments = nullptr;
6990 
6991   if (const RecordType *RT = Ty->getAs<RecordType>()) {
6992 
6993     ClassTemplateSpecializationDecl *Specialization =
6994         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6995     if (!Specialization)
6996       return false;
6997 
6998     Template = Specialization->getSpecializedTemplate();
6999     Arguments = Specialization->getTemplateArgs().data();
7000   } else if (const TemplateSpecializationType *TST =
7001                  Ty->getAs<TemplateSpecializationType>()) {
7002     Template = dyn_cast_or_null<ClassTemplateDecl>(
7003         TST->getTemplateName().getAsTemplateDecl());
7004     Arguments = TST->getArgs();
7005   }
7006   if (!Template)
7007     return false;
7008 
7009   if (!StdInitializerList) {
7010     // Haven't recognized std::initializer_list yet, maybe this is it.
7011     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7012     if (TemplateClass->getIdentifier() !=
7013             &PP.getIdentifierTable().get("initializer_list") ||
7014         !getStdNamespace()->InEnclosingNamespaceSetOf(
7015             TemplateClass->getDeclContext()))
7016       return false;
7017     // This is a template called std::initializer_list, but is it the right
7018     // template?
7019     TemplateParameterList *Params = Template->getTemplateParameters();
7020     if (Params->getMinRequiredArguments() != 1)
7021       return false;
7022     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7023       return false;
7024 
7025     // It's the right template.
7026     StdInitializerList = Template;
7027   }
7028 
7029   if (Template != StdInitializerList)
7030     return false;
7031 
7032   // This is an instance of std::initializer_list. Find the argument type.
7033   if (Element)
7034     *Element = Arguments[0].getAsType();
7035   return true;
7036 }
7037 
7038 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7039   NamespaceDecl *Std = S.getStdNamespace();
7040   if (!Std) {
7041     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7042     return nullptr;
7043   }
7044 
7045   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7046                       Loc, Sema::LookupOrdinaryName);
7047   if (!S.LookupQualifiedName(Result, Std)) {
7048     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7049     return nullptr;
7050   }
7051   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7052   if (!Template) {
7053     Result.suppressDiagnostics();
7054     // We found something weird. Complain about the first thing we found.
7055     NamedDecl *Found = *Result.begin();
7056     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7057     return nullptr;
7058   }
7059 
7060   // We found some template called std::initializer_list. Now verify that it's
7061   // correct.
7062   TemplateParameterList *Params = Template->getTemplateParameters();
7063   if (Params->getMinRequiredArguments() != 1 ||
7064       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7065     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7066     return nullptr;
7067   }
7068 
7069   return Template;
7070 }
7071 
7072 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7073   if (!StdInitializerList) {
7074     StdInitializerList = LookupStdInitializerList(*this, Loc);
7075     if (!StdInitializerList)
7076       return QualType();
7077   }
7078 
7079   TemplateArgumentListInfo Args(Loc, Loc);
7080   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7081                                        Context.getTrivialTypeSourceInfo(Element,
7082                                                                         Loc)));
7083   return Context.getCanonicalType(
7084       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7085 }
7086 
7087 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7088   // C++ [dcl.init.list]p2:
7089   //   A constructor is an initializer-list constructor if its first parameter
7090   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7091   //   std::initializer_list<E> for some type E, and either there are no other
7092   //   parameters or else all other parameters have default arguments.
7093   if (Ctor->getNumParams() < 1 ||
7094       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7095     return false;
7096 
7097   QualType ArgType = Ctor->getParamDecl(0)->getType();
7098   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7099     ArgType = RT->getPointeeType().getUnqualifiedType();
7100 
7101   return isStdInitializerList(ArgType, nullptr);
7102 }
7103 
7104 /// \brief Determine whether a using statement is in a context where it will be
7105 /// apply in all contexts.
7106 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7107   switch (CurContext->getDeclKind()) {
7108     case Decl::TranslationUnit:
7109       return true;
7110     case Decl::LinkageSpec:
7111       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7112     default:
7113       return false;
7114   }
7115 }
7116 
7117 namespace {
7118 
7119 // Callback to only accept typo corrections that are namespaces.
7120 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7121 public:
7122   bool ValidateCandidate(const TypoCorrection &candidate) override {
7123     if (NamedDecl *ND = candidate.getCorrectionDecl())
7124       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7125     return false;
7126   }
7127 };
7128 
7129 }
7130 
7131 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7132                                        CXXScopeSpec &SS,
7133                                        SourceLocation IdentLoc,
7134                                        IdentifierInfo *Ident) {
7135   NamespaceValidatorCCC Validator;
7136   R.clear();
7137   if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
7138                                                R.getLookupKind(), Sc, &SS,
7139                                                Validator,
7140                                                Sema::CTK_ErrorRecovery)) {
7141     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7142       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7143       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7144                               Ident->getName().equals(CorrectedStr);
7145       S.diagnoseTypo(Corrected,
7146                      S.PDiag(diag::err_using_directive_member_suggest)
7147                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7148                      S.PDiag(diag::note_namespace_defined_here));
7149     } else {
7150       S.diagnoseTypo(Corrected,
7151                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7152                      S.PDiag(diag::note_namespace_defined_here));
7153     }
7154     R.addDecl(Corrected.getCorrectionDecl());
7155     return true;
7156   }
7157   return false;
7158 }
7159 
7160 Decl *Sema::ActOnUsingDirective(Scope *S,
7161                                           SourceLocation UsingLoc,
7162                                           SourceLocation NamespcLoc,
7163                                           CXXScopeSpec &SS,
7164                                           SourceLocation IdentLoc,
7165                                           IdentifierInfo *NamespcName,
7166                                           AttributeList *AttrList) {
7167   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7168   assert(NamespcName && "Invalid NamespcName.");
7169   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7170 
7171   // This can only happen along a recovery path.
7172   while (S->getFlags() & Scope::TemplateParamScope)
7173     S = S->getParent();
7174   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7175 
7176   UsingDirectiveDecl *UDir = nullptr;
7177   NestedNameSpecifier *Qualifier = nullptr;
7178   if (SS.isSet())
7179     Qualifier = SS.getScopeRep();
7180 
7181   // Lookup namespace name.
7182   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7183   LookupParsedName(R, S, &SS);
7184   if (R.isAmbiguous())
7185     return nullptr;
7186 
7187   if (R.empty()) {
7188     R.clear();
7189     // Allow "using namespace std;" or "using namespace ::std;" even if
7190     // "std" hasn't been defined yet, for GCC compatibility.
7191     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7192         NamespcName->isStr("std")) {
7193       Diag(IdentLoc, diag::ext_using_undefined_std);
7194       R.addDecl(getOrCreateStdNamespace());
7195       R.resolveKind();
7196     }
7197     // Otherwise, attempt typo correction.
7198     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7199   }
7200 
7201   if (!R.empty()) {
7202     NamedDecl *Named = R.getFoundDecl();
7203     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7204         && "expected namespace decl");
7205     // C++ [namespace.udir]p1:
7206     //   A using-directive specifies that the names in the nominated
7207     //   namespace can be used in the scope in which the
7208     //   using-directive appears after the using-directive. During
7209     //   unqualified name lookup (3.4.1), the names appear as if they
7210     //   were declared in the nearest enclosing namespace which
7211     //   contains both the using-directive and the nominated
7212     //   namespace. [Note: in this context, "contains" means "contains
7213     //   directly or indirectly". ]
7214 
7215     // Find enclosing context containing both using-directive and
7216     // nominated namespace.
7217     NamespaceDecl *NS = getNamespaceDecl(Named);
7218     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7219     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7220       CommonAncestor = CommonAncestor->getParent();
7221 
7222     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7223                                       SS.getWithLocInContext(Context),
7224                                       IdentLoc, Named, CommonAncestor);
7225 
7226     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7227         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7228       Diag(IdentLoc, diag::warn_using_directive_in_header);
7229     }
7230 
7231     PushUsingDirective(S, UDir);
7232   } else {
7233     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7234   }
7235 
7236   if (UDir)
7237     ProcessDeclAttributeList(S, UDir, AttrList);
7238 
7239   return UDir;
7240 }
7241 
7242 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7243   // If the scope has an associated entity and the using directive is at
7244   // namespace or translation unit scope, add the UsingDirectiveDecl into
7245   // its lookup structure so qualified name lookup can find it.
7246   DeclContext *Ctx = S->getEntity();
7247   if (Ctx && !Ctx->isFunctionOrMethod())
7248     Ctx->addDecl(UDir);
7249   else
7250     // Otherwise, it is at block scope. The using-directives will affect lookup
7251     // only to the end of the scope.
7252     S->PushUsingDirective(UDir);
7253 }
7254 
7255 
7256 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7257                                   AccessSpecifier AS,
7258                                   bool HasUsingKeyword,
7259                                   SourceLocation UsingLoc,
7260                                   CXXScopeSpec &SS,
7261                                   UnqualifiedId &Name,
7262                                   AttributeList *AttrList,
7263                                   bool HasTypenameKeyword,
7264                                   SourceLocation TypenameLoc) {
7265   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7266 
7267   switch (Name.getKind()) {
7268   case UnqualifiedId::IK_ImplicitSelfParam:
7269   case UnqualifiedId::IK_Identifier:
7270   case UnqualifiedId::IK_OperatorFunctionId:
7271   case UnqualifiedId::IK_LiteralOperatorId:
7272   case UnqualifiedId::IK_ConversionFunctionId:
7273     break;
7274 
7275   case UnqualifiedId::IK_ConstructorName:
7276   case UnqualifiedId::IK_ConstructorTemplateId:
7277     // C++11 inheriting constructors.
7278     Diag(Name.getLocStart(),
7279          getLangOpts().CPlusPlus11 ?
7280            diag::warn_cxx98_compat_using_decl_constructor :
7281            diag::err_using_decl_constructor)
7282       << SS.getRange();
7283 
7284     if (getLangOpts().CPlusPlus11) break;
7285 
7286     return nullptr;
7287 
7288   case UnqualifiedId::IK_DestructorName:
7289     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7290       << SS.getRange();
7291     return nullptr;
7292 
7293   case UnqualifiedId::IK_TemplateId:
7294     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7295       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7296     return nullptr;
7297   }
7298 
7299   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7300   DeclarationName TargetName = TargetNameInfo.getName();
7301   if (!TargetName)
7302     return nullptr;
7303 
7304   // Warn about access declarations.
7305   if (!HasUsingKeyword) {
7306     Diag(Name.getLocStart(),
7307          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7308                                    : diag::warn_access_decl_deprecated)
7309       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7310   }
7311 
7312   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7313       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7314     return nullptr;
7315 
7316   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7317                                         TargetNameInfo, AttrList,
7318                                         /* IsInstantiation */ false,
7319                                         HasTypenameKeyword, TypenameLoc);
7320   if (UD)
7321     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7322 
7323   return UD;
7324 }
7325 
7326 /// \brief Determine whether a using declaration considers the given
7327 /// declarations as "equivalent", e.g., if they are redeclarations of
7328 /// the same entity or are both typedefs of the same type.
7329 static bool
7330 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7331   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7332     return true;
7333 
7334   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7335     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7336       return Context.hasSameType(TD1->getUnderlyingType(),
7337                                  TD2->getUnderlyingType());
7338 
7339   return false;
7340 }
7341 
7342 
7343 /// Determines whether to create a using shadow decl for a particular
7344 /// decl, given the set of decls existing prior to this using lookup.
7345 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7346                                 const LookupResult &Previous,
7347                                 UsingShadowDecl *&PrevShadow) {
7348   // Diagnose finding a decl which is not from a base class of the
7349   // current class.  We do this now because there are cases where this
7350   // function will silently decide not to build a shadow decl, which
7351   // will pre-empt further diagnostics.
7352   //
7353   // We don't need to do this in C++0x because we do the check once on
7354   // the qualifier.
7355   //
7356   // FIXME: diagnose the following if we care enough:
7357   //   struct A { int foo; };
7358   //   struct B : A { using A::foo; };
7359   //   template <class T> struct C : A {};
7360   //   template <class T> struct D : C<T> { using B::foo; } // <---
7361   // This is invalid (during instantiation) in C++03 because B::foo
7362   // resolves to the using decl in B, which is not a base class of D<T>.
7363   // We can't diagnose it immediately because C<T> is an unknown
7364   // specialization.  The UsingShadowDecl in D<T> then points directly
7365   // to A::foo, which will look well-formed when we instantiate.
7366   // The right solution is to not collapse the shadow-decl chain.
7367   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7368     DeclContext *OrigDC = Orig->getDeclContext();
7369 
7370     // Handle enums and anonymous structs.
7371     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7372     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7373     while (OrigRec->isAnonymousStructOrUnion())
7374       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7375 
7376     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7377       if (OrigDC == CurContext) {
7378         Diag(Using->getLocation(),
7379              diag::err_using_decl_nested_name_specifier_is_current_class)
7380           << Using->getQualifierLoc().getSourceRange();
7381         Diag(Orig->getLocation(), diag::note_using_decl_target);
7382         return true;
7383       }
7384 
7385       Diag(Using->getQualifierLoc().getBeginLoc(),
7386            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7387         << Using->getQualifier()
7388         << cast<CXXRecordDecl>(CurContext)
7389         << Using->getQualifierLoc().getSourceRange();
7390       Diag(Orig->getLocation(), diag::note_using_decl_target);
7391       return true;
7392     }
7393   }
7394 
7395   if (Previous.empty()) return false;
7396 
7397   NamedDecl *Target = Orig;
7398   if (isa<UsingShadowDecl>(Target))
7399     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7400 
7401   // If the target happens to be one of the previous declarations, we
7402   // don't have a conflict.
7403   //
7404   // FIXME: but we might be increasing its access, in which case we
7405   // should redeclare it.
7406   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7407   bool FoundEquivalentDecl = false;
7408   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7409          I != E; ++I) {
7410     NamedDecl *D = (*I)->getUnderlyingDecl();
7411     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7412       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7413         PrevShadow = Shadow;
7414       FoundEquivalentDecl = true;
7415     }
7416 
7417     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7418   }
7419 
7420   if (FoundEquivalentDecl)
7421     return false;
7422 
7423   if (FunctionDecl *FD = Target->getAsFunction()) {
7424     NamedDecl *OldDecl = nullptr;
7425     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7426                           /*IsForUsingDecl*/ true)) {
7427     case Ovl_Overload:
7428       return false;
7429 
7430     case Ovl_NonFunction:
7431       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7432       break;
7433 
7434     // We found a decl with the exact signature.
7435     case Ovl_Match:
7436       // If we're in a record, we want to hide the target, so we
7437       // return true (without a diagnostic) to tell the caller not to
7438       // build a shadow decl.
7439       if (CurContext->isRecord())
7440         return true;
7441 
7442       // If we're not in a record, this is an error.
7443       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7444       break;
7445     }
7446 
7447     Diag(Target->getLocation(), diag::note_using_decl_target);
7448     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7449     return true;
7450   }
7451 
7452   // Target is not a function.
7453 
7454   if (isa<TagDecl>(Target)) {
7455     // No conflict between a tag and a non-tag.
7456     if (!Tag) return false;
7457 
7458     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7459     Diag(Target->getLocation(), diag::note_using_decl_target);
7460     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7461     return true;
7462   }
7463 
7464   // No conflict between a tag and a non-tag.
7465   if (!NonTag) return false;
7466 
7467   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7468   Diag(Target->getLocation(), diag::note_using_decl_target);
7469   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7470   return true;
7471 }
7472 
7473 /// Builds a shadow declaration corresponding to a 'using' declaration.
7474 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7475                                             UsingDecl *UD,
7476                                             NamedDecl *Orig,
7477                                             UsingShadowDecl *PrevDecl) {
7478 
7479   // If we resolved to another shadow declaration, just coalesce them.
7480   NamedDecl *Target = Orig;
7481   if (isa<UsingShadowDecl>(Target)) {
7482     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7483     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7484   }
7485 
7486   UsingShadowDecl *Shadow
7487     = UsingShadowDecl::Create(Context, CurContext,
7488                               UD->getLocation(), UD, Target);
7489   UD->addShadowDecl(Shadow);
7490 
7491   Shadow->setAccess(UD->getAccess());
7492   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7493     Shadow->setInvalidDecl();
7494 
7495   Shadow->setPreviousDecl(PrevDecl);
7496 
7497   if (S)
7498     PushOnScopeChains(Shadow, S);
7499   else
7500     CurContext->addDecl(Shadow);
7501 
7502 
7503   return Shadow;
7504 }
7505 
7506 /// Hides a using shadow declaration.  This is required by the current
7507 /// using-decl implementation when a resolvable using declaration in a
7508 /// class is followed by a declaration which would hide or override
7509 /// one or more of the using decl's targets; for example:
7510 ///
7511 ///   struct Base { void foo(int); };
7512 ///   struct Derived : Base {
7513 ///     using Base::foo;
7514 ///     void foo(int);
7515 ///   };
7516 ///
7517 /// The governing language is C++03 [namespace.udecl]p12:
7518 ///
7519 ///   When a using-declaration brings names from a base class into a
7520 ///   derived class scope, member functions in the derived class
7521 ///   override and/or hide member functions with the same name and
7522 ///   parameter types in a base class (rather than conflicting).
7523 ///
7524 /// There are two ways to implement this:
7525 ///   (1) optimistically create shadow decls when they're not hidden
7526 ///       by existing declarations, or
7527 ///   (2) don't create any shadow decls (or at least don't make them
7528 ///       visible) until we've fully parsed/instantiated the class.
7529 /// The problem with (1) is that we might have to retroactively remove
7530 /// a shadow decl, which requires several O(n) operations because the
7531 /// decl structures are (very reasonably) not designed for removal.
7532 /// (2) avoids this but is very fiddly and phase-dependent.
7533 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7534   if (Shadow->getDeclName().getNameKind() ==
7535         DeclarationName::CXXConversionFunctionName)
7536     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7537 
7538   // Remove it from the DeclContext...
7539   Shadow->getDeclContext()->removeDecl(Shadow);
7540 
7541   // ...and the scope, if applicable...
7542   if (S) {
7543     S->RemoveDecl(Shadow);
7544     IdResolver.RemoveDecl(Shadow);
7545   }
7546 
7547   // ...and the using decl.
7548   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7549 
7550   // TODO: complain somehow if Shadow was used.  It shouldn't
7551   // be possible for this to happen, because...?
7552 }
7553 
7554 /// Find the base specifier for a base class with the given type.
7555 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7556                                                 QualType DesiredBase,
7557                                                 bool &AnyDependentBases) {
7558   // Check whether the named type is a direct base class.
7559   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7560   for (auto &Base : Derived->bases()) {
7561     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7562     if (CanonicalDesiredBase == BaseType)
7563       return &Base;
7564     if (BaseType->isDependentType())
7565       AnyDependentBases = true;
7566   }
7567   return nullptr;
7568 }
7569 
7570 namespace {
7571 class UsingValidatorCCC : public CorrectionCandidateCallback {
7572 public:
7573   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7574                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7575       : HasTypenameKeyword(HasTypenameKeyword),
7576         IsInstantiation(IsInstantiation), OldNNS(NNS),
7577         RequireMemberOf(RequireMemberOf) {}
7578 
7579   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7580     NamedDecl *ND = Candidate.getCorrectionDecl();
7581 
7582     // Keywords are not valid here.
7583     if (!ND || isa<NamespaceDecl>(ND))
7584       return false;
7585 
7586     // Completely unqualified names are invalid for a 'using' declaration.
7587     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7588       return false;
7589 
7590     if (RequireMemberOf) {
7591       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7592       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7593         // No-one ever wants a using-declaration to name an injected-class-name
7594         // of a base class, unless they're declaring an inheriting constructor.
7595         ASTContext &Ctx = ND->getASTContext();
7596         if (!Ctx.getLangOpts().CPlusPlus11)
7597           return false;
7598         QualType FoundType = Ctx.getRecordType(FoundRecord);
7599 
7600         // Check that the injected-class-name is named as a member of its own
7601         // type; we don't want to suggest 'using Derived::Base;', since that
7602         // means something else.
7603         NestedNameSpecifier *Specifier =
7604             Candidate.WillReplaceSpecifier()
7605                 ? Candidate.getCorrectionSpecifier()
7606                 : OldNNS;
7607         if (!Specifier->getAsType() ||
7608             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7609           return false;
7610 
7611         // Check that this inheriting constructor declaration actually names a
7612         // direct base class of the current class.
7613         bool AnyDependentBases = false;
7614         if (!findDirectBaseWithType(RequireMemberOf,
7615                                     Ctx.getRecordType(FoundRecord),
7616                                     AnyDependentBases) &&
7617             !AnyDependentBases)
7618           return false;
7619       } else {
7620         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7621         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7622           return false;
7623 
7624         // FIXME: Check that the base class member is accessible?
7625       }
7626     }
7627 
7628     if (isa<TypeDecl>(ND))
7629       return HasTypenameKeyword || !IsInstantiation;
7630 
7631     return !HasTypenameKeyword;
7632   }
7633 
7634 private:
7635   bool HasTypenameKeyword;
7636   bool IsInstantiation;
7637   NestedNameSpecifier *OldNNS;
7638   CXXRecordDecl *RequireMemberOf;
7639 };
7640 } // end anonymous namespace
7641 
7642 /// Builds a using declaration.
7643 ///
7644 /// \param IsInstantiation - Whether this call arises from an
7645 ///   instantiation of an unresolved using declaration.  We treat
7646 ///   the lookup differently for these declarations.
7647 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7648                                        SourceLocation UsingLoc,
7649                                        CXXScopeSpec &SS,
7650                                        DeclarationNameInfo NameInfo,
7651                                        AttributeList *AttrList,
7652                                        bool IsInstantiation,
7653                                        bool HasTypenameKeyword,
7654                                        SourceLocation TypenameLoc) {
7655   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7656   SourceLocation IdentLoc = NameInfo.getLoc();
7657   assert(IdentLoc.isValid() && "Invalid TargetName location.");
7658 
7659   // FIXME: We ignore attributes for now.
7660 
7661   if (SS.isEmpty()) {
7662     Diag(IdentLoc, diag::err_using_requires_qualname);
7663     return nullptr;
7664   }
7665 
7666   // Do the redeclaration lookup in the current scope.
7667   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7668                         ForRedeclaration);
7669   Previous.setHideTags(false);
7670   if (S) {
7671     LookupName(Previous, S);
7672 
7673     // It is really dumb that we have to do this.
7674     LookupResult::Filter F = Previous.makeFilter();
7675     while (F.hasNext()) {
7676       NamedDecl *D = F.next();
7677       if (!isDeclInScope(D, CurContext, S))
7678         F.erase();
7679       // If we found a local extern declaration that's not ordinarily visible,
7680       // and this declaration is being added to a non-block scope, ignore it.
7681       // We're only checking for scope conflicts here, not also for violations
7682       // of the linkage rules.
7683       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7684                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7685         F.erase();
7686     }
7687     F.done();
7688   } else {
7689     assert(IsInstantiation && "no scope in non-instantiation");
7690     assert(CurContext->isRecord() && "scope not record in instantiation");
7691     LookupQualifiedName(Previous, CurContext);
7692   }
7693 
7694   // Check for invalid redeclarations.
7695   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7696                                   SS, IdentLoc, Previous))
7697     return nullptr;
7698 
7699   // Check for bad qualifiers.
7700   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
7701     return nullptr;
7702 
7703   DeclContext *LookupContext = computeDeclContext(SS);
7704   NamedDecl *D;
7705   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7706   if (!LookupContext) {
7707     if (HasTypenameKeyword) {
7708       // FIXME: not all declaration name kinds are legal here
7709       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7710                                               UsingLoc, TypenameLoc,
7711                                               QualifierLoc,
7712                                               IdentLoc, NameInfo.getName());
7713     } else {
7714       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7715                                            QualifierLoc, NameInfo);
7716     }
7717     D->setAccess(AS);
7718     CurContext->addDecl(D);
7719     return D;
7720   }
7721 
7722   auto Build = [&](bool Invalid) {
7723     UsingDecl *UD =
7724         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7725                           HasTypenameKeyword);
7726     UD->setAccess(AS);
7727     CurContext->addDecl(UD);
7728     UD->setInvalidDecl(Invalid);
7729     return UD;
7730   };
7731   auto BuildInvalid = [&]{ return Build(true); };
7732   auto BuildValid = [&]{ return Build(false); };
7733 
7734   if (RequireCompleteDeclContext(SS, LookupContext))
7735     return BuildInvalid();
7736 
7737   // The normal rules do not apply to inheriting constructor declarations.
7738   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7739     UsingDecl *UD = BuildValid();
7740     CheckInheritingConstructorUsingDecl(UD);
7741     return UD;
7742   }
7743 
7744   // Otherwise, look up the target name.
7745 
7746   LookupResult R(*this, NameInfo, LookupOrdinaryName);
7747 
7748   // Unlike most lookups, we don't always want to hide tag
7749   // declarations: tag names are visible through the using declaration
7750   // even if hidden by ordinary names, *except* in a dependent context
7751   // where it's important for the sanity of two-phase lookup.
7752   if (!IsInstantiation)
7753     R.setHideTags(false);
7754 
7755   // For the purposes of this lookup, we have a base object type
7756   // equal to that of the current context.
7757   if (CurContext->isRecord()) {
7758     R.setBaseObjectType(
7759                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7760   }
7761 
7762   LookupQualifiedName(R, LookupContext);
7763 
7764   // Try to correct typos if possible.
7765   if (R.empty()) {
7766     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
7767                           dyn_cast<CXXRecordDecl>(CurContext));
7768     if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7769                                                R.getLookupKind(), S, &SS, CCC,
7770                                                CTK_ErrorRecovery)){
7771       // We reject any correction for which ND would be NULL.
7772       NamedDecl *ND = Corrected.getCorrectionDecl();
7773 
7774       // We reject candidates where DroppedSpecifier == true, hence the
7775       // literal '0' below.
7776       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7777                                 << NameInfo.getName() << LookupContext << 0
7778                                 << SS.getRange());
7779 
7780       // If we corrected to an inheriting constructor, handle it as one.
7781       auto *RD = dyn_cast<CXXRecordDecl>(ND);
7782       if (RD && RD->isInjectedClassName()) {
7783         // Fix up the information we'll use to build the using declaration.
7784         if (Corrected.WillReplaceSpecifier()) {
7785           NestedNameSpecifierLocBuilder Builder;
7786           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7787                               QualifierLoc.getSourceRange());
7788           QualifierLoc = Builder.getWithLocInContext(Context);
7789         }
7790 
7791         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7792             Context.getCanonicalType(Context.getRecordType(RD))));
7793         NameInfo.setNamedTypeInfo(nullptr);
7794 
7795         // Build it and process it as an inheriting constructor.
7796         UsingDecl *UD = BuildValid();
7797         CheckInheritingConstructorUsingDecl(UD);
7798         return UD;
7799       }
7800 
7801       // FIXME: Pick up all the declarations if we found an overloaded function.
7802       R.setLookupName(Corrected.getCorrection());
7803       R.addDecl(ND);
7804     } else {
7805       Diag(IdentLoc, diag::err_no_member)
7806         << NameInfo.getName() << LookupContext << SS.getRange();
7807       return BuildInvalid();
7808     }
7809   }
7810 
7811   if (R.isAmbiguous())
7812     return BuildInvalid();
7813 
7814   if (HasTypenameKeyword) {
7815     // If we asked for a typename and got a non-type decl, error out.
7816     if (!R.getAsSingle<TypeDecl>()) {
7817       Diag(IdentLoc, diag::err_using_typename_non_type);
7818       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7819         Diag((*I)->getUnderlyingDecl()->getLocation(),
7820              diag::note_using_decl_target);
7821       return BuildInvalid();
7822     }
7823   } else {
7824     // If we asked for a non-typename and we got a type, error out,
7825     // but only if this is an instantiation of an unresolved using
7826     // decl.  Otherwise just silently find the type name.
7827     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7828       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7829       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7830       return BuildInvalid();
7831     }
7832   }
7833 
7834   // C++0x N2914 [namespace.udecl]p6:
7835   // A using-declaration shall not name a namespace.
7836   if (R.getAsSingle<NamespaceDecl>()) {
7837     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7838       << SS.getRange();
7839     return BuildInvalid();
7840   }
7841 
7842   UsingDecl *UD = BuildValid();
7843   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7844     UsingShadowDecl *PrevDecl = nullptr;
7845     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7846       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7847   }
7848 
7849   return UD;
7850 }
7851 
7852 /// Additional checks for a using declaration referring to a constructor name.
7853 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7854   assert(!UD->hasTypename() && "expecting a constructor name");
7855 
7856   const Type *SourceType = UD->getQualifier()->getAsType();
7857   assert(SourceType &&
7858          "Using decl naming constructor doesn't have type in scope spec.");
7859   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7860 
7861   // Check whether the named type is a direct base class.
7862   bool AnyDependentBases = false;
7863   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7864                                       AnyDependentBases);
7865   if (!Base && !AnyDependentBases) {
7866     Diag(UD->getUsingLoc(),
7867          diag::err_using_decl_constructor_not_in_direct_base)
7868       << UD->getNameInfo().getSourceRange()
7869       << QualType(SourceType, 0) << TargetClass;
7870     UD->setInvalidDecl();
7871     return true;
7872   }
7873 
7874   if (Base)
7875     Base->setInheritConstructors();
7876 
7877   return false;
7878 }
7879 
7880 /// Checks that the given using declaration is not an invalid
7881 /// redeclaration.  Note that this is checking only for the using decl
7882 /// itself, not for any ill-formedness among the UsingShadowDecls.
7883 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7884                                        bool HasTypenameKeyword,
7885                                        const CXXScopeSpec &SS,
7886                                        SourceLocation NameLoc,
7887                                        const LookupResult &Prev) {
7888   // C++03 [namespace.udecl]p8:
7889   // C++0x [namespace.udecl]p10:
7890   //   A using-declaration is a declaration and can therefore be used
7891   //   repeatedly where (and only where) multiple declarations are
7892   //   allowed.
7893   //
7894   // That's in non-member contexts.
7895   if (!CurContext->getRedeclContext()->isRecord())
7896     return false;
7897 
7898   NestedNameSpecifier *Qual = SS.getScopeRep();
7899 
7900   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7901     NamedDecl *D = *I;
7902 
7903     bool DTypename;
7904     NestedNameSpecifier *DQual;
7905     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7906       DTypename = UD->hasTypename();
7907       DQual = UD->getQualifier();
7908     } else if (UnresolvedUsingValueDecl *UD
7909                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7910       DTypename = false;
7911       DQual = UD->getQualifier();
7912     } else if (UnresolvedUsingTypenameDecl *UD
7913                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7914       DTypename = true;
7915       DQual = UD->getQualifier();
7916     } else continue;
7917 
7918     // using decls differ if one says 'typename' and the other doesn't.
7919     // FIXME: non-dependent using decls?
7920     if (HasTypenameKeyword != DTypename) continue;
7921 
7922     // using decls differ if they name different scopes (but note that
7923     // template instantiation can cause this check to trigger when it
7924     // didn't before instantiation).
7925     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7926         Context.getCanonicalNestedNameSpecifier(DQual))
7927       continue;
7928 
7929     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7930     Diag(D->getLocation(), diag::note_using_decl) << 1;
7931     return true;
7932   }
7933 
7934   return false;
7935 }
7936 
7937 
7938 /// Checks that the given nested-name qualifier used in a using decl
7939 /// in the current context is appropriately related to the current
7940 /// scope.  If an error is found, diagnoses it and returns true.
7941 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7942                                    const CXXScopeSpec &SS,
7943                                    const DeclarationNameInfo &NameInfo,
7944                                    SourceLocation NameLoc) {
7945   DeclContext *NamedContext = computeDeclContext(SS);
7946 
7947   if (!CurContext->isRecord()) {
7948     // C++03 [namespace.udecl]p3:
7949     // C++0x [namespace.udecl]p8:
7950     //   A using-declaration for a class member shall be a member-declaration.
7951 
7952     // If we weren't able to compute a valid scope, it must be a
7953     // dependent class scope.
7954     if (!NamedContext || NamedContext->isRecord()) {
7955       auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7956       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
7957         RD = nullptr;
7958 
7959       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7960         << SS.getRange();
7961 
7962       // If we have a complete, non-dependent source type, try to suggest a
7963       // way to get the same effect.
7964       if (!RD)
7965         return true;
7966 
7967       // Find what this using-declaration was referring to.
7968       LookupResult R(*this, NameInfo, LookupOrdinaryName);
7969       R.setHideTags(false);
7970       R.suppressDiagnostics();
7971       LookupQualifiedName(R, RD);
7972 
7973       if (R.getAsSingle<TypeDecl>()) {
7974         if (getLangOpts().CPlusPlus11) {
7975           // Convert 'using X::Y;' to 'using Y = X::Y;'.
7976           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7977             << 0 // alias declaration
7978             << FixItHint::CreateInsertion(SS.getBeginLoc(),
7979                                           NameInfo.getName().getAsString() +
7980                                               " = ");
7981         } else {
7982           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7983           SourceLocation InsertLoc =
7984               PP.getLocForEndOfToken(NameInfo.getLocEnd());
7985           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7986             << 1 // typedef declaration
7987             << FixItHint::CreateReplacement(UsingLoc, "typedef")
7988             << FixItHint::CreateInsertion(
7989                    InsertLoc, " " + NameInfo.getName().getAsString());
7990         }
7991       } else if (R.getAsSingle<VarDecl>()) {
7992         // Don't provide a fixit outside C++11 mode; we don't want to suggest
7993         // repeating the type of the static data member here.
7994         FixItHint FixIt;
7995         if (getLangOpts().CPlusPlus11) {
7996           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7997           FixIt = FixItHint::CreateReplacement(
7998               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7999         }
8000 
8001         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8002           << 2 // reference declaration
8003           << FixIt;
8004       }
8005       return true;
8006     }
8007 
8008     // Otherwise, everything is known to be fine.
8009     return false;
8010   }
8011 
8012   // The current scope is a record.
8013 
8014   // If the named context is dependent, we can't decide much.
8015   if (!NamedContext) {
8016     // FIXME: in C++0x, we can diagnose if we can prove that the
8017     // nested-name-specifier does not refer to a base class, which is
8018     // still possible in some cases.
8019 
8020     // Otherwise we have to conservatively report that things might be
8021     // okay.
8022     return false;
8023   }
8024 
8025   if (!NamedContext->isRecord()) {
8026     // Ideally this would point at the last name in the specifier,
8027     // but we don't have that level of source info.
8028     Diag(SS.getRange().getBegin(),
8029          diag::err_using_decl_nested_name_specifier_is_not_class)
8030       << SS.getScopeRep() << SS.getRange();
8031     return true;
8032   }
8033 
8034   if (!NamedContext->isDependentContext() &&
8035       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8036     return true;
8037 
8038   if (getLangOpts().CPlusPlus11) {
8039     // C++0x [namespace.udecl]p3:
8040     //   In a using-declaration used as a member-declaration, the
8041     //   nested-name-specifier shall name a base class of the class
8042     //   being defined.
8043 
8044     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8045                                  cast<CXXRecordDecl>(NamedContext))) {
8046       if (CurContext == NamedContext) {
8047         Diag(NameLoc,
8048              diag::err_using_decl_nested_name_specifier_is_current_class)
8049           << SS.getRange();
8050         return true;
8051       }
8052 
8053       Diag(SS.getRange().getBegin(),
8054            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8055         << SS.getScopeRep()
8056         << cast<CXXRecordDecl>(CurContext)
8057         << SS.getRange();
8058       return true;
8059     }
8060 
8061     return false;
8062   }
8063 
8064   // C++03 [namespace.udecl]p4:
8065   //   A using-declaration used as a member-declaration shall refer
8066   //   to a member of a base class of the class being defined [etc.].
8067 
8068   // Salient point: SS doesn't have to name a base class as long as
8069   // lookup only finds members from base classes.  Therefore we can
8070   // diagnose here only if we can prove that that can't happen,
8071   // i.e. if the class hierarchies provably don't intersect.
8072 
8073   // TODO: it would be nice if "definitely valid" results were cached
8074   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8075   // need to be repeated.
8076 
8077   struct UserData {
8078     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
8079 
8080     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8081       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8082       Data->Bases.insert(Base);
8083       return true;
8084     }
8085 
8086     bool hasDependentBases(const CXXRecordDecl *Class) {
8087       return !Class->forallBases(collect, this);
8088     }
8089 
8090     /// Returns true if the base is dependent or is one of the
8091     /// accumulated base classes.
8092     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8093       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8094       return !Data->Bases.count(Base);
8095     }
8096 
8097     bool mightShareBases(const CXXRecordDecl *Class) {
8098       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8099     }
8100   };
8101 
8102   UserData Data;
8103 
8104   // Returns false if we find a dependent base.
8105   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8106     return false;
8107 
8108   // Returns false if the class has a dependent base or if it or one
8109   // of its bases is present in the base set of the current context.
8110   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8111     return false;
8112 
8113   Diag(SS.getRange().getBegin(),
8114        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8115     << SS.getScopeRep()
8116     << cast<CXXRecordDecl>(CurContext)
8117     << SS.getRange();
8118 
8119   return true;
8120 }
8121 
8122 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8123                                   AccessSpecifier AS,
8124                                   MultiTemplateParamsArg TemplateParamLists,
8125                                   SourceLocation UsingLoc,
8126                                   UnqualifiedId &Name,
8127                                   AttributeList *AttrList,
8128                                   TypeResult Type) {
8129   // Skip up to the relevant declaration scope.
8130   while (S->getFlags() & Scope::TemplateParamScope)
8131     S = S->getParent();
8132   assert((S->getFlags() & Scope::DeclScope) &&
8133          "got alias-declaration outside of declaration scope");
8134 
8135   if (Type.isInvalid())
8136     return nullptr;
8137 
8138   bool Invalid = false;
8139   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8140   TypeSourceInfo *TInfo = nullptr;
8141   GetTypeFromParser(Type.get(), &TInfo);
8142 
8143   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8144     return nullptr;
8145 
8146   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8147                                       UPPC_DeclarationType)) {
8148     Invalid = true;
8149     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8150                                              TInfo->getTypeLoc().getBeginLoc());
8151   }
8152 
8153   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8154   LookupName(Previous, S);
8155 
8156   // Warn about shadowing the name of a template parameter.
8157   if (Previous.isSingleResult() &&
8158       Previous.getFoundDecl()->isTemplateParameter()) {
8159     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8160     Previous.clear();
8161   }
8162 
8163   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8164          "name in alias declaration must be an identifier");
8165   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8166                                                Name.StartLocation,
8167                                                Name.Identifier, TInfo);
8168 
8169   NewTD->setAccess(AS);
8170 
8171   if (Invalid)
8172     NewTD->setInvalidDecl();
8173 
8174   ProcessDeclAttributeList(S, NewTD, AttrList);
8175 
8176   CheckTypedefForVariablyModifiedType(S, NewTD);
8177   Invalid |= NewTD->isInvalidDecl();
8178 
8179   bool Redeclaration = false;
8180 
8181   NamedDecl *NewND;
8182   if (TemplateParamLists.size()) {
8183     TypeAliasTemplateDecl *OldDecl = nullptr;
8184     TemplateParameterList *OldTemplateParams = nullptr;
8185 
8186     if (TemplateParamLists.size() != 1) {
8187       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8188         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8189          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8190     }
8191     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8192 
8193     // Only consider previous declarations in the same scope.
8194     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8195                          /*ExplicitInstantiationOrSpecialization*/false);
8196     if (!Previous.empty()) {
8197       Redeclaration = true;
8198 
8199       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8200       if (!OldDecl && !Invalid) {
8201         Diag(UsingLoc, diag::err_redefinition_different_kind)
8202           << Name.Identifier;
8203 
8204         NamedDecl *OldD = Previous.getRepresentativeDecl();
8205         if (OldD->getLocation().isValid())
8206           Diag(OldD->getLocation(), diag::note_previous_definition);
8207 
8208         Invalid = true;
8209       }
8210 
8211       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8212         if (TemplateParameterListsAreEqual(TemplateParams,
8213                                            OldDecl->getTemplateParameters(),
8214                                            /*Complain=*/true,
8215                                            TPL_TemplateMatch))
8216           OldTemplateParams = OldDecl->getTemplateParameters();
8217         else
8218           Invalid = true;
8219 
8220         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8221         if (!Invalid &&
8222             !Context.hasSameType(OldTD->getUnderlyingType(),
8223                                  NewTD->getUnderlyingType())) {
8224           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8225           // but we can't reasonably accept it.
8226           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8227             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8228           if (OldTD->getLocation().isValid())
8229             Diag(OldTD->getLocation(), diag::note_previous_definition);
8230           Invalid = true;
8231         }
8232       }
8233     }
8234 
8235     // Merge any previous default template arguments into our parameters,
8236     // and check the parameter list.
8237     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8238                                    TPC_TypeAliasTemplate))
8239       return nullptr;
8240 
8241     TypeAliasTemplateDecl *NewDecl =
8242       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8243                                     Name.Identifier, TemplateParams,
8244                                     NewTD);
8245     NewTD->setDescribedAliasTemplate(NewDecl);
8246 
8247     NewDecl->setAccess(AS);
8248 
8249     if (Invalid)
8250       NewDecl->setInvalidDecl();
8251     else if (OldDecl)
8252       NewDecl->setPreviousDecl(OldDecl);
8253 
8254     NewND = NewDecl;
8255   } else {
8256     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8257     NewND = NewTD;
8258   }
8259 
8260   if (!Redeclaration)
8261     PushOnScopeChains(NewND, S);
8262 
8263   ActOnDocumentableDecl(NewND);
8264   return NewND;
8265 }
8266 
8267 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
8268                                              SourceLocation NamespaceLoc,
8269                                              SourceLocation AliasLoc,
8270                                              IdentifierInfo *Alias,
8271                                              CXXScopeSpec &SS,
8272                                              SourceLocation IdentLoc,
8273                                              IdentifierInfo *Ident) {
8274 
8275   // Lookup the namespace name.
8276   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8277   LookupParsedName(R, S, &SS);
8278 
8279   // Check if we have a previous declaration with the same name.
8280   NamedDecl *PrevDecl
8281     = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8282                        ForRedeclaration);
8283   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8284     PrevDecl = nullptr;
8285 
8286   if (PrevDecl) {
8287     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8288       // We already have an alias with the same name that points to the same
8289       // namespace, so don't create a new one.
8290       // FIXME: At some point, we'll want to create the (redundant)
8291       // declaration to maintain better source information.
8292       if (!R.isAmbiguous() && !R.empty() &&
8293           AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
8294         return nullptr;
8295     }
8296 
8297     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8298       diag::err_redefinition_different_kind;
8299     Diag(AliasLoc, DiagID) << Alias;
8300     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8301     return nullptr;
8302   }
8303 
8304   if (R.isAmbiguous())
8305     return nullptr;
8306 
8307   if (R.empty()) {
8308     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8309       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8310       return nullptr;
8311     }
8312   }
8313 
8314   NamespaceAliasDecl *AliasDecl =
8315     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8316                                Alias, SS.getWithLocInContext(Context),
8317                                IdentLoc, R.getFoundDecl());
8318 
8319   PushOnScopeChains(AliasDecl, S);
8320   return AliasDecl;
8321 }
8322 
8323 Sema::ImplicitExceptionSpecification
8324 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8325                                                CXXMethodDecl *MD) {
8326   CXXRecordDecl *ClassDecl = MD->getParent();
8327 
8328   // C++ [except.spec]p14:
8329   //   An implicitly declared special member function (Clause 12) shall have an
8330   //   exception-specification. [...]
8331   ImplicitExceptionSpecification ExceptSpec(*this);
8332   if (ClassDecl->isInvalidDecl())
8333     return ExceptSpec;
8334 
8335   // Direct base-class constructors.
8336   for (const auto &B : ClassDecl->bases()) {
8337     if (B.isVirtual()) // Handled below.
8338       continue;
8339 
8340     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8341       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8342       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8343       // If this is a deleted function, add it anyway. This might be conformant
8344       // with the standard. This might not. I'm not sure. It might not matter.
8345       if (Constructor)
8346         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8347     }
8348   }
8349 
8350   // Virtual base-class constructors.
8351   for (const auto &B : ClassDecl->vbases()) {
8352     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8353       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8354       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8355       // If this is a deleted function, add it anyway. This might be conformant
8356       // with the standard. This might not. I'm not sure. It might not matter.
8357       if (Constructor)
8358         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8359     }
8360   }
8361 
8362   // Field constructors.
8363   for (const auto *F : ClassDecl->fields()) {
8364     if (F->hasInClassInitializer()) {
8365       if (Expr *E = F->getInClassInitializer())
8366         ExceptSpec.CalledExpr(E);
8367       else if (!F->isInvalidDecl())
8368         // DR1351:
8369         //   If the brace-or-equal-initializer of a non-static data member
8370         //   invokes a defaulted default constructor of its class or of an
8371         //   enclosing class in a potentially evaluated subexpression, the
8372         //   program is ill-formed.
8373         //
8374         // This resolution is unworkable: the exception specification of the
8375         // default constructor can be needed in an unevaluated context, in
8376         // particular, in the operand of a noexcept-expression, and we can be
8377         // unable to compute an exception specification for an enclosed class.
8378         //
8379         // We do not allow an in-class initializer to require the evaluation
8380         // of the exception specification for any in-class initializer whose
8381         // definition is not lexically complete.
8382         Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
8383     } else if (const RecordType *RecordTy
8384               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8385       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8386       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8387       // If this is a deleted function, add it anyway. This might be conformant
8388       // with the standard. This might not. I'm not sure. It might not matter.
8389       // In particular, the problem is that this function never gets called. It
8390       // might just be ill-formed because this function attempts to refer to
8391       // a deleted function here.
8392       if (Constructor)
8393         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8394     }
8395   }
8396 
8397   return ExceptSpec;
8398 }
8399 
8400 Sema::ImplicitExceptionSpecification
8401 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8402   CXXRecordDecl *ClassDecl = CD->getParent();
8403 
8404   // C++ [except.spec]p14:
8405   //   An inheriting constructor [...] shall have an exception-specification. [...]
8406   ImplicitExceptionSpecification ExceptSpec(*this);
8407   if (ClassDecl->isInvalidDecl())
8408     return ExceptSpec;
8409 
8410   // Inherited constructor.
8411   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8412   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8413   // FIXME: Copying or moving the parameters could add extra exceptions to the
8414   // set, as could the default arguments for the inherited constructor. This
8415   // will be addressed when we implement the resolution of core issue 1351.
8416   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8417 
8418   // Direct base-class constructors.
8419   for (const auto &B : ClassDecl->bases()) {
8420     if (B.isVirtual()) // Handled below.
8421       continue;
8422 
8423     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8424       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8425       if (BaseClassDecl == InheritedDecl)
8426         continue;
8427       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8428       if (Constructor)
8429         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8430     }
8431   }
8432 
8433   // Virtual base-class constructors.
8434   for (const auto &B : ClassDecl->vbases()) {
8435     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8436       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8437       if (BaseClassDecl == InheritedDecl)
8438         continue;
8439       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8440       if (Constructor)
8441         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8442     }
8443   }
8444 
8445   // Field constructors.
8446   for (const auto *F : ClassDecl->fields()) {
8447     if (F->hasInClassInitializer()) {
8448       if (Expr *E = F->getInClassInitializer())
8449         ExceptSpec.CalledExpr(E);
8450       else if (!F->isInvalidDecl())
8451         Diag(CD->getLocation(),
8452              diag::err_in_class_initializer_references_def_ctor) << CD;
8453     } else if (const RecordType *RecordTy
8454               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8455       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8456       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8457       if (Constructor)
8458         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8459     }
8460   }
8461 
8462   return ExceptSpec;
8463 }
8464 
8465 namespace {
8466 /// RAII object to register a special member as being currently declared.
8467 struct DeclaringSpecialMember {
8468   Sema &S;
8469   Sema::SpecialMemberDecl D;
8470   bool WasAlreadyBeingDeclared;
8471 
8472   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8473     : S(S), D(RD, CSM) {
8474     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8475     if (WasAlreadyBeingDeclared)
8476       // This almost never happens, but if it does, ensure that our cache
8477       // doesn't contain a stale result.
8478       S.SpecialMemberCache.clear();
8479 
8480     // FIXME: Register a note to be produced if we encounter an error while
8481     // declaring the special member.
8482   }
8483   ~DeclaringSpecialMember() {
8484     if (!WasAlreadyBeingDeclared)
8485       S.SpecialMembersBeingDeclared.erase(D);
8486   }
8487 
8488   /// \brief Are we already trying to declare this special member?
8489   bool isAlreadyBeingDeclared() const {
8490     return WasAlreadyBeingDeclared;
8491   }
8492 };
8493 }
8494 
8495 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8496                                                      CXXRecordDecl *ClassDecl) {
8497   // C++ [class.ctor]p5:
8498   //   A default constructor for a class X is a constructor of class X
8499   //   that can be called without an argument. If there is no
8500   //   user-declared constructor for class X, a default constructor is
8501   //   implicitly declared. An implicitly-declared default constructor
8502   //   is an inline public member of its class.
8503   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8504          "Should not build implicit default constructor!");
8505 
8506   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8507   if (DSM.isAlreadyBeingDeclared())
8508     return nullptr;
8509 
8510   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8511                                                      CXXDefaultConstructor,
8512                                                      false);
8513 
8514   // Create the actual constructor declaration.
8515   CanQualType ClassType
8516     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8517   SourceLocation ClassLoc = ClassDecl->getLocation();
8518   DeclarationName Name
8519     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8520   DeclarationNameInfo NameInfo(Name, ClassLoc);
8521   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8522       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8523       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8524       /*isImplicitlyDeclared=*/true, Constexpr);
8525   DefaultCon->setAccess(AS_public);
8526   DefaultCon->setDefaulted();
8527   DefaultCon->setImplicit();
8528 
8529   // Build an exception specification pointing back at this constructor.
8530   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8531   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8532 
8533   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8534   // constructors is easy to compute.
8535   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8536 
8537   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8538     SetDeclDeleted(DefaultCon, ClassLoc);
8539 
8540   // Note that we have declared this constructor.
8541   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8542 
8543   if (Scope *S = getScopeForContext(ClassDecl))
8544     PushOnScopeChains(DefaultCon, S, false);
8545   ClassDecl->addDecl(DefaultCon);
8546 
8547   return DefaultCon;
8548 }
8549 
8550 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8551                                             CXXConstructorDecl *Constructor) {
8552   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8553           !Constructor->doesThisDeclarationHaveABody() &&
8554           !Constructor->isDeleted()) &&
8555     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8556 
8557   CXXRecordDecl *ClassDecl = Constructor->getParent();
8558   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8559 
8560   SynthesizedFunctionScope Scope(*this, Constructor);
8561   DiagnosticErrorTrap Trap(Diags);
8562   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8563       Trap.hasErrorOccurred()) {
8564     Diag(CurrentLocation, diag::note_member_synthesized_at)
8565       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8566     Constructor->setInvalidDecl();
8567     return;
8568   }
8569 
8570   SourceLocation Loc = Constructor->getLocEnd().isValid()
8571                            ? Constructor->getLocEnd()
8572                            : Constructor->getLocation();
8573   Constructor->setBody(new (Context) CompoundStmt(Loc));
8574 
8575   Constructor->markUsed(Context);
8576   MarkVTableUsed(CurrentLocation, ClassDecl);
8577 
8578   if (ASTMutationListener *L = getASTMutationListener()) {
8579     L->CompletedImplicitDefinition(Constructor);
8580   }
8581 
8582   DiagnoseUninitializedFields(*this, Constructor);
8583 }
8584 
8585 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8586   // Perform any delayed checks on exception specifications.
8587   CheckDelayedMemberExceptionSpecs();
8588 }
8589 
8590 namespace {
8591 /// Information on inheriting constructors to declare.
8592 class InheritingConstructorInfo {
8593 public:
8594   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8595       : SemaRef(SemaRef), Derived(Derived) {
8596     // Mark the constructors that we already have in the derived class.
8597     //
8598     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8599     //   unless there is a user-declared constructor with the same signature in
8600     //   the class where the using-declaration appears.
8601     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8602   }
8603 
8604   void inheritAll(CXXRecordDecl *RD) {
8605     visitAll(RD, &InheritingConstructorInfo::inherit);
8606   }
8607 
8608 private:
8609   /// Information about an inheriting constructor.
8610   struct InheritingConstructor {
8611     InheritingConstructor()
8612       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
8613 
8614     /// If \c true, a constructor with this signature is already declared
8615     /// in the derived class.
8616     bool DeclaredInDerived;
8617 
8618     /// The constructor which is inherited.
8619     const CXXConstructorDecl *BaseCtor;
8620 
8621     /// The derived constructor we declared.
8622     CXXConstructorDecl *DerivedCtor;
8623   };
8624 
8625   /// Inheriting constructors with a given canonical type. There can be at
8626   /// most one such non-template constructor, and any number of templated
8627   /// constructors.
8628   struct InheritingConstructorsForType {
8629     InheritingConstructor NonTemplate;
8630     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8631         Templates;
8632 
8633     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8634       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8635         TemplateParameterList *ParamList = FTD->getTemplateParameters();
8636         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8637           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8638                                                false, S.TPL_TemplateMatch))
8639             return Templates[I].second;
8640         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8641         return Templates.back().second;
8642       }
8643 
8644       return NonTemplate;
8645     }
8646   };
8647 
8648   /// Get or create the inheriting constructor record for a constructor.
8649   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8650                                   QualType CtorType) {
8651     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8652         .getEntry(SemaRef, Ctor);
8653   }
8654 
8655   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8656 
8657   /// Process all constructors for a class.
8658   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8659     for (const auto *Ctor : RD->ctors())
8660       (this->*Callback)(Ctor);
8661     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8662              I(RD->decls_begin()), E(RD->decls_end());
8663          I != E; ++I) {
8664       const FunctionDecl *FD = (*I)->getTemplatedDecl();
8665       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8666         (this->*Callback)(CD);
8667     }
8668   }
8669 
8670   /// Note that a constructor (or constructor template) was declared in Derived.
8671   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8672     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8673   }
8674 
8675   /// Inherit a single constructor.
8676   void inherit(const CXXConstructorDecl *Ctor) {
8677     const FunctionProtoType *CtorType =
8678         Ctor->getType()->castAs<FunctionProtoType>();
8679     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
8680     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8681 
8682     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8683 
8684     // Core issue (no number yet): the ellipsis is always discarded.
8685     if (EPI.Variadic) {
8686       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8687       SemaRef.Diag(Ctor->getLocation(),
8688                    diag::note_using_decl_constructor_ellipsis);
8689       EPI.Variadic = false;
8690     }
8691 
8692     // Declare a constructor for each number of parameters.
8693     //
8694     // C++11 [class.inhctor]p1:
8695     //   The candidate set of inherited constructors from the class X named in
8696     //   the using-declaration consists of [... modulo defects ...] for each
8697     //   constructor or constructor template of X, the set of constructors or
8698     //   constructor templates that results from omitting any ellipsis parameter
8699     //   specification and successively omitting parameters with a default
8700     //   argument from the end of the parameter-type-list
8701     unsigned MinParams = minParamsToInherit(Ctor);
8702     unsigned Params = Ctor->getNumParams();
8703     if (Params >= MinParams) {
8704       do
8705         declareCtor(UsingLoc, Ctor,
8706                     SemaRef.Context.getFunctionType(
8707                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
8708       while (Params > MinParams &&
8709              Ctor->getParamDecl(--Params)->hasDefaultArg());
8710     }
8711   }
8712 
8713   /// Find the using-declaration which specified that we should inherit the
8714   /// constructors of \p Base.
8715   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8716     // No fancy lookup required; just look for the base constructor name
8717     // directly within the derived class.
8718     ASTContext &Context = SemaRef.Context;
8719     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8720         Context.getCanonicalType(Context.getRecordType(Base)));
8721     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8722     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8723   }
8724 
8725   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8726     // C++11 [class.inhctor]p3:
8727     //   [F]or each constructor template in the candidate set of inherited
8728     //   constructors, a constructor template is implicitly declared
8729     if (Ctor->getDescribedFunctionTemplate())
8730       return 0;
8731 
8732     //   For each non-template constructor in the candidate set of inherited
8733     //   constructors other than a constructor having no parameters or a
8734     //   copy/move constructor having a single parameter, a constructor is
8735     //   implicitly declared [...]
8736     if (Ctor->getNumParams() == 0)
8737       return 1;
8738     if (Ctor->isCopyOrMoveConstructor())
8739       return 2;
8740 
8741     // Per discussion on core reflector, never inherit a constructor which
8742     // would become a default, copy, or move constructor of Derived either.
8743     const ParmVarDecl *PD = Ctor->getParamDecl(0);
8744     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8745     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8746   }
8747 
8748   /// Declare a single inheriting constructor, inheriting the specified
8749   /// constructor, with the given type.
8750   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8751                    QualType DerivedType) {
8752     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8753 
8754     // C++11 [class.inhctor]p3:
8755     //   ... a constructor is implicitly declared with the same constructor
8756     //   characteristics unless there is a user-declared constructor with
8757     //   the same signature in the class where the using-declaration appears
8758     if (Entry.DeclaredInDerived)
8759       return;
8760 
8761     // C++11 [class.inhctor]p7:
8762     //   If two using-declarations declare inheriting constructors with the
8763     //   same signature, the program is ill-formed
8764     if (Entry.DerivedCtor) {
8765       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8766         // Only diagnose this once per constructor.
8767         if (Entry.DerivedCtor->isInvalidDecl())
8768           return;
8769         Entry.DerivedCtor->setInvalidDecl();
8770 
8771         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8772         SemaRef.Diag(BaseCtor->getLocation(),
8773                      diag::note_using_decl_constructor_conflict_current_ctor);
8774         SemaRef.Diag(Entry.BaseCtor->getLocation(),
8775                      diag::note_using_decl_constructor_conflict_previous_ctor);
8776         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8777                      diag::note_using_decl_constructor_conflict_previous_using);
8778       } else {
8779         // Core issue (no number): if the same inheriting constructor is
8780         // produced by multiple base class constructors from the same base
8781         // class, the inheriting constructor is defined as deleted.
8782         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8783       }
8784 
8785       return;
8786     }
8787 
8788     ASTContext &Context = SemaRef.Context;
8789     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8790         Context.getCanonicalType(Context.getRecordType(Derived)));
8791     DeclarationNameInfo NameInfo(Name, UsingLoc);
8792 
8793     TemplateParameterList *TemplateParams = nullptr;
8794     if (const FunctionTemplateDecl *FTD =
8795             BaseCtor->getDescribedFunctionTemplate()) {
8796       TemplateParams = FTD->getTemplateParameters();
8797       // We're reusing template parameters from a different DeclContext. This
8798       // is questionable at best, but works out because the template depth in
8799       // both places is guaranteed to be 0.
8800       // FIXME: Rebuild the template parameters in the new context, and
8801       // transform the function type to refer to them.
8802     }
8803 
8804     // Build type source info pointing at the using-declaration. This is
8805     // required by template instantiation.
8806     TypeSourceInfo *TInfo =
8807         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8808     FunctionProtoTypeLoc ProtoLoc =
8809         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8810 
8811     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8812         Context, Derived, UsingLoc, NameInfo, DerivedType,
8813         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8814         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8815 
8816     // Build an unevaluated exception specification for this constructor.
8817     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8818     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8819     EPI.ExceptionSpec.Type = EST_Unevaluated;
8820     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
8821     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
8822                                                  FPT->getParamTypes(), EPI));
8823 
8824     // Build the parameter declarations.
8825     SmallVector<ParmVarDecl *, 16> ParamDecls;
8826     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
8827       TypeSourceInfo *TInfo =
8828           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
8829       ParmVarDecl *PD = ParmVarDecl::Create(
8830           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8831           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
8832       PD->setScopeInfo(0, I);
8833       PD->setImplicit();
8834       ParamDecls.push_back(PD);
8835       ProtoLoc.setParam(I, PD);
8836     }
8837 
8838     // Set up the new constructor.
8839     DerivedCtor->setAccess(BaseCtor->getAccess());
8840     DerivedCtor->setParams(ParamDecls);
8841     DerivedCtor->setInheritedConstructor(BaseCtor);
8842     if (BaseCtor->isDeleted())
8843       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8844 
8845     // If this is a constructor template, build the template declaration.
8846     if (TemplateParams) {
8847       FunctionTemplateDecl *DerivedTemplate =
8848           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8849                                        TemplateParams, DerivedCtor);
8850       DerivedTemplate->setAccess(BaseCtor->getAccess());
8851       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8852       Derived->addDecl(DerivedTemplate);
8853     } else {
8854       Derived->addDecl(DerivedCtor);
8855     }
8856 
8857     Entry.BaseCtor = BaseCtor;
8858     Entry.DerivedCtor = DerivedCtor;
8859   }
8860 
8861   Sema &SemaRef;
8862   CXXRecordDecl *Derived;
8863   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8864   MapType Map;
8865 };
8866 }
8867 
8868 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8869   // Defer declaring the inheriting constructors until the class is
8870   // instantiated.
8871   if (ClassDecl->isDependentContext())
8872     return;
8873 
8874   // Find base classes from which we might inherit constructors.
8875   SmallVector<CXXRecordDecl*, 4> InheritedBases;
8876   for (const auto &BaseIt : ClassDecl->bases())
8877     if (BaseIt.getInheritConstructors())
8878       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
8879 
8880   // Go no further if we're not inheriting any constructors.
8881   if (InheritedBases.empty())
8882     return;
8883 
8884   // Declare the inherited constructors.
8885   InheritingConstructorInfo ICI(*this, ClassDecl);
8886   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8887     ICI.inheritAll(InheritedBases[I]);
8888 }
8889 
8890 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8891                                        CXXConstructorDecl *Constructor) {
8892   CXXRecordDecl *ClassDecl = Constructor->getParent();
8893   assert(Constructor->getInheritedConstructor() &&
8894          !Constructor->doesThisDeclarationHaveABody() &&
8895          !Constructor->isDeleted());
8896 
8897   SynthesizedFunctionScope Scope(*this, Constructor);
8898   DiagnosticErrorTrap Trap(Diags);
8899   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8900       Trap.hasErrorOccurred()) {
8901     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8902       << Context.getTagDeclType(ClassDecl);
8903     Constructor->setInvalidDecl();
8904     return;
8905   }
8906 
8907   SourceLocation Loc = Constructor->getLocation();
8908   Constructor->setBody(new (Context) CompoundStmt(Loc));
8909 
8910   Constructor->markUsed(Context);
8911   MarkVTableUsed(CurrentLocation, ClassDecl);
8912 
8913   if (ASTMutationListener *L = getASTMutationListener()) {
8914     L->CompletedImplicitDefinition(Constructor);
8915   }
8916 }
8917 
8918 
8919 Sema::ImplicitExceptionSpecification
8920 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8921   CXXRecordDecl *ClassDecl = MD->getParent();
8922 
8923   // C++ [except.spec]p14:
8924   //   An implicitly declared special member function (Clause 12) shall have
8925   //   an exception-specification.
8926   ImplicitExceptionSpecification ExceptSpec(*this);
8927   if (ClassDecl->isInvalidDecl())
8928     return ExceptSpec;
8929 
8930   // Direct base-class destructors.
8931   for (const auto &B : ClassDecl->bases()) {
8932     if (B.isVirtual()) // Handled below.
8933       continue;
8934 
8935     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8936       ExceptSpec.CalledDecl(B.getLocStart(),
8937                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8938   }
8939 
8940   // Virtual base-class destructors.
8941   for (const auto &B : ClassDecl->vbases()) {
8942     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8943       ExceptSpec.CalledDecl(B.getLocStart(),
8944                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8945   }
8946 
8947   // Field destructors.
8948   for (const auto *F : ClassDecl->fields()) {
8949     if (const RecordType *RecordTy
8950         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8951       ExceptSpec.CalledDecl(F->getLocation(),
8952                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8953   }
8954 
8955   return ExceptSpec;
8956 }
8957 
8958 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8959   // C++ [class.dtor]p2:
8960   //   If a class has no user-declared destructor, a destructor is
8961   //   declared implicitly. An implicitly-declared destructor is an
8962   //   inline public member of its class.
8963   assert(ClassDecl->needsImplicitDestructor());
8964 
8965   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8966   if (DSM.isAlreadyBeingDeclared())
8967     return nullptr;
8968 
8969   // Create the actual destructor declaration.
8970   CanQualType ClassType
8971     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8972   SourceLocation ClassLoc = ClassDecl->getLocation();
8973   DeclarationName Name
8974     = Context.DeclarationNames.getCXXDestructorName(ClassType);
8975   DeclarationNameInfo NameInfo(Name, ClassLoc);
8976   CXXDestructorDecl *Destructor
8977       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8978                                   QualType(), nullptr, /*isInline=*/true,
8979                                   /*isImplicitlyDeclared=*/true);
8980   Destructor->setAccess(AS_public);
8981   Destructor->setDefaulted();
8982   Destructor->setImplicit();
8983 
8984   // Build an exception specification pointing back at this destructor.
8985   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
8986   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8987 
8988   AddOverriddenMethods(ClassDecl, Destructor);
8989 
8990   // We don't need to use SpecialMemberIsTrivial here; triviality for
8991   // destructors is easy to compute.
8992   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8993 
8994   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8995     SetDeclDeleted(Destructor, ClassLoc);
8996 
8997   // Note that we have declared this destructor.
8998   ++ASTContext::NumImplicitDestructorsDeclared;
8999 
9000   // Introduce this destructor into its scope.
9001   if (Scope *S = getScopeForContext(ClassDecl))
9002     PushOnScopeChains(Destructor, S, false);
9003   ClassDecl->addDecl(Destructor);
9004 
9005   return Destructor;
9006 }
9007 
9008 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9009                                     CXXDestructorDecl *Destructor) {
9010   assert((Destructor->isDefaulted() &&
9011           !Destructor->doesThisDeclarationHaveABody() &&
9012           !Destructor->isDeleted()) &&
9013          "DefineImplicitDestructor - call it for implicit default dtor");
9014   CXXRecordDecl *ClassDecl = Destructor->getParent();
9015   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9016 
9017   if (Destructor->isInvalidDecl())
9018     return;
9019 
9020   SynthesizedFunctionScope Scope(*this, Destructor);
9021 
9022   DiagnosticErrorTrap Trap(Diags);
9023   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9024                                          Destructor->getParent());
9025 
9026   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9027     Diag(CurrentLocation, diag::note_member_synthesized_at)
9028       << CXXDestructor << Context.getTagDeclType(ClassDecl);
9029 
9030     Destructor->setInvalidDecl();
9031     return;
9032   }
9033 
9034   SourceLocation Loc = Destructor->getLocEnd().isValid()
9035                            ? Destructor->getLocEnd()
9036                            : Destructor->getLocation();
9037   Destructor->setBody(new (Context) CompoundStmt(Loc));
9038   Destructor->markUsed(Context);
9039   MarkVTableUsed(CurrentLocation, ClassDecl);
9040 
9041   if (ASTMutationListener *L = getASTMutationListener()) {
9042     L->CompletedImplicitDefinition(Destructor);
9043   }
9044 }
9045 
9046 /// \brief Perform any semantic analysis which needs to be delayed until all
9047 /// pending class member declarations have been parsed.
9048 void Sema::ActOnFinishCXXMemberDecls() {
9049   // If the context is an invalid C++ class, just suppress these checks.
9050   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9051     if (Record->isInvalidDecl()) {
9052       DelayedDefaultedMemberExceptionSpecs.clear();
9053       DelayedDestructorExceptionSpecChecks.clear();
9054       return;
9055     }
9056   }
9057 }
9058 
9059 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9060                                          CXXDestructorDecl *Destructor) {
9061   assert(getLangOpts().CPlusPlus11 &&
9062          "adjusting dtor exception specs was introduced in c++11");
9063 
9064   // C++11 [class.dtor]p3:
9065   //   A declaration of a destructor that does not have an exception-
9066   //   specification is implicitly considered to have the same exception-
9067   //   specification as an implicit declaration.
9068   const FunctionProtoType *DtorType = Destructor->getType()->
9069                                         getAs<FunctionProtoType>();
9070   if (DtorType->hasExceptionSpec())
9071     return;
9072 
9073   // Replace the destructor's type, building off the existing one. Fortunately,
9074   // the only thing of interest in the destructor type is its extended info.
9075   // The return and arguments are fixed.
9076   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9077   EPI.ExceptionSpec.Type = EST_Unevaluated;
9078   EPI.ExceptionSpec.SourceDecl = Destructor;
9079   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9080 
9081   // FIXME: If the destructor has a body that could throw, and the newly created
9082   // spec doesn't allow exceptions, we should emit a warning, because this
9083   // change in behavior can break conforming C++03 programs at runtime.
9084   // However, we don't have a body or an exception specification yet, so it
9085   // needs to be done somewhere else.
9086 }
9087 
9088 namespace {
9089 /// \brief An abstract base class for all helper classes used in building the
9090 //  copy/move operators. These classes serve as factory functions and help us
9091 //  avoid using the same Expr* in the AST twice.
9092 class ExprBuilder {
9093   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9094   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9095 
9096 protected:
9097   static Expr *assertNotNull(Expr *E) {
9098     assert(E && "Expression construction must not fail.");
9099     return E;
9100   }
9101 
9102 public:
9103   ExprBuilder() {}
9104   virtual ~ExprBuilder() {}
9105 
9106   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9107 };
9108 
9109 class RefBuilder: public ExprBuilder {
9110   VarDecl *Var;
9111   QualType VarType;
9112 
9113 public:
9114   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9115     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9116   }
9117 
9118   RefBuilder(VarDecl *Var, QualType VarType)
9119       : Var(Var), VarType(VarType) {}
9120 };
9121 
9122 class ThisBuilder: public ExprBuilder {
9123 public:
9124   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9125     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9126   }
9127 };
9128 
9129 class CastBuilder: public ExprBuilder {
9130   const ExprBuilder &Builder;
9131   QualType Type;
9132   ExprValueKind Kind;
9133   const CXXCastPath &Path;
9134 
9135 public:
9136   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9137     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9138                                              CK_UncheckedDerivedToBase, Kind,
9139                                              &Path).get());
9140   }
9141 
9142   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9143               const CXXCastPath &Path)
9144       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9145 };
9146 
9147 class DerefBuilder: public ExprBuilder {
9148   const ExprBuilder &Builder;
9149 
9150 public:
9151   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9152     return assertNotNull(
9153         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9154   }
9155 
9156   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9157 };
9158 
9159 class MemberBuilder: public ExprBuilder {
9160   const ExprBuilder &Builder;
9161   QualType Type;
9162   CXXScopeSpec SS;
9163   bool IsArrow;
9164   LookupResult &MemberLookup;
9165 
9166 public:
9167   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9168     return assertNotNull(S.BuildMemberReferenceExpr(
9169         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9170         nullptr, MemberLookup, nullptr).get());
9171   }
9172 
9173   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9174                 LookupResult &MemberLookup)
9175       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9176         MemberLookup(MemberLookup) {}
9177 };
9178 
9179 class MoveCastBuilder: public ExprBuilder {
9180   const ExprBuilder &Builder;
9181 
9182 public:
9183   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9184     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9185   }
9186 
9187   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9188 };
9189 
9190 class LvalueConvBuilder: public ExprBuilder {
9191   const ExprBuilder &Builder;
9192 
9193 public:
9194   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9195     return assertNotNull(
9196         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9197   }
9198 
9199   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9200 };
9201 
9202 class SubscriptBuilder: public ExprBuilder {
9203   const ExprBuilder &Base;
9204   const ExprBuilder &Index;
9205 
9206 public:
9207   virtual Expr *build(Sema &S, SourceLocation Loc) const override {
9208     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9209         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9210   }
9211 
9212   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9213       : Base(Base), Index(Index) {}
9214 };
9215 
9216 } // end anonymous namespace
9217 
9218 /// When generating a defaulted copy or move assignment operator, if a field
9219 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9220 /// do so. This optimization only applies for arrays of scalars, and for arrays
9221 /// of class type where the selected copy/move-assignment operator is trivial.
9222 static StmtResult
9223 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9224                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9225   // Compute the size of the memory buffer to be copied.
9226   QualType SizeType = S.Context.getSizeType();
9227   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9228                    S.Context.getTypeSizeInChars(T).getQuantity());
9229 
9230   // Take the address of the field references for "from" and "to". We
9231   // directly construct UnaryOperators here because semantic analysis
9232   // does not permit us to take the address of an xvalue.
9233   Expr *From = FromB.build(S, Loc);
9234   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9235                          S.Context.getPointerType(From->getType()),
9236                          VK_RValue, OK_Ordinary, Loc);
9237   Expr *To = ToB.build(S, Loc);
9238   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9239                        S.Context.getPointerType(To->getType()),
9240                        VK_RValue, OK_Ordinary, Loc);
9241 
9242   const Type *E = T->getBaseElementTypeUnsafe();
9243   bool NeedsCollectableMemCpy =
9244     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9245 
9246   // Create a reference to the __builtin_objc_memmove_collectable function
9247   StringRef MemCpyName = NeedsCollectableMemCpy ?
9248     "__builtin_objc_memmove_collectable" :
9249     "__builtin_memcpy";
9250   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9251                  Sema::LookupOrdinaryName);
9252   S.LookupName(R, S.TUScope, true);
9253 
9254   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9255   if (!MemCpy)
9256     // Something went horribly wrong earlier, and we will have complained
9257     // about it.
9258     return StmtError();
9259 
9260   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9261                                             VK_RValue, Loc, nullptr);
9262   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9263 
9264   Expr *CallArgs[] = {
9265     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9266   };
9267   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9268                                     Loc, CallArgs, Loc);
9269 
9270   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9271   return Call.getAs<Stmt>();
9272 }
9273 
9274 /// \brief Builds a statement that copies/moves the given entity from \p From to
9275 /// \c To.
9276 ///
9277 /// This routine is used to copy/move the members of a class with an
9278 /// implicitly-declared copy/move assignment operator. When the entities being
9279 /// copied are arrays, this routine builds for loops to copy them.
9280 ///
9281 /// \param S The Sema object used for type-checking.
9282 ///
9283 /// \param Loc The location where the implicit copy/move is being generated.
9284 ///
9285 /// \param T The type of the expressions being copied/moved. Both expressions
9286 /// must have this type.
9287 ///
9288 /// \param To The expression we are copying/moving to.
9289 ///
9290 /// \param From The expression we are copying/moving from.
9291 ///
9292 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9293 /// Otherwise, it's a non-static member subobject.
9294 ///
9295 /// \param Copying Whether we're copying or moving.
9296 ///
9297 /// \param Depth Internal parameter recording the depth of the recursion.
9298 ///
9299 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9300 /// if a memcpy should be used instead.
9301 static StmtResult
9302 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9303                                  const ExprBuilder &To, const ExprBuilder &From,
9304                                  bool CopyingBaseSubobject, bool Copying,
9305                                  unsigned Depth = 0) {
9306   // C++11 [class.copy]p28:
9307   //   Each subobject is assigned in the manner appropriate to its type:
9308   //
9309   //     - if the subobject is of class type, as if by a call to operator= with
9310   //       the subobject as the object expression and the corresponding
9311   //       subobject of x as a single function argument (as if by explicit
9312   //       qualification; that is, ignoring any possible virtual overriding
9313   //       functions in more derived classes);
9314   //
9315   // C++03 [class.copy]p13:
9316   //     - if the subobject is of class type, the copy assignment operator for
9317   //       the class is used (as if by explicit qualification; that is,
9318   //       ignoring any possible virtual overriding functions in more derived
9319   //       classes);
9320   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9321     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9322 
9323     // Look for operator=.
9324     DeclarationName Name
9325       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9326     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9327     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9328 
9329     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9330     // operator.
9331     if (!S.getLangOpts().CPlusPlus11) {
9332       LookupResult::Filter F = OpLookup.makeFilter();
9333       while (F.hasNext()) {
9334         NamedDecl *D = F.next();
9335         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9336           if (Method->isCopyAssignmentOperator() ||
9337               (!Copying && Method->isMoveAssignmentOperator()))
9338             continue;
9339 
9340         F.erase();
9341       }
9342       F.done();
9343     }
9344 
9345     // Suppress the protected check (C++ [class.protected]) for each of the
9346     // assignment operators we found. This strange dance is required when
9347     // we're assigning via a base classes's copy-assignment operator. To
9348     // ensure that we're getting the right base class subobject (without
9349     // ambiguities), we need to cast "this" to that subobject type; to
9350     // ensure that we don't go through the virtual call mechanism, we need
9351     // to qualify the operator= name with the base class (see below). However,
9352     // this means that if the base class has a protected copy assignment
9353     // operator, the protected member access check will fail. So, we
9354     // rewrite "protected" access to "public" access in this case, since we
9355     // know by construction that we're calling from a derived class.
9356     if (CopyingBaseSubobject) {
9357       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9358            L != LEnd; ++L) {
9359         if (L.getAccess() == AS_protected)
9360           L.setAccess(AS_public);
9361       }
9362     }
9363 
9364     // Create the nested-name-specifier that will be used to qualify the
9365     // reference to operator=; this is required to suppress the virtual
9366     // call mechanism.
9367     CXXScopeSpec SS;
9368     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9369     SS.MakeTrivial(S.Context,
9370                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9371                                                CanonicalT),
9372                    Loc);
9373 
9374     // Create the reference to operator=.
9375     ExprResult OpEqualRef
9376       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9377                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9378                                    /*FirstQualifierInScope=*/nullptr,
9379                                    OpLookup,
9380                                    /*TemplateArgs=*/nullptr,
9381                                    /*SuppressQualifierCheck=*/true);
9382     if (OpEqualRef.isInvalid())
9383       return StmtError();
9384 
9385     // Build the call to the assignment operator.
9386 
9387     Expr *FromInst = From.build(S, Loc);
9388     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9389                                                   OpEqualRef.getAs<Expr>(),
9390                                                   Loc, FromInst, Loc);
9391     if (Call.isInvalid())
9392       return StmtError();
9393 
9394     // If we built a call to a trivial 'operator=' while copying an array,
9395     // bail out. We'll replace the whole shebang with a memcpy.
9396     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9397     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9398       return StmtResult((Stmt*)nullptr);
9399 
9400     // Convert to an expression-statement, and clean up any produced
9401     // temporaries.
9402     return S.ActOnExprStmt(Call);
9403   }
9404 
9405   //     - if the subobject is of scalar type, the built-in assignment
9406   //       operator is used.
9407   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9408   if (!ArrayTy) {
9409     ExprResult Assignment = S.CreateBuiltinBinOp(
9410         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9411     if (Assignment.isInvalid())
9412       return StmtError();
9413     return S.ActOnExprStmt(Assignment);
9414   }
9415 
9416   //     - if the subobject is an array, each element is assigned, in the
9417   //       manner appropriate to the element type;
9418 
9419   // Construct a loop over the array bounds, e.g.,
9420   //
9421   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9422   //
9423   // that will copy each of the array elements.
9424   QualType SizeType = S.Context.getSizeType();
9425 
9426   // Create the iteration variable.
9427   IdentifierInfo *IterationVarName = nullptr;
9428   {
9429     SmallString<8> Str;
9430     llvm::raw_svector_ostream OS(Str);
9431     OS << "__i" << Depth;
9432     IterationVarName = &S.Context.Idents.get(OS.str());
9433   }
9434   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9435                                           IterationVarName, SizeType,
9436                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9437                                           SC_None);
9438 
9439   // Initialize the iteration variable to zero.
9440   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9441   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9442 
9443   // Creates a reference to the iteration variable.
9444   RefBuilder IterationVarRef(IterationVar, SizeType);
9445   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9446 
9447   // Create the DeclStmt that holds the iteration variable.
9448   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9449 
9450   // Subscript the "from" and "to" expressions with the iteration variable.
9451   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9452   MoveCastBuilder FromIndexMove(FromIndexCopy);
9453   const ExprBuilder *FromIndex;
9454   if (Copying)
9455     FromIndex = &FromIndexCopy;
9456   else
9457     FromIndex = &FromIndexMove;
9458 
9459   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9460 
9461   // Build the copy/move for an individual element of the array.
9462   StmtResult Copy =
9463     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9464                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9465                                      Copying, Depth + 1);
9466   // Bail out if copying fails or if we determined that we should use memcpy.
9467   if (Copy.isInvalid() || !Copy.get())
9468     return Copy;
9469 
9470   // Create the comparison against the array bound.
9471   llvm::APInt Upper
9472     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9473   Expr *Comparison
9474     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9475                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9476                                      BO_NE, S.Context.BoolTy,
9477                                      VK_RValue, OK_Ordinary, Loc, false);
9478 
9479   // Create the pre-increment of the iteration variable.
9480   Expr *Increment
9481     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9482                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9483 
9484   // Construct the loop that copies all elements of this array.
9485   return S.ActOnForStmt(Loc, Loc, InitStmt,
9486                         S.MakeFullExpr(Comparison),
9487                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9488                         Loc, Copy.get());
9489 }
9490 
9491 static StmtResult
9492 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9493                       const ExprBuilder &To, const ExprBuilder &From,
9494                       bool CopyingBaseSubobject, bool Copying) {
9495   // Maybe we should use a memcpy?
9496   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9497       T.isTriviallyCopyableType(S.Context))
9498     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9499 
9500   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9501                                                      CopyingBaseSubobject,
9502                                                      Copying, 0));
9503 
9504   // If we ended up picking a trivial assignment operator for an array of a
9505   // non-trivially-copyable class type, just emit a memcpy.
9506   if (!Result.isInvalid() && !Result.get())
9507     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9508 
9509   return Result;
9510 }
9511 
9512 Sema::ImplicitExceptionSpecification
9513 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9514   CXXRecordDecl *ClassDecl = MD->getParent();
9515 
9516   ImplicitExceptionSpecification ExceptSpec(*this);
9517   if (ClassDecl->isInvalidDecl())
9518     return ExceptSpec;
9519 
9520   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9521   assert(T->getNumParams() == 1 && "not a copy assignment op");
9522   unsigned ArgQuals =
9523       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9524 
9525   // C++ [except.spec]p14:
9526   //   An implicitly declared special member function (Clause 12) shall have an
9527   //   exception-specification. [...]
9528 
9529   // It is unspecified whether or not an implicit copy assignment operator
9530   // attempts to deduplicate calls to assignment operators of virtual bases are
9531   // made. As such, this exception specification is effectively unspecified.
9532   // Based on a similar decision made for constness in C++0x, we're erring on
9533   // the side of assuming such calls to be made regardless of whether they
9534   // actually happen.
9535   for (const auto &Base : ClassDecl->bases()) {
9536     if (Base.isVirtual())
9537       continue;
9538 
9539     CXXRecordDecl *BaseClassDecl
9540       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9541     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9542                                                             ArgQuals, false, 0))
9543       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9544   }
9545 
9546   for (const auto &Base : ClassDecl->vbases()) {
9547     CXXRecordDecl *BaseClassDecl
9548       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9549     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9550                                                             ArgQuals, false, 0))
9551       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
9552   }
9553 
9554   for (const auto *Field : ClassDecl->fields()) {
9555     QualType FieldType = Context.getBaseElementType(Field->getType());
9556     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9557       if (CXXMethodDecl *CopyAssign =
9558           LookupCopyingAssignment(FieldClassDecl,
9559                                   ArgQuals | FieldType.getCVRQualifiers(),
9560                                   false, 0))
9561         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9562     }
9563   }
9564 
9565   return ExceptSpec;
9566 }
9567 
9568 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9569   // Note: The following rules are largely analoguous to the copy
9570   // constructor rules. Note that virtual bases are not taken into account
9571   // for determining the argument type of the operator. Note also that
9572   // operators taking an object instead of a reference are allowed.
9573   assert(ClassDecl->needsImplicitCopyAssignment());
9574 
9575   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9576   if (DSM.isAlreadyBeingDeclared())
9577     return nullptr;
9578 
9579   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9580   QualType RetType = Context.getLValueReferenceType(ArgType);
9581   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9582   if (Const)
9583     ArgType = ArgType.withConst();
9584   ArgType = Context.getLValueReferenceType(ArgType);
9585 
9586   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9587                                                      CXXCopyAssignment,
9588                                                      Const);
9589 
9590   //   An implicitly-declared copy assignment operator is an inline public
9591   //   member of its class.
9592   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9593   SourceLocation ClassLoc = ClassDecl->getLocation();
9594   DeclarationNameInfo NameInfo(Name, ClassLoc);
9595   CXXMethodDecl *CopyAssignment =
9596       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9597                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9598                             /*isInline=*/true, Constexpr, SourceLocation());
9599   CopyAssignment->setAccess(AS_public);
9600   CopyAssignment->setDefaulted();
9601   CopyAssignment->setImplicit();
9602 
9603   // Build an exception specification pointing back at this member.
9604   FunctionProtoType::ExtProtoInfo EPI =
9605       getImplicitMethodEPI(*this, CopyAssignment);
9606   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9607 
9608   // Add the parameter to the operator.
9609   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9610                                                ClassLoc, ClassLoc,
9611                                                /*Id=*/nullptr, ArgType,
9612                                                /*TInfo=*/nullptr, SC_None,
9613                                                nullptr);
9614   CopyAssignment->setParams(FromParam);
9615 
9616   AddOverriddenMethods(ClassDecl, CopyAssignment);
9617 
9618   CopyAssignment->setTrivial(
9619     ClassDecl->needsOverloadResolutionForCopyAssignment()
9620       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9621       : ClassDecl->hasTrivialCopyAssignment());
9622 
9623   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9624     SetDeclDeleted(CopyAssignment, ClassLoc);
9625 
9626   // Note that we have added this copy-assignment operator.
9627   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9628 
9629   if (Scope *S = getScopeForContext(ClassDecl))
9630     PushOnScopeChains(CopyAssignment, S, false);
9631   ClassDecl->addDecl(CopyAssignment);
9632 
9633   return CopyAssignment;
9634 }
9635 
9636 /// Diagnose an implicit copy operation for a class which is odr-used, but
9637 /// which is deprecated because the class has a user-declared copy constructor,
9638 /// copy assignment operator, or destructor.
9639 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9640                                             SourceLocation UseLoc) {
9641   assert(CopyOp->isImplicit());
9642 
9643   CXXRecordDecl *RD = CopyOp->getParent();
9644   CXXMethodDecl *UserDeclaredOperation = nullptr;
9645 
9646   // In Microsoft mode, assignment operations don't affect constructors and
9647   // vice versa.
9648   if (RD->hasUserDeclaredDestructor()) {
9649     UserDeclaredOperation = RD->getDestructor();
9650   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9651              RD->hasUserDeclaredCopyConstructor() &&
9652              !S.getLangOpts().MSVCCompat) {
9653     // Find any user-declared copy constructor.
9654     for (auto *I : RD->ctors()) {
9655       if (I->isCopyConstructor()) {
9656         UserDeclaredOperation = I;
9657         break;
9658       }
9659     }
9660     assert(UserDeclaredOperation);
9661   } else if (isa<CXXConstructorDecl>(CopyOp) &&
9662              RD->hasUserDeclaredCopyAssignment() &&
9663              !S.getLangOpts().MSVCCompat) {
9664     // Find any user-declared move assignment operator.
9665     for (auto *I : RD->methods()) {
9666       if (I->isCopyAssignmentOperator()) {
9667         UserDeclaredOperation = I;
9668         break;
9669       }
9670     }
9671     assert(UserDeclaredOperation);
9672   }
9673 
9674   if (UserDeclaredOperation) {
9675     S.Diag(UserDeclaredOperation->getLocation(),
9676          diag::warn_deprecated_copy_operation)
9677       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9678       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9679     S.Diag(UseLoc, diag::note_member_synthesized_at)
9680       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9681                                           : Sema::CXXCopyAssignment)
9682       << RD;
9683   }
9684 }
9685 
9686 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9687                                         CXXMethodDecl *CopyAssignOperator) {
9688   assert((CopyAssignOperator->isDefaulted() &&
9689           CopyAssignOperator->isOverloadedOperator() &&
9690           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9691           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9692           !CopyAssignOperator->isDeleted()) &&
9693          "DefineImplicitCopyAssignment called for wrong function");
9694 
9695   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9696 
9697   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9698     CopyAssignOperator->setInvalidDecl();
9699     return;
9700   }
9701 
9702   // C++11 [class.copy]p18:
9703   //   The [definition of an implicitly declared copy assignment operator] is
9704   //   deprecated if the class has a user-declared copy constructor or a
9705   //   user-declared destructor.
9706   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9707     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9708 
9709   CopyAssignOperator->markUsed(Context);
9710 
9711   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9712   DiagnosticErrorTrap Trap(Diags);
9713 
9714   // C++0x [class.copy]p30:
9715   //   The implicitly-defined or explicitly-defaulted copy assignment operator
9716   //   for a non-union class X performs memberwise copy assignment of its
9717   //   subobjects. The direct base classes of X are assigned first, in the
9718   //   order of their declaration in the base-specifier-list, and then the
9719   //   immediate non-static data members of X are assigned, in the order in
9720   //   which they were declared in the class definition.
9721 
9722   // The statements that form the synthesized function body.
9723   SmallVector<Stmt*, 8> Statements;
9724 
9725   // The parameter for the "other" object, which we are copying from.
9726   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9727   Qualifiers OtherQuals = Other->getType().getQualifiers();
9728   QualType OtherRefType = Other->getType();
9729   if (const LValueReferenceType *OtherRef
9730                                 = OtherRefType->getAs<LValueReferenceType>()) {
9731     OtherRefType = OtherRef->getPointeeType();
9732     OtherQuals = OtherRefType.getQualifiers();
9733   }
9734 
9735   // Our location for everything implicitly-generated.
9736   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9737                            ? CopyAssignOperator->getLocEnd()
9738                            : CopyAssignOperator->getLocation();
9739 
9740   // Builds a DeclRefExpr for the "other" object.
9741   RefBuilder OtherRef(Other, OtherRefType);
9742 
9743   // Builds the "this" pointer.
9744   ThisBuilder This;
9745 
9746   // Assign base classes.
9747   bool Invalid = false;
9748   for (auto &Base : ClassDecl->bases()) {
9749     // Form the assignment:
9750     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9751     QualType BaseType = Base.getType().getUnqualifiedType();
9752     if (!BaseType->isRecordType()) {
9753       Invalid = true;
9754       continue;
9755     }
9756 
9757     CXXCastPath BasePath;
9758     BasePath.push_back(&Base);
9759 
9760     // Construct the "from" expression, which is an implicit cast to the
9761     // appropriately-qualified base type.
9762     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9763                      VK_LValue, BasePath);
9764 
9765     // Dereference "this".
9766     DerefBuilder DerefThis(This);
9767     CastBuilder To(DerefThis,
9768                    Context.getCVRQualifiedType(
9769                        BaseType, CopyAssignOperator->getTypeQualifiers()),
9770                    VK_LValue, BasePath);
9771 
9772     // Build the copy.
9773     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9774                                             To, From,
9775                                             /*CopyingBaseSubobject=*/true,
9776                                             /*Copying=*/true);
9777     if (Copy.isInvalid()) {
9778       Diag(CurrentLocation, diag::note_member_synthesized_at)
9779         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9780       CopyAssignOperator->setInvalidDecl();
9781       return;
9782     }
9783 
9784     // Success! Record the copy.
9785     Statements.push_back(Copy.getAs<Expr>());
9786   }
9787 
9788   // Assign non-static members.
9789   for (auto *Field : ClassDecl->fields()) {
9790     if (Field->isUnnamedBitfield())
9791       continue;
9792 
9793     if (Field->isInvalidDecl()) {
9794       Invalid = true;
9795       continue;
9796     }
9797 
9798     // Check for members of reference type; we can't copy those.
9799     if (Field->getType()->isReferenceType()) {
9800       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9801         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9802       Diag(Field->getLocation(), diag::note_declared_at);
9803       Diag(CurrentLocation, diag::note_member_synthesized_at)
9804         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9805       Invalid = true;
9806       continue;
9807     }
9808 
9809     // Check for members of const-qualified, non-class type.
9810     QualType BaseType = Context.getBaseElementType(Field->getType());
9811     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9812       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9813         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9814       Diag(Field->getLocation(), diag::note_declared_at);
9815       Diag(CurrentLocation, diag::note_member_synthesized_at)
9816         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9817       Invalid = true;
9818       continue;
9819     }
9820 
9821     // Suppress assigning zero-width bitfields.
9822     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9823       continue;
9824 
9825     QualType FieldType = Field->getType().getNonReferenceType();
9826     if (FieldType->isIncompleteArrayType()) {
9827       assert(ClassDecl->hasFlexibleArrayMember() &&
9828              "Incomplete array type is not valid");
9829       continue;
9830     }
9831 
9832     // Build references to the field in the object we're copying from and to.
9833     CXXScopeSpec SS; // Intentionally empty
9834     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9835                               LookupMemberName);
9836     MemberLookup.addDecl(Field);
9837     MemberLookup.resolveKind();
9838 
9839     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9840 
9841     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9842 
9843     // Build the copy of this field.
9844     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9845                                             To, From,
9846                                             /*CopyingBaseSubobject=*/false,
9847                                             /*Copying=*/true);
9848     if (Copy.isInvalid()) {
9849       Diag(CurrentLocation, diag::note_member_synthesized_at)
9850         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9851       CopyAssignOperator->setInvalidDecl();
9852       return;
9853     }
9854 
9855     // Success! Record the copy.
9856     Statements.push_back(Copy.getAs<Stmt>());
9857   }
9858 
9859   if (!Invalid) {
9860     // Add a "return *this;"
9861     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9862 
9863     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
9864     if (Return.isInvalid())
9865       Invalid = true;
9866     else {
9867       Statements.push_back(Return.getAs<Stmt>());
9868 
9869       if (Trap.hasErrorOccurred()) {
9870         Diag(CurrentLocation, diag::note_member_synthesized_at)
9871           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9872         Invalid = true;
9873       }
9874     }
9875   }
9876 
9877   if (Invalid) {
9878     CopyAssignOperator->setInvalidDecl();
9879     return;
9880   }
9881 
9882   StmtResult Body;
9883   {
9884     CompoundScopeRAII CompoundScope(*this);
9885     Body = ActOnCompoundStmt(Loc, Loc, Statements,
9886                              /*isStmtExpr=*/false);
9887     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9888   }
9889   CopyAssignOperator->setBody(Body.getAs<Stmt>());
9890 
9891   if (ASTMutationListener *L = getASTMutationListener()) {
9892     L->CompletedImplicitDefinition(CopyAssignOperator);
9893   }
9894 }
9895 
9896 Sema::ImplicitExceptionSpecification
9897 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9898   CXXRecordDecl *ClassDecl = MD->getParent();
9899 
9900   ImplicitExceptionSpecification ExceptSpec(*this);
9901   if (ClassDecl->isInvalidDecl())
9902     return ExceptSpec;
9903 
9904   // C++0x [except.spec]p14:
9905   //   An implicitly declared special member function (Clause 12) shall have an
9906   //   exception-specification. [...]
9907 
9908   // It is unspecified whether or not an implicit move assignment operator
9909   // attempts to deduplicate calls to assignment operators of virtual bases are
9910   // made. As such, this exception specification is effectively unspecified.
9911   // Based on a similar decision made for constness in C++0x, we're erring on
9912   // the side of assuming such calls to be made regardless of whether they
9913   // actually happen.
9914   // Note that a move constructor is not implicitly declared when there are
9915   // virtual bases, but it can still be user-declared and explicitly defaulted.
9916   for (const auto &Base : ClassDecl->bases()) {
9917     if (Base.isVirtual())
9918       continue;
9919 
9920     CXXRecordDecl *BaseClassDecl
9921       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9922     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9923                                                            0, false, 0))
9924       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9925   }
9926 
9927   for (const auto &Base : ClassDecl->vbases()) {
9928     CXXRecordDecl *BaseClassDecl
9929       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
9930     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9931                                                            0, false, 0))
9932       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
9933   }
9934 
9935   for (const auto *Field : ClassDecl->fields()) {
9936     QualType FieldType = Context.getBaseElementType(Field->getType());
9937     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9938       if (CXXMethodDecl *MoveAssign =
9939               LookupMovingAssignment(FieldClassDecl,
9940                                      FieldType.getCVRQualifiers(),
9941                                      false, 0))
9942         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9943     }
9944   }
9945 
9946   return ExceptSpec;
9947 }
9948 
9949 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9950   assert(ClassDecl->needsImplicitMoveAssignment());
9951 
9952   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9953   if (DSM.isAlreadyBeingDeclared())
9954     return nullptr;
9955 
9956   // Note: The following rules are largely analoguous to the move
9957   // constructor rules.
9958 
9959   QualType ArgType = Context.getTypeDeclType(ClassDecl);
9960   QualType RetType = Context.getLValueReferenceType(ArgType);
9961   ArgType = Context.getRValueReferenceType(ArgType);
9962 
9963   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9964                                                      CXXMoveAssignment,
9965                                                      false);
9966 
9967   //   An implicitly-declared move assignment operator is an inline public
9968   //   member of its class.
9969   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9970   SourceLocation ClassLoc = ClassDecl->getLocation();
9971   DeclarationNameInfo NameInfo(Name, ClassLoc);
9972   CXXMethodDecl *MoveAssignment =
9973       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9974                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9975                             /*isInline=*/true, Constexpr, SourceLocation());
9976   MoveAssignment->setAccess(AS_public);
9977   MoveAssignment->setDefaulted();
9978   MoveAssignment->setImplicit();
9979 
9980   // Build an exception specification pointing back at this member.
9981   FunctionProtoType::ExtProtoInfo EPI =
9982       getImplicitMethodEPI(*this, MoveAssignment);
9983   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9984 
9985   // Add the parameter to the operator.
9986   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9987                                                ClassLoc, ClassLoc,
9988                                                /*Id=*/nullptr, ArgType,
9989                                                /*TInfo=*/nullptr, SC_None,
9990                                                nullptr);
9991   MoveAssignment->setParams(FromParam);
9992 
9993   AddOverriddenMethods(ClassDecl, MoveAssignment);
9994 
9995   MoveAssignment->setTrivial(
9996     ClassDecl->needsOverloadResolutionForMoveAssignment()
9997       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9998       : ClassDecl->hasTrivialMoveAssignment());
9999 
10000   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10001     ClassDecl->setImplicitMoveAssignmentIsDeleted();
10002     SetDeclDeleted(MoveAssignment, ClassLoc);
10003   }
10004 
10005   // Note that we have added this copy-assignment operator.
10006   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10007 
10008   if (Scope *S = getScopeForContext(ClassDecl))
10009     PushOnScopeChains(MoveAssignment, S, false);
10010   ClassDecl->addDecl(MoveAssignment);
10011 
10012   return MoveAssignment;
10013 }
10014 
10015 /// Check if we're implicitly defining a move assignment operator for a class
10016 /// with virtual bases. Such a move assignment might move-assign the virtual
10017 /// base multiple times.
10018 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10019                                                SourceLocation CurrentLocation) {
10020   assert(!Class->isDependentContext() && "should not define dependent move");
10021 
10022   // Only a virtual base could get implicitly move-assigned multiple times.
10023   // Only a non-trivial move assignment can observe this. We only want to
10024   // diagnose if we implicitly define an assignment operator that assigns
10025   // two base classes, both of which move-assign the same virtual base.
10026   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10027       Class->getNumBases() < 2)
10028     return;
10029 
10030   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10031   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10032   VBaseMap VBases;
10033 
10034   for (auto &BI : Class->bases()) {
10035     Worklist.push_back(&BI);
10036     while (!Worklist.empty()) {
10037       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10038       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10039 
10040       // If the base has no non-trivial move assignment operators,
10041       // we don't care about moves from it.
10042       if (!Base->hasNonTrivialMoveAssignment())
10043         continue;
10044 
10045       // If there's nothing virtual here, skip it.
10046       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10047         continue;
10048 
10049       // If we're not actually going to call a move assignment for this base,
10050       // or the selected move assignment is trivial, skip it.
10051       Sema::SpecialMemberOverloadResult *SMOR =
10052         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10053                               /*ConstArg*/false, /*VolatileArg*/false,
10054                               /*RValueThis*/true, /*ConstThis*/false,
10055                               /*VolatileThis*/false);
10056       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10057           !SMOR->getMethod()->isMoveAssignmentOperator())
10058         continue;
10059 
10060       if (BaseSpec->isVirtual()) {
10061         // We're going to move-assign this virtual base, and its move
10062         // assignment operator is not trivial. If this can happen for
10063         // multiple distinct direct bases of Class, diagnose it. (If it
10064         // only happens in one base, we'll diagnose it when synthesizing
10065         // that base class's move assignment operator.)
10066         CXXBaseSpecifier *&Existing =
10067             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10068                 .first->second;
10069         if (Existing && Existing != &BI) {
10070           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10071             << Class << Base;
10072           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10073             << (Base->getCanonicalDecl() ==
10074                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10075             << Base << Existing->getType() << Existing->getSourceRange();
10076           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10077             << (Base->getCanonicalDecl() ==
10078                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10079             << Base << BI.getType() << BaseSpec->getSourceRange();
10080 
10081           // Only diagnose each vbase once.
10082           Existing = nullptr;
10083         }
10084       } else {
10085         // Only walk over bases that have defaulted move assignment operators.
10086         // We assume that any user-provided move assignment operator handles
10087         // the multiple-moves-of-vbase case itself somehow.
10088         if (!SMOR->getMethod()->isDefaulted())
10089           continue;
10090 
10091         // We're going to move the base classes of Base. Add them to the list.
10092         for (auto &BI : Base->bases())
10093           Worklist.push_back(&BI);
10094       }
10095     }
10096   }
10097 }
10098 
10099 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10100                                         CXXMethodDecl *MoveAssignOperator) {
10101   assert((MoveAssignOperator->isDefaulted() &&
10102           MoveAssignOperator->isOverloadedOperator() &&
10103           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10104           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10105           !MoveAssignOperator->isDeleted()) &&
10106          "DefineImplicitMoveAssignment called for wrong function");
10107 
10108   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10109 
10110   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10111     MoveAssignOperator->setInvalidDecl();
10112     return;
10113   }
10114 
10115   MoveAssignOperator->markUsed(Context);
10116 
10117   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10118   DiagnosticErrorTrap Trap(Diags);
10119 
10120   // C++0x [class.copy]p28:
10121   //   The implicitly-defined or move assignment operator for a non-union class
10122   //   X performs memberwise move assignment of its subobjects. The direct base
10123   //   classes of X are assigned first, in the order of their declaration in the
10124   //   base-specifier-list, and then the immediate non-static data members of X
10125   //   are assigned, in the order in which they were declared in the class
10126   //   definition.
10127 
10128   // Issue a warning if our implicit move assignment operator will move
10129   // from a virtual base more than once.
10130   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10131 
10132   // The statements that form the synthesized function body.
10133   SmallVector<Stmt*, 8> Statements;
10134 
10135   // The parameter for the "other" object, which we are move from.
10136   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10137   QualType OtherRefType = Other->getType()->
10138       getAs<RValueReferenceType>()->getPointeeType();
10139   assert(!OtherRefType.getQualifiers() &&
10140          "Bad argument type of defaulted move assignment");
10141 
10142   // Our location for everything implicitly-generated.
10143   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10144                            ? MoveAssignOperator->getLocEnd()
10145                            : MoveAssignOperator->getLocation();
10146 
10147   // Builds a reference to the "other" object.
10148   RefBuilder OtherRef(Other, OtherRefType);
10149   // Cast to rvalue.
10150   MoveCastBuilder MoveOther(OtherRef);
10151 
10152   // Builds the "this" pointer.
10153   ThisBuilder This;
10154 
10155   // Assign base classes.
10156   bool Invalid = false;
10157   for (auto &Base : ClassDecl->bases()) {
10158     // C++11 [class.copy]p28:
10159     //   It is unspecified whether subobjects representing virtual base classes
10160     //   are assigned more than once by the implicitly-defined copy assignment
10161     //   operator.
10162     // FIXME: Do not assign to a vbase that will be assigned by some other base
10163     // class. For a move-assignment, this can result in the vbase being moved
10164     // multiple times.
10165 
10166     // Form the assignment:
10167     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10168     QualType BaseType = Base.getType().getUnqualifiedType();
10169     if (!BaseType->isRecordType()) {
10170       Invalid = true;
10171       continue;
10172     }
10173 
10174     CXXCastPath BasePath;
10175     BasePath.push_back(&Base);
10176 
10177     // Construct the "from" expression, which is an implicit cast to the
10178     // appropriately-qualified base type.
10179     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10180 
10181     // Dereference "this".
10182     DerefBuilder DerefThis(This);
10183 
10184     // Implicitly cast "this" to the appropriately-qualified base type.
10185     CastBuilder To(DerefThis,
10186                    Context.getCVRQualifiedType(
10187                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10188                    VK_LValue, BasePath);
10189 
10190     // Build the move.
10191     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10192                                             To, From,
10193                                             /*CopyingBaseSubobject=*/true,
10194                                             /*Copying=*/false);
10195     if (Move.isInvalid()) {
10196       Diag(CurrentLocation, diag::note_member_synthesized_at)
10197         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10198       MoveAssignOperator->setInvalidDecl();
10199       return;
10200     }
10201 
10202     // Success! Record the move.
10203     Statements.push_back(Move.getAs<Expr>());
10204   }
10205 
10206   // Assign non-static members.
10207   for (auto *Field : ClassDecl->fields()) {
10208     if (Field->isUnnamedBitfield())
10209       continue;
10210 
10211     if (Field->isInvalidDecl()) {
10212       Invalid = true;
10213       continue;
10214     }
10215 
10216     // Check for members of reference type; we can't move those.
10217     if (Field->getType()->isReferenceType()) {
10218       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10219         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10220       Diag(Field->getLocation(), diag::note_declared_at);
10221       Diag(CurrentLocation, diag::note_member_synthesized_at)
10222         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10223       Invalid = true;
10224       continue;
10225     }
10226 
10227     // Check for members of const-qualified, non-class type.
10228     QualType BaseType = Context.getBaseElementType(Field->getType());
10229     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10230       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10231         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10232       Diag(Field->getLocation(), diag::note_declared_at);
10233       Diag(CurrentLocation, diag::note_member_synthesized_at)
10234         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10235       Invalid = true;
10236       continue;
10237     }
10238 
10239     // Suppress assigning zero-width bitfields.
10240     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10241       continue;
10242 
10243     QualType FieldType = Field->getType().getNonReferenceType();
10244     if (FieldType->isIncompleteArrayType()) {
10245       assert(ClassDecl->hasFlexibleArrayMember() &&
10246              "Incomplete array type is not valid");
10247       continue;
10248     }
10249 
10250     // Build references to the field in the object we're copying from and to.
10251     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10252                               LookupMemberName);
10253     MemberLookup.addDecl(Field);
10254     MemberLookup.resolveKind();
10255     MemberBuilder From(MoveOther, OtherRefType,
10256                        /*IsArrow=*/false, MemberLookup);
10257     MemberBuilder To(This, getCurrentThisType(),
10258                      /*IsArrow=*/true, MemberLookup);
10259 
10260     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10261         "Member reference with rvalue base must be rvalue except for reference "
10262         "members, which aren't allowed for move assignment.");
10263 
10264     // Build the move of this field.
10265     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10266                                             To, From,
10267                                             /*CopyingBaseSubobject=*/false,
10268                                             /*Copying=*/false);
10269     if (Move.isInvalid()) {
10270       Diag(CurrentLocation, diag::note_member_synthesized_at)
10271         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10272       MoveAssignOperator->setInvalidDecl();
10273       return;
10274     }
10275 
10276     // Success! Record the copy.
10277     Statements.push_back(Move.getAs<Stmt>());
10278   }
10279 
10280   if (!Invalid) {
10281     // Add a "return *this;"
10282     ExprResult ThisObj =
10283         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10284 
10285     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10286     if (Return.isInvalid())
10287       Invalid = true;
10288     else {
10289       Statements.push_back(Return.getAs<Stmt>());
10290 
10291       if (Trap.hasErrorOccurred()) {
10292         Diag(CurrentLocation, diag::note_member_synthesized_at)
10293           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10294         Invalid = true;
10295       }
10296     }
10297   }
10298 
10299   if (Invalid) {
10300     MoveAssignOperator->setInvalidDecl();
10301     return;
10302   }
10303 
10304   StmtResult Body;
10305   {
10306     CompoundScopeRAII CompoundScope(*this);
10307     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10308                              /*isStmtExpr=*/false);
10309     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10310   }
10311   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10312 
10313   if (ASTMutationListener *L = getASTMutationListener()) {
10314     L->CompletedImplicitDefinition(MoveAssignOperator);
10315   }
10316 }
10317 
10318 Sema::ImplicitExceptionSpecification
10319 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10320   CXXRecordDecl *ClassDecl = MD->getParent();
10321 
10322   ImplicitExceptionSpecification ExceptSpec(*this);
10323   if (ClassDecl->isInvalidDecl())
10324     return ExceptSpec;
10325 
10326   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10327   assert(T->getNumParams() >= 1 && "not a copy ctor");
10328   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10329 
10330   // C++ [except.spec]p14:
10331   //   An implicitly declared special member function (Clause 12) shall have an
10332   //   exception-specification. [...]
10333   for (const auto &Base : ClassDecl->bases()) {
10334     // Virtual bases are handled below.
10335     if (Base.isVirtual())
10336       continue;
10337 
10338     CXXRecordDecl *BaseClassDecl
10339       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10340     if (CXXConstructorDecl *CopyConstructor =
10341           LookupCopyingConstructor(BaseClassDecl, Quals))
10342       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10343   }
10344   for (const auto &Base : ClassDecl->vbases()) {
10345     CXXRecordDecl *BaseClassDecl
10346       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10347     if (CXXConstructorDecl *CopyConstructor =
10348           LookupCopyingConstructor(BaseClassDecl, Quals))
10349       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10350   }
10351   for (const auto *Field : ClassDecl->fields()) {
10352     QualType FieldType = Context.getBaseElementType(Field->getType());
10353     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10354       if (CXXConstructorDecl *CopyConstructor =
10355               LookupCopyingConstructor(FieldClassDecl,
10356                                        Quals | FieldType.getCVRQualifiers()))
10357       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10358     }
10359   }
10360 
10361   return ExceptSpec;
10362 }
10363 
10364 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10365                                                     CXXRecordDecl *ClassDecl) {
10366   // C++ [class.copy]p4:
10367   //   If the class definition does not explicitly declare a copy
10368   //   constructor, one is declared implicitly.
10369   assert(ClassDecl->needsImplicitCopyConstructor());
10370 
10371   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10372   if (DSM.isAlreadyBeingDeclared())
10373     return nullptr;
10374 
10375   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10376   QualType ArgType = ClassType;
10377   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10378   if (Const)
10379     ArgType = ArgType.withConst();
10380   ArgType = Context.getLValueReferenceType(ArgType);
10381 
10382   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10383                                                      CXXCopyConstructor,
10384                                                      Const);
10385 
10386   DeclarationName Name
10387     = Context.DeclarationNames.getCXXConstructorName(
10388                                            Context.getCanonicalType(ClassType));
10389   SourceLocation ClassLoc = ClassDecl->getLocation();
10390   DeclarationNameInfo NameInfo(Name, ClassLoc);
10391 
10392   //   An implicitly-declared copy constructor is an inline public
10393   //   member of its class.
10394   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10395       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10396       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10397       Constexpr);
10398   CopyConstructor->setAccess(AS_public);
10399   CopyConstructor->setDefaulted();
10400 
10401   // Build an exception specification pointing back at this member.
10402   FunctionProtoType::ExtProtoInfo EPI =
10403       getImplicitMethodEPI(*this, CopyConstructor);
10404   CopyConstructor->setType(
10405       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10406 
10407   // Add the parameter to the constructor.
10408   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10409                                                ClassLoc, ClassLoc,
10410                                                /*IdentifierInfo=*/nullptr,
10411                                                ArgType, /*TInfo=*/nullptr,
10412                                                SC_None, nullptr);
10413   CopyConstructor->setParams(FromParam);
10414 
10415   CopyConstructor->setTrivial(
10416     ClassDecl->needsOverloadResolutionForCopyConstructor()
10417       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10418       : ClassDecl->hasTrivialCopyConstructor());
10419 
10420   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10421     SetDeclDeleted(CopyConstructor, ClassLoc);
10422 
10423   // Note that we have declared this constructor.
10424   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10425 
10426   if (Scope *S = getScopeForContext(ClassDecl))
10427     PushOnScopeChains(CopyConstructor, S, false);
10428   ClassDecl->addDecl(CopyConstructor);
10429 
10430   return CopyConstructor;
10431 }
10432 
10433 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10434                                    CXXConstructorDecl *CopyConstructor) {
10435   assert((CopyConstructor->isDefaulted() &&
10436           CopyConstructor->isCopyConstructor() &&
10437           !CopyConstructor->doesThisDeclarationHaveABody() &&
10438           !CopyConstructor->isDeleted()) &&
10439          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10440 
10441   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10442   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10443 
10444   // C++11 [class.copy]p7:
10445   //   The [definition of an implicitly declared copy constructor] is
10446   //   deprecated if the class has a user-declared copy assignment operator
10447   //   or a user-declared destructor.
10448   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10449     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10450 
10451   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10452   DiagnosticErrorTrap Trap(Diags);
10453 
10454   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10455       Trap.hasErrorOccurred()) {
10456     Diag(CurrentLocation, diag::note_member_synthesized_at)
10457       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10458     CopyConstructor->setInvalidDecl();
10459   }  else {
10460     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10461                              ? CopyConstructor->getLocEnd()
10462                              : CopyConstructor->getLocation();
10463     Sema::CompoundScopeRAII CompoundScope(*this);
10464     CopyConstructor->setBody(
10465         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10466   }
10467 
10468   CopyConstructor->markUsed(Context);
10469   MarkVTableUsed(CurrentLocation, ClassDecl);
10470 
10471   if (ASTMutationListener *L = getASTMutationListener()) {
10472     L->CompletedImplicitDefinition(CopyConstructor);
10473   }
10474 }
10475 
10476 Sema::ImplicitExceptionSpecification
10477 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10478   CXXRecordDecl *ClassDecl = MD->getParent();
10479 
10480   // C++ [except.spec]p14:
10481   //   An implicitly declared special member function (Clause 12) shall have an
10482   //   exception-specification. [...]
10483   ImplicitExceptionSpecification ExceptSpec(*this);
10484   if (ClassDecl->isInvalidDecl())
10485     return ExceptSpec;
10486 
10487   // Direct base-class constructors.
10488   for (const auto &B : ClassDecl->bases()) {
10489     if (B.isVirtual()) // Handled below.
10490       continue;
10491 
10492     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10493       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10494       CXXConstructorDecl *Constructor =
10495           LookupMovingConstructor(BaseClassDecl, 0);
10496       // If this is a deleted function, add it anyway. This might be conformant
10497       // with the standard. This might not. I'm not sure. It might not matter.
10498       if (Constructor)
10499         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10500     }
10501   }
10502 
10503   // Virtual base-class constructors.
10504   for (const auto &B : ClassDecl->vbases()) {
10505     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10506       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10507       CXXConstructorDecl *Constructor =
10508           LookupMovingConstructor(BaseClassDecl, 0);
10509       // If this is a deleted function, add it anyway. This might be conformant
10510       // with the standard. This might not. I'm not sure. It might not matter.
10511       if (Constructor)
10512         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10513     }
10514   }
10515 
10516   // Field constructors.
10517   for (const auto *F : ClassDecl->fields()) {
10518     QualType FieldType = Context.getBaseElementType(F->getType());
10519     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10520       CXXConstructorDecl *Constructor =
10521           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10522       // If this is a deleted function, add it anyway. This might be conformant
10523       // with the standard. This might not. I'm not sure. It might not matter.
10524       // In particular, the problem is that this function never gets called. It
10525       // might just be ill-formed because this function attempts to refer to
10526       // a deleted function here.
10527       if (Constructor)
10528         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10529     }
10530   }
10531 
10532   return ExceptSpec;
10533 }
10534 
10535 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10536                                                     CXXRecordDecl *ClassDecl) {
10537   assert(ClassDecl->needsImplicitMoveConstructor());
10538 
10539   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10540   if (DSM.isAlreadyBeingDeclared())
10541     return nullptr;
10542 
10543   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10544   QualType ArgType = Context.getRValueReferenceType(ClassType);
10545 
10546   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10547                                                      CXXMoveConstructor,
10548                                                      false);
10549 
10550   DeclarationName Name
10551     = Context.DeclarationNames.getCXXConstructorName(
10552                                            Context.getCanonicalType(ClassType));
10553   SourceLocation ClassLoc = ClassDecl->getLocation();
10554   DeclarationNameInfo NameInfo(Name, ClassLoc);
10555 
10556   // C++11 [class.copy]p11:
10557   //   An implicitly-declared copy/move constructor is an inline public
10558   //   member of its class.
10559   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10560       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10561       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10562       Constexpr);
10563   MoveConstructor->setAccess(AS_public);
10564   MoveConstructor->setDefaulted();
10565 
10566   // Build an exception specification pointing back at this member.
10567   FunctionProtoType::ExtProtoInfo EPI =
10568       getImplicitMethodEPI(*this, MoveConstructor);
10569   MoveConstructor->setType(
10570       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10571 
10572   // Add the parameter to the constructor.
10573   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10574                                                ClassLoc, ClassLoc,
10575                                                /*IdentifierInfo=*/nullptr,
10576                                                ArgType, /*TInfo=*/nullptr,
10577                                                SC_None, nullptr);
10578   MoveConstructor->setParams(FromParam);
10579 
10580   MoveConstructor->setTrivial(
10581     ClassDecl->needsOverloadResolutionForMoveConstructor()
10582       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10583       : ClassDecl->hasTrivialMoveConstructor());
10584 
10585   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10586     ClassDecl->setImplicitMoveConstructorIsDeleted();
10587     SetDeclDeleted(MoveConstructor, ClassLoc);
10588   }
10589 
10590   // Note that we have declared this constructor.
10591   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10592 
10593   if (Scope *S = getScopeForContext(ClassDecl))
10594     PushOnScopeChains(MoveConstructor, S, false);
10595   ClassDecl->addDecl(MoveConstructor);
10596 
10597   return MoveConstructor;
10598 }
10599 
10600 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10601                                    CXXConstructorDecl *MoveConstructor) {
10602   assert((MoveConstructor->isDefaulted() &&
10603           MoveConstructor->isMoveConstructor() &&
10604           !MoveConstructor->doesThisDeclarationHaveABody() &&
10605           !MoveConstructor->isDeleted()) &&
10606          "DefineImplicitMoveConstructor - call it for implicit move ctor");
10607 
10608   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10609   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10610 
10611   SynthesizedFunctionScope Scope(*this, MoveConstructor);
10612   DiagnosticErrorTrap Trap(Diags);
10613 
10614   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10615       Trap.hasErrorOccurred()) {
10616     Diag(CurrentLocation, diag::note_member_synthesized_at)
10617       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10618     MoveConstructor->setInvalidDecl();
10619   }  else {
10620     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10621                              ? MoveConstructor->getLocEnd()
10622                              : MoveConstructor->getLocation();
10623     Sema::CompoundScopeRAII CompoundScope(*this);
10624     MoveConstructor->setBody(ActOnCompoundStmt(
10625         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
10626   }
10627 
10628   MoveConstructor->markUsed(Context);
10629   MarkVTableUsed(CurrentLocation, ClassDecl);
10630 
10631   if (ASTMutationListener *L = getASTMutationListener()) {
10632     L->CompletedImplicitDefinition(MoveConstructor);
10633   }
10634 }
10635 
10636 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10637   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10638 }
10639 
10640 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10641                             SourceLocation CurrentLocation,
10642                             CXXConversionDecl *Conv) {
10643   CXXRecordDecl *Lambda = Conv->getParent();
10644   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10645   // If we are defining a specialization of a conversion to function-ptr
10646   // cache the deduced template arguments for this specialization
10647   // so that we can use them to retrieve the corresponding call-operator
10648   // and static-invoker.
10649   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10650 
10651   // Retrieve the corresponding call-operator specialization.
10652   if (Lambda->isGenericLambda()) {
10653     assert(Conv->isFunctionTemplateSpecialization());
10654     FunctionTemplateDecl *CallOpTemplate =
10655         CallOp->getDescribedFunctionTemplate();
10656     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10657     void *InsertPos = nullptr;
10658     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10659                                                 DeducedTemplateArgs->asArray(),
10660                                                 InsertPos);
10661     assert(CallOpSpec &&
10662           "Conversion operator must have a corresponding call operator");
10663     CallOp = cast<CXXMethodDecl>(CallOpSpec);
10664   }
10665   // Mark the call operator referenced (and add to pending instantiations
10666   // if necessary).
10667   // For both the conversion and static-invoker template specializations
10668   // we construct their body's in this function, so no need to add them
10669   // to the PendingInstantiations.
10670   MarkFunctionReferenced(CurrentLocation, CallOp);
10671 
10672   SynthesizedFunctionScope Scope(*this, Conv);
10673   DiagnosticErrorTrap Trap(Diags);
10674 
10675   // Retrieve the static invoker...
10676   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10677   // ... and get the corresponding specialization for a generic lambda.
10678   if (Lambda->isGenericLambda()) {
10679     assert(DeducedTemplateArgs &&
10680       "Must have deduced template arguments from Conversion Operator");
10681     FunctionTemplateDecl *InvokeTemplate =
10682                           Invoker->getDescribedFunctionTemplate();
10683     void *InsertPos = nullptr;
10684     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10685                                                 DeducedTemplateArgs->asArray(),
10686                                                 InsertPos);
10687     assert(InvokeSpec &&
10688       "Must have a corresponding static invoker specialization");
10689     Invoker = cast<CXXMethodDecl>(InvokeSpec);
10690   }
10691   // Construct the body of the conversion function { return __invoke; }.
10692   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10693                                         VK_LValue, Conv->getLocation()).get();
10694    assert(FunctionRef && "Can't refer to __invoke function?");
10695    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
10696    Conv->setBody(new (Context) CompoundStmt(Context, Return,
10697                                             Conv->getLocation(),
10698                                             Conv->getLocation()));
10699 
10700   Conv->markUsed(Context);
10701   Conv->setReferenced();
10702 
10703   // Fill in the __invoke function with a dummy implementation. IR generation
10704   // will fill in the actual details.
10705   Invoker->markUsed(Context);
10706   Invoker->setReferenced();
10707   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10708 
10709   if (ASTMutationListener *L = getASTMutationListener()) {
10710     L->CompletedImplicitDefinition(Conv);
10711     L->CompletedImplicitDefinition(Invoker);
10712    }
10713 }
10714 
10715 
10716 
10717 void Sema::DefineImplicitLambdaToBlockPointerConversion(
10718        SourceLocation CurrentLocation,
10719        CXXConversionDecl *Conv)
10720 {
10721   assert(!Conv->getParent()->isGenericLambda());
10722 
10723   Conv->markUsed(Context);
10724 
10725   SynthesizedFunctionScope Scope(*this, Conv);
10726   DiagnosticErrorTrap Trap(Diags);
10727 
10728   // Copy-initialize the lambda object as needed to capture it.
10729   Expr *This = ActOnCXXThis(CurrentLocation).get();
10730   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
10731 
10732   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10733                                                         Conv->getLocation(),
10734                                                         Conv, DerefThis);
10735 
10736   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10737   // behavior.  Note that only the general conversion function does this
10738   // (since it's unusable otherwise); in the case where we inline the
10739   // block literal, it has block literal lifetime semantics.
10740   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10741     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10742                                           CK_CopyAndAutoreleaseBlockObject,
10743                                           BuildBlock.get(), nullptr, VK_RValue);
10744 
10745   if (BuildBlock.isInvalid()) {
10746     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10747     Conv->setInvalidDecl();
10748     return;
10749   }
10750 
10751   // Create the return statement that returns the block from the conversion
10752   // function.
10753   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
10754   if (Return.isInvalid()) {
10755     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10756     Conv->setInvalidDecl();
10757     return;
10758   }
10759 
10760   // Set the body of the conversion function.
10761   Stmt *ReturnS = Return.get();
10762   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10763                                            Conv->getLocation(),
10764                                            Conv->getLocation()));
10765 
10766   // We're done; notify the mutation listener, if any.
10767   if (ASTMutationListener *L = getASTMutationListener()) {
10768     L->CompletedImplicitDefinition(Conv);
10769   }
10770 }
10771 
10772 /// \brief Determine whether the given list arguments contains exactly one
10773 /// "real" (non-default) argument.
10774 static bool hasOneRealArgument(MultiExprArg Args) {
10775   switch (Args.size()) {
10776   case 0:
10777     return false;
10778 
10779   default:
10780     if (!Args[1]->isDefaultArgument())
10781       return false;
10782 
10783     // fall through
10784   case 1:
10785     return !Args[0]->isDefaultArgument();
10786   }
10787 
10788   return false;
10789 }
10790 
10791 ExprResult
10792 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10793                             CXXConstructorDecl *Constructor,
10794                             MultiExprArg ExprArgs,
10795                             bool HadMultipleCandidates,
10796                             bool IsListInitialization,
10797                             bool IsStdInitListInitialization,
10798                             bool RequiresZeroInit,
10799                             unsigned ConstructKind,
10800                             SourceRange ParenRange) {
10801   bool Elidable = false;
10802 
10803   // C++0x [class.copy]p34:
10804   //   When certain criteria are met, an implementation is allowed to
10805   //   omit the copy/move construction of a class object, even if the
10806   //   copy/move constructor and/or destructor for the object have
10807   //   side effects. [...]
10808   //     - when a temporary class object that has not been bound to a
10809   //       reference (12.2) would be copied/moved to a class object
10810   //       with the same cv-unqualified type, the copy/move operation
10811   //       can be omitted by constructing the temporary object
10812   //       directly into the target of the omitted copy/move
10813   if (ConstructKind == CXXConstructExpr::CK_Complete &&
10814       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10815     Expr *SubExpr = ExprArgs[0];
10816     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10817   }
10818 
10819   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10820                                Elidable, ExprArgs, HadMultipleCandidates,
10821                                IsListInitialization,
10822                                IsStdInitListInitialization, RequiresZeroInit,
10823                                ConstructKind, ParenRange);
10824 }
10825 
10826 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
10827 /// including handling of its default argument expressions.
10828 ExprResult
10829 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10830                             CXXConstructorDecl *Constructor, bool Elidable,
10831                             MultiExprArg ExprArgs,
10832                             bool HadMultipleCandidates,
10833                             bool IsListInitialization,
10834                             bool IsStdInitListInitialization,
10835                             bool RequiresZeroInit,
10836                             unsigned ConstructKind,
10837                             SourceRange ParenRange) {
10838   MarkFunctionReferenced(ConstructLoc, Constructor);
10839   return CXXConstructExpr::Create(
10840       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
10841       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
10842       RequiresZeroInit,
10843       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10844       ParenRange);
10845 }
10846 
10847 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10848   if (VD->isInvalidDecl()) return;
10849 
10850   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10851   if (ClassDecl->isInvalidDecl()) return;
10852   if (ClassDecl->hasIrrelevantDestructor()) return;
10853   if (ClassDecl->isDependentContext()) return;
10854 
10855   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10856   MarkFunctionReferenced(VD->getLocation(), Destructor);
10857   CheckDestructorAccess(VD->getLocation(), Destructor,
10858                         PDiag(diag::err_access_dtor_var)
10859                         << VD->getDeclName()
10860                         << VD->getType());
10861   DiagnoseUseOfDecl(Destructor, VD->getLocation());
10862 
10863   if (Destructor->isTrivial()) return;
10864   if (!VD->hasGlobalStorage()) return;
10865 
10866   // Emit warning for non-trivial dtor in global scope (a real global,
10867   // class-static, function-static).
10868   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10869 
10870   // TODO: this should be re-enabled for static locals by !CXAAtExit
10871   if (!VD->isStaticLocal())
10872     Diag(VD->getLocation(), diag::warn_global_destructor);
10873 }
10874 
10875 /// \brief Given a constructor and the set of arguments provided for the
10876 /// constructor, convert the arguments and add any required default arguments
10877 /// to form a proper call to this constructor.
10878 ///
10879 /// \returns true if an error occurred, false otherwise.
10880 bool
10881 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10882                               MultiExprArg ArgsPtr,
10883                               SourceLocation Loc,
10884                               SmallVectorImpl<Expr*> &ConvertedArgs,
10885                               bool AllowExplicit,
10886                               bool IsListInitialization) {
10887   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10888   unsigned NumArgs = ArgsPtr.size();
10889   Expr **Args = ArgsPtr.data();
10890 
10891   const FunctionProtoType *Proto
10892     = Constructor->getType()->getAs<FunctionProtoType>();
10893   assert(Proto && "Constructor without a prototype?");
10894   unsigned NumParams = Proto->getNumParams();
10895 
10896   // If too few arguments are available, we'll fill in the rest with defaults.
10897   if (NumArgs < NumParams)
10898     ConvertedArgs.reserve(NumParams);
10899   else
10900     ConvertedArgs.reserve(NumArgs);
10901 
10902   VariadicCallType CallType =
10903     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10904   SmallVector<Expr *, 8> AllArgs;
10905   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10906                                         Proto, 0,
10907                                         llvm::makeArrayRef(Args, NumArgs),
10908                                         AllArgs,
10909                                         CallType, AllowExplicit,
10910                                         IsListInitialization);
10911   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10912 
10913   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10914 
10915   CheckConstructorCall(Constructor,
10916                        llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10917                                                         AllArgs.size()),
10918                        Proto, Loc);
10919 
10920   return Invalid;
10921 }
10922 
10923 static inline bool
10924 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10925                                        const FunctionDecl *FnDecl) {
10926   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10927   if (isa<NamespaceDecl>(DC)) {
10928     return SemaRef.Diag(FnDecl->getLocation(),
10929                         diag::err_operator_new_delete_declared_in_namespace)
10930       << FnDecl->getDeclName();
10931   }
10932 
10933   if (isa<TranslationUnitDecl>(DC) &&
10934       FnDecl->getStorageClass() == SC_Static) {
10935     return SemaRef.Diag(FnDecl->getLocation(),
10936                         diag::err_operator_new_delete_declared_static)
10937       << FnDecl->getDeclName();
10938   }
10939 
10940   return false;
10941 }
10942 
10943 static inline bool
10944 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10945                             CanQualType ExpectedResultType,
10946                             CanQualType ExpectedFirstParamType,
10947                             unsigned DependentParamTypeDiag,
10948                             unsigned InvalidParamTypeDiag) {
10949   QualType ResultType =
10950       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
10951 
10952   // Check that the result type is not dependent.
10953   if (ResultType->isDependentType())
10954     return SemaRef.Diag(FnDecl->getLocation(),
10955                         diag::err_operator_new_delete_dependent_result_type)
10956     << FnDecl->getDeclName() << ExpectedResultType;
10957 
10958   // Check that the result type is what we expect.
10959   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10960     return SemaRef.Diag(FnDecl->getLocation(),
10961                         diag::err_operator_new_delete_invalid_result_type)
10962     << FnDecl->getDeclName() << ExpectedResultType;
10963 
10964   // A function template must have at least 2 parameters.
10965   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10966     return SemaRef.Diag(FnDecl->getLocation(),
10967                       diag::err_operator_new_delete_template_too_few_parameters)
10968         << FnDecl->getDeclName();
10969 
10970   // The function decl must have at least 1 parameter.
10971   if (FnDecl->getNumParams() == 0)
10972     return SemaRef.Diag(FnDecl->getLocation(),
10973                         diag::err_operator_new_delete_too_few_parameters)
10974       << FnDecl->getDeclName();
10975 
10976   // Check the first parameter type is not dependent.
10977   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10978   if (FirstParamType->isDependentType())
10979     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10980       << FnDecl->getDeclName() << ExpectedFirstParamType;
10981 
10982   // Check that the first parameter type is what we expect.
10983   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10984       ExpectedFirstParamType)
10985     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10986     << FnDecl->getDeclName() << ExpectedFirstParamType;
10987 
10988   return false;
10989 }
10990 
10991 static bool
10992 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10993   // C++ [basic.stc.dynamic.allocation]p1:
10994   //   A program is ill-formed if an allocation function is declared in a
10995   //   namespace scope other than global scope or declared static in global
10996   //   scope.
10997   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10998     return true;
10999 
11000   CanQualType SizeTy =
11001     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11002 
11003   // C++ [basic.stc.dynamic.allocation]p1:
11004   //  The return type shall be void*. The first parameter shall have type
11005   //  std::size_t.
11006   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11007                                   SizeTy,
11008                                   diag::err_operator_new_dependent_param_type,
11009                                   diag::err_operator_new_param_type))
11010     return true;
11011 
11012   // C++ [basic.stc.dynamic.allocation]p1:
11013   //  The first parameter shall not have an associated default argument.
11014   if (FnDecl->getParamDecl(0)->hasDefaultArg())
11015     return SemaRef.Diag(FnDecl->getLocation(),
11016                         diag::err_operator_new_default_arg)
11017       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11018 
11019   return false;
11020 }
11021 
11022 static bool
11023 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11024   // C++ [basic.stc.dynamic.deallocation]p1:
11025   //   A program is ill-formed if deallocation functions are declared in a
11026   //   namespace scope other than global scope or declared static in global
11027   //   scope.
11028   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11029     return true;
11030 
11031   // C++ [basic.stc.dynamic.deallocation]p2:
11032   //   Each deallocation function shall return void and its first parameter
11033   //   shall be void*.
11034   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11035                                   SemaRef.Context.VoidPtrTy,
11036                                  diag::err_operator_delete_dependent_param_type,
11037                                  diag::err_operator_delete_param_type))
11038     return true;
11039 
11040   return false;
11041 }
11042 
11043 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11044 /// of this overloaded operator is well-formed. If so, returns false;
11045 /// otherwise, emits appropriate diagnostics and returns true.
11046 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11047   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11048          "Expected an overloaded operator declaration");
11049 
11050   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11051 
11052   // C++ [over.oper]p5:
11053   //   The allocation and deallocation functions, operator new,
11054   //   operator new[], operator delete and operator delete[], are
11055   //   described completely in 3.7.3. The attributes and restrictions
11056   //   found in the rest of this subclause do not apply to them unless
11057   //   explicitly stated in 3.7.3.
11058   if (Op == OO_Delete || Op == OO_Array_Delete)
11059     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11060 
11061   if (Op == OO_New || Op == OO_Array_New)
11062     return CheckOperatorNewDeclaration(*this, FnDecl);
11063 
11064   // C++ [over.oper]p6:
11065   //   An operator function shall either be a non-static member
11066   //   function or be a non-member function and have at least one
11067   //   parameter whose type is a class, a reference to a class, an
11068   //   enumeration, or a reference to an enumeration.
11069   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11070     if (MethodDecl->isStatic())
11071       return Diag(FnDecl->getLocation(),
11072                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11073   } else {
11074     bool ClassOrEnumParam = false;
11075     for (auto Param : FnDecl->params()) {
11076       QualType ParamType = Param->getType().getNonReferenceType();
11077       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11078           ParamType->isEnumeralType()) {
11079         ClassOrEnumParam = true;
11080         break;
11081       }
11082     }
11083 
11084     if (!ClassOrEnumParam)
11085       return Diag(FnDecl->getLocation(),
11086                   diag::err_operator_overload_needs_class_or_enum)
11087         << FnDecl->getDeclName();
11088   }
11089 
11090   // C++ [over.oper]p8:
11091   //   An operator function cannot have default arguments (8.3.6),
11092   //   except where explicitly stated below.
11093   //
11094   // Only the function-call operator allows default arguments
11095   // (C++ [over.call]p1).
11096   if (Op != OO_Call) {
11097     for (auto Param : FnDecl->params()) {
11098       if (Param->hasDefaultArg())
11099         return Diag(Param->getLocation(),
11100                     diag::err_operator_overload_default_arg)
11101           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11102     }
11103   }
11104 
11105   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11106     { false, false, false }
11107 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11108     , { Unary, Binary, MemberOnly }
11109 #include "clang/Basic/OperatorKinds.def"
11110   };
11111 
11112   bool CanBeUnaryOperator = OperatorUses[Op][0];
11113   bool CanBeBinaryOperator = OperatorUses[Op][1];
11114   bool MustBeMemberOperator = OperatorUses[Op][2];
11115 
11116   // C++ [over.oper]p8:
11117   //   [...] Operator functions cannot have more or fewer parameters
11118   //   than the number required for the corresponding operator, as
11119   //   described in the rest of this subclause.
11120   unsigned NumParams = FnDecl->getNumParams()
11121                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11122   if (Op != OO_Call &&
11123       ((NumParams == 1 && !CanBeUnaryOperator) ||
11124        (NumParams == 2 && !CanBeBinaryOperator) ||
11125        (NumParams < 1) || (NumParams > 2))) {
11126     // We have the wrong number of parameters.
11127     unsigned ErrorKind;
11128     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11129       ErrorKind = 2;  // 2 -> unary or binary.
11130     } else if (CanBeUnaryOperator) {
11131       ErrorKind = 0;  // 0 -> unary
11132     } else {
11133       assert(CanBeBinaryOperator &&
11134              "All non-call overloaded operators are unary or binary!");
11135       ErrorKind = 1;  // 1 -> binary
11136     }
11137 
11138     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11139       << FnDecl->getDeclName() << NumParams << ErrorKind;
11140   }
11141 
11142   // Overloaded operators other than operator() cannot be variadic.
11143   if (Op != OO_Call &&
11144       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11145     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11146       << FnDecl->getDeclName();
11147   }
11148 
11149   // Some operators must be non-static member functions.
11150   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11151     return Diag(FnDecl->getLocation(),
11152                 diag::err_operator_overload_must_be_member)
11153       << FnDecl->getDeclName();
11154   }
11155 
11156   // C++ [over.inc]p1:
11157   //   The user-defined function called operator++ implements the
11158   //   prefix and postfix ++ operator. If this function is a member
11159   //   function with no parameters, or a non-member function with one
11160   //   parameter of class or enumeration type, it defines the prefix
11161   //   increment operator ++ for objects of that type. If the function
11162   //   is a member function with one parameter (which shall be of type
11163   //   int) or a non-member function with two parameters (the second
11164   //   of which shall be of type int), it defines the postfix
11165   //   increment operator ++ for objects of that type.
11166   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11167     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11168     QualType ParamType = LastParam->getType();
11169 
11170     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11171         !ParamType->isDependentType())
11172       return Diag(LastParam->getLocation(),
11173                   diag::err_operator_overload_post_incdec_must_be_int)
11174         << LastParam->getType() << (Op == OO_MinusMinus);
11175   }
11176 
11177   return false;
11178 }
11179 
11180 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11181 /// of this literal operator function is well-formed. If so, returns
11182 /// false; otherwise, emits appropriate diagnostics and returns true.
11183 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11184   if (isa<CXXMethodDecl>(FnDecl)) {
11185     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11186       << FnDecl->getDeclName();
11187     return true;
11188   }
11189 
11190   if (FnDecl->isExternC()) {
11191     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11192     return true;
11193   }
11194 
11195   bool Valid = false;
11196 
11197   // This might be the definition of a literal operator template.
11198   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11199   // This might be a specialization of a literal operator template.
11200   if (!TpDecl)
11201     TpDecl = FnDecl->getPrimaryTemplate();
11202 
11203   // template <char...> type operator "" name() and
11204   // template <class T, T...> type operator "" name() are the only valid
11205   // template signatures, and the only valid signatures with no parameters.
11206   if (TpDecl) {
11207     if (FnDecl->param_size() == 0) {
11208       // Must have one or two template parameters
11209       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11210       if (Params->size() == 1) {
11211         NonTypeTemplateParmDecl *PmDecl =
11212           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11213 
11214         // The template parameter must be a char parameter pack.
11215         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11216             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11217           Valid = true;
11218       } else if (Params->size() == 2) {
11219         TemplateTypeParmDecl *PmType =
11220           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11221         NonTypeTemplateParmDecl *PmArgs =
11222           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11223 
11224         // The second template parameter must be a parameter pack with the
11225         // first template parameter as its type.
11226         if (PmType && PmArgs &&
11227             !PmType->isTemplateParameterPack() &&
11228             PmArgs->isTemplateParameterPack()) {
11229           const TemplateTypeParmType *TArgs =
11230             PmArgs->getType()->getAs<TemplateTypeParmType>();
11231           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11232               TArgs->getIndex() == PmType->getIndex()) {
11233             Valid = true;
11234             if (ActiveTemplateInstantiations.empty())
11235               Diag(FnDecl->getLocation(),
11236                    diag::ext_string_literal_operator_template);
11237           }
11238         }
11239       }
11240     }
11241   } else if (FnDecl->param_size()) {
11242     // Check the first parameter
11243     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11244 
11245     QualType T = (*Param)->getType().getUnqualifiedType();
11246 
11247     // unsigned long long int, long double, and any character type are allowed
11248     // as the only parameters.
11249     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11250         Context.hasSameType(T, Context.LongDoubleTy) ||
11251         Context.hasSameType(T, Context.CharTy) ||
11252         Context.hasSameType(T, Context.WideCharTy) ||
11253         Context.hasSameType(T, Context.Char16Ty) ||
11254         Context.hasSameType(T, Context.Char32Ty)) {
11255       if (++Param == FnDecl->param_end())
11256         Valid = true;
11257       goto FinishedParams;
11258     }
11259 
11260     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11261     const PointerType *PT = T->getAs<PointerType>();
11262     if (!PT)
11263       goto FinishedParams;
11264     T = PT->getPointeeType();
11265     if (!T.isConstQualified() || T.isVolatileQualified())
11266       goto FinishedParams;
11267     T = T.getUnqualifiedType();
11268 
11269     // Move on to the second parameter;
11270     ++Param;
11271 
11272     // If there is no second parameter, the first must be a const char *
11273     if (Param == FnDecl->param_end()) {
11274       if (Context.hasSameType(T, Context.CharTy))
11275         Valid = true;
11276       goto FinishedParams;
11277     }
11278 
11279     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11280     // are allowed as the first parameter to a two-parameter function
11281     if (!(Context.hasSameType(T, Context.CharTy) ||
11282           Context.hasSameType(T, Context.WideCharTy) ||
11283           Context.hasSameType(T, Context.Char16Ty) ||
11284           Context.hasSameType(T, Context.Char32Ty)))
11285       goto FinishedParams;
11286 
11287     // The second and final parameter must be an std::size_t
11288     T = (*Param)->getType().getUnqualifiedType();
11289     if (Context.hasSameType(T, Context.getSizeType()) &&
11290         ++Param == FnDecl->param_end())
11291       Valid = true;
11292   }
11293 
11294   // FIXME: This diagnostic is absolutely terrible.
11295 FinishedParams:
11296   if (!Valid) {
11297     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11298       << FnDecl->getDeclName();
11299     return true;
11300   }
11301 
11302   // A parameter-declaration-clause containing a default argument is not
11303   // equivalent to any of the permitted forms.
11304   for (auto Param : FnDecl->params()) {
11305     if (Param->hasDefaultArg()) {
11306       Diag(Param->getDefaultArgRange().getBegin(),
11307            diag::err_literal_operator_default_argument)
11308         << Param->getDefaultArgRange();
11309       break;
11310     }
11311   }
11312 
11313   StringRef LiteralName
11314     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11315   if (LiteralName[0] != '_') {
11316     // C++11 [usrlit.suffix]p1:
11317     //   Literal suffix identifiers that do not start with an underscore
11318     //   are reserved for future standardization.
11319     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11320       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11321   }
11322 
11323   return false;
11324 }
11325 
11326 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11327 /// linkage specification, including the language and (if present)
11328 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11329 /// language string literal. LBraceLoc, if valid, provides the location of
11330 /// the '{' brace. Otherwise, this linkage specification does not
11331 /// have any braces.
11332 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11333                                            Expr *LangStr,
11334                                            SourceLocation LBraceLoc) {
11335   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11336   if (!Lit->isAscii()) {
11337     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11338       << LangStr->getSourceRange();
11339     return nullptr;
11340   }
11341 
11342   StringRef Lang = Lit->getString();
11343   LinkageSpecDecl::LanguageIDs Language;
11344   if (Lang == "C")
11345     Language = LinkageSpecDecl::lang_c;
11346   else if (Lang == "C++")
11347     Language = LinkageSpecDecl::lang_cxx;
11348   else {
11349     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11350       << LangStr->getSourceRange();
11351     return nullptr;
11352   }
11353 
11354   // FIXME: Add all the various semantics of linkage specifications
11355 
11356   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11357                                                LangStr->getExprLoc(), Language,
11358                                                LBraceLoc.isValid());
11359   CurContext->addDecl(D);
11360   PushDeclContext(S, D);
11361   return D;
11362 }
11363 
11364 /// ActOnFinishLinkageSpecification - Complete the definition of
11365 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11366 /// valid, it's the position of the closing '}' brace in a linkage
11367 /// specification that uses braces.
11368 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11369                                             Decl *LinkageSpec,
11370                                             SourceLocation RBraceLoc) {
11371   if (RBraceLoc.isValid()) {
11372     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11373     LSDecl->setRBraceLoc(RBraceLoc);
11374   }
11375   PopDeclContext();
11376   return LinkageSpec;
11377 }
11378 
11379 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11380                                   AttributeList *AttrList,
11381                                   SourceLocation SemiLoc) {
11382   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11383   // Attribute declarations appertain to empty declaration so we handle
11384   // them here.
11385   if (AttrList)
11386     ProcessDeclAttributeList(S, ED, AttrList);
11387 
11388   CurContext->addDecl(ED);
11389   return ED;
11390 }
11391 
11392 /// \brief Perform semantic analysis for the variable declaration that
11393 /// occurs within a C++ catch clause, returning the newly-created
11394 /// variable.
11395 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11396                                          TypeSourceInfo *TInfo,
11397                                          SourceLocation StartLoc,
11398                                          SourceLocation Loc,
11399                                          IdentifierInfo *Name) {
11400   bool Invalid = false;
11401   QualType ExDeclType = TInfo->getType();
11402 
11403   // Arrays and functions decay.
11404   if (ExDeclType->isArrayType())
11405     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11406   else if (ExDeclType->isFunctionType())
11407     ExDeclType = Context.getPointerType(ExDeclType);
11408 
11409   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11410   // The exception-declaration shall not denote a pointer or reference to an
11411   // incomplete type, other than [cv] void*.
11412   // N2844 forbids rvalue references.
11413   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11414     Diag(Loc, diag::err_catch_rvalue_ref);
11415     Invalid = true;
11416   }
11417 
11418   QualType BaseType = ExDeclType;
11419   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11420   unsigned DK = diag::err_catch_incomplete;
11421   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11422     BaseType = Ptr->getPointeeType();
11423     Mode = 1;
11424     DK = diag::err_catch_incomplete_ptr;
11425   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11426     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11427     BaseType = Ref->getPointeeType();
11428     Mode = 2;
11429     DK = diag::err_catch_incomplete_ref;
11430   }
11431   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11432       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11433     Invalid = true;
11434 
11435   if (!Invalid && !ExDeclType->isDependentType() &&
11436       RequireNonAbstractType(Loc, ExDeclType,
11437                              diag::err_abstract_type_in_decl,
11438                              AbstractVariableType))
11439     Invalid = true;
11440 
11441   // Only the non-fragile NeXT runtime currently supports C++ catches
11442   // of ObjC types, and no runtime supports catching ObjC types by value.
11443   if (!Invalid && getLangOpts().ObjC1) {
11444     QualType T = ExDeclType;
11445     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11446       T = RT->getPointeeType();
11447 
11448     if (T->isObjCObjectType()) {
11449       Diag(Loc, diag::err_objc_object_catch);
11450       Invalid = true;
11451     } else if (T->isObjCObjectPointerType()) {
11452       // FIXME: should this be a test for macosx-fragile specifically?
11453       if (getLangOpts().ObjCRuntime.isFragile())
11454         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11455     }
11456   }
11457 
11458   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11459                                     ExDeclType, TInfo, SC_None);
11460   ExDecl->setExceptionVariable(true);
11461 
11462   // In ARC, infer 'retaining' for variables of retainable type.
11463   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11464     Invalid = true;
11465 
11466   if (!Invalid && !ExDeclType->isDependentType()) {
11467     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11468       // Insulate this from anything else we might currently be parsing.
11469       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11470 
11471       // C++ [except.handle]p16:
11472       //   The object declared in an exception-declaration or, if the
11473       //   exception-declaration does not specify a name, a temporary (12.2) is
11474       //   copy-initialized (8.5) from the exception object. [...]
11475       //   The object is destroyed when the handler exits, after the destruction
11476       //   of any automatic objects initialized within the handler.
11477       //
11478       // We just pretend to initialize the object with itself, then make sure
11479       // it can be destroyed later.
11480       QualType initType = ExDeclType;
11481 
11482       InitializedEntity entity =
11483         InitializedEntity::InitializeVariable(ExDecl);
11484       InitializationKind initKind =
11485         InitializationKind::CreateCopy(Loc, SourceLocation());
11486 
11487       Expr *opaqueValue =
11488         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11489       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11490       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11491       if (result.isInvalid())
11492         Invalid = true;
11493       else {
11494         // If the constructor used was non-trivial, set this as the
11495         // "initializer".
11496         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
11497         if (!construct->getConstructor()->isTrivial()) {
11498           Expr *init = MaybeCreateExprWithCleanups(construct);
11499           ExDecl->setInit(init);
11500         }
11501 
11502         // And make sure it's destructable.
11503         FinalizeVarWithDestructor(ExDecl, recordType);
11504       }
11505     }
11506   }
11507 
11508   if (Invalid)
11509     ExDecl->setInvalidDecl();
11510 
11511   return ExDecl;
11512 }
11513 
11514 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11515 /// handler.
11516 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11517   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11518   bool Invalid = D.isInvalidType();
11519 
11520   // Check for unexpanded parameter packs.
11521   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11522                                       UPPC_ExceptionType)) {
11523     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11524                                              D.getIdentifierLoc());
11525     Invalid = true;
11526   }
11527 
11528   IdentifierInfo *II = D.getIdentifier();
11529   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11530                                              LookupOrdinaryName,
11531                                              ForRedeclaration)) {
11532     // The scope should be freshly made just for us. There is just no way
11533     // it contains any previous declaration, except for function parameters in
11534     // a function-try-block's catch statement.
11535     assert(!S->isDeclScope(PrevDecl));
11536     if (isDeclInScope(PrevDecl, CurContext, S)) {
11537       Diag(D.getIdentifierLoc(), diag::err_redefinition)
11538         << D.getIdentifier();
11539       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11540       Invalid = true;
11541     } else if (PrevDecl->isTemplateParameter())
11542       // Maybe we will complain about the shadowed template parameter.
11543       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11544   }
11545 
11546   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11547     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11548       << D.getCXXScopeSpec().getRange();
11549     Invalid = true;
11550   }
11551 
11552   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11553                                               D.getLocStart(),
11554                                               D.getIdentifierLoc(),
11555                                               D.getIdentifier());
11556   if (Invalid)
11557     ExDecl->setInvalidDecl();
11558 
11559   // Add the exception declaration into this scope.
11560   if (II)
11561     PushOnScopeChains(ExDecl, S);
11562   else
11563     CurContext->addDecl(ExDecl);
11564 
11565   ProcessDeclAttributes(S, ExDecl, D);
11566   return ExDecl;
11567 }
11568 
11569 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11570                                          Expr *AssertExpr,
11571                                          Expr *AssertMessageExpr,
11572                                          SourceLocation RParenLoc) {
11573   StringLiteral *AssertMessage =
11574       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
11575 
11576   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11577     return nullptr;
11578 
11579   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11580                                       AssertMessage, RParenLoc, false);
11581 }
11582 
11583 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11584                                          Expr *AssertExpr,
11585                                          StringLiteral *AssertMessage,
11586                                          SourceLocation RParenLoc,
11587                                          bool Failed) {
11588   assert(AssertExpr != nullptr && "Expected non-null condition");
11589   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11590       !Failed) {
11591     // In a static_assert-declaration, the constant-expression shall be a
11592     // constant expression that can be contextually converted to bool.
11593     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11594     if (Converted.isInvalid())
11595       Failed = true;
11596 
11597     llvm::APSInt Cond;
11598     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11599           diag::err_static_assert_expression_is_not_constant,
11600           /*AllowFold=*/false).isInvalid())
11601       Failed = true;
11602 
11603     if (!Failed && !Cond) {
11604       SmallString<256> MsgBuffer;
11605       llvm::raw_svector_ostream Msg(MsgBuffer);
11606       if (AssertMessage)
11607         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
11608       Diag(StaticAssertLoc, diag::err_static_assert_failed)
11609         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
11610       Failed = true;
11611     }
11612   }
11613 
11614   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11615                                         AssertExpr, AssertMessage, RParenLoc,
11616                                         Failed);
11617 
11618   CurContext->addDecl(Decl);
11619   return Decl;
11620 }
11621 
11622 /// \brief Perform semantic analysis of the given friend type declaration.
11623 ///
11624 /// \returns A friend declaration that.
11625 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11626                                       SourceLocation FriendLoc,
11627                                       TypeSourceInfo *TSInfo) {
11628   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11629 
11630   QualType T = TSInfo->getType();
11631   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11632 
11633   // C++03 [class.friend]p2:
11634   //   An elaborated-type-specifier shall be used in a friend declaration
11635   //   for a class.*
11636   //
11637   //   * The class-key of the elaborated-type-specifier is required.
11638   if (!ActiveTemplateInstantiations.empty()) {
11639     // Do not complain about the form of friend template types during
11640     // template instantiation; we will already have complained when the
11641     // template was declared.
11642   } else {
11643     if (!T->isElaboratedTypeSpecifier()) {
11644       // If we evaluated the type to a record type, suggest putting
11645       // a tag in front.
11646       if (const RecordType *RT = T->getAs<RecordType>()) {
11647         RecordDecl *RD = RT->getDecl();
11648 
11649         SmallString<16> InsertionText(" ");
11650         InsertionText += RD->getKindName();
11651 
11652         Diag(TypeRange.getBegin(),
11653              getLangOpts().CPlusPlus11 ?
11654                diag::warn_cxx98_compat_unelaborated_friend_type :
11655                diag::ext_unelaborated_friend_type)
11656           << (unsigned) RD->getTagKind()
11657           << T
11658           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11659                                         InsertionText);
11660       } else {
11661         Diag(FriendLoc,
11662              getLangOpts().CPlusPlus11 ?
11663                diag::warn_cxx98_compat_nonclass_type_friend :
11664                diag::ext_nonclass_type_friend)
11665           << T
11666           << TypeRange;
11667       }
11668     } else if (T->getAs<EnumType>()) {
11669       Diag(FriendLoc,
11670            getLangOpts().CPlusPlus11 ?
11671              diag::warn_cxx98_compat_enum_friend :
11672              diag::ext_enum_friend)
11673         << T
11674         << TypeRange;
11675     }
11676 
11677     // C++11 [class.friend]p3:
11678     //   A friend declaration that does not declare a function shall have one
11679     //   of the following forms:
11680     //     friend elaborated-type-specifier ;
11681     //     friend simple-type-specifier ;
11682     //     friend typename-specifier ;
11683     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11684       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11685   }
11686 
11687   //   If the type specifier in a friend declaration designates a (possibly
11688   //   cv-qualified) class type, that class is declared as a friend; otherwise,
11689   //   the friend declaration is ignored.
11690   return FriendDecl::Create(Context, CurContext,
11691                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
11692                             FriendLoc);
11693 }
11694 
11695 /// Handle a friend tag declaration where the scope specifier was
11696 /// templated.
11697 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11698                                     unsigned TagSpec, SourceLocation TagLoc,
11699                                     CXXScopeSpec &SS,
11700                                     IdentifierInfo *Name,
11701                                     SourceLocation NameLoc,
11702                                     AttributeList *Attr,
11703                                     MultiTemplateParamsArg TempParamLists) {
11704   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11705 
11706   bool isExplicitSpecialization = false;
11707   bool Invalid = false;
11708 
11709   if (TemplateParameterList *TemplateParams =
11710           MatchTemplateParametersToScopeSpecifier(
11711               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
11712               isExplicitSpecialization, Invalid)) {
11713     if (TemplateParams->size() > 0) {
11714       // This is a declaration of a class template.
11715       if (Invalid)
11716         return nullptr;
11717 
11718       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
11719                                 NameLoc, Attr, TemplateParams, AS_public,
11720                                 /*ModulePrivateLoc=*/SourceLocation(),
11721                                 FriendLoc, TempParamLists.size() - 1,
11722                                 TempParamLists.data()).get();
11723     } else {
11724       // The "template<>" header is extraneous.
11725       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11726         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11727       isExplicitSpecialization = true;
11728     }
11729   }
11730 
11731   if (Invalid) return nullptr;
11732 
11733   bool isAllExplicitSpecializations = true;
11734   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11735     if (TempParamLists[I]->size()) {
11736       isAllExplicitSpecializations = false;
11737       break;
11738     }
11739   }
11740 
11741   // FIXME: don't ignore attributes.
11742 
11743   // If it's explicit specializations all the way down, just forget
11744   // about the template header and build an appropriate non-templated
11745   // friend.  TODO: for source fidelity, remember the headers.
11746   if (isAllExplicitSpecializations) {
11747     if (SS.isEmpty()) {
11748       bool Owned = false;
11749       bool IsDependent = false;
11750       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11751                       Attr, AS_public,
11752                       /*ModulePrivateLoc=*/SourceLocation(),
11753                       MultiTemplateParamsArg(), Owned, IsDependent,
11754                       /*ScopedEnumKWLoc=*/SourceLocation(),
11755                       /*ScopedEnumUsesClassTag=*/false,
11756                       /*UnderlyingType=*/TypeResult(),
11757                       /*IsTypeSpecifier=*/false);
11758     }
11759 
11760     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11761     ElaboratedTypeKeyword Keyword
11762       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11763     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11764                                    *Name, NameLoc);
11765     if (T.isNull())
11766       return nullptr;
11767 
11768     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11769     if (isa<DependentNameType>(T)) {
11770       DependentNameTypeLoc TL =
11771           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11772       TL.setElaboratedKeywordLoc(TagLoc);
11773       TL.setQualifierLoc(QualifierLoc);
11774       TL.setNameLoc(NameLoc);
11775     } else {
11776       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11777       TL.setElaboratedKeywordLoc(TagLoc);
11778       TL.setQualifierLoc(QualifierLoc);
11779       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11780     }
11781 
11782     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11783                                             TSI, FriendLoc, TempParamLists);
11784     Friend->setAccess(AS_public);
11785     CurContext->addDecl(Friend);
11786     return Friend;
11787   }
11788 
11789   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11790 
11791 
11792 
11793   // Handle the case of a templated-scope friend class.  e.g.
11794   //   template <class T> class A<T>::B;
11795   // FIXME: we don't support these right now.
11796   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11797     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
11798   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11799   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11800   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11801   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11802   TL.setElaboratedKeywordLoc(TagLoc);
11803   TL.setQualifierLoc(SS.getWithLocInContext(Context));
11804   TL.setNameLoc(NameLoc);
11805 
11806   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11807                                           TSI, FriendLoc, TempParamLists);
11808   Friend->setAccess(AS_public);
11809   Friend->setUnsupportedFriend(true);
11810   CurContext->addDecl(Friend);
11811   return Friend;
11812 }
11813 
11814 
11815 /// Handle a friend type declaration.  This works in tandem with
11816 /// ActOnTag.
11817 ///
11818 /// Notes on friend class templates:
11819 ///
11820 /// We generally treat friend class declarations as if they were
11821 /// declaring a class.  So, for example, the elaborated type specifier
11822 /// in a friend declaration is required to obey the restrictions of a
11823 /// class-head (i.e. no typedefs in the scope chain), template
11824 /// parameters are required to match up with simple template-ids, &c.
11825 /// However, unlike when declaring a template specialization, it's
11826 /// okay to refer to a template specialization without an empty
11827 /// template parameter declaration, e.g.
11828 ///   friend class A<T>::B<unsigned>;
11829 /// We permit this as a special case; if there are any template
11830 /// parameters present at all, require proper matching, i.e.
11831 ///   template <> template \<class T> friend class A<int>::B;
11832 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11833                                 MultiTemplateParamsArg TempParams) {
11834   SourceLocation Loc = DS.getLocStart();
11835 
11836   assert(DS.isFriendSpecified());
11837   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11838 
11839   // Try to convert the decl specifier to a type.  This works for
11840   // friend templates because ActOnTag never produces a ClassTemplateDecl
11841   // for a TUK_Friend.
11842   Declarator TheDeclarator(DS, Declarator::MemberContext);
11843   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11844   QualType T = TSI->getType();
11845   if (TheDeclarator.isInvalidType())
11846     return nullptr;
11847 
11848   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11849     return nullptr;
11850 
11851   // This is definitely an error in C++98.  It's probably meant to
11852   // be forbidden in C++0x, too, but the specification is just
11853   // poorly written.
11854   //
11855   // The problem is with declarations like the following:
11856   //   template <T> friend A<T>::foo;
11857   // where deciding whether a class C is a friend or not now hinges
11858   // on whether there exists an instantiation of A that causes
11859   // 'foo' to equal C.  There are restrictions on class-heads
11860   // (which we declare (by fiat) elaborated friend declarations to
11861   // be) that makes this tractable.
11862   //
11863   // FIXME: handle "template <> friend class A<T>;", which
11864   // is possibly well-formed?  Who even knows?
11865   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11866     Diag(Loc, diag::err_tagless_friend_type_template)
11867       << DS.getSourceRange();
11868     return nullptr;
11869   }
11870 
11871   // C++98 [class.friend]p1: A friend of a class is a function
11872   //   or class that is not a member of the class . . .
11873   // This is fixed in DR77, which just barely didn't make the C++03
11874   // deadline.  It's also a very silly restriction that seriously
11875   // affects inner classes and which nobody else seems to implement;
11876   // thus we never diagnose it, not even in -pedantic.
11877   //
11878   // But note that we could warn about it: it's always useless to
11879   // friend one of your own members (it's not, however, worthless to
11880   // friend a member of an arbitrary specialization of your template).
11881 
11882   Decl *D;
11883   if (unsigned NumTempParamLists = TempParams.size())
11884     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11885                                    NumTempParamLists,
11886                                    TempParams.data(),
11887                                    TSI,
11888                                    DS.getFriendSpecLoc());
11889   else
11890     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11891 
11892   if (!D)
11893     return nullptr;
11894 
11895   D->setAccess(AS_public);
11896   CurContext->addDecl(D);
11897 
11898   return D;
11899 }
11900 
11901 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11902                                         MultiTemplateParamsArg TemplateParams) {
11903   const DeclSpec &DS = D.getDeclSpec();
11904 
11905   assert(DS.isFriendSpecified());
11906   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11907 
11908   SourceLocation Loc = D.getIdentifierLoc();
11909   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11910 
11911   // C++ [class.friend]p1
11912   //   A friend of a class is a function or class....
11913   // Note that this sees through typedefs, which is intended.
11914   // It *doesn't* see through dependent types, which is correct
11915   // according to [temp.arg.type]p3:
11916   //   If a declaration acquires a function type through a
11917   //   type dependent on a template-parameter and this causes
11918   //   a declaration that does not use the syntactic form of a
11919   //   function declarator to have a function type, the program
11920   //   is ill-formed.
11921   if (!TInfo->getType()->isFunctionType()) {
11922     Diag(Loc, diag::err_unexpected_friend);
11923 
11924     // It might be worthwhile to try to recover by creating an
11925     // appropriate declaration.
11926     return nullptr;
11927   }
11928 
11929   // C++ [namespace.memdef]p3
11930   //  - If a friend declaration in a non-local class first declares a
11931   //    class or function, the friend class or function is a member
11932   //    of the innermost enclosing namespace.
11933   //  - The name of the friend is not found by simple name lookup
11934   //    until a matching declaration is provided in that namespace
11935   //    scope (either before or after the class declaration granting
11936   //    friendship).
11937   //  - If a friend function is called, its name may be found by the
11938   //    name lookup that considers functions from namespaces and
11939   //    classes associated with the types of the function arguments.
11940   //  - When looking for a prior declaration of a class or a function
11941   //    declared as a friend, scopes outside the innermost enclosing
11942   //    namespace scope are not considered.
11943 
11944   CXXScopeSpec &SS = D.getCXXScopeSpec();
11945   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11946   DeclarationName Name = NameInfo.getName();
11947   assert(Name);
11948 
11949   // Check for unexpanded parameter packs.
11950   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11951       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11952       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11953     return nullptr;
11954 
11955   // The context we found the declaration in, or in which we should
11956   // create the declaration.
11957   DeclContext *DC;
11958   Scope *DCScope = S;
11959   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11960                         ForRedeclaration);
11961 
11962   // There are five cases here.
11963   //   - There's no scope specifier and we're in a local class. Only look
11964   //     for functions declared in the immediately-enclosing block scope.
11965   // We recover from invalid scope qualifiers as if they just weren't there.
11966   FunctionDecl *FunctionContainingLocalClass = nullptr;
11967   if ((SS.isInvalid() || !SS.isSet()) &&
11968       (FunctionContainingLocalClass =
11969            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11970     // C++11 [class.friend]p11:
11971     //   If a friend declaration appears in a local class and the name
11972     //   specified is an unqualified name, a prior declaration is
11973     //   looked up without considering scopes that are outside the
11974     //   innermost enclosing non-class scope. For a friend function
11975     //   declaration, if there is no prior declaration, the program is
11976     //   ill-formed.
11977 
11978     // Find the innermost enclosing non-class scope. This is the block
11979     // scope containing the local class definition (or for a nested class,
11980     // the outer local class).
11981     DCScope = S->getFnParent();
11982 
11983     // Look up the function name in the scope.
11984     Previous.clear(LookupLocalFriendName);
11985     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11986 
11987     if (!Previous.empty()) {
11988       // All possible previous declarations must have the same context:
11989       // either they were declared at block scope or they are members of
11990       // one of the enclosing local classes.
11991       DC = Previous.getRepresentativeDecl()->getDeclContext();
11992     } else {
11993       // This is ill-formed, but provide the context that we would have
11994       // declared the function in, if we were permitted to, for error recovery.
11995       DC = FunctionContainingLocalClass;
11996     }
11997     adjustContextForLocalExternDecl(DC);
11998 
11999     // C++ [class.friend]p6:
12000     //   A function can be defined in a friend declaration of a class if and
12001     //   only if the class is a non-local class (9.8), the function name is
12002     //   unqualified, and the function has namespace scope.
12003     if (D.isFunctionDefinition()) {
12004       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12005     }
12006 
12007   //   - There's no scope specifier, in which case we just go to the
12008   //     appropriate scope and look for a function or function template
12009   //     there as appropriate.
12010   } else if (SS.isInvalid() || !SS.isSet()) {
12011     // C++11 [namespace.memdef]p3:
12012     //   If the name in a friend declaration is neither qualified nor
12013     //   a template-id and the declaration is a function or an
12014     //   elaborated-type-specifier, the lookup to determine whether
12015     //   the entity has been previously declared shall not consider
12016     //   any scopes outside the innermost enclosing namespace.
12017     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12018 
12019     // Find the appropriate context according to the above.
12020     DC = CurContext;
12021 
12022     // Skip class contexts.  If someone can cite chapter and verse
12023     // for this behavior, that would be nice --- it's what GCC and
12024     // EDG do, and it seems like a reasonable intent, but the spec
12025     // really only says that checks for unqualified existing
12026     // declarations should stop at the nearest enclosing namespace,
12027     // not that they should only consider the nearest enclosing
12028     // namespace.
12029     while (DC->isRecord())
12030       DC = DC->getParent();
12031 
12032     DeclContext *LookupDC = DC;
12033     while (LookupDC->isTransparentContext())
12034       LookupDC = LookupDC->getParent();
12035 
12036     while (true) {
12037       LookupQualifiedName(Previous, LookupDC);
12038 
12039       if (!Previous.empty()) {
12040         DC = LookupDC;
12041         break;
12042       }
12043 
12044       if (isTemplateId) {
12045         if (isa<TranslationUnitDecl>(LookupDC)) break;
12046       } else {
12047         if (LookupDC->isFileContext()) break;
12048       }
12049       LookupDC = LookupDC->getParent();
12050     }
12051 
12052     DCScope = getScopeForDeclContext(S, DC);
12053 
12054   //   - There's a non-dependent scope specifier, in which case we
12055   //     compute it and do a previous lookup there for a function
12056   //     or function template.
12057   } else if (!SS.getScopeRep()->isDependent()) {
12058     DC = computeDeclContext(SS);
12059     if (!DC) return nullptr;
12060 
12061     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12062 
12063     LookupQualifiedName(Previous, DC);
12064 
12065     // Ignore things found implicitly in the wrong scope.
12066     // TODO: better diagnostics for this case.  Suggesting the right
12067     // qualified scope would be nice...
12068     LookupResult::Filter F = Previous.makeFilter();
12069     while (F.hasNext()) {
12070       NamedDecl *D = F.next();
12071       if (!DC->InEnclosingNamespaceSetOf(
12072               D->getDeclContext()->getRedeclContext()))
12073         F.erase();
12074     }
12075     F.done();
12076 
12077     if (Previous.empty()) {
12078       D.setInvalidType();
12079       Diag(Loc, diag::err_qualified_friend_not_found)
12080           << Name << TInfo->getType();
12081       return nullptr;
12082     }
12083 
12084     // C++ [class.friend]p1: A friend of a class is a function or
12085     //   class that is not a member of the class . . .
12086     if (DC->Equals(CurContext))
12087       Diag(DS.getFriendSpecLoc(),
12088            getLangOpts().CPlusPlus11 ?
12089              diag::warn_cxx98_compat_friend_is_member :
12090              diag::err_friend_is_member);
12091 
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       SemaDiagnosticBuilder DB
12098         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12099 
12100       DB << SS.getScopeRep();
12101       if (DC->isFileContext())
12102         DB << FixItHint::CreateRemoval(SS.getRange());
12103       SS.clear();
12104     }
12105 
12106   //   - There's a scope specifier that does not match any template
12107   //     parameter lists, in which case we use some arbitrary context,
12108   //     create a method or method template, and wait for instantiation.
12109   //   - There's a scope specifier that does match some template
12110   //     parameter lists, which we don't handle right now.
12111   } else {
12112     if (D.isFunctionDefinition()) {
12113       // C++ [class.friend]p6:
12114       //   A function can be defined in a friend declaration of a class if and
12115       //   only if the class is a non-local class (9.8), the function name is
12116       //   unqualified, and the function has namespace scope.
12117       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12118         << SS.getScopeRep();
12119     }
12120 
12121     DC = CurContext;
12122     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12123   }
12124 
12125   if (!DC->isRecord()) {
12126     // This implies that it has to be an operator or function.
12127     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12128         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12129         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12130       Diag(Loc, diag::err_introducing_special_friend) <<
12131         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12132          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12133       return nullptr;
12134     }
12135   }
12136 
12137   // FIXME: This is an egregious hack to cope with cases where the scope stack
12138   // does not contain the declaration context, i.e., in an out-of-line
12139   // definition of a class.
12140   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12141   if (!DCScope) {
12142     FakeDCScope.setEntity(DC);
12143     DCScope = &FakeDCScope;
12144   }
12145 
12146   bool AddToScope = true;
12147   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12148                                           TemplateParams, AddToScope);
12149   if (!ND) return nullptr;
12150 
12151   assert(ND->getLexicalDeclContext() == CurContext);
12152 
12153   // If we performed typo correction, we might have added a scope specifier
12154   // and changed the decl context.
12155   DC = ND->getDeclContext();
12156 
12157   // Add the function declaration to the appropriate lookup tables,
12158   // adjusting the redeclarations list as necessary.  We don't
12159   // want to do this yet if the friending class is dependent.
12160   //
12161   // Also update the scope-based lookup if the target context's
12162   // lookup context is in lexical scope.
12163   if (!CurContext->isDependentContext()) {
12164     DC = DC->getRedeclContext();
12165     DC->makeDeclVisibleInContext(ND);
12166     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12167       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12168   }
12169 
12170   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12171                                        D.getIdentifierLoc(), ND,
12172                                        DS.getFriendSpecLoc());
12173   FrD->setAccess(AS_public);
12174   CurContext->addDecl(FrD);
12175 
12176   if (ND->isInvalidDecl()) {
12177     FrD->setInvalidDecl();
12178   } else {
12179     if (DC->isRecord()) CheckFriendAccess(ND);
12180 
12181     FunctionDecl *FD;
12182     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12183       FD = FTD->getTemplatedDecl();
12184     else
12185       FD = cast<FunctionDecl>(ND);
12186 
12187     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12188     // default argument expression, that declaration shall be a definition
12189     // and shall be the only declaration of the function or function
12190     // template in the translation unit.
12191     if (functionDeclHasDefaultArgument(FD)) {
12192       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12193         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12194         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12195       } else if (!D.isFunctionDefinition())
12196         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12197     }
12198 
12199     // Mark templated-scope function declarations as unsupported.
12200     if (FD->getNumTemplateParameterLists())
12201       FrD->setUnsupportedFriend(true);
12202   }
12203 
12204   return ND;
12205 }
12206 
12207 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12208   AdjustDeclIfTemplate(Dcl);
12209 
12210   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12211   if (!Fn) {
12212     Diag(DelLoc, diag::err_deleted_non_function);
12213     return;
12214   }
12215 
12216   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12217     // Don't consider the implicit declaration we generate for explicit
12218     // specializations. FIXME: Do not generate these implicit declarations.
12219     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12220          Prev->getPreviousDecl()) &&
12221         !Prev->isDefined()) {
12222       Diag(DelLoc, diag::err_deleted_decl_not_first);
12223       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12224            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12225                               : diag::note_previous_declaration);
12226     }
12227     // If the declaration wasn't the first, we delete the function anyway for
12228     // recovery.
12229     Fn = Fn->getCanonicalDecl();
12230   }
12231 
12232   // dllimport/dllexport cannot be deleted.
12233   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12234     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12235     Fn->setInvalidDecl();
12236   }
12237 
12238   if (Fn->isDeleted())
12239     return;
12240 
12241   // See if we're deleting a function which is already known to override a
12242   // non-deleted virtual function.
12243   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12244     bool IssuedDiagnostic = false;
12245     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12246                                         E = MD->end_overridden_methods();
12247          I != E; ++I) {
12248       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12249         if (!IssuedDiagnostic) {
12250           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12251           IssuedDiagnostic = true;
12252         }
12253         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12254       }
12255     }
12256   }
12257 
12258   // C++11 [basic.start.main]p3:
12259   //   A program that defines main as deleted [...] is ill-formed.
12260   if (Fn->isMain())
12261     Diag(DelLoc, diag::err_deleted_main);
12262 
12263   Fn->setDeletedAsWritten();
12264 }
12265 
12266 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12267   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12268 
12269   if (MD) {
12270     if (MD->getParent()->isDependentType()) {
12271       MD->setDefaulted();
12272       MD->setExplicitlyDefaulted();
12273       return;
12274     }
12275 
12276     CXXSpecialMember Member = getSpecialMember(MD);
12277     if (Member == CXXInvalid) {
12278       if (!MD->isInvalidDecl())
12279         Diag(DefaultLoc, diag::err_default_special_members);
12280       return;
12281     }
12282 
12283     MD->setDefaulted();
12284     MD->setExplicitlyDefaulted();
12285 
12286     // If this definition appears within the record, do the checking when
12287     // the record is complete.
12288     const FunctionDecl *Primary = MD;
12289     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12290       // Find the uninstantiated declaration that actually had the '= default'
12291       // on it.
12292       Pattern->isDefined(Primary);
12293 
12294     // If the method was defaulted on its first declaration, we will have
12295     // already performed the checking in CheckCompletedCXXClass. Such a
12296     // declaration doesn't trigger an implicit definition.
12297     if (Primary == Primary->getCanonicalDecl())
12298       return;
12299 
12300     CheckExplicitlyDefaultedSpecialMember(MD);
12301 
12302     // The exception specification is needed because we are defining the
12303     // function.
12304     ResolveExceptionSpec(DefaultLoc,
12305                          MD->getType()->castAs<FunctionProtoType>());
12306 
12307     if (MD->isInvalidDecl())
12308       return;
12309 
12310     switch (Member) {
12311     case CXXDefaultConstructor:
12312       DefineImplicitDefaultConstructor(DefaultLoc,
12313                                        cast<CXXConstructorDecl>(MD));
12314       break;
12315     case CXXCopyConstructor:
12316       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12317       break;
12318     case CXXCopyAssignment:
12319       DefineImplicitCopyAssignment(DefaultLoc, MD);
12320       break;
12321     case CXXDestructor:
12322       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12323       break;
12324     case CXXMoveConstructor:
12325       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12326       break;
12327     case CXXMoveAssignment:
12328       DefineImplicitMoveAssignment(DefaultLoc, MD);
12329       break;
12330     case CXXInvalid:
12331       llvm_unreachable("Invalid special member.");
12332     }
12333   } else {
12334     Diag(DefaultLoc, diag::err_default_special_members);
12335   }
12336 }
12337 
12338 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12339   for (Stmt::child_range CI = S->children(); CI; ++CI) {
12340     Stmt *SubStmt = *CI;
12341     if (!SubStmt)
12342       continue;
12343     if (isa<ReturnStmt>(SubStmt))
12344       Self.Diag(SubStmt->getLocStart(),
12345            diag::err_return_in_constructor_handler);
12346     if (!isa<Expr>(SubStmt))
12347       SearchForReturnInStmt(Self, SubStmt);
12348   }
12349 }
12350 
12351 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12352   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12353     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12354     SearchForReturnInStmt(*this, Handler);
12355   }
12356 }
12357 
12358 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12359                                              const CXXMethodDecl *Old) {
12360   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12361   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12362 
12363   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12364 
12365   // If the calling conventions match, everything is fine
12366   if (NewCC == OldCC)
12367     return false;
12368 
12369   // If the calling conventions mismatch because the new function is static,
12370   // suppress the calling convention mismatch error; the error about static
12371   // function override (err_static_overrides_virtual from
12372   // Sema::CheckFunctionDeclaration) is more clear.
12373   if (New->getStorageClass() == SC_Static)
12374     return false;
12375 
12376   Diag(New->getLocation(),
12377        diag::err_conflicting_overriding_cc_attributes)
12378     << New->getDeclName() << New->getType() << Old->getType();
12379   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12380   return true;
12381 }
12382 
12383 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12384                                              const CXXMethodDecl *Old) {
12385   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12386   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12387 
12388   if (Context.hasSameType(NewTy, OldTy) ||
12389       NewTy->isDependentType() || OldTy->isDependentType())
12390     return false;
12391 
12392   // Check if the return types are covariant
12393   QualType NewClassTy, OldClassTy;
12394 
12395   /// Both types must be pointers or references to classes.
12396   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12397     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12398       NewClassTy = NewPT->getPointeeType();
12399       OldClassTy = OldPT->getPointeeType();
12400     }
12401   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12402     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12403       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12404         NewClassTy = NewRT->getPointeeType();
12405         OldClassTy = OldRT->getPointeeType();
12406       }
12407     }
12408   }
12409 
12410   // The return types aren't either both pointers or references to a class type.
12411   if (NewClassTy.isNull()) {
12412     Diag(New->getLocation(),
12413          diag::err_different_return_type_for_overriding_virtual_function)
12414         << New->getDeclName() << NewTy << OldTy
12415         << New->getReturnTypeSourceRange();
12416     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12417         << Old->getReturnTypeSourceRange();
12418 
12419     return true;
12420   }
12421 
12422   // C++ [class.virtual]p6:
12423   //   If the return type of D::f differs from the return type of B::f, the
12424   //   class type in the return type of D::f shall be complete at the point of
12425   //   declaration of D::f or shall be the class type D.
12426   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12427     if (!RT->isBeingDefined() &&
12428         RequireCompleteType(New->getLocation(), NewClassTy,
12429                             diag::err_covariant_return_incomplete,
12430                             New->getDeclName()))
12431     return true;
12432   }
12433 
12434   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12435     // Check if the new class derives from the old class.
12436     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12437       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12438           << New->getDeclName() << NewTy << OldTy
12439           << New->getReturnTypeSourceRange();
12440       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12441           << Old->getReturnTypeSourceRange();
12442       return true;
12443     }
12444 
12445     // Check if we the conversion from derived to base is valid.
12446     if (CheckDerivedToBaseConversion(
12447             NewClassTy, OldClassTy,
12448             diag::err_covariant_return_inaccessible_base,
12449             diag::err_covariant_return_ambiguous_derived_to_base_conv,
12450             New->getLocation(), New->getReturnTypeSourceRange(),
12451             New->getDeclName(), nullptr)) {
12452       // FIXME: this note won't trigger for delayed access control
12453       // diagnostics, and it's impossible to get an undelayed error
12454       // here from access control during the original parse because
12455       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12456       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12457           << Old->getReturnTypeSourceRange();
12458       return true;
12459     }
12460   }
12461 
12462   // The qualifiers of the return types must be the same.
12463   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12464     Diag(New->getLocation(),
12465          diag::err_covariant_return_type_different_qualifications)
12466         << New->getDeclName() << NewTy << OldTy
12467         << New->getReturnTypeSourceRange();
12468     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12469         << Old->getReturnTypeSourceRange();
12470     return true;
12471   };
12472 
12473 
12474   // The new class type must have the same or less qualifiers as the old type.
12475   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12476     Diag(New->getLocation(),
12477          diag::err_covariant_return_type_class_type_more_qualified)
12478         << New->getDeclName() << NewTy << OldTy
12479         << New->getReturnTypeSourceRange();
12480     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12481         << Old->getReturnTypeSourceRange();
12482     return true;
12483   };
12484 
12485   return false;
12486 }
12487 
12488 /// \brief Mark the given method pure.
12489 ///
12490 /// \param Method the method to be marked pure.
12491 ///
12492 /// \param InitRange the source range that covers the "0" initializer.
12493 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12494   SourceLocation EndLoc = InitRange.getEnd();
12495   if (EndLoc.isValid())
12496     Method->setRangeEnd(EndLoc);
12497 
12498   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12499     Method->setPure();
12500     return false;
12501   }
12502 
12503   if (!Method->isInvalidDecl())
12504     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12505       << Method->getDeclName() << InitRange;
12506   return true;
12507 }
12508 
12509 /// \brief Determine whether the given declaration is a static data member.
12510 static bool isStaticDataMember(const Decl *D) {
12511   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12512     return Var->isStaticDataMember();
12513 
12514   return false;
12515 }
12516 
12517 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12518 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12519 /// is a fresh scope pushed for just this purpose.
12520 ///
12521 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12522 /// static data member of class X, names should be looked up in the scope of
12523 /// class X.
12524 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12525   // If there is no declaration, there was an error parsing it.
12526   if (!D || D->isInvalidDecl())
12527     return;
12528 
12529   // We will always have a nested name specifier here, but this declaration
12530   // might not be out of line if the specifier names the current namespace:
12531   //   extern int n;
12532   //   int ::n = 0;
12533   if (D->isOutOfLine())
12534     EnterDeclaratorContext(S, D->getDeclContext());
12535 
12536   // If we are parsing the initializer for a static data member, push a
12537   // new expression evaluation context that is associated with this static
12538   // data member.
12539   if (isStaticDataMember(D))
12540     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12541 }
12542 
12543 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12544 /// initializer for the out-of-line declaration 'D'.
12545 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12546   // If there is no declaration, there was an error parsing it.
12547   if (!D || D->isInvalidDecl())
12548     return;
12549 
12550   if (isStaticDataMember(D))
12551     PopExpressionEvaluationContext();
12552 
12553   if (D->isOutOfLine())
12554     ExitDeclaratorContext(S);
12555 }
12556 
12557 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12558 /// C++ if/switch/while/for statement.
12559 /// e.g: "if (int x = f()) {...}"
12560 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12561   // C++ 6.4p2:
12562   // The declarator shall not specify a function or an array.
12563   // The type-specifier-seq shall not contain typedef and shall not declare a
12564   // new class or enumeration.
12565   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12566          "Parser allowed 'typedef' as storage class of condition decl.");
12567 
12568   Decl *Dcl = ActOnDeclarator(S, D);
12569   if (!Dcl)
12570     return true;
12571 
12572   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12573     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12574       << D.getSourceRange();
12575     return true;
12576   }
12577 
12578   return Dcl;
12579 }
12580 
12581 void Sema::LoadExternalVTableUses() {
12582   if (!ExternalSource)
12583     return;
12584 
12585   SmallVector<ExternalVTableUse, 4> VTables;
12586   ExternalSource->ReadUsedVTables(VTables);
12587   SmallVector<VTableUse, 4> NewUses;
12588   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12589     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12590       = VTablesUsed.find(VTables[I].Record);
12591     // Even if a definition wasn't required before, it may be required now.
12592     if (Pos != VTablesUsed.end()) {
12593       if (!Pos->second && VTables[I].DefinitionRequired)
12594         Pos->second = true;
12595       continue;
12596     }
12597 
12598     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12599     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12600   }
12601 
12602   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12603 }
12604 
12605 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12606                           bool DefinitionRequired) {
12607   // Ignore any vtable uses in unevaluated operands or for classes that do
12608   // not have a vtable.
12609   if (!Class->isDynamicClass() || Class->isDependentContext() ||
12610       CurContext->isDependentContext() || isUnevaluatedContext())
12611     return;
12612 
12613   // Try to insert this class into the map.
12614   LoadExternalVTableUses();
12615   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12616   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12617     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12618   if (!Pos.second) {
12619     // If we already had an entry, check to see if we are promoting this vtable
12620     // to required a definition. If so, we need to reappend to the VTableUses
12621     // list, since we may have already processed the first entry.
12622     if (DefinitionRequired && !Pos.first->second) {
12623       Pos.first->second = true;
12624     } else {
12625       // Otherwise, we can early exit.
12626       return;
12627     }
12628   } else {
12629     // The Microsoft ABI requires that we perform the destructor body
12630     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12631     // the deleting destructor is emitted with the vtable, not with the
12632     // destructor definition as in the Itanium ABI.
12633     // If it has a definition, we do the check at that point instead.
12634     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12635         Class->hasUserDeclaredDestructor() &&
12636         !Class->getDestructor()->isDefined() &&
12637         !Class->getDestructor()->isDeleted()) {
12638       CXXDestructorDecl *DD = Class->getDestructor();
12639       ContextRAII SavedContext(*this, DD);
12640       CheckDestructor(DD);
12641     }
12642   }
12643 
12644   // Local classes need to have their virtual members marked
12645   // immediately. For all other classes, we mark their virtual members
12646   // at the end of the translation unit.
12647   if (Class->isLocalClass())
12648     MarkVirtualMembersReferenced(Loc, Class);
12649   else
12650     VTableUses.push_back(std::make_pair(Class, Loc));
12651 }
12652 
12653 bool Sema::DefineUsedVTables() {
12654   LoadExternalVTableUses();
12655   if (VTableUses.empty())
12656     return false;
12657 
12658   // Note: The VTableUses vector could grow as a result of marking
12659   // the members of a class as "used", so we check the size each
12660   // time through the loop and prefer indices (which are stable) to
12661   // iterators (which are not).
12662   bool DefinedAnything = false;
12663   for (unsigned I = 0; I != VTableUses.size(); ++I) {
12664     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12665     if (!Class)
12666       continue;
12667 
12668     SourceLocation Loc = VTableUses[I].second;
12669 
12670     bool DefineVTable = true;
12671 
12672     // If this class has a key function, but that key function is
12673     // defined in another translation unit, we don't need to emit the
12674     // vtable even though we're using it.
12675     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12676     if (KeyFunction && !KeyFunction->hasBody()) {
12677       // The key function is in another translation unit.
12678       DefineVTable = false;
12679       TemplateSpecializationKind TSK =
12680           KeyFunction->getTemplateSpecializationKind();
12681       assert(TSK != TSK_ExplicitInstantiationDefinition &&
12682              TSK != TSK_ImplicitInstantiation &&
12683              "Instantiations don't have key functions");
12684       (void)TSK;
12685     } else if (!KeyFunction) {
12686       // If we have a class with no key function that is the subject
12687       // of an explicit instantiation declaration, suppress the
12688       // vtable; it will live with the explicit instantiation
12689       // definition.
12690       bool IsExplicitInstantiationDeclaration
12691         = Class->getTemplateSpecializationKind()
12692                                       == TSK_ExplicitInstantiationDeclaration;
12693       for (auto R : Class->redecls()) {
12694         TemplateSpecializationKind TSK
12695           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
12696         if (TSK == TSK_ExplicitInstantiationDeclaration)
12697           IsExplicitInstantiationDeclaration = true;
12698         else if (TSK == TSK_ExplicitInstantiationDefinition) {
12699           IsExplicitInstantiationDeclaration = false;
12700           break;
12701         }
12702       }
12703 
12704       if (IsExplicitInstantiationDeclaration)
12705         DefineVTable = false;
12706     }
12707 
12708     // The exception specifications for all virtual members may be needed even
12709     // if we are not providing an authoritative form of the vtable in this TU.
12710     // We may choose to emit it available_externally anyway.
12711     if (!DefineVTable) {
12712       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12713       continue;
12714     }
12715 
12716     // Mark all of the virtual members of this class as referenced, so
12717     // that we can build a vtable. Then, tell the AST consumer that a
12718     // vtable for this class is required.
12719     DefinedAnything = true;
12720     MarkVirtualMembersReferenced(Loc, Class);
12721     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12722     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12723 
12724     // Optionally warn if we're emitting a weak vtable.
12725     if (Class->isExternallyVisible() &&
12726         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12727       const FunctionDecl *KeyFunctionDef = nullptr;
12728       if (!KeyFunction ||
12729           (KeyFunction->hasBody(KeyFunctionDef) &&
12730            KeyFunctionDef->isInlined()))
12731         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12732              TSK_ExplicitInstantiationDefinition
12733              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12734           << Class;
12735     }
12736   }
12737   VTableUses.clear();
12738 
12739   return DefinedAnything;
12740 }
12741 
12742 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12743                                                  const CXXRecordDecl *RD) {
12744   for (const auto *I : RD->methods())
12745     if (I->isVirtual() && !I->isPure())
12746       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
12747 }
12748 
12749 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12750                                         const CXXRecordDecl *RD) {
12751   // Mark all functions which will appear in RD's vtable as used.
12752   CXXFinalOverriderMap FinalOverriders;
12753   RD->getFinalOverriders(FinalOverriders);
12754   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12755                                             E = FinalOverriders.end();
12756        I != E; ++I) {
12757     for (OverridingMethods::const_iterator OI = I->second.begin(),
12758                                            OE = I->second.end();
12759          OI != OE; ++OI) {
12760       assert(OI->second.size() > 0 && "no final overrider");
12761       CXXMethodDecl *Overrider = OI->second.front().Method;
12762 
12763       // C++ [basic.def.odr]p2:
12764       //   [...] A virtual member function is used if it is not pure. [...]
12765       if (!Overrider->isPure())
12766         MarkFunctionReferenced(Loc, Overrider);
12767     }
12768   }
12769 
12770   // Only classes that have virtual bases need a VTT.
12771   if (RD->getNumVBases() == 0)
12772     return;
12773 
12774   for (const auto &I : RD->bases()) {
12775     const CXXRecordDecl *Base =
12776         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
12777     if (Base->getNumVBases() == 0)
12778       continue;
12779     MarkVirtualMembersReferenced(Loc, Base);
12780   }
12781 }
12782 
12783 /// SetIvarInitializers - This routine builds initialization ASTs for the
12784 /// Objective-C implementation whose ivars need be initialized.
12785 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12786   if (!getLangOpts().CPlusPlus)
12787     return;
12788   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12789     SmallVector<ObjCIvarDecl*, 8> ivars;
12790     CollectIvarsToConstructOrDestruct(OID, ivars);
12791     if (ivars.empty())
12792       return;
12793     SmallVector<CXXCtorInitializer*, 32> AllToInit;
12794     for (unsigned i = 0; i < ivars.size(); i++) {
12795       FieldDecl *Field = ivars[i];
12796       if (Field->isInvalidDecl())
12797         continue;
12798 
12799       CXXCtorInitializer *Member;
12800       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12801       InitializationKind InitKind =
12802         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12803 
12804       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12805       ExprResult MemberInit =
12806         InitSeq.Perform(*this, InitEntity, InitKind, None);
12807       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12808       // Note, MemberInit could actually come back empty if no initialization
12809       // is required (e.g., because it would call a trivial default constructor)
12810       if (!MemberInit.get() || MemberInit.isInvalid())
12811         continue;
12812 
12813       Member =
12814         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12815                                          SourceLocation(),
12816                                          MemberInit.getAs<Expr>(),
12817                                          SourceLocation());
12818       AllToInit.push_back(Member);
12819 
12820       // Be sure that the destructor is accessible and is marked as referenced.
12821       if (const RecordType *RecordTy
12822                   = Context.getBaseElementType(Field->getType())
12823                                                         ->getAs<RecordType>()) {
12824                     CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12825         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12826           MarkFunctionReferenced(Field->getLocation(), Destructor);
12827           CheckDestructorAccess(Field->getLocation(), Destructor,
12828                             PDiag(diag::err_access_dtor_ivar)
12829                               << Context.getBaseElementType(Field->getType()));
12830         }
12831       }
12832     }
12833     ObjCImplementation->setIvarInitializers(Context,
12834                                             AllToInit.data(), AllToInit.size());
12835   }
12836 }
12837 
12838 static
12839 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12840                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12841                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12842                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12843                            Sema &S) {
12844   if (Ctor->isInvalidDecl())
12845     return;
12846 
12847   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12848 
12849   // Target may not be determinable yet, for instance if this is a dependent
12850   // call in an uninstantiated template.
12851   if (Target) {
12852     const FunctionDecl *FNTarget = nullptr;
12853     (void)Target->hasBody(FNTarget);
12854     Target = const_cast<CXXConstructorDecl*>(
12855       cast_or_null<CXXConstructorDecl>(FNTarget));
12856   }
12857 
12858   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12859                      // Avoid dereferencing a null pointer here.
12860                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
12861 
12862   if (!Current.insert(Canonical))
12863     return;
12864 
12865   // We know that beyond here, we aren't chaining into a cycle.
12866   if (!Target || !Target->isDelegatingConstructor() ||
12867       Target->isInvalidDecl() || Valid.count(TCanonical)) {
12868     Valid.insert(Current.begin(), Current.end());
12869     Current.clear();
12870   // We've hit a cycle.
12871   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12872              Current.count(TCanonical)) {
12873     // If we haven't diagnosed this cycle yet, do so now.
12874     if (!Invalid.count(TCanonical)) {
12875       S.Diag((*Ctor->init_begin())->getSourceLocation(),
12876              diag::warn_delegating_ctor_cycle)
12877         << Ctor;
12878 
12879       // Don't add a note for a function delegating directly to itself.
12880       if (TCanonical != Canonical)
12881         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12882 
12883       CXXConstructorDecl *C = Target;
12884       while (C->getCanonicalDecl() != Canonical) {
12885         const FunctionDecl *FNTarget = nullptr;
12886         (void)C->getTargetConstructor()->hasBody(FNTarget);
12887         assert(FNTarget && "Ctor cycle through bodiless function");
12888 
12889         C = const_cast<CXXConstructorDecl*>(
12890           cast<CXXConstructorDecl>(FNTarget));
12891         S.Diag(C->getLocation(), diag::note_which_delegates_to);
12892       }
12893     }
12894 
12895     Invalid.insert(Current.begin(), Current.end());
12896     Current.clear();
12897   } else {
12898     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12899   }
12900 }
12901 
12902 
12903 void Sema::CheckDelegatingCtorCycles() {
12904   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12905 
12906   for (DelegatingCtorDeclsType::iterator
12907          I = DelegatingCtorDecls.begin(ExternalSource),
12908          E = DelegatingCtorDecls.end();
12909        I != E; ++I)
12910     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12911 
12912   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12913                                                          CE = Invalid.end();
12914        CI != CE; ++CI)
12915     (*CI)->setInvalidDecl();
12916 }
12917 
12918 namespace {
12919   /// \brief AST visitor that finds references to the 'this' expression.
12920   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12921     Sema &S;
12922 
12923   public:
12924     explicit FindCXXThisExpr(Sema &S) : S(S) { }
12925 
12926     bool VisitCXXThisExpr(CXXThisExpr *E) {
12927       S.Diag(E->getLocation(), diag::err_this_static_member_func)
12928         << E->isImplicit();
12929       return false;
12930     }
12931   };
12932 }
12933 
12934 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12935   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12936   if (!TSInfo)
12937     return false;
12938 
12939   TypeLoc TL = TSInfo->getTypeLoc();
12940   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12941   if (!ProtoTL)
12942     return false;
12943 
12944   // C++11 [expr.prim.general]p3:
12945   //   [The expression this] shall not appear before the optional
12946   //   cv-qualifier-seq and it shall not appear within the declaration of a
12947   //   static member function (although its type and value category are defined
12948   //   within a static member function as they are within a non-static member
12949   //   function). [ Note: this is because declaration matching does not occur
12950   //  until the complete declarator is known. - end note ]
12951   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12952   FindCXXThisExpr Finder(*this);
12953 
12954   // If the return type came after the cv-qualifier-seq, check it now.
12955   if (Proto->hasTrailingReturn() &&
12956       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
12957     return true;
12958 
12959   // Check the exception specification.
12960   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12961     return true;
12962 
12963   return checkThisInStaticMemberFunctionAttributes(Method);
12964 }
12965 
12966 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12967   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12968   if (!TSInfo)
12969     return false;
12970 
12971   TypeLoc TL = TSInfo->getTypeLoc();
12972   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12973   if (!ProtoTL)
12974     return false;
12975 
12976   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12977   FindCXXThisExpr Finder(*this);
12978 
12979   switch (Proto->getExceptionSpecType()) {
12980   case EST_Uninstantiated:
12981   case EST_Unevaluated:
12982   case EST_BasicNoexcept:
12983   case EST_DynamicNone:
12984   case EST_MSAny:
12985   case EST_None:
12986     break;
12987 
12988   case EST_ComputedNoexcept:
12989     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12990       return true;
12991 
12992   case EST_Dynamic:
12993     for (const auto &E : Proto->exceptions()) {
12994       if (!Finder.TraverseType(E))
12995         return true;
12996     }
12997     break;
12998   }
12999 
13000   return false;
13001 }
13002 
13003 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13004   FindCXXThisExpr Finder(*this);
13005 
13006   // Check attributes.
13007   for (const auto *A : Method->attrs()) {
13008     // FIXME: This should be emitted by tblgen.
13009     Expr *Arg = nullptr;
13010     ArrayRef<Expr *> Args;
13011     if (const auto *G = dyn_cast<GuardedByAttr>(A))
13012       Arg = G->getArg();
13013     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13014       Arg = G->getArg();
13015     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13016       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13017     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13018       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13019     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13020       Arg = ETLF->getSuccessValue();
13021       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13022     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13023       Arg = STLF->getSuccessValue();
13024       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13025     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13026       Arg = LR->getArg();
13027     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13028       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13029     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13030       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13031     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13032       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13033     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13034       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13035     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13036       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13037 
13038     if (Arg && !Finder.TraverseStmt(Arg))
13039       return true;
13040 
13041     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13042       if (!Finder.TraverseStmt(Args[I]))
13043         return true;
13044     }
13045   }
13046 
13047   return false;
13048 }
13049 
13050 void
13051 Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
13052                                   ArrayRef<ParsedType> DynamicExceptions,
13053                                   ArrayRef<SourceRange> DynamicExceptionRanges,
13054                                   Expr *NoexceptExpr,
13055                                   SmallVectorImpl<QualType> &Exceptions,
13056                                   FunctionProtoType::ExceptionSpecInfo &ESI) {
13057   Exceptions.clear();
13058   ESI.Type = EST;
13059   if (EST == EST_Dynamic) {
13060     Exceptions.reserve(DynamicExceptions.size());
13061     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13062       // FIXME: Preserve type source info.
13063       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13064 
13065       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13066       collectUnexpandedParameterPacks(ET, Unexpanded);
13067       if (!Unexpanded.empty()) {
13068         DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
13069                                          UPPC_ExceptionType,
13070                                          Unexpanded);
13071         continue;
13072       }
13073 
13074       // Check that the type is valid for an exception spec, and
13075       // drop it if not.
13076       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13077         Exceptions.push_back(ET);
13078     }
13079     ESI.Exceptions = Exceptions;
13080     return;
13081   }
13082 
13083   if (EST == EST_ComputedNoexcept) {
13084     // If an error occurred, there's no expression here.
13085     if (NoexceptExpr) {
13086       assert((NoexceptExpr->isTypeDependent() ||
13087               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13088               Context.BoolTy) &&
13089              "Parser should have made sure that the expression is boolean");
13090       if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13091         ESI.Type = EST_BasicNoexcept;
13092         return;
13093       }
13094 
13095       if (!NoexceptExpr->isValueDependent())
13096         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13097                          diag::err_noexcept_needs_constant_expression,
13098                          /*AllowFold*/ false).get();
13099       ESI.NoexceptExpr = NoexceptExpr;
13100     }
13101     return;
13102   }
13103 }
13104 
13105 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
13106 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
13107   // Implicitly declared functions (e.g. copy constructors) are
13108   // __host__ __device__
13109   if (D->isImplicit())
13110     return CFT_HostDevice;
13111 
13112   if (D->hasAttr<CUDAGlobalAttr>())
13113     return CFT_Global;
13114 
13115   if (D->hasAttr<CUDADeviceAttr>()) {
13116     if (D->hasAttr<CUDAHostAttr>())
13117       return CFT_HostDevice;
13118     return CFT_Device;
13119   }
13120 
13121   return CFT_Host;
13122 }
13123 
13124 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
13125                            CUDAFunctionTarget CalleeTarget) {
13126   // CUDA B.1.1 "The __device__ qualifier declares a function that is...
13127   // Callable from the device only."
13128   if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
13129     return true;
13130 
13131   // CUDA B.1.2 "The __global__ qualifier declares a function that is...
13132   // Callable from the host only."
13133   // CUDA B.1.3 "The __host__ qualifier declares a function that is...
13134   // Callable from the host only."
13135   if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
13136       (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
13137     return true;
13138 
13139   if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
13140     return true;
13141 
13142   return false;
13143 }
13144 
13145 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13146 ///
13147 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13148                                        SourceLocation DeclStart,
13149                                        Declarator &D, Expr *BitWidth,
13150                                        InClassInitStyle InitStyle,
13151                                        AccessSpecifier AS,
13152                                        AttributeList *MSPropertyAttr) {
13153   IdentifierInfo *II = D.getIdentifier();
13154   if (!II) {
13155     Diag(DeclStart, diag::err_anonymous_property);
13156     return nullptr;
13157   }
13158   SourceLocation Loc = D.getIdentifierLoc();
13159 
13160   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13161   QualType T = TInfo->getType();
13162   if (getLangOpts().CPlusPlus) {
13163     CheckExtraCXXDefaultArguments(D);
13164 
13165     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13166                                         UPPC_DataMemberType)) {
13167       D.setInvalidType();
13168       T = Context.IntTy;
13169       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13170     }
13171   }
13172 
13173   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13174 
13175   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13176     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13177          diag::err_invalid_thread)
13178       << DeclSpec::getSpecifierName(TSCS);
13179 
13180   // Check to see if this name was declared as a member previously
13181   NamedDecl *PrevDecl = nullptr;
13182   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13183   LookupName(Previous, S);
13184   switch (Previous.getResultKind()) {
13185   case LookupResult::Found:
13186   case LookupResult::FoundUnresolvedValue:
13187     PrevDecl = Previous.getAsSingle<NamedDecl>();
13188     break;
13189 
13190   case LookupResult::FoundOverloaded:
13191     PrevDecl = Previous.getRepresentativeDecl();
13192     break;
13193 
13194   case LookupResult::NotFound:
13195   case LookupResult::NotFoundInCurrentInstantiation:
13196   case LookupResult::Ambiguous:
13197     break;
13198   }
13199 
13200   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13201     // Maybe we will complain about the shadowed template parameter.
13202     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13203     // Just pretend that we didn't see the previous declaration.
13204     PrevDecl = nullptr;
13205   }
13206 
13207   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13208     PrevDecl = nullptr;
13209 
13210   SourceLocation TSSL = D.getLocStart();
13211   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13212   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13213       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13214   ProcessDeclAttributes(TUScope, NewPD, D);
13215   NewPD->setAccess(AS);
13216 
13217   if (NewPD->isInvalidDecl())
13218     Record->setInvalidDecl();
13219 
13220   if (D.getDeclSpec().isModulePrivateSpecified())
13221     NewPD->setModulePrivate();
13222 
13223   if (NewPD->isInvalidDecl() && PrevDecl) {
13224     // Don't introduce NewFD into scope; there's already something
13225     // with the same name in the same scope.
13226   } else if (II) {
13227     PushOnScopeChains(NewPD, S);
13228   } else
13229     Record->addDecl(NewPD);
13230 
13231   return NewPD;
13232 }
13233